Debian Codegraph @

tests/test_zmq_shell.py

raw
1 """Tests for zmq shell / display publisher."""
2
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
5
6 import os
7 import unittest
8 import warnings
9 from queue import Queue
10 from threading import Thread
11 from unittest.mock import MagicMock
12
13 import pytest
14 import zmq
15 from jupyter_client.session import Session
16 from traitlets import Int
17
18 from ipykernel.zmqshell import ( # type:ignore
19 InteractiveShell,
20 KernelMagics,
21 ZMQDisplayPublisher,
22 ZMQInteractiveShell,
23 )
24
25 try:
26 from IPython.core.history import HistoryOutput
27 except ImportError:
28 HistoryOutput = None # type: ignore[assignment,misc]
29
30
31 class NoReturnDisplayHook:
32 """
33 A dummy DisplayHook which allows us to monitor
34 the number of times an object is called, but which
35 does *not* return a message when it is called.
36 """
37
38 call_count = 0
39
40 def __call__(self, obj):
41 self.call_count += 1
42
43
44 class ReturnDisplayHook(NoReturnDisplayHook):
45 """
46 A dummy DisplayHook with the same counting ability
47 as its base class, but which also returns the same
48 message when it is called.
49 """
50
51 def __call__(self, obj):
52 super().__call__(obj)
53 return obj
54
55
56 class CounterSession(Session):
57 """
58 This is a simple subclass to allow us to count
59 the calls made to the session object by the display
60 publisher.
61 """
62
63 send_count = Int(0)
64
65 def send(self, *args, **kwargs):
66 """
67 A trivial override to just augment the existing call
68 with an increment to the send counter.
69 """
70 self.send_count += 1
71 super().send(*args, **kwargs)
72
73
74 class ZMQDisplayPublisherTests(unittest.TestCase):
75 """
76 Tests the ZMQDisplayPublisher in zmqshell.py
77 """
78
79 def setUp(self):
80 self.context = zmq.Context()
81 self.socket = self.context.socket(zmq.PUB)
82 self.session = CounterSession()
83
84 self.disp_pub = ZMQDisplayPublisher(session=self.session, pub_socket=self.socket)
85
86 def tearDown(self):
87 """
88 We need to close the socket in order to proceed with the
89 tests.
90 TODO - There is still an open file handler to '/dev/null',
91 presumably created by zmq.
92 """
93 self.disp_pub.clear_output()
94 self.socket.close()
95 self.context.term()
96
97 def test_display_publisher_creation(self):
98 """
99 Since there's no explicit constructor, here we confirm
100 that keyword args get assigned correctly, and override
101 the defaults.
102 """
103 assert self.disp_pub.session == self.session
104 assert self.disp_pub.pub_socket == self.socket
105
106 def test_thread_local_hooks(self):
107 """
108 Confirms that the thread_local attribute is correctly
109 initialised with an empty list for the display hooks
110 """
111 assert self.disp_pub._hooks == []
112
113 def hook(msg):
114 return msg
115
116 self.disp_pub.register_hook(hook)
117 assert self.disp_pub._hooks == [hook]
118
119 q: Queue = Queue()
120
121 def set_thread_hooks():
122 q.put(self.disp_pub._hooks)
123
124 t = Thread(target=set_thread_hooks)
125 t.start()
126 thread_hooks = q.get(timeout=10)
127 assert thread_hooks == []
128
129 def test_publish(self):
130 """
131 Publish should prepare the message and eventually call
132 `send` by default.
133 """
134 data = dict(a=1)
135 assert self.session.send_count == 0
136 self.disp_pub.publish(data)
137 assert self.session.send_count == 1
138
139 def test_display_hook_halts_send(self):
140 """
141 If a hook is installed, and on calling the object
142 it does *not* return a message, then we assume that
143 the message has been consumed, and should not be
144 processed (`sent`) in the normal manner.
145 """
146 data = dict(a=1)
147 hook = NoReturnDisplayHook()
148
149 self.disp_pub.register_hook(hook)
150 assert hook.call_count == 0
151 assert self.session.send_count == 0
152
153 self.disp_pub.publish(data)
154
155 assert hook.call_count == 1
156 assert self.session.send_count == 0
157
158 def test_display_hook_return_calls_send(self):
159 """
160 If a hook is installed and on calling the object
161 it returns a new message, then we assume that this
162 is just a message transformation, and the message
163 should be sent in the usual manner.
164 """
165 data = dict(a=1)
166 hook = ReturnDisplayHook()
167
168 self.disp_pub.register_hook(hook)
169 assert hook.call_count == 0
170 assert self.session.send_count == 0
171
172 self.disp_pub.publish(data)
173
174 assert hook.call_count == 1
175 assert self.session.send_count == 1
176
177 def test_unregister_hook(self):
178 """
179 Once a hook is unregistered, it should not be called
180 during `publish`.
181 """
182 data = dict(a=1)
183 hook = NoReturnDisplayHook()
184
185 self.disp_pub.register_hook(hook)
186 assert hook.call_count == 0
187 assert self.session.send_count == 0
188
189 self.disp_pub.publish(data)
190
191 assert hook.call_count == 1
192 assert self.session.send_count == 0
193
194 #
195 # After unregistering the `NoReturn` hook, any calls
196 # to publish should *not* got through the DisplayHook,
197 # but should instead hit the usual `session.send` call
198 # at the end.
199 #
200 # As a result, the hook call count should *not* increase,
201 # but the session send count *should* increase.
202 #
203 first = self.disp_pub.unregister_hook(hook)
204 self.disp_pub.publish(data)
205
206 assert bool(first)
207 assert hook.call_count == 1
208 assert self.session.send_count == 1
209
210 #
211 # If a hook is not installed, `unregister_hook`
212 # should return false.
213 #
214 second = self.disp_pub.unregister_hook(hook)
215 assert not bool(second)
216
217 @unittest.skipIf(HistoryOutput is None, "HistoryOutput not available")
218 def test_display_stored_in_history(self):
219 """
220 Test that published display data gets stored in shell history
221 for %notebook magic support, and not stored when disabled.
222 """
223 for enable in [False, True]:
224 # Mock shell with history manager
225 mock_shell = MagicMock()
226 mock_shell.execution_count = 1
227 mock_shell.history_manager.outputs = dict()
228 mock_shell.display_pub._in_post_execute = False
229
230 self.disp_pub.shell = mock_shell
231 self.disp_pub.store_display_history = enable
232
233 data = {"text/plain": "test output"}
234 self.disp_pub.publish(data)
235
236 if enable:
237 # Check that output was stored in history
238 stored_outputs = mock_shell.history_manager.outputs[1]
239 assert len(stored_outputs) == 1
240 assert stored_outputs[0].output_type == "display_data"
241 assert stored_outputs[0].bundle == data
242 else:
243 # Should not store anything in history
244 assert mock_shell.history_manager.outputs == {}
245
246
247 def test_magics(tmp_path):
248 context = zmq.Context()
249 socket = context.socket(zmq.PUB)
250 shell = InteractiveShell()
251 shell.user_ns["hi"] = 1
252 magics = KernelMagics(shell)
253
254 tmp_file = tmp_path / "test.txt"
255 tmp_file.write_text("hi", "utf8")
256 magics.edit(str(tmp_file))
257 payload = shell.payload_manager.read_payload()[0]
258 assert payload["filename"] == str(tmp_file)
259
260 magics.clear([])
261 magics.less(str(tmp_file))
262 if os.name == "posix":
263 magics.man("ls")
264 magics.autosave("10")
265
266 socket.close()
267 context.destroy()
268
269
270 def test_zmq_interactive_shell(kernel):
271 shell = ZMQInteractiveShell()
272
273 with pytest.raises(RuntimeError):
274 shell.enable_gui("tk")
275
276 with warnings.catch_warnings():
277 warnings.simplefilter("ignore", DeprecationWarning)
278 shell.data_pub_class = MagicMock() # type:ignore
279 shell.data_pub
280 shell.kernel = kernel
281 shell.set_next_input("hi")
282 assert shell.get_parent() == {}
283 if os.name == "posix":
284 shell.system_piped("ls")
285 else:
286 shell.system_piped("dir")
287 shell.ask_exit()
288
289
290 if __name__ == "__main__":
291 unittest.main()