def test_Bug_2543(): # Test that it possible to add all values to itself / deepcopy # This was not possible because validate_bool_maybe_none did not # accept None as an argument. # https://github.com/matplotlib/matplotlib/issues/2543 # We filter warnings at this stage since a number of them are raised # for deprecated rcparams as they should. We don't want these in the # printed in the test suite. with cbook._suppress_matplotlib_deprecation_warning(): with mpl.rc_context(): _copy = mpl.rcParams.copy() for key in _copy: mpl.rcParams[key] = _copy[key] with mpl.rc_context(): copy.deepcopy(mpl.rcParams) # real test is that this does not raise assert validate_bool_maybe_none(None) is None assert validate_bool_maybe_none("none") is None with pytest.raises(ValueError): validate_bool_maybe_none("blah") with pytest.raises(ValueError): validate_bool(None) with pytest.raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True
def use(style): """ Use Matplotlib style settings from a style specification. The style name of 'default' is reserved for reverting back to the default style settings. .. note:: This updates the `.rcParams` with the settings from the style. `.rcParams` not defined in the style are kept. Parameters ---------- style : str, dict, Path or list A style specification. Valid options are: +------+-------------------------------------------------------------+ | str | The name of a style or a path/URL to a style file. For a | | | list of available style names, see `style.available`. | +------+-------------------------------------------------------------+ | dict | Dictionary with valid key/value pairs for | | | `matplotlib.rcParams`. | +------+-------------------------------------------------------------+ | Path | A path-like object which is a path to a style file. | +------+-------------------------------------------------------------+ | list | A list of style specifiers (str, Path or dict) applied from | | | first to last in the list. | +------+-------------------------------------------------------------+ """ style_alias = {'mpl20': 'default', 'mpl15': 'classic'} if isinstance(style, (str, Path)) or hasattr(style, 'keys'): # If name is a single str, Path or dict, make it a single element list. styles = [style] else: styles = style styles = (style_alias.get(s, s) if isinstance(s, str) else s for s in styles) for style in styles: if not isinstance(style, (str, Path)): _apply_style(style) elif style == 'default': # Deprecation warnings were already handled when creating # rcParamsDefault, no need to reemit them here. with cbook._suppress_matplotlib_deprecation_warning(): _apply_style(rcParamsDefault, warn=False) elif style in library: _apply_style(library[style]) else: try: rc = rc_params_from_file(style, use_default_template=False) _apply_style(rc) except IOError as err: raise IOError( "{!r} not found in the style library and input is not a " "valid URL or path; see `style.available` for list of " "available styles".format(style)) from err
def test_ParasiteAxesAuxTrans(parasite_cls): # Remove this line when this test image is regenerated. plt.rcParams['pcolormesh.snap'] = False data = np.ones((6, 6)) data[2, 2] = 2 data[0, :] = 0 data[-2, :] = 0 data[:, 0] = 0 data[:, -2] = 0 x = np.arange(6) y = np.arange(6) xx, yy = np.meshgrid(x, y) funcnames = ['pcolor', 'pcolormesh', 'contourf'] fig = plt.figure() for i, name in enumerate(funcnames): ax1 = SubplotHost(fig, 1, 3, i + 1) fig.add_subplot(ax1) with cbook._suppress_matplotlib_deprecation_warning(): ax2 = parasite_cls(ax1, IdentityTransform()) ax1.parasites.append(ax2) if name.startswith('pcolor'): getattr(ax2, name)(xx, yy, data[:-1, :-1]) else: getattr(ax2, name)(xx, yy, data) ax1.set_xlim((0, 5)) ax1.set_ylim((0, 5)) ax2.contour(xx, yy, data, colors='k')
def test_Bug_2543(): # Test that it possible to add all values to itself / deepcopy # This was not possible because validate_bool_maybe_none did not # accept None as an argument. # https://github.com/matplotlib/matplotlib/issues/2543 # We filter warnings at this stage since a number of them are raised # for deprecated rcparams as they should. We don't want these in the # printed in the test suite. with cbook._suppress_matplotlib_deprecation_warning(): with mpl.rc_context(): _copy = mpl.rcParams.copy() for key in _copy: mpl.rcParams[key] = _copy[key] with mpl.rc_context(): copy.deepcopy(mpl.rcParams) # real test is that this does not raise assert validate_bool_maybe_none(None) is None assert validate_bool_maybe_none("none") is None with pytest.raises(ValueError): validate_bool_maybe_none("blah") with pytest.raises(ValueError): validate_bool(None) with pytest.raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True
def _matplotlib_change_style(params): from matplotlib.cbook import _suppress_matplotlib_deprecation_warning with _suppress_matplotlib_deprecation_warning(): current = matplotlib.rcParams.copy() params = params.copy() if 'backend' in params: params.pop('backend') matplotlib.rcParams.update(params) return current
def use(style): """Use matplotlib style settings from a style specification. The style name of 'default' is reserved for reverting back to the default style settings. Parameters ---------- style : str, dict, or list A style specification. Valid options are: +------+-------------------------------------------------------------+ | str | The name of a style or a path/URL to a style file. For a | | | list of available style names, see `style.available`. | +------+-------------------------------------------------------------+ | dict | Dictionary with valid key/value pairs for | | | `matplotlib.rcParams`. | +------+-------------------------------------------------------------+ | list | A list of style specifiers (str or dict) applied from first | | | to last in the list. | +------+-------------------------------------------------------------+ """ style_alias = {'mpl20': 'default', 'mpl15': 'classic'} if isinstance(style, str) or hasattr(style, 'keys'): # If name is a single str or dict, make it a single element list. styles = [style] else: styles = style styles = (style_alias.get(s, s) if isinstance(s, str) else s for s in styles) for style in styles: if not isinstance(style, str): _apply_style(style) elif style == 'default': # Deprecation warnings were already handled when creating # rcParamsDefault, no need to reemit them here. with cbook._suppress_matplotlib_deprecation_warning(): _apply_style(rcParamsDefault, warn=False) elif style in library: _apply_style(library[style]) else: try: rc = rc_params_from_file(style, use_default_template=False) _apply_style(rc) except IOError: raise IOError( "{!r} not found in the style library and input is not a " "valid URL or path; see `style.available` for list of " "available styles".format(style))
def mpl_test_settings(request): from matplotlib.testing.decorators import _cleanup_cm with _cleanup_cm(): backend = None backend_marker = request.node.get_closest_marker('backend') if backend_marker is not None: assert len(backend_marker.args) == 1, \ "Marker 'backend' must specify 1 backend." backend, = backend_marker.args skip_on_importerror = backend_marker.kwargs.get( 'skip_on_importerror', False) prev_backend = matplotlib.get_backend() # Default of cleanup and image_comparison too. style = ["classic", "_classic_test_patch"] style_marker = request.node.get_closest_marker('style') if style_marker is not None: assert len(style_marker.args) == 1, \ "Marker 'style' must specify 1 style." style, = style_marker.args matplotlib.testing.setup() if backend is not None: # This import must come after setup() so it doesn't load the # default backend prematurely. import matplotlib.pyplot as plt try: plt.switch_backend(backend) except ImportError as exc: # Should only occur for the cairo backend tests, if neither # pycairo nor cairocffi are installed. if 'cairo' in backend.lower() or skip_on_importerror: pytest.skip("Failed to switch to backend {} ({})." .format(backend, exc)) else: raise with cbook._suppress_matplotlib_deprecation_warning(): matplotlib.style.use(style) try: yield finally: if backend is not None: plt.switch_backend(prev_backend)
def mpl_test_settings(request): from matplotlib.testing.decorators import _cleanup_cm with _cleanup_cm(): backend = None backend_marker = request.node.get_closest_marker('backend') if backend_marker is not None: assert len(backend_marker.args) == 1, \ "Marker 'backend' must specify 1 backend." backend, = backend_marker.args prev_backend = matplotlib.get_backend() style = '_classic_test' # Default of cleanup and image_comparison too. style_marker = request.node.get_closest_marker('style') if style_marker is not None: assert len(style_marker.args) == 1, \ "Marker 'style' must specify 1 style." style, = style_marker.args matplotlib.testing.setup() if backend is not None: # This import must come after setup() so it doesn't load the # default backend prematurely. import matplotlib.pyplot as plt try: plt.switch_backend(backend) except ImportError as exc: # Should only occur for the cairo backend tests, if neither # pycairo nor cairocffi are installed. if 'cairo' in backend.lower(): pytest.skip("Failed to switch to backend {} ({})." .format(backend, exc)) else: raise with cbook._suppress_matplotlib_deprecation_warning(): matplotlib.style.use(style) try: yield finally: if backend is not None: plt.switch_backend(prev_backend)
def setup(): # The baseline images are created in this locale, so we should use # it during all of the tests. try: locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') except locale.Error: try: locale.setlocale(locale.LC_ALL, 'English_United States.1252') except locale.Error: _log.warning("Could not set locale to English/United States. " "Some date-related tests may fail.") mpl.use('Agg') with cbook._suppress_matplotlib_deprecation_warning(): mpl.rcdefaults() # Start with all defaults # These settings *must* be hardcoded for running the comparison tests and # are not necessarily the default values as specified in rcsetup.py. set_font_settings_for_testing() set_reproducibility_for_testing()
def setup(): # The baseline images are created in this locale, so we should use # it during all of the tests. try: locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') except locale.Error: try: locale.setlocale(locale.LC_ALL, 'English_United States.1252') except locale.Error: _log.warning( "Could not set locale to English/United States. " "Some date-related tests may fail.") mpl.use('Agg', force=True, warn=False) # use Agg backend for these tests with cbook._suppress_matplotlib_deprecation_warning(): mpl.rcdefaults() # Start with all defaults # These settings *must* be hardcoded for running the comparison tests and # are not necessarily the default values as specified in rcsetup.py. set_font_settings_for_testing() set_reproducibility_for_testing()
def mpl_test_settings(request): from matplotlib.testing.decorators import _cleanup_cm with _cleanup_cm(): backend = None backend_marker = request.node.get_closest_marker('backend') if backend_marker is not None: assert len(backend_marker.args) == 1, \ "Marker 'backend' must specify 1 backend." backend, = backend_marker.args skip_on_importerror = backend_marker.kwargs.get( 'skip_on_importerror', False) prev_backend = matplotlib.get_backend() # special case Qt backend importing to avoid conflicts if backend.lower().startswith('qt4'): if any(k in sys.modules for k in ('PyQt5', 'PySide2')): pytest.skip('Qt5 binding already imported') try: import PyQt4 # RuntimeError if PyQt5 already imported. except (ImportError, RuntimeError): try: import PySide except ImportError: pytest.skip("Failed to import a Qt4 binding.") elif backend.lower().startswith('qt5'): if any(k in sys.modules for k in ('PyQt4', 'PySide')): pytest.skip('Qt4 binding already imported') try: import PyQt5 # RuntimeError if PyQt4 already imported. except (ImportError, RuntimeError): try: import PySide2 except ImportError: pytest.skip("Failed to import a Qt5 binding.") # Default of cleanup and image_comparison too. style = ["classic", "_classic_test_patch"] style_marker = request.node.get_closest_marker('style') if style_marker is not None: assert len(style_marker.args) == 1, \ "Marker 'style' must specify 1 style." style, = style_marker.args matplotlib.testing.setup() with cbook._suppress_matplotlib_deprecation_warning(): if backend is not None: # This import must come after setup() so it doesn't load the # default backend prematurely. import matplotlib.pyplot as plt try: plt.switch_backend(backend) except ImportError as exc: # Should only occur for the cairo backend tests, if neither # pycairo nor cairocffi are installed. if 'cairo' in backend.lower() or skip_on_importerror: pytest.skip( "Failed to switch to backend {} ({}).".format( backend, exc)) else: raise matplotlib.style.use(style) try: yield finally: if backend is not None: plt.switch_backend(prev_backend)
def test_normalize_kwargs_pass(inp, expected, kwargs_to_norm): with cbook._suppress_matplotlib_deprecation_warning(): # No other warning should be emitted. assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm)
def test_normalize_kwargs_fail(inp, kwargs_to_norm): with pytest.raises(TypeError), \ cbook._suppress_matplotlib_deprecation_warning(): cbook.normalize_kwargs(inp, **kwargs_to_norm)
def test_formatting(self, x, label): with cbook._suppress_matplotlib_deprecation_warning(): formatter = mticker.IndexFormatter(['label0', 'label1', 'label2']) assert formatter(x) == label
self.width = width self.stretch = stretch self.stretch_order = stretch_order self.shrink = shrink self.shrink_order = shrink_order def copy(self): return GlueSpec(self.width, self.stretch, self.stretch_order, self.shrink, self.shrink_order) @classmethod def factory(cls, glue_type): return cls._types[glue_type] with cbook._suppress_matplotlib_deprecation_warning(): GlueSpec._types = { k: GlueSpec(**v._asdict()) for k, v in _mathtext._GlueSpec._named.items() } @cbook.deprecated("3.4") def ship(ox, oy, box): _mathtext.ship(ox, oy, box) ############################################################################## # MAIN
def test_mathtext_to_png(tmpdir): with cbook._suppress_matplotlib_deprecation_warning(): mt = mathtext.MathTextParser('bitmap') mt.to_png(str(tmpdir.join('example.png')), '$x^2$') mt.to_png(io.BytesIO(), '$x^2$')
def test_normalize_kwargs_pass(inp, expected, kwargs_to_norm, recwarn): with cbook._suppress_matplotlib_deprecation_warning(): assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm) assert len(recwarn) == 0