test_backends_interactive.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. import functools
  2. import importlib
  3. import importlib.util
  4. import inspect
  5. import json
  6. import os
  7. import platform
  8. import signal
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import time
  13. import urllib.request
  14. from PIL import Image
  15. import pytest
  16. import matplotlib as mpl
  17. from matplotlib import _c_internal_utils
  18. from matplotlib.backend_tools import ToolToggleBase
  19. from matplotlib.testing import subprocess_run_helper as _run_helper, is_ci_environment
  20. class _WaitForStringPopen(subprocess.Popen):
  21. """
  22. A Popen that passes flags that allow triggering KeyboardInterrupt.
  23. """
  24. def __init__(self, *args, **kwargs):
  25. if sys.platform == 'win32':
  26. kwargs['creationflags'] = subprocess.CREATE_NEW_CONSOLE
  27. super().__init__(
  28. *args, **kwargs,
  29. # Force Agg so that each test can switch to its desired backend.
  30. env={**os.environ, "MPLBACKEND": "Agg", "SOURCE_DATE_EPOCH": "0"},
  31. stdout=subprocess.PIPE, universal_newlines=True)
  32. def wait_for(self, terminator):
  33. """Read until the terminator is reached."""
  34. buf = ''
  35. while True:
  36. c = self.stdout.read(1)
  37. if not c:
  38. raise RuntimeError(
  39. f'Subprocess died before emitting expected {terminator!r}')
  40. buf += c
  41. if buf.endswith(terminator):
  42. return
  43. # Minimal smoke-testing of the backends for which the dependencies are
  44. # PyPI-installable on CI. They are not available for all tested Python
  45. # versions so we don't fail on missing backends.
  46. @functools.lru_cache
  47. def _get_available_interactive_backends():
  48. _is_linux_and_display_invalid = (sys.platform == "linux" and
  49. not _c_internal_utils.display_is_valid())
  50. _is_linux_and_xdisplay_invalid = (sys.platform == "linux" and
  51. not _c_internal_utils.xdisplay_is_valid())
  52. envs = []
  53. for deps, env in [
  54. *[([qt_api],
  55. {"MPLBACKEND": "qtagg", "QT_API": qt_api})
  56. for qt_api in ["PyQt6", "PySide6", "PyQt5", "PySide2"]],
  57. *[([qt_api, "cairocffi"],
  58. {"MPLBACKEND": "qtcairo", "QT_API": qt_api})
  59. for qt_api in ["PyQt6", "PySide6", "PyQt5", "PySide2"]],
  60. *[(["cairo", "gi"], {"MPLBACKEND": f"gtk{version}{renderer}"})
  61. for version in [3, 4] for renderer in ["agg", "cairo"]],
  62. (["tkinter"], {"MPLBACKEND": "tkagg"}),
  63. (["wx"], {"MPLBACKEND": "wx"}),
  64. (["wx"], {"MPLBACKEND": "wxagg"}),
  65. (["matplotlib.backends._macosx"], {"MPLBACKEND": "macosx"}),
  66. ]:
  67. reason = None
  68. missing = [dep for dep in deps if not importlib.util.find_spec(dep)]
  69. if missing:
  70. reason = "{} cannot be imported".format(", ".join(missing))
  71. elif _is_linux_and_xdisplay_invalid and (
  72. env["MPLBACKEND"] == "tkagg"
  73. # Remove when https://github.com/wxWidgets/Phoenix/pull/2638 is out.
  74. or env["MPLBACKEND"].startswith("wx")):
  75. reason = "$DISPLAY is unset"
  76. elif _is_linux_and_display_invalid:
  77. reason = "$DISPLAY and $WAYLAND_DISPLAY are unset"
  78. elif env["MPLBACKEND"] == 'macosx' and os.environ.get('TF_BUILD'):
  79. reason = "macosx backend fails on Azure"
  80. elif env["MPLBACKEND"].startswith('gtk'):
  81. try:
  82. import gi # type: ignore[import]
  83. except ImportError:
  84. # Though we check that `gi` exists above, it is possible that its
  85. # C-level dependencies are not available, and then it still raises an
  86. # `ImportError`, so guard against that.
  87. available_gtk_versions = []
  88. else:
  89. gi_repo = gi.Repository.get_default()
  90. available_gtk_versions = gi_repo.enumerate_versions('Gtk')
  91. version = env["MPLBACKEND"][3]
  92. if f'{version}.0' not in available_gtk_versions:
  93. reason = "no usable GTK bindings"
  94. marks = []
  95. if reason:
  96. marks.append(pytest.mark.skip(reason=f"Skipping {env} because {reason}"))
  97. elif env["MPLBACKEND"].startswith('wx') and sys.platform == 'darwin':
  98. # ignore on macosx because that's currently broken (github #16849)
  99. marks.append(pytest.mark.xfail(reason='github #16849'))
  100. elif (env['MPLBACKEND'] == 'tkagg' and
  101. ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and
  102. sys.platform == 'darwin' and
  103. sys.version_info[:2] < (3, 11)
  104. ):
  105. marks.append( # https://github.com/actions/setup-python/issues/649
  106. pytest.mark.xfail(reason='Tk version mismatch on Azure macOS CI'))
  107. envs.append(({**env, 'BACKEND_DEPS': ','.join(deps)}, marks))
  108. return envs
  109. def _get_testable_interactive_backends():
  110. # We re-create this because some of the callers below might modify the markers.
  111. return [pytest.param({**env}, marks=[*marks],
  112. id='-'.join(f'{k}={v}' for k, v in env.items()))
  113. for env, marks in _get_available_interactive_backends()]
  114. # Reasonable safe values for slower CI/Remote and local architectures.
  115. _test_timeout = 120 if is_ci_environment() else 20
  116. def _test_toolbar_button_la_mode_icon(fig):
  117. # test a toolbar button icon using an image in LA mode (GH issue 25174)
  118. # create an icon in LA mode
  119. with tempfile.TemporaryDirectory() as tempdir:
  120. img = Image.new("LA", (26, 26))
  121. tmp_img_path = os.path.join(tempdir, "test_la_icon.png")
  122. img.save(tmp_img_path)
  123. class CustomTool(ToolToggleBase):
  124. image = tmp_img_path
  125. description = "" # gtk3 backend does not allow None
  126. toolmanager = fig.canvas.manager.toolmanager
  127. toolbar = fig.canvas.manager.toolbar
  128. toolmanager.add_tool("test", CustomTool)
  129. toolbar.add_tool("test", "group")
  130. # The source of this function gets extracted and run in another process, so it
  131. # must be fully self-contained.
  132. # Using a timer not only allows testing of timers (on other backends), but is
  133. # also necessary on gtk3 and wx, where directly processing a KeyEvent() for "q"
  134. # from draw_event causes breakage as the canvas widget gets deleted too early.
  135. def _test_interactive_impl():
  136. import importlib.util
  137. import io
  138. import json
  139. import sys
  140. import pytest
  141. import matplotlib as mpl
  142. from matplotlib import pyplot as plt
  143. from matplotlib.backend_bases import KeyEvent
  144. mpl.rcParams.update({
  145. "webagg.open_in_browser": False,
  146. "webagg.port_retries": 1,
  147. })
  148. mpl.rcParams.update(json.loads(sys.argv[1]))
  149. backend = plt.rcParams["backend"].lower()
  150. if backend.endswith("agg") and not backend.startswith(("gtk", "web")):
  151. # Force interactive framework setup.
  152. fig = plt.figure()
  153. plt.close(fig)
  154. # Check that we cannot switch to a backend using another interactive
  155. # framework, but can switch to a backend using cairo instead of agg,
  156. # or a non-interactive backend. In the first case, we use tkagg as
  157. # the "other" interactive backend as it is (essentially) guaranteed
  158. # to be present. Moreover, don't test switching away from gtk3 (as
  159. # Gtk.main_level() is not set up at this point yet) and webagg (which
  160. # uses no interactive framework).
  161. if backend != "tkagg":
  162. with pytest.raises(ImportError):
  163. mpl.use("tkagg", force=True)
  164. def check_alt_backend(alt_backend):
  165. mpl.use(alt_backend, force=True)
  166. fig = plt.figure()
  167. assert (type(fig.canvas).__module__ ==
  168. f"matplotlib.backends.backend_{alt_backend}")
  169. plt.close("all")
  170. if importlib.util.find_spec("cairocffi"):
  171. check_alt_backend(backend[:-3] + "cairo")
  172. check_alt_backend("svg")
  173. mpl.use(backend, force=True)
  174. fig, ax = plt.subplots()
  175. assert type(fig.canvas).__module__ == f"matplotlib.backends.backend_{backend}"
  176. assert fig.canvas.manager.get_window_title() == "Figure 1"
  177. if mpl.rcParams["toolbar"] == "toolmanager":
  178. # test toolbar button icon LA mode see GH issue 25174
  179. _test_toolbar_button_la_mode_icon(fig)
  180. ax.plot([0, 1], [2, 3])
  181. if fig.canvas.toolbar: # i.e toolbar2.
  182. fig.canvas.toolbar.draw_rubberband(None, 1., 1, 2., 2)
  183. timer = fig.canvas.new_timer(1.) # Test that floats are cast to int.
  184. timer.add_callback(KeyEvent("key_press_event", fig.canvas, "q")._process)
  185. # Trigger quitting upon draw.
  186. fig.canvas.mpl_connect("draw_event", lambda event: timer.start())
  187. fig.canvas.mpl_connect("close_event", print)
  188. result = io.BytesIO()
  189. fig.savefig(result, format='png')
  190. plt.show()
  191. # Ensure that the window is really closed.
  192. plt.pause(0.5)
  193. # Test that saving works after interactive window is closed, but the figure
  194. # is not deleted.
  195. result_after = io.BytesIO()
  196. fig.savefig(result_after, format='png')
  197. assert result.getvalue() == result_after.getvalue()
  198. @pytest.mark.parametrize("env", _get_testable_interactive_backends())
  199. @pytest.mark.parametrize("toolbar", ["toolbar2", "toolmanager"])
  200. @pytest.mark.flaky(reruns=3)
  201. def test_interactive_backend(env, toolbar):
  202. if env["MPLBACKEND"] == "macosx":
  203. if toolbar == "toolmanager":
  204. pytest.skip("toolmanager is not implemented for macosx.")
  205. if env["MPLBACKEND"] == "wx":
  206. pytest.skip("wx backend is deprecated; tests failed on appveyor")
  207. if env["MPLBACKEND"] == "wxagg" and toolbar == "toolmanager":
  208. pytest.skip("Temporarily deactivated: show() changes figure height "
  209. "and thus fails the test")
  210. try:
  211. proc = _run_helper(
  212. _test_interactive_impl,
  213. json.dumps({"toolbar": toolbar}),
  214. timeout=_test_timeout,
  215. extra_env=env,
  216. )
  217. except subprocess.CalledProcessError as err:
  218. pytest.fail(
  219. "Subprocess failed to test intended behavior\n"
  220. + str(err.stderr))
  221. assert proc.stdout.count("CloseEvent") == 1
  222. def _test_thread_impl():
  223. from concurrent.futures import ThreadPoolExecutor
  224. import matplotlib as mpl
  225. from matplotlib import pyplot as plt
  226. mpl.rcParams.update({
  227. "webagg.open_in_browser": False,
  228. "webagg.port_retries": 1,
  229. })
  230. # Test artist creation and drawing does not crash from thread
  231. # No other guarantees!
  232. fig, ax = plt.subplots()
  233. # plt.pause needed vs plt.show(block=False) at least on toolbar2-tkagg
  234. plt.pause(0.5)
  235. future = ThreadPoolExecutor().submit(ax.plot, [1, 3, 6])
  236. future.result() # Joins the thread; rethrows any exception.
  237. fig.canvas.mpl_connect("close_event", print)
  238. future = ThreadPoolExecutor().submit(fig.canvas.draw)
  239. plt.pause(0.5) # flush_events fails here on at least Tkagg (bpo-41176)
  240. future.result() # Joins the thread; rethrows any exception.
  241. plt.close() # backend is responsible for flushing any events here
  242. if plt.rcParams["backend"].lower().startswith("wx"):
  243. # TODO: debug why WX needs this only on py >= 3.8
  244. fig.canvas.flush_events()
  245. _thread_safe_backends = _get_testable_interactive_backends()
  246. # Known unsafe backends. Remove the xfails if they start to pass!
  247. for param in _thread_safe_backends:
  248. backend = param.values[0]["MPLBACKEND"]
  249. if "cairo" in backend:
  250. # Cairo backends save a cairo_t on the graphics context, and sharing
  251. # these is not threadsafe.
  252. param.marks.append(
  253. pytest.mark.xfail(raises=subprocess.CalledProcessError))
  254. elif backend == "wx":
  255. param.marks.append(
  256. pytest.mark.xfail(raises=subprocess.CalledProcessError))
  257. elif backend == "macosx":
  258. from packaging.version import parse
  259. mac_ver = platform.mac_ver()[0]
  260. # Note, macOS Big Sur is both 11 and 10.16, depending on SDK that
  261. # Python was compiled against.
  262. if mac_ver and parse(mac_ver) < parse('10.16'):
  263. param.marks.append(
  264. pytest.mark.xfail(raises=subprocess.TimeoutExpired,
  265. strict=True))
  266. elif param.values[0].get("QT_API") == "PySide2":
  267. param.marks.append(
  268. pytest.mark.xfail(raises=subprocess.CalledProcessError))
  269. elif backend == "tkagg" and platform.python_implementation() != 'CPython':
  270. param.marks.append(
  271. pytest.mark.xfail(
  272. reason='PyPy does not support Tkinter threading: '
  273. 'https://foss.heptapod.net/pypy/pypy/-/issues/1929',
  274. strict=True))
  275. elif (backend == 'tkagg' and
  276. ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and
  277. sys.platform == 'darwin' and sys.version_info[:2] < (3, 11)):
  278. param.marks.append( # https://github.com/actions/setup-python/issues/649
  279. pytest.mark.xfail('Tk version mismatch on Azure macOS CI'))
  280. @pytest.mark.parametrize("env", _thread_safe_backends)
  281. @pytest.mark.flaky(reruns=3)
  282. def test_interactive_thread_safety(env):
  283. proc = _run_helper(_test_thread_impl, timeout=_test_timeout, extra_env=env)
  284. assert proc.stdout.count("CloseEvent") == 1
  285. def _impl_test_lazy_auto_backend_selection():
  286. import matplotlib
  287. import matplotlib.pyplot as plt
  288. # just importing pyplot should not be enough to trigger resolution
  289. bk = matplotlib.rcParams._get('backend')
  290. assert not isinstance(bk, str)
  291. assert plt._backend_mod is None
  292. # but actually plotting should
  293. plt.plot(5)
  294. assert plt._backend_mod is not None
  295. bk = matplotlib.rcParams._get('backend')
  296. assert isinstance(bk, str)
  297. def test_lazy_auto_backend_selection():
  298. _run_helper(_impl_test_lazy_auto_backend_selection,
  299. timeout=_test_timeout)
  300. def _implqt5agg():
  301. import matplotlib.backends.backend_qt5agg # noqa
  302. import sys
  303. assert 'PyQt6' not in sys.modules
  304. assert 'pyside6' not in sys.modules
  305. assert 'PyQt5' in sys.modules or 'pyside2' in sys.modules
  306. def _implcairo():
  307. import matplotlib.backends.backend_qt5cairo # noqa
  308. import sys
  309. assert 'PyQt6' not in sys.modules
  310. assert 'pyside6' not in sys.modules
  311. assert 'PyQt5' in sys.modules or 'pyside2' in sys.modules
  312. def _implcore():
  313. import matplotlib.backends.backend_qt5 # noqa
  314. import sys
  315. assert 'PyQt6' not in sys.modules
  316. assert 'pyside6' not in sys.modules
  317. assert 'PyQt5' in sys.modules or 'pyside2' in sys.modules
  318. def test_qt5backends_uses_qt5():
  319. qt5_bindings = [
  320. dep for dep in ['PyQt5', 'pyside2']
  321. if importlib.util.find_spec(dep) is not None
  322. ]
  323. qt6_bindings = [
  324. dep for dep in ['PyQt6', 'pyside6']
  325. if importlib.util.find_spec(dep) is not None
  326. ]
  327. if len(qt5_bindings) == 0 or len(qt6_bindings) == 0:
  328. pytest.skip('need both QT6 and QT5 bindings')
  329. _run_helper(_implqt5agg, timeout=_test_timeout)
  330. if importlib.util.find_spec('pycairo') is not None:
  331. _run_helper(_implcairo, timeout=_test_timeout)
  332. _run_helper(_implcore, timeout=_test_timeout)
  333. def _impl_missing():
  334. import sys
  335. # Simulate uninstalled
  336. sys.modules["PyQt6"] = None
  337. sys.modules["PyQt5"] = None
  338. sys.modules["PySide2"] = None
  339. sys.modules["PySide6"] = None
  340. import matplotlib.pyplot as plt
  341. with pytest.raises(ImportError, match="Failed to import any of the following Qt"):
  342. plt.switch_backend("qtagg")
  343. # Specifically ensure that Pyside6/Pyqt6 are not in the error message for qt5agg
  344. with pytest.raises(ImportError, match="^(?:(?!(PySide6|PyQt6)).)*$"):
  345. plt.switch_backend("qt5agg")
  346. def test_qt_missing():
  347. _run_helper(_impl_missing, timeout=_test_timeout)
  348. def _impl_test_cross_Qt_imports():
  349. import importlib
  350. import sys
  351. import warnings
  352. _, host_binding, mpl_binding = sys.argv
  353. # import the mpl binding. This will force us to use that binding
  354. importlib.import_module(f'{mpl_binding}.QtCore')
  355. mpl_binding_qwidgets = importlib.import_module(f'{mpl_binding}.QtWidgets')
  356. import matplotlib.backends.backend_qt
  357. host_qwidgets = importlib.import_module(f'{host_binding}.QtWidgets')
  358. host_app = host_qwidgets.QApplication(["mpl testing"])
  359. warnings.filterwarnings("error", message=r".*Mixing Qt major.*",
  360. category=UserWarning)
  361. matplotlib.backends.backend_qt._create_qApp()
  362. def qt5_and_qt6_pairs():
  363. qt5_bindings = [
  364. dep for dep in ['PyQt5', 'PySide2']
  365. if importlib.util.find_spec(dep) is not None
  366. ]
  367. qt6_bindings = [
  368. dep for dep in ['PyQt6', 'PySide6']
  369. if importlib.util.find_spec(dep) is not None
  370. ]
  371. if len(qt5_bindings) == 0 or len(qt6_bindings) == 0:
  372. yield pytest.param(None, None,
  373. marks=[pytest.mark.skip('need both QT6 and QT5 bindings')])
  374. return
  375. for qt5 in qt5_bindings:
  376. for qt6 in qt6_bindings:
  377. yield from ([qt5, qt6], [qt6, qt5])
  378. @pytest.mark.skipif(
  379. sys.platform == "linux" and not _c_internal_utils.display_is_valid(),
  380. reason="$DISPLAY and $WAYLAND_DISPLAY are unset")
  381. @pytest.mark.parametrize('host, mpl', [*qt5_and_qt6_pairs()])
  382. def test_cross_Qt_imports(host, mpl):
  383. try:
  384. proc = _run_helper(_impl_test_cross_Qt_imports, host, mpl,
  385. timeout=_test_timeout)
  386. except subprocess.CalledProcessError as ex:
  387. # We do try to warn the user they are doing something that we do not
  388. # expect to work, so we're going to ignore if the subprocess crashes or
  389. # is killed, and just check that the warning is printed.
  390. stderr = ex.stderr
  391. else:
  392. stderr = proc.stderr
  393. assert "Mixing Qt major versions may not work as expected." in stderr
  394. @pytest.mark.skipif('TF_BUILD' in os.environ,
  395. reason="this test fails an azure for unknown reasons")
  396. @pytest.mark.skipif(sys.platform == "win32", reason="Cannot send SIGINT on Windows.")
  397. def test_webagg():
  398. pytest.importorskip("tornado")
  399. proc = subprocess.Popen(
  400. [sys.executable, "-c",
  401. inspect.getsource(_test_interactive_impl)
  402. + "\n_test_interactive_impl()", "{}"],
  403. env={**os.environ, "MPLBACKEND": "webagg", "SOURCE_DATE_EPOCH": "0"})
  404. url = f'http://{mpl.rcParams["webagg.address"]}:{mpl.rcParams["webagg.port"]}'
  405. timeout = time.perf_counter() + _test_timeout
  406. try:
  407. while True:
  408. try:
  409. retcode = proc.poll()
  410. # check that the subprocess for the server is not dead
  411. assert retcode is None
  412. conn = urllib.request.urlopen(url)
  413. break
  414. except urllib.error.URLError:
  415. if time.perf_counter() > timeout:
  416. pytest.fail("Failed to connect to the webagg server.")
  417. else:
  418. continue
  419. conn.close()
  420. proc.send_signal(signal.SIGINT)
  421. assert proc.wait(timeout=_test_timeout) == 0
  422. finally:
  423. if proc.poll() is None:
  424. proc.kill()
  425. def _lazy_headless():
  426. import os
  427. import sys
  428. backend, deps = sys.argv[1:]
  429. deps = deps.split(',')
  430. # make it look headless
  431. os.environ.pop('DISPLAY', None)
  432. os.environ.pop('WAYLAND_DISPLAY', None)
  433. for dep in deps:
  434. assert dep not in sys.modules
  435. # we should fast-track to Agg
  436. import matplotlib.pyplot as plt
  437. assert plt.get_backend() == 'agg'
  438. for dep in deps:
  439. assert dep not in sys.modules
  440. # make sure we really have dependencies installed
  441. for dep in deps:
  442. importlib.import_module(dep)
  443. assert dep in sys.modules
  444. # try to switch and make sure we fail with ImportError
  445. try:
  446. plt.switch_backend(backend)
  447. except ImportError:
  448. pass
  449. else:
  450. sys.exit(1)
  451. @pytest.mark.skipif(sys.platform != "linux", reason="this a linux-only test")
  452. @pytest.mark.parametrize("env", _get_testable_interactive_backends())
  453. def test_lazy_linux_headless(env):
  454. proc = _run_helper(
  455. _lazy_headless,
  456. env.pop('MPLBACKEND'), env.pop("BACKEND_DEPS"),
  457. timeout=_test_timeout,
  458. extra_env={**env, 'DISPLAY': '', 'WAYLAND_DISPLAY': ''}
  459. )
  460. def _test_number_of_draws_script():
  461. import matplotlib.pyplot as plt
  462. fig, ax = plt.subplots()
  463. # animated=True tells matplotlib to only draw the artist when we
  464. # explicitly request it
  465. ln, = ax.plot([0, 1], [1, 2], animated=True)
  466. # make sure the window is raised, but the script keeps going
  467. plt.show(block=False)
  468. plt.pause(0.3)
  469. # Connect to draw_event to count the occurrences
  470. fig.canvas.mpl_connect('draw_event', print)
  471. # get copy of entire figure (everything inside fig.bbox)
  472. # sans animated artist
  473. bg = fig.canvas.copy_from_bbox(fig.bbox)
  474. # draw the animated artist, this uses a cached renderer
  475. ax.draw_artist(ln)
  476. # show the result to the screen
  477. fig.canvas.blit(fig.bbox)
  478. for j in range(10):
  479. # reset the background back in the canvas state, screen unchanged
  480. fig.canvas.restore_region(bg)
  481. # Create a **new** artist here, this is poor usage of blitting
  482. # but good for testing to make sure that this doesn't create
  483. # excessive draws
  484. ln, = ax.plot([0, 1], [1, 2])
  485. # render the artist, updating the canvas state, but not the screen
  486. ax.draw_artist(ln)
  487. # copy the image to the GUI state, but screen might not changed yet
  488. fig.canvas.blit(fig.bbox)
  489. # flush any pending GUI events, re-painting the screen if needed
  490. fig.canvas.flush_events()
  491. # Let the event loop process everything before leaving
  492. plt.pause(0.1)
  493. _blit_backends = _get_testable_interactive_backends()
  494. for param in _blit_backends:
  495. backend = param.values[0]["MPLBACKEND"]
  496. if backend == "gtk3cairo":
  497. # copy_from_bbox only works when rendering to an ImageSurface
  498. param.marks.append(
  499. pytest.mark.skip("gtk3cairo does not support blitting"))
  500. elif backend == "gtk4cairo":
  501. # copy_from_bbox only works when rendering to an ImageSurface
  502. param.marks.append(
  503. pytest.mark.skip("gtk4cairo does not support blitting"))
  504. elif backend == "wx":
  505. param.marks.append(
  506. pytest.mark.skip("wx does not support blitting"))
  507. elif (backend == 'tkagg' and
  508. ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and
  509. sys.platform == 'darwin' and
  510. sys.version_info[:2] < (3, 11)
  511. ):
  512. param.marks.append( # https://github.com/actions/setup-python/issues/649
  513. pytest.mark.xfail('Tk version mismatch on Azure macOS CI')
  514. )
  515. @pytest.mark.parametrize("env", _blit_backends)
  516. # subprocesses can struggle to get the display, so rerun a few times
  517. @pytest.mark.flaky(reruns=4)
  518. def test_blitting_events(env):
  519. proc = _run_helper(
  520. _test_number_of_draws_script, timeout=_test_timeout, extra_env=env)
  521. # Count the number of draw_events we got. We could count some initial
  522. # canvas draws (which vary in number by backend), but the critical
  523. # check here is that it isn't 10 draws, which would be called if
  524. # blitting is not properly implemented
  525. ndraws = proc.stdout.count("DrawEvent")
  526. assert 0 < ndraws < 5
  527. def _impl_test_interactive_timers():
  528. # A timer with <1 millisecond gets converted to int and therefore 0
  529. # milliseconds, which the mac framework interprets as singleshot.
  530. # We only want singleshot if we specify that ourselves, otherwise we want
  531. # a repeating timer
  532. from unittest.mock import Mock
  533. import matplotlib.pyplot as plt
  534. pause_time = 0.5
  535. fig = plt.figure()
  536. plt.pause(pause_time)
  537. timer = fig.canvas.new_timer(0.1)
  538. mock = Mock()
  539. timer.add_callback(mock)
  540. timer.start()
  541. plt.pause(pause_time)
  542. timer.stop()
  543. assert mock.call_count > 1
  544. # Now turn it into a single shot timer and verify only one gets triggered
  545. mock.call_count = 0
  546. timer.single_shot = True
  547. timer.start()
  548. plt.pause(pause_time)
  549. assert mock.call_count == 1
  550. # Make sure we can start the timer a second time
  551. timer.start()
  552. plt.pause(pause_time)
  553. assert mock.call_count == 2
  554. plt.close("all")
  555. @pytest.mark.parametrize("env", _get_testable_interactive_backends())
  556. def test_interactive_timers(env):
  557. if env["MPLBACKEND"] == "gtk3cairo" and os.getenv("CI"):
  558. pytest.skip("gtk3cairo timers do not work in remote CI")
  559. if env["MPLBACKEND"] == "wx":
  560. pytest.skip("wx backend is deprecated; tests failed on appveyor")
  561. _run_helper(_impl_test_interactive_timers,
  562. timeout=_test_timeout, extra_env=env)
  563. def _test_sigint_impl(backend, target_name, kwargs):
  564. import sys
  565. import matplotlib.pyplot as plt
  566. import os
  567. import threading
  568. plt.switch_backend(backend)
  569. def interrupter():
  570. if sys.platform == 'win32':
  571. import win32api
  572. win32api.GenerateConsoleCtrlEvent(0, 0)
  573. else:
  574. import signal
  575. os.kill(os.getpid(), signal.SIGINT)
  576. target = getattr(plt, target_name)
  577. timer = threading.Timer(1, interrupter)
  578. fig = plt.figure()
  579. fig.canvas.mpl_connect(
  580. 'draw_event',
  581. lambda *args: print('DRAW', flush=True)
  582. )
  583. fig.canvas.mpl_connect(
  584. 'draw_event',
  585. lambda *args: timer.start()
  586. )
  587. try:
  588. target(**kwargs)
  589. except KeyboardInterrupt:
  590. print('SUCCESS', flush=True)
  591. @pytest.mark.parametrize("env", _get_testable_interactive_backends())
  592. @pytest.mark.parametrize("target, kwargs", [
  593. ('show', {'block': True}),
  594. ('pause', {'interval': 10})
  595. ])
  596. def test_sigint(env, target, kwargs):
  597. backend = env.get("MPLBACKEND")
  598. if not backend.startswith(("qt", "macosx")):
  599. pytest.skip("SIGINT currently only tested on qt and macosx")
  600. proc = _WaitForStringPopen(
  601. [sys.executable, "-c",
  602. inspect.getsource(_test_sigint_impl) +
  603. f"\n_test_sigint_impl({backend!r}, {target!r}, {kwargs!r})"])
  604. try:
  605. proc.wait_for('DRAW')
  606. stdout, _ = proc.communicate(timeout=_test_timeout)
  607. except Exception:
  608. proc.kill()
  609. stdout, _ = proc.communicate()
  610. raise
  611. assert 'SUCCESS' in stdout
  612. def _test_other_signal_before_sigint_impl(backend, target_name, kwargs):
  613. import signal
  614. import matplotlib.pyplot as plt
  615. plt.switch_backend(backend)
  616. target = getattr(plt, target_name)
  617. fig = plt.figure()
  618. fig.canvas.mpl_connect('draw_event', lambda *args: print('DRAW', flush=True))
  619. timer = fig.canvas.new_timer(interval=1)
  620. timer.single_shot = True
  621. timer.add_callback(print, 'SIGUSR1', flush=True)
  622. def custom_signal_handler(signum, frame):
  623. timer.start()
  624. signal.signal(signal.SIGUSR1, custom_signal_handler)
  625. try:
  626. target(**kwargs)
  627. except KeyboardInterrupt:
  628. print('SUCCESS', flush=True)
  629. @pytest.mark.skipif(sys.platform == 'win32',
  630. reason='No other signal available to send on Windows')
  631. @pytest.mark.parametrize("env", _get_testable_interactive_backends())
  632. @pytest.mark.parametrize("target, kwargs", [
  633. ('show', {'block': True}),
  634. ('pause', {'interval': 10})
  635. ])
  636. def test_other_signal_before_sigint(env, target, kwargs, request):
  637. backend = env.get("MPLBACKEND")
  638. if not backend.startswith(("qt", "macosx")):
  639. pytest.skip("SIGINT currently only tested on qt and macosx")
  640. if backend == "macosx":
  641. request.node.add_marker(pytest.mark.xfail(reason="macosx backend is buggy"))
  642. if sys.platform == "darwin" and target == "show":
  643. # We've not previously had these toolkits installed on CI, and so were never
  644. # aware that this was crashing. However, we've had little luck reproducing it
  645. # locally, so mark it xfail for now. For more information, see
  646. # https://github.com/matplotlib/matplotlib/issues/27984
  647. request.node.add_marker(
  648. pytest.mark.xfail(reason="Qt backend is buggy on macOS"))
  649. proc = _WaitForStringPopen(
  650. [sys.executable, "-c",
  651. inspect.getsource(_test_other_signal_before_sigint_impl) +
  652. "\n_test_other_signal_before_sigint_impl("
  653. f"{backend!r}, {target!r}, {kwargs!r})"])
  654. try:
  655. proc.wait_for('DRAW')
  656. os.kill(proc.pid, signal.SIGUSR1)
  657. proc.wait_for('SIGUSR1')
  658. os.kill(proc.pid, signal.SIGINT)
  659. stdout, _ = proc.communicate(timeout=_test_timeout)
  660. except Exception:
  661. proc.kill()
  662. stdout, _ = proc.communicate()
  663. raise
  664. print(stdout)
  665. assert 'SUCCESS' in stdout