conftest.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import pytest
  2. import sys
  3. import matplotlib
  4. from matplotlib import _api
  5. def pytest_configure(config):
  6. # config is initialized here rather than in pytest.ini so that `pytest
  7. # --pyargs matplotlib` (which would not find pytest.ini) works. The only
  8. # entries in pytest.ini set minversion (which is checked earlier),
  9. # testpaths/python_files, as they are required to properly find the tests
  10. for key, value in [
  11. ("markers", "flaky: (Provided by pytest-rerunfailures.)"),
  12. ("markers", "timeout: (Provided by pytest-timeout.)"),
  13. ("markers", "backend: Set alternate Matplotlib backend temporarily."),
  14. ("markers", "baseline_images: Compare output against references."),
  15. ("markers", "pytz: Tests that require pytz to be installed."),
  16. ("filterwarnings", "error"),
  17. ("filterwarnings",
  18. "ignore:.*The py23 module has been deprecated:DeprecationWarning"),
  19. ("filterwarnings",
  20. r"ignore:DynamicImporter.find_spec\(\) not found; "
  21. r"falling back to find_module\(\):ImportWarning"),
  22. ]:
  23. config.addinivalue_line(key, value)
  24. matplotlib.use('agg', force=True)
  25. matplotlib._called_from_pytest = True
  26. matplotlib._init_tests()
  27. def pytest_unconfigure(config):
  28. matplotlib._called_from_pytest = False
  29. @pytest.fixture(autouse=True)
  30. def mpl_test_settings(request):
  31. from matplotlib.testing.decorators import _cleanup_cm
  32. with _cleanup_cm():
  33. backend = None
  34. backend_marker = request.node.get_closest_marker('backend')
  35. prev_backend = matplotlib.get_backend()
  36. if backend_marker is not None:
  37. assert len(backend_marker.args) == 1, \
  38. "Marker 'backend' must specify 1 backend."
  39. backend, = backend_marker.args
  40. skip_on_importerror = backend_marker.kwargs.get(
  41. 'skip_on_importerror', False)
  42. # special case Qt backend importing to avoid conflicts
  43. if backend.lower().startswith('qt5'):
  44. if any(sys.modules.get(k) for k in ('PyQt4', 'PySide')):
  45. pytest.skip('Qt4 binding already imported')
  46. matplotlib.testing.setup()
  47. with _api.suppress_matplotlib_deprecation_warning():
  48. if backend is not None:
  49. # This import must come after setup() so it doesn't load the
  50. # default backend prematurely.
  51. import matplotlib.pyplot as plt
  52. try:
  53. plt.switch_backend(backend)
  54. except ImportError as exc:
  55. # Should only occur for the cairo backend tests, if neither
  56. # pycairo nor cairocffi are installed.
  57. if 'cairo' in backend.lower() or skip_on_importerror:
  58. pytest.skip("Failed to switch to backend "
  59. f"{backend} ({exc}).")
  60. else:
  61. raise
  62. # Default of cleanup and image_comparison too.
  63. matplotlib.style.use(["classic", "_classic_test_patch"])
  64. try:
  65. yield
  66. finally:
  67. if backend is not None:
  68. plt.close("all")
  69. matplotlib.use(prev_backend)
  70. @pytest.fixture
  71. def pd():
  72. """Fixture to import and configure pandas."""
  73. pd = pytest.importorskip('pandas')
  74. try:
  75. from pandas.plotting import (
  76. deregister_matplotlib_converters as deregister)
  77. deregister()
  78. except ImportError:
  79. pass
  80. return pd
  81. @pytest.fixture
  82. def xr():
  83. """Fixture to import xarray."""
  84. xr = pytest.importorskip('xarray')
  85. return xr