test_style.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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(tmpdir):
  48. path = Path(tmpdir, '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(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}', encoding='utf-8')
  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. with style.context({PARAM: other_value}):
  114. assert mpl.rcParams[PARAM] == other_value
  115. x = style.context({PARAM: original_value, 'badparam': None})
  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. np.testing.break_cycles()
  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
  143. def test_up_to_date_blacklist():
  144. assert mpl.style.core.STYLE_BLACKLIST <= {*mpl.rcsetup._validators}
  145. def test_style_from_module(tmp_path, monkeypatch):
  146. monkeypatch.syspath_prepend(tmp_path)
  147. monkeypatch.chdir(tmp_path)
  148. pkg_path = tmp_path / "mpl_test_style_pkg"
  149. pkg_path.mkdir()
  150. (pkg_path / "test_style.mplstyle").write_text(
  151. "lines.linewidth: 42", encoding="utf-8")
  152. pkg_path.with_suffix(".mplstyle").write_text(
  153. "lines.linewidth: 84", encoding="utf-8")
  154. mpl.style.use("mpl_test_style_pkg.test_style")
  155. assert mpl.rcParams["lines.linewidth"] == 42
  156. mpl.style.use("mpl_test_style_pkg.mplstyle")
  157. assert mpl.rcParams["lines.linewidth"] == 84
  158. mpl.style.use("./mpl_test_style_pkg.mplstyle")
  159. assert mpl.rcParams["lines.linewidth"] == 84