##// END OF EJS Templates
update embed_kernel test to Client API
MinRK -
Show More
@@ -1,193 +1,193 b''
1 """test IPython.embed_kernel()"""
1 """test IPython.embed_kernel()"""
2
2
3 #-------------------------------------------------------------------------------
3 #-------------------------------------------------------------------------------
4 # Copyright (C) 2012 The IPython Development Team
4 # Copyright (C) 2012 The IPython Development Team
5 #
5 #
6 # Distributed under the terms of the BSD License. The full license is in
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #-------------------------------------------------------------------------------
8 #-------------------------------------------------------------------------------
9
9
10 #-------------------------------------------------------------------------------
10 #-------------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-------------------------------------------------------------------------------
12 #-------------------------------------------------------------------------------
13
13
14 import os
14 import os
15 import shutil
15 import shutil
16 import sys
16 import sys
17 import tempfile
17 import tempfile
18 import time
18 import time
19
19
20 from contextlib import contextmanager
20 from contextlib import contextmanager
21 from subprocess import Popen, PIPE
21 from subprocess import Popen, PIPE
22
22
23 import nose.tools as nt
23 import nose.tools as nt
24
24
25 from IPython.kernel.blocking import BlockingKernelManager
25 from IPython.kernel import BlockingKernelClient
26 from IPython.utils import path, py3compat
26 from IPython.utils import path, py3compat
27
27
28 #-------------------------------------------------------------------------------
28 #-------------------------------------------------------------------------------
29 # Tests
29 # Tests
30 #-------------------------------------------------------------------------------
30 #-------------------------------------------------------------------------------
31
31
32 def setup():
32 def setup():
33 """setup temporary IPYTHONDIR for tests"""
33 """setup temporary IPYTHONDIR for tests"""
34 global IPYTHONDIR
34 global IPYTHONDIR
35 global env
35 global env
36 global save_get_ipython_dir
36 global save_get_ipython_dir
37
37
38 IPYTHONDIR = tempfile.mkdtemp()
38 IPYTHONDIR = tempfile.mkdtemp()
39
39
40 env = os.environ.copy()
40 env = os.environ.copy()
41 env["IPYTHONDIR"] = IPYTHONDIR
41 env["IPYTHONDIR"] = IPYTHONDIR
42
42
43 save_get_ipython_dir = path.get_ipython_dir
43 save_get_ipython_dir = path.get_ipython_dir
44 path.get_ipython_dir = lambda : IPYTHONDIR
44 path.get_ipython_dir = lambda : IPYTHONDIR
45
45
46
46
47 def teardown():
47 def teardown():
48 path.get_ipython_dir = save_get_ipython_dir
48 path.get_ipython_dir = save_get_ipython_dir
49
49
50 try:
50 try:
51 shutil.rmtree(IPYTHONDIR)
51 shutil.rmtree(IPYTHONDIR)
52 except (OSError, IOError):
52 except (OSError, IOError):
53 # no such file
53 # no such file
54 pass
54 pass
55
55
56
56
57 @contextmanager
57 @contextmanager
58 def setup_kernel(cmd):
58 def setup_kernel(cmd):
59 """start an embedded kernel in a subprocess, and wait for it to be ready
59 """start an embedded kernel in a subprocess, and wait for it to be ready
60
60
61 Returns
61 Returns
62 -------
62 -------
63 kernel_manager: connected KernelManager instance
63 kernel_manager: connected KernelManager instance
64 """
64 """
65 kernel = Popen([sys.executable, '-c', cmd], stdout=PIPE, stderr=PIPE, env=env)
65 kernel = Popen([sys.executable, '-c', cmd], stdout=PIPE, stderr=PIPE, env=env)
66 connection_file = os.path.join(IPYTHONDIR,
66 connection_file = os.path.join(IPYTHONDIR,
67 'profile_default',
67 'profile_default',
68 'security',
68 'security',
69 'kernel-%i.json' % kernel.pid
69 'kernel-%i.json' % kernel.pid
70 )
70 )
71 # wait for connection file to exist, timeout after 5s
71 # wait for connection file to exist, timeout after 5s
72 tic = time.time()
72 tic = time.time()
73 while not os.path.exists(connection_file) and kernel.poll() is None and time.time() < tic + 10:
73 while not os.path.exists(connection_file) and kernel.poll() is None and time.time() < tic + 10:
74 time.sleep(0.1)
74 time.sleep(0.1)
75
75
76 if kernel.poll() is not None:
76 if kernel.poll() is not None:
77 o,e = kernel.communicate()
77 o,e = kernel.communicate()
78 e = py3compat.cast_unicode(e)
78 e = py3compat.cast_unicode(e)
79 raise IOError("Kernel failed to start:\n%s" % e)
79 raise IOError("Kernel failed to start:\n%s" % e)
80
80
81 if not os.path.exists(connection_file):
81 if not os.path.exists(connection_file):
82 if kernel.poll() is None:
82 if kernel.poll() is None:
83 kernel.terminate()
83 kernel.terminate()
84 raise IOError("Connection file %r never arrived" % connection_file)
84 raise IOError("Connection file %r never arrived" % connection_file)
85
85
86 km = BlockingKernelManager(connection_file=connection_file)
86 client = BlockingKernelClient(connection_file=connection_file)
87 km.load_connection_file()
87 client.load_connection_file()
88 km.start_channels()
88 client.start_channels()
89
89
90 try:
90 try:
91 yield km
91 yield client
92 finally:
92 finally:
93 km.stop_channels()
93 client.stop_channels()
94 kernel.terminate()
94 kernel.terminate()
95
95
96 def test_embed_kernel_basic():
96 def test_embed_kernel_basic():
97 """IPython.embed_kernel() is basically functional"""
97 """IPython.embed_kernel() is basically functional"""
98 cmd = '\n'.join([
98 cmd = '\n'.join([
99 'from IPython import embed_kernel',
99 'from IPython import embed_kernel',
100 'def go():',
100 'def go():',
101 ' a=5',
101 ' a=5',
102 ' b="hi there"',
102 ' b="hi there"',
103 ' embed_kernel()',
103 ' embed_kernel()',
104 'go()',
104 'go()',
105 '',
105 '',
106 ])
106 ])
107
107
108 with setup_kernel(cmd) as km:
108 with setup_kernel(cmd) as client:
109 shell = km.shell_channel
109 shell = client.shell_channel
110
110
111 # oinfo a (int)
111 # oinfo a (int)
112 msg_id = shell.object_info('a')
112 msg_id = shell.object_info('a')
113 msg = shell.get_msg(block=True, timeout=2)
113 msg = shell.get_msg(block=True, timeout=2)
114 content = msg['content']
114 content = msg['content']
115 nt.assert_true(content['found'])
115 nt.assert_true(content['found'])
116
116
117 msg_id = shell.execute("c=a*2")
117 msg_id = shell.execute("c=a*2")
118 msg = shell.get_msg(block=True, timeout=2)
118 msg = shell.get_msg(block=True, timeout=2)
119 content = msg['content']
119 content = msg['content']
120 nt.assert_equal(content['status'], u'ok')
120 nt.assert_equal(content['status'], u'ok')
121
121
122 # oinfo c (should be 10)
122 # oinfo c (should be 10)
123 msg_id = shell.object_info('c')
123 msg_id = shell.object_info('c')
124 msg = shell.get_msg(block=True, timeout=2)
124 msg = shell.get_msg(block=True, timeout=2)
125 content = msg['content']
125 content = msg['content']
126 nt.assert_true(content['found'])
126 nt.assert_true(content['found'])
127 nt.assert_equal(content['string_form'], u'10')
127 nt.assert_equal(content['string_form'], u'10')
128
128
129 def test_embed_kernel_namespace():
129 def test_embed_kernel_namespace():
130 """IPython.embed_kernel() inherits calling namespace"""
130 """IPython.embed_kernel() inherits calling namespace"""
131 cmd = '\n'.join([
131 cmd = '\n'.join([
132 'from IPython import embed_kernel',
132 'from IPython import embed_kernel',
133 'def go():',
133 'def go():',
134 ' a=5',
134 ' a=5',
135 ' b="hi there"',
135 ' b="hi there"',
136 ' embed_kernel()',
136 ' embed_kernel()',
137 'go()',
137 'go()',
138 '',
138 '',
139 ])
139 ])
140
140
141 with setup_kernel(cmd) as km:
141 with setup_kernel(cmd) as client:
142 shell = km.shell_channel
142 shell = client.shell_channel
143
143
144 # oinfo a (int)
144 # oinfo a (int)
145 msg_id = shell.object_info('a')
145 msg_id = shell.object_info('a')
146 msg = shell.get_msg(block=True, timeout=2)
146 msg = shell.get_msg(block=True, timeout=2)
147 content = msg['content']
147 content = msg['content']
148 nt.assert_true(content['found'])
148 nt.assert_true(content['found'])
149 nt.assert_equal(content['string_form'], u'5')
149 nt.assert_equal(content['string_form'], u'5')
150
150
151 # oinfo b (str)
151 # oinfo b (str)
152 msg_id = shell.object_info('b')
152 msg_id = shell.object_info('b')
153 msg = shell.get_msg(block=True, timeout=2)
153 msg = shell.get_msg(block=True, timeout=2)
154 content = msg['content']
154 content = msg['content']
155 nt.assert_true(content['found'])
155 nt.assert_true(content['found'])
156 nt.assert_equal(content['string_form'], u'hi there')
156 nt.assert_equal(content['string_form'], u'hi there')
157
157
158 # oinfo c (undefined)
158 # oinfo c (undefined)
159 msg_id = shell.object_info('c')
159 msg_id = shell.object_info('c')
160 msg = shell.get_msg(block=True, timeout=2)
160 msg = shell.get_msg(block=True, timeout=2)
161 content = msg['content']
161 content = msg['content']
162 nt.assert_false(content['found'])
162 nt.assert_false(content['found'])
163
163
164 def test_embed_kernel_reentrant():
164 def test_embed_kernel_reentrant():
165 """IPython.embed_kernel() can be called multiple times"""
165 """IPython.embed_kernel() can be called multiple times"""
166 cmd = '\n'.join([
166 cmd = '\n'.join([
167 'from IPython import embed_kernel',
167 'from IPython import embed_kernel',
168 'count = 0',
168 'count = 0',
169 'def go():',
169 'def go():',
170 ' global count',
170 ' global count',
171 ' embed_kernel()',
171 ' embed_kernel()',
172 ' count = count + 1',
172 ' count = count + 1',
173 '',
173 '',
174 'while True:'
174 'while True:'
175 ' go()',
175 ' go()',
176 '',
176 '',
177 ])
177 ])
178
178
179 with setup_kernel(cmd) as km:
179 with setup_kernel(cmd) as client:
180 shell = km.shell_channel
180 shell = client.shell_channel
181 for i in range(5):
181 for i in range(5):
182 msg_id = shell.object_info('count')
182 msg_id = shell.object_info('count')
183 msg = shell.get_msg(block=True, timeout=2)
183 msg = shell.get_msg(block=True, timeout=2)
184 content = msg['content']
184 content = msg['content']
185 nt.assert_true(content['found'])
185 nt.assert_true(content['found'])
186 nt.assert_equal(content['string_form'], unicode(i))
186 nt.assert_equal(content['string_form'], unicode(i))
187
187
188 # exit from embed_kernel
188 # exit from embed_kernel
189 shell.execute("get_ipython().exit_now = True")
189 shell.execute("get_ipython().exit_now = True")
190 msg = shell.get_msg(block=True, timeout=2)
190 msg = shell.get_msg(block=True, timeout=2)
191 time.sleep(0.2)
191 time.sleep(0.2)
192
192
193
193
General Comments 0
You need to be logged in to leave comments. Login now