test_backends_interactive.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import importlib
  2. import importlib.util
  3. import os
  4. import signal
  5. import subprocess
  6. import sys
  7. import time
  8. import urllib.request
  9. import pytest
  10. import matplotlib as mpl
  11. # Minimal smoke-testing of the backends for which the dependencies are
  12. # PyPI-installable on Travis. They are not available for all tested Python
  13. # versions so we don't fail on missing backends.
  14. def _get_testable_interactive_backends():
  15. backends = []
  16. for deps, backend in [
  17. (["cairo", "gi"], "gtk3agg"),
  18. (["cairo", "gi"], "gtk3cairo"),
  19. (["PyQt5"], "qt5agg"),
  20. (["PyQt5", "cairocffi"], "qt5cairo"),
  21. (["tkinter"], "tkagg"),
  22. (["wx"], "wx"),
  23. (["wx"], "wxagg"),
  24. ]:
  25. reason = None
  26. if not os.environ.get("DISPLAY"):
  27. reason = "No $DISPLAY"
  28. elif any(importlib.util.find_spec(dep) is None for dep in deps):
  29. reason = "Missing dependency"
  30. if reason:
  31. backend = pytest.param(
  32. backend, marks=pytest.mark.skip(reason=reason))
  33. backends.append(backend)
  34. return backends
  35. # Using a timer not only allows testing of timers (on other backends), but is
  36. # also necessary on gtk3 and wx, where a direct call to key_press_event("q")
  37. # from draw_event causes breakage due to the canvas widget being deleted too
  38. # early. Also, gtk3 redefines key_press_event with a different signature, so
  39. # we directly invoke it from the superclass instead.
  40. _test_script = """\
  41. import importlib
  42. import importlib.util
  43. import sys
  44. from unittest import TestCase
  45. import matplotlib as mpl
  46. from matplotlib import pyplot as plt, rcParams
  47. from matplotlib.backend_bases import FigureCanvasBase
  48. rcParams.update({
  49. "webagg.open_in_browser": False,
  50. "webagg.port_retries": 1,
  51. })
  52. backend = plt.rcParams["backend"].lower()
  53. assert_equal = TestCase().assertEqual
  54. assert_raises = TestCase().assertRaises
  55. if backend.endswith("agg") and not backend.startswith(("gtk3", "web")):
  56. # Force interactive framework setup.
  57. plt.figure()
  58. # Check that we cannot switch to a backend using another interactive
  59. # framework, but can switch to a backend using cairo instead of agg, or a
  60. # non-interactive backend. In the first case, we use tkagg as the "other"
  61. # interactive backend as it is (essentially) guaranteed to be present.
  62. # Moreover, don't test switching away from gtk3 (as Gtk.main_level() is
  63. # not set up at this point yet) and webagg (which uses no interactive
  64. # framework).
  65. if backend != "tkagg":
  66. with assert_raises(ImportError):
  67. mpl.use("tkagg", force=True)
  68. def check_alt_backend(alt_backend):
  69. mpl.use(alt_backend, force=True)
  70. fig = plt.figure()
  71. assert_equal(
  72. type(fig.canvas).__module__,
  73. "matplotlib.backends.backend_{}".format(alt_backend))
  74. if importlib.util.find_spec("cairocffi"):
  75. check_alt_backend(backend[:-3] + "cairo")
  76. check_alt_backend("svg")
  77. mpl.use(backend, force=True)
  78. fig, ax = plt.subplots()
  79. assert_equal(
  80. type(fig.canvas).__module__,
  81. "matplotlib.backends.backend_{}".format(backend))
  82. ax.plot([0, 1], [2, 3])
  83. timer = fig.canvas.new_timer(1)
  84. timer.add_callback(FigureCanvasBase.key_press_event, fig.canvas, "q")
  85. # Trigger quitting upon draw.
  86. fig.canvas.mpl_connect("draw_event", lambda event: timer.start())
  87. plt.show()
  88. """
  89. _test_timeout = 10 # Empirically, 1s is not enough on Travis.
  90. @pytest.mark.parametrize("backend", _get_testable_interactive_backends())
  91. @pytest.mark.flaky(reruns=3)
  92. def test_interactive_backend(backend):
  93. proc = subprocess.run([sys.executable, "-c", _test_script],
  94. env={**os.environ, "MPLBACKEND": backend},
  95. timeout=_test_timeout)
  96. if proc.returncode:
  97. pytest.fail("The subprocess returned with non-zero exit status "
  98. f"{proc.returncode}.")
  99. @pytest.mark.skipif('SYSTEM_TEAMFOUNDATIONCOLLECTIONURI' in os.environ,
  100. reason="this test fails an azure for unknown reasons")
  101. @pytest.mark.skipif(os.name == "nt", reason="Cannot send SIGINT on Windows.")
  102. def test_webagg():
  103. pytest.importorskip("tornado")
  104. proc = subprocess.Popen([sys.executable, "-c", _test_script],
  105. env={**os.environ, "MPLBACKEND": "webagg"})
  106. url = "http://{}:{}".format(
  107. mpl.rcParams["webagg.address"], mpl.rcParams["webagg.port"])
  108. timeout = time.perf_counter() + _test_timeout
  109. while True:
  110. try:
  111. retcode = proc.poll()
  112. # check that the subprocess for the server is not dead
  113. assert retcode is None
  114. conn = urllib.request.urlopen(url)
  115. break
  116. except urllib.error.URLError:
  117. if time.perf_counter() > timeout:
  118. pytest.fail("Failed to connect to the webagg server.")
  119. else:
  120. continue
  121. conn.close()
  122. proc.send_signal(signal.SIGINT)
  123. assert proc.wait(timeout=_test_timeout) == 0