|
| 1 | +import os |
| 2 | +import shutil |
| 3 | +import tempfile |
| 4 | +from contextlib import contextmanager |
| 5 | + |
| 6 | +import matplotlib as mpl |
| 7 | +from matplotlib import style |
| 8 | +from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION |
| 9 | + |
| 10 | + |
| 11 | +PARAM = 'image.cmap' |
| 12 | +VALUE = 'pink' |
| 13 | +DUMMY_SETTINGS = {PARAM: VALUE} |
| 14 | + |
| 15 | + |
| 16 | +@contextmanager |
| 17 | +def temp_style(style_name, settings=None): |
| 18 | + """Context manager to create a style sheet in a temporary directory.""" |
| 19 | + settings = DUMMY_SETTINGS |
| 20 | + temp_file = '%s.%s' % (style_name, STYLE_EXTENSION) |
| 21 | + |
| 22 | + # Write style settings to file in the temp directory. |
| 23 | + tempdir = tempfile.mkdtemp() |
| 24 | + with open(os.path.join(tempdir, temp_file), 'w') as f: |
| 25 | + for k, v in settings.iteritems(): |
| 26 | + f.write('%s: %s' % (k, v)) |
| 27 | + |
| 28 | + # Add temp directory to style path and reload so we can access this style. |
| 29 | + USER_LIBRARY_PATHS.append(tempdir) |
| 30 | + style.reload_library() |
| 31 | + |
| 32 | + try: |
| 33 | + yield |
| 34 | + finally: |
| 35 | + shutil.rmtree(tempdir) |
| 36 | + style.reload_library() |
| 37 | + |
| 38 | + |
| 39 | +def test_available(): |
| 40 | + with temp_style('_test_', DUMMY_SETTINGS): |
| 41 | + assert '_test_' in style.available |
| 42 | + |
| 43 | + |
| 44 | +def test_use(): |
| 45 | + mpl.rcParams[PARAM] = 'gray' |
| 46 | + with temp_style('test', DUMMY_SETTINGS): |
| 47 | + with style.context('test'): |
| 48 | + assert mpl.rcParams[PARAM] == VALUE |
| 49 | + |
| 50 | + |
| 51 | +def test_use_url(): |
| 52 | + with temp_style('test', DUMMY_SETTINGS): |
| 53 | + with style.context('https://gist.github.com/adrn/6590261/raw'): |
| 54 | + assert mpl.rcParams['axes.facecolor'] == "#adeade" |
| 55 | + |
| 56 | + |
| 57 | +def test_context(): |
| 58 | + mpl.rcParams[PARAM] = 'gray' |
| 59 | + with temp_style('test', DUMMY_SETTINGS): |
| 60 | + with style.context('test'): |
| 61 | + assert mpl.rcParams[PARAM] == VALUE |
| 62 | + # Check that this value is reset after the exiting the context. |
| 63 | + assert mpl.rcParams[PARAM] == 'gray' |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + from numpy import testing |
| 68 | + testing.run_module_suite() |
0 commit comments