test_style.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. from collections import OrderedDict
  2. from contextlib import contextmanager
  3. import gc
  4. from pathlib import Path
  5. from tempfile import TemporaryDirectory
  6. import sys
  7. import pytest
  8. import matplotlib as mpl
  9. from matplotlib import pyplot as plt, style
  10. from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION
  11. PARAM = 'image.cmap'
  12. VALUE = 'pink'
  13. DUMMY_SETTINGS = {PARAM: VALUE}
  14. @contextmanager
  15. def temp_style(style_name, settings=None):
  16. """Context manager to create a style sheet in a temporary directory."""
  17. if not settings:
  18. settings = DUMMY_SETTINGS
  19. temp_file = '%s.%s' % (style_name, STYLE_EXTENSION)
  20. try:
  21. with TemporaryDirectory() as tmpdir:
  22. # Write style settings to file in the tmpdir.
  23. Path(tmpdir, temp_file).write_text(
  24. "\n".join("{}: {}".format(k, v) for k, v in settings.items()))
  25. # Add tmpdir to style path and reload so we can access this style.
  26. USER_LIBRARY_PATHS.append(tmpdir)
  27. style.reload_library()
  28. yield
  29. finally:
  30. style.reload_library()
  31. def test_invalid_rc_warning_includes_filename(capsys):
  32. SETTINGS = {'foo': 'bar'}
  33. basename = 'basename'
  34. with temp_style(basename, SETTINGS):
  35. # style.reload_library() in temp_style() triggers the warning
  36. pass
  37. assert basename in capsys.readouterr().err
  38. def test_available():
  39. with temp_style('_test_', DUMMY_SETTINGS):
  40. assert '_test_' in style.available
  41. def test_use():
  42. mpl.rcParams[PARAM] = 'gray'
  43. with temp_style('test', DUMMY_SETTINGS):
  44. with style.context('test'):
  45. assert mpl.rcParams[PARAM] == VALUE
  46. def test_use_url(tmpdir):
  47. path = Path(tmpdir, 'file')
  48. path.write_text('axes.facecolor: adeade')
  49. with temp_style('test', DUMMY_SETTINGS):
  50. url = ('file:'
  51. + ('///' if sys.platform == 'win32' else '')
  52. + path.resolve().as_posix())
  53. with style.context(url):
  54. assert mpl.rcParams['axes.facecolor'] == "#adeade"
  55. def test_single_path(tmpdir):
  56. mpl.rcParams[PARAM] = 'gray'
  57. temp_file = f'text.{STYLE_EXTENSION}'
  58. path = Path(tmpdir, temp_file)
  59. path.write_text(f'{PARAM} : {VALUE}')
  60. with style.context(path):
  61. assert mpl.rcParams[PARAM] == VALUE
  62. assert mpl.rcParams[PARAM] == 'gray'
  63. def test_context():
  64. mpl.rcParams[PARAM] = 'gray'
  65. with temp_style('test', DUMMY_SETTINGS):
  66. with style.context('test'):
  67. assert mpl.rcParams[PARAM] == VALUE
  68. # Check that this value is reset after the exiting the context.
  69. assert mpl.rcParams[PARAM] == 'gray'
  70. def test_context_with_dict():
  71. original_value = 'gray'
  72. other_value = 'blue'
  73. mpl.rcParams[PARAM] = original_value
  74. with style.context({PARAM: other_value}):
  75. assert mpl.rcParams[PARAM] == other_value
  76. assert mpl.rcParams[PARAM] == original_value
  77. def test_context_with_dict_after_namedstyle():
  78. # Test dict after style name where dict modifies the same parameter.
  79. original_value = 'gray'
  80. other_value = 'blue'
  81. mpl.rcParams[PARAM] = original_value
  82. with temp_style('test', DUMMY_SETTINGS):
  83. with style.context(['test', {PARAM: other_value}]):
  84. assert mpl.rcParams[PARAM] == other_value
  85. assert mpl.rcParams[PARAM] == original_value
  86. def test_context_with_dict_before_namedstyle():
  87. # Test dict before style name where dict modifies the same parameter.
  88. original_value = 'gray'
  89. other_value = 'blue'
  90. mpl.rcParams[PARAM] = original_value
  91. with temp_style('test', DUMMY_SETTINGS):
  92. with style.context([{PARAM: other_value}, 'test']):
  93. assert mpl.rcParams[PARAM] == VALUE
  94. assert mpl.rcParams[PARAM] == original_value
  95. def test_context_with_union_of_dict_and_namedstyle():
  96. # Test dict after style name where dict modifies the a different parameter.
  97. original_value = 'gray'
  98. other_param = 'text.usetex'
  99. other_value = True
  100. d = {other_param: other_value}
  101. mpl.rcParams[PARAM] = original_value
  102. mpl.rcParams[other_param] = (not other_value)
  103. with temp_style('test', DUMMY_SETTINGS):
  104. with style.context(['test', d]):
  105. assert mpl.rcParams[PARAM] == VALUE
  106. assert mpl.rcParams[other_param] == other_value
  107. assert mpl.rcParams[PARAM] == original_value
  108. assert mpl.rcParams[other_param] == (not other_value)
  109. def test_context_with_badparam():
  110. original_value = 'gray'
  111. other_value = 'blue'
  112. d = OrderedDict([(PARAM, original_value), ('badparam', None)])
  113. with style.context({PARAM: other_value}):
  114. assert mpl.rcParams[PARAM] == other_value
  115. x = style.context([d])
  116. with pytest.raises(KeyError):
  117. with x:
  118. pass
  119. assert mpl.rcParams[PARAM] == other_value
  120. @pytest.mark.parametrize('equiv_styles',
  121. [('mpl20', 'default'),
  122. ('mpl15', 'classic')],
  123. ids=['mpl20', 'mpl15'])
  124. def test_alias(equiv_styles):
  125. rc_dicts = []
  126. for sty in equiv_styles:
  127. with style.context(sty):
  128. rc_dicts.append(mpl.rcParams.copy())
  129. rc_base = rc_dicts[0]
  130. for nm, rc in zip(equiv_styles[1:], rc_dicts[1:]):
  131. assert rc_base == rc
  132. def test_xkcd_no_cm():
  133. assert mpl.rcParams["path.sketch"] is None
  134. plt.xkcd()
  135. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  136. gc.collect()
  137. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  138. def test_xkcd_cm():
  139. assert mpl.rcParams["path.sketch"] is None
  140. with plt.xkcd():
  141. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  142. assert mpl.rcParams["path.sketch"] is None