test_style.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. from contextlib import contextmanager
  2. from pathlib import Path
  3. from tempfile import TemporaryDirectory
  4. import sys
  5. import numpy as np
  6. import pytest
  7. import matplotlib as mpl
  8. from matplotlib import pyplot as plt, style
  9. from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION
  10. PARAM = 'image.cmap'
  11. VALUE = 'pink'
  12. DUMMY_SETTINGS = {PARAM: VALUE}
  13. @contextmanager
  14. def temp_style(style_name, settings=None):
  15. """Context manager to create a style sheet in a temporary directory."""
  16. if not settings:
  17. settings = DUMMY_SETTINGS
  18. temp_file = f'{style_name}.{STYLE_EXTENSION}'
  19. try:
  20. with TemporaryDirectory() as tmpdir:
  21. # Write style settings to file in the tmpdir.
  22. Path(tmpdir, temp_file).write_text(
  23. "\n".join(f"{k}: {v}" for k, v in settings.items()),
  24. encoding="utf-8")
  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(tmp_path):
  48. path = tmp_path / 'file'
  49. path.write_text('axes.facecolor: adeade', encoding='utf-8')
  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(tmp_path):
  57. mpl.rcParams[PARAM] = 'gray'
  58. path = tmp_path / f'text.{STYLE_EXTENSION}'
  59. path.write_text(f'{PARAM} : {VALUE}', encoding='utf-8')
  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. with style.context({PARAM: other_value}):
  113. assert mpl.rcParams[PARAM] == other_value
  114. x = style.context({PARAM: original_value, 'badparam': None})
  115. with pytest.raises(KeyError):
  116. with x:
  117. pass
  118. assert mpl.rcParams[PARAM] == other_value
  119. @pytest.mark.parametrize('equiv_styles',
  120. [('mpl20', 'default'),
  121. ('mpl15', 'classic')],
  122. ids=['mpl20', 'mpl15'])
  123. def test_alias(equiv_styles):
  124. rc_dicts = []
  125. for sty in equiv_styles:
  126. with style.context(sty):
  127. rc_dicts.append(mpl.rcParams.copy())
  128. rc_base = rc_dicts[0]
  129. for nm, rc in zip(equiv_styles[1:], rc_dicts[1:]):
  130. assert rc_base == rc
  131. def test_xkcd_no_cm():
  132. assert mpl.rcParams["path.sketch"] is None
  133. plt.xkcd()
  134. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  135. np.testing.break_cycles()
  136. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  137. def test_xkcd_cm():
  138. assert mpl.rcParams["path.sketch"] is None
  139. with plt.xkcd():
  140. assert mpl.rcParams["path.sketch"] == (1, 100, 2)
  141. assert mpl.rcParams["path.sketch"] is None
  142. def test_up_to_date_blacklist():
  143. assert mpl.style.core.STYLE_BLACKLIST <= {*mpl.rcsetup._validators}
  144. def test_style_from_module(tmp_path, monkeypatch):
  145. monkeypatch.syspath_prepend(tmp_path)
  146. monkeypatch.chdir(tmp_path)
  147. pkg_path = tmp_path / "mpl_test_style_pkg"
  148. pkg_path.mkdir()
  149. (pkg_path / "test_style.mplstyle").write_text(
  150. "lines.linewidth: 42", encoding="utf-8")
  151. pkg_path.with_suffix(".mplstyle").write_text(
  152. "lines.linewidth: 84", encoding="utf-8")
  153. mpl.style.use("mpl_test_style_pkg.test_style")
  154. assert mpl.rcParams["lines.linewidth"] == 42
  155. mpl.style.use("mpl_test_style_pkg.mplstyle")
  156. assert mpl.rcParams["lines.linewidth"] == 84
  157. mpl.style.use("./mpl_test_style_pkg.mplstyle")
  158. assert mpl.rcParams["lines.linewidth"] == 84