test_style.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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(caplog):
  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 (len(caplog.records) == 1
  38. and basename in caplog.records[0].getMessage())
  39. def test_available():
  40. with temp_style('_test_', DUMMY_SETTINGS):
  41. assert '_test_' in style.available
  42. def test_use():
  43. mpl.rcParams[PARAM] = 'gray'
  44. with temp_style('test', DUMMY_SETTINGS):
  45. with style.context('test'):
  46. assert mpl.rcParams[PARAM] == VALUE
  47. def test_use_url(tmpdir):
  48. path = Path(tmpdir, 'file')
  49. path.write_text('axes.facecolor: adeade')
  50. with temp_style('test', DUMMY_SETTINGS):
  51. url = ('file:'
  52. + ('///' if sys.platform == 'win32' else '')
  53. + path.resolve().as_posix())
  54. with style.context(url):
  55. assert mpl.rcParams['axes.facecolor'] == "#adeade"
  56. def test_single_path(tmpdir):
  57. mpl.rcParams[PARAM] = 'gray'
  58. temp_file = f'text.{STYLE_EXTENSION}'
  59. path = Path(tmpdir, temp_file)
  60. path.write_text(f'{PARAM} : {VALUE}')
  61. with style.context(path):
  62. assert mpl.rcParams[PARAM] == VALUE
  63. assert mpl.rcParams[PARAM] == 'gray'
  64. def test_context():
  65. mpl.rcParams[PARAM] = 'gray'
  66. with temp_style('test', DUMMY_SETTINGS):
  67. with style.context('test'):
  68. assert mpl.rcParams[PARAM] == VALUE
  69. # Check that this value is reset after the exiting the context.
  70. assert mpl.rcParams[PARAM] == 'gray'
  71. def test_context_with_dict():
  72. original_value = 'gray'
  73. other_value = 'blue'
  74. mpl.rcParams[PARAM] = original_value
  75. with style.context({PARAM: other_value}):
  76. assert mpl.rcParams[PARAM] == other_value
  77. assert mpl.rcParams[PARAM] == original_value
  78. def test_context_with_dict_after_namedstyle():
  79. # Test dict after style name where dict modifies the same parameter.
  80. original_value = 'gray'
  81. other_value = 'blue'
  82. mpl.rcParams[PARAM] = original_value
  83. with temp_style('test', DUMMY_SETTINGS):
  84. with style.context(['test', {PARAM: other_value}]):
  85. assert mpl.rcParams[PARAM] == other_value
  86. assert mpl.rcParams[PARAM] == original_value
  87. def test_context_with_dict_before_namedstyle():
  88. # Test dict before style name where dict modifies the same parameter.
  89. original_value = 'gray'
  90. other_value = 'blue'
  91. mpl.rcParams[PARAM] = original_value
  92. with temp_style('test', DUMMY_SETTINGS):
  93. with style.context([{PARAM: other_value}, 'test']):
  94. assert mpl.rcParams[PARAM] == VALUE
  95. assert mpl.rcParams[PARAM] == original_value
  96. def test_context_with_union_of_dict_and_namedstyle():
  97. # Test dict after style name where dict modifies the a different parameter.
  98. original_value = 'gray'
  99. other_param = 'text.usetex'
  100. other_value = True
  101. d = {other_param: other_value}
  102. mpl.rcParams[PARAM] = original_value
  103. mpl.rcParams[other_param] = (not other_value)
  104. with temp_style('test', DUMMY_SETTINGS):
  105. with style.context(['test', d]):
  106. assert mpl.rcParams[PARAM] == VALUE
  107. assert mpl.rcParams[other_param] == other_value
  108. assert mpl.rcParams[PARAM] == original_value
  109. assert mpl.rcParams[other_param] == (not other_value)
  110. def test_context_with_badparam():
  111. original_value = 'gray'
  112. other_value = 'blue'
  113. d = OrderedDict([(PARAM, original_value), ('badparam', None)])
  114. with style.context({PARAM: other_value}):
  115. assert mpl.rcParams[PARAM] == other_value
  116. x = style.context([d])
  117. with pytest.raises(KeyError):
  118. with x:
  119. pass
  120. assert mpl.rcParams[PARAM] == other_value
  121. @pytest.mark.parametrize('equiv_styles',
  122. [('mpl20', 'default'),
  123. ('mpl15', 'classic')],
  124. ids=['mpl20', 'mpl15'])
  125. def test_alias(equiv_styles):
  126. rc_dicts = []
  127. for sty in equiv_styles:
  128. with style.context(sty):
  129. rc_dicts.append(mpl.rcParams.copy())
  130. rc_base = rc_dicts[0]
  131. for nm, rc in zip(equiv_styles[1:], rc_dicts[1:]):
  132. assert rc_base == rc
  133. def test_xkcd_no_cm():
  134. assert mpl.rcParams["path.sketch"] is None
  135. plt.xkcd()
  136. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  137. gc.collect()
  138. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  139. def test_xkcd_cm():
  140. assert mpl.rcParams["path.sketch"] is None
  141. with plt.xkcd():
  142. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  143. assert mpl.rcParams["path.sketch"] is None