Debian Codegraph @

tests/test_matplotlib_eventloops.py

raw
1 import os
2 import sys
3 import time
4
5 import pytest
6 from jupyter_client.blocking.client import BlockingKernelClient
7
8 from .test_eventloop import qt_guis_avail
9 from .utils import assemble_output
10
11 # these tests don't seem to work with xvfb yet
12 # these tests seem to be a problem on CI in general
13 pytestmark = pytest.mark.skipif(
14 bool(os.getenv("CI")),
15 reason="tests not working yet reliably on CI",
16 )
17
18 guis = []
19 if not sys.platform.startswith("tk"):
20 guis.append("tk")
21 if qt_guis_avail:
22 guis.append("qt")
23 if sys.platform == "darwin":
24 guis.append("osx")
25
26 backends = {
27 "tk": "tkagg",
28 "qt": "qtagg",
29 "osx": "macosx",
30 }
31
32
33 def execute(
34 kc: BlockingKernelClient,
35 code: str,
36 timeout=120,
37 ):
38 msg_id = kc.execute(code)
39 stdout, stderr = assemble_output(kc.get_iopub_msg, timeout=timeout, parent_msg_id=msg_id)
40 assert not stderr.strip()
41 return stdout.strip(), stderr.strip()
42
43
44 @pytest.mark.parametrize("gui", guis)
45 @pytest.mark.timeout(300)
46 def test_matplotlib_gui(kc, gui):
47 """Make sure matplotlib activates and its eventloop runs while the kernel is also responsive"""
48 pytest.importorskip("matplotlib", reason="this test requires matplotlib")
49 stdout, stderr = execute(kc, f"%matplotlib {gui}")
50 assert not stderr
51 # debug: show output from invoking the matplotlib magic
52 print(stdout)
53 execute(
54 kc,
55 """
56 from concurrent.futures import Future
57 import matplotlib as mpl
58 import matplotlib.pyplot as plt
59 """,
60 )
61 stdout, _ = execute(kc, "print(mpl.get_backend())")
62 assert stdout == backends[gui]
63 execute(
64 kc,
65 """
66 fig, ax = plt.subplots()
67 timer = fig.canvas.new_timer(interval=10)
68 f = Future()
69
70 call_count = 0
71 def add_call():
72 global call_count
73 call_count += 1
74 if not f.done():
75 f.set_result(None)
76
77 timer.add_callback(add_call)
78 timer.start()
79 """,
80 )
81 # wait for the first call (up to 60 seconds)
82 deadline = time.monotonic() + 60
83 done = False
84 while time.monotonic() <= deadline:
85 stdout, _ = execute(kc, "print(f.done())")
86 if stdout.strip() == "True":
87 done = True
88 break
89 if stdout == "False":
90 time.sleep(0.1)
91 else:
92 pytest.fail(f"Unexpected output {stdout}")
93 if not done:
94 pytest.fail("future never finished...")
95
96 time.sleep(0.25)
97 stdout, _ = execute(kc, "print(call_count)")
98 call_count = int(stdout)
99 assert call_count > 0
100 time.sleep(0.25)
101 stdout, _ = execute(kc, "timer.stop()\nprint(call_count)")
102 call_count_2 = int(stdout)
103 assert call_count_2 > call_count
104 stdout, _ = execute(kc, "print(call_count)")
105 call_count_3 = int(stdout)
106 assert call_count_3 <= call_count_2 + 5