Skip to content

Commit 83b0d7f

Browse files
authored
Add more tests (#1034)
1 parent fe8b7b0 commit 83b0d7f

File tree

4 files changed

+114
-5
lines changed

4 files changed

+114
-5
lines changed

ipykernel/iostream.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ def __getattr__(self, attr):
264264
super().__getattr__(attr) # type:ignore[misc]
265265

266266
def __setattr__(self, attr, value):
267-
if attr == "io_thread" or (attr.startswith("__" and attr.endswith("__"))):
267+
if attr == "io_thread" or (attr.startswith("__") and attr.endswith("__")):
268268
super().__setattr__(attr, value)
269269
else:
270270
warnings.warn(

ipykernel/tests/test_io.py

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
"""Test IO capturing functionality"""
22

33
import io
4+
import warnings
45

56
import pytest
67
import zmq
78
from jupyter_client.session import Session
89

9-
from ipykernel.iostream import IOPubThread, OutStream
10+
from ipykernel.iostream import MASTER, BackgroundSocket, IOPubThread, OutStream
1011

1112

1213
def test_io_api():
@@ -51,3 +52,57 @@ def test_io_isatty():
5152

5253
stream = OutStream(session, thread, "stdout", isatty=True)
5354
assert stream.isatty()
55+
56+
57+
def test_io_thread():
58+
ctx = zmq.Context()
59+
pub = ctx.socket(zmq.PUB)
60+
thread = IOPubThread(pub)
61+
thread._setup_pipe_in()
62+
msg = [thread._pipe_uuid, b"a"]
63+
thread._handle_pipe_msg(msg)
64+
ctx1, pipe = thread._setup_pipe_out()
65+
pipe.close()
66+
thread._pipe_in.close()
67+
thread._check_mp_mode = lambda: MASTER
68+
thread._really_send([b"hi"])
69+
ctx1.destroy()
70+
thread.close()
71+
thread.close()
72+
thread._really_send(None)
73+
74+
75+
def test_background_socket():
76+
ctx = zmq.Context()
77+
pub = ctx.socket(zmq.PUB)
78+
thread = IOPubThread(pub)
79+
sock = BackgroundSocket(thread)
80+
assert sock.__class__ == BackgroundSocket
81+
with warnings.catch_warnings():
82+
warnings.simplefilter("ignore", DeprecationWarning)
83+
sock.linger = 101
84+
assert thread.socket.linger == 101
85+
assert sock.io_thread == thread
86+
sock.send(b"hi")
87+
88+
89+
def test_outstream():
90+
session = Session()
91+
ctx = zmq.Context()
92+
pub = ctx.socket(zmq.PUB)
93+
thread = IOPubThread(pub)
94+
thread.start()
95+
96+
with warnings.catch_warnings():
97+
warnings.simplefilter("ignore", DeprecationWarning)
98+
stream = OutStream(session, pub, "stdout")
99+
stream = OutStream(session, thread, "stdout", pipe=object())
100+
101+
stream = OutStream(session, thread, "stdout", isatty=True, echo=io.StringIO())
102+
with pytest.raises(io.UnsupportedOperation):
103+
stream.fileno()
104+
stream._watch_pipe_fd()
105+
stream.flush()
106+
stream.write("hi")
107+
stream.writelines(["ab", "cd"])
108+
assert stream.writable

ipykernel/tests/test_zmq_shell.py

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,24 @@
33
# Copyright (c) IPython Development Team.
44
# Distributed under the terms of the Modified BSD License.
55

6+
import os
67
import unittest
8+
import warnings
79
from queue import Queue
810
from threading import Thread
11+
from unittest.mock import MagicMock
912

13+
import pytest
1014
import zmq
1115
from jupyter_client.session import Session
1216
from traitlets import Int
1317

14-
from ipykernel.zmqshell import ZMQDisplayPublisher
18+
from ipykernel.zmqshell import (
19+
InteractiveShell,
20+
KernelMagics,
21+
ZMQDisplayPublisher,
22+
ZMQInteractiveShell,
23+
)
1524

1625

1726
class NoReturnDisplayHook:
@@ -201,5 +210,49 @@ def test_unregister_hook(self):
201210
self.assertFalse(second)
202211

203212

213+
def test_magics(tmp_path):
214+
context = zmq.Context()
215+
socket = context.socket(zmq.PUB)
216+
shell = InteractiveShell()
217+
shell.user_ns["hi"] = 1
218+
magics = KernelMagics(shell)
219+
220+
def find_edit_target(*args):
221+
return str(tmp_path), 0, 1
222+
223+
tmp_file = tmp_path / "test.txt"
224+
tmp_file.write_text("hi", "utf8")
225+
magics._find_edit_target = find_edit_target
226+
magics.edit("hi")
227+
magics.clear([])
228+
magics.less(str(tmp_file))
229+
if os.name == "posix":
230+
magics.man("ls")
231+
magics.autosave("10")
232+
233+
socket.close()
234+
context.destroy()
235+
236+
237+
def test_zmq_interactive_shell(kernel):
238+
shell = ZMQInteractiveShell()
239+
240+
with pytest.raises(RuntimeError):
241+
shell.enable_gui("tk")
242+
243+
with warnings.catch_warnings():
244+
warnings.simplefilter("ignore", DeprecationWarning)
245+
shell.data_pub_class = MagicMock()
246+
shell.data_pub
247+
shell.kernel = kernel
248+
shell.set_next_input("hi")
249+
assert shell.get_parent() is None
250+
if os.name == "posix":
251+
shell.system_piped("ls")
252+
else:
253+
shell.system_piped("dir")
254+
shell.ask_exit()
255+
256+
204257
if __name__ == "__main__":
205258
unittest.main()

ipykernel/zmqshell.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ def edit(self, parameter_s="", last_call=None):
285285
opts, args = self.parse_options(parameter_s, "prn:")
286286

287287
try:
288-
filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
288+
filename, lineno, _ = self._find_edit_target(self.shell, args, opts, last_call)
289289
except MacroToEdit:
290290
# TODO: Implement macro editing over 2 processes.
291291
print("Macro editing not yet implemented in 2-process model.")
@@ -326,7 +326,8 @@ def less(self, arg_s):
326326
if arg_s.endswith(".py"):
327327
cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
328328
else:
329-
cont = open(arg_s).read()
329+
with open(arg_s) as fid:
330+
cont = fid.read()
330331
page.page(cont)
331332

332333
more = line_magic("more")(less)

0 commit comments

Comments
 (0)