##// END OF EJS Templates
Merge pull request #4165 from takluyver/parametric-begone...
Min RK -
r12407:f8a7c9a5 merge
parent child Browse files
Show More
@@ -6,12 +6,11 b''
6 # The full license is in the file COPYING.txt, distributed with this software.
6 # The full license is in the file COPYING.txt, distributed with this software.
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8
8
9 from nose.tools import assert_equal, assert_true
9 from nose.tools import assert_equal
10
10
11 from IPython.external import argparse
11 from IPython.external import argparse
12 from IPython.core.magic_arguments import (argument, argument_group, kwds,
12 from IPython.core.magic_arguments import (argument, argument_group, kwds,
13 magic_arguments, parse_argstring, real_name)
13 magic_arguments, parse_argstring, real_name)
14 from IPython.testing.decorators import parametric
15
14
16
15
17 @magic_arguments()
16 @magic_arguments()
@@ -74,48 +73,46 b' def foo(self, args):'
74 return parse_argstring(foo, args)
73 return parse_argstring(foo, args)
75
74
76
75
77 @parametric
78 def test_magic_arguments():
76 def test_magic_arguments():
79 # Ideally, these would be doctests, but I could not get it to work.
77 assert_equal(magic_foo1.__doc__, '%foo1 [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
80 yield assert_equal(magic_foo1.__doc__, '%foo1 [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
78 assert_equal(getattr(magic_foo1, 'argcmd_name', None), None)
81 yield assert_equal(getattr(magic_foo1, 'argcmd_name', None), None)
79 assert_equal(real_name(magic_foo1), 'foo1')
82 yield assert_equal(real_name(magic_foo1), 'foo1')
80 assert_equal(magic_foo1(None, ''), argparse.Namespace(foo=None))
83 yield assert_equal(magic_foo1(None, ''), argparse.Namespace(foo=None))
81 assert hasattr(magic_foo1, 'has_arguments')
84 yield assert_true(hasattr(magic_foo1, 'has_arguments'))
82
85
83 assert_equal(magic_foo2.__doc__, '%foo2\n\n A docstring.\n')
86 yield assert_equal(magic_foo2.__doc__, '%foo2\n\n A docstring.\n')
84 assert_equal(getattr(magic_foo2, 'argcmd_name', None), None)
87 yield assert_equal(getattr(magic_foo2, 'argcmd_name', None), None)
85 assert_equal(real_name(magic_foo2), 'foo2')
88 yield assert_equal(real_name(magic_foo2), 'foo2')
86 assert_equal(magic_foo2(None, ''), argparse.Namespace())
89 yield assert_equal(magic_foo2(None, ''), argparse.Namespace())
87 assert hasattr(magic_foo2, 'has_arguments')
90 yield assert_true(hasattr(magic_foo2, 'has_arguments'))
88
91
89 assert_equal(magic_foo3.__doc__, '%foo3 [-f FOO] [-b BAR] [-z BAZ]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n\nGroup:\n -b BAR, --bar BAR a grouped argument\n\nSecond Group:\n -z BAZ, --baz BAZ another grouped argument\n')
92 yield assert_equal(magic_foo3.__doc__, '%foo3 [-f FOO] [-b BAR] [-z BAZ]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n\nGroup:\n -b BAR, --bar BAR a grouped argument\n\nSecond Group:\n -z BAZ, --baz BAZ another grouped argument\n')
90 assert_equal(getattr(magic_foo3, 'argcmd_name', None), None)
93 yield assert_equal(getattr(magic_foo3, 'argcmd_name', None), None)
91 assert_equal(real_name(magic_foo3), 'foo3')
94 yield assert_equal(real_name(magic_foo3), 'foo3')
92 assert_equal(magic_foo3(None, ''),
95 yield assert_equal(magic_foo3(None, ''),
96 argparse.Namespace(bar=None, baz=None, foo=None))
93 argparse.Namespace(bar=None, baz=None, foo=None))
97 yield assert_true(hasattr(magic_foo3, 'has_arguments'))
94 assert hasattr(magic_foo3, 'has_arguments')
98
95
99 yield assert_equal(magic_foo4.__doc__, '%foo4 [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
96 assert_equal(magic_foo4.__doc__, '%foo4 [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
100 yield assert_equal(getattr(magic_foo4, 'argcmd_name', None), None)
97 assert_equal(getattr(magic_foo4, 'argcmd_name', None), None)
101 yield assert_equal(real_name(magic_foo4), 'foo4')
98 assert_equal(real_name(magic_foo4), 'foo4')
102 yield assert_equal(magic_foo4(None, ''), argparse.Namespace())
99 assert_equal(magic_foo4(None, ''), argparse.Namespace())
103 yield assert_true(hasattr(magic_foo4, 'has_arguments'))
100 assert hasattr(magic_foo4, 'has_arguments')
104
101
105 yield assert_equal(magic_foo5.__doc__, '%frobnicate [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
102 assert_equal(magic_foo5.__doc__, '%frobnicate [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
106 yield assert_equal(getattr(magic_foo5, 'argcmd_name', None), 'frobnicate')
103 assert_equal(getattr(magic_foo5, 'argcmd_name', None), 'frobnicate')
107 yield assert_equal(real_name(magic_foo5), 'frobnicate')
104 assert_equal(real_name(magic_foo5), 'frobnicate')
108 yield assert_equal(magic_foo5(None, ''), argparse.Namespace(foo=None))
105 assert_equal(magic_foo5(None, ''), argparse.Namespace(foo=None))
109 yield assert_true(hasattr(magic_foo5, 'has_arguments'))
106 assert hasattr(magic_foo5, 'has_arguments')
110
107
111 yield assert_equal(magic_magic_foo.__doc__, '%magic_foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
108 assert_equal(magic_magic_foo.__doc__, '%magic_foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
112 yield assert_equal(getattr(magic_magic_foo, 'argcmd_name', None), None)
109 assert_equal(getattr(magic_magic_foo, 'argcmd_name', None), None)
113 yield assert_equal(real_name(magic_magic_foo), 'magic_foo')
110 assert_equal(real_name(magic_magic_foo), 'magic_foo')
114 yield assert_equal(magic_magic_foo(None, ''), argparse.Namespace(foo=None))
111 assert_equal(magic_magic_foo(None, ''), argparse.Namespace(foo=None))
115 yield assert_true(hasattr(magic_magic_foo, 'has_arguments'))
112 assert hasattr(magic_magic_foo, 'has_arguments')
116
113
117 yield assert_equal(foo.__doc__, '%foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
114 assert_equal(foo.__doc__, '%foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n')
118 yield assert_equal(getattr(foo, 'argcmd_name', None), None)
115 assert_equal(getattr(foo, 'argcmd_name', None), None)
119 yield assert_equal(real_name(foo), 'foo')
116 assert_equal(real_name(foo), 'foo')
120 yield assert_equal(foo(None, ''), argparse.Namespace(foo=None))
117 assert_equal(foo(None, ''), argparse.Namespace(foo=None))
121 yield assert_true(hasattr(foo, 'has_arguments'))
118 assert hasattr(foo, 'has_arguments')
@@ -6,7 +6,6 b''
6 import nose.tools as nt
6 import nose.tools as nt
7
7
8 from IPython.core.prefilter import AutocallChecker
8 from IPython.core.prefilter import AutocallChecker
9 from IPython.testing import decorators as dec
10 from IPython.testing.globalipapp import get_ipython
9 from IPython.testing.globalipapp import get_ipython
11
10
12 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
@@ -14,7 +13,6 b' from IPython.testing.globalipapp import get_ipython'
14 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
15 ip = get_ipython()
14 ip = get_ipython()
16
15
17 @dec.parametric
18 def test_prefilter():
16 def test_prefilter():
19 """Test user input conversions"""
17 """Test user input conversions"""
20
18
@@ -23,19 +21,18 b' def test_prefilter():'
23 ]
21 ]
24
22
25 for raw, correct in pairs:
23 for raw, correct in pairs:
26 yield nt.assert_equal(ip.prefilter(raw), correct)
24 nt.assert_equal(ip.prefilter(raw), correct)
27
25
28
26
29 @dec.parametric
30 def test_autocall_binops():
27 def test_autocall_binops():
31 """See https://github.com/ipython/ipython/issues/81"""
28 """See https://github.com/ipython/ipython/issues/81"""
32 ip.magic('autocall 2')
29 ip.magic('autocall 2')
33 f = lambda x: x
30 f = lambda x: x
34 ip.user_ns['f'] = f
31 ip.user_ns['f'] = f
35 try:
32 try:
36 yield nt.assert_equal(ip.prefilter('f 1'),'f(1)')
33 nt.assert_equal(ip.prefilter('f 1'),'f(1)')
37 for t in ['f +1', 'f -1']:
34 for t in ['f +1', 'f -1']:
38 yield nt.assert_equal(ip.prefilter(t), t)
35 nt.assert_equal(ip.prefilter(t), t)
39
36
40 # Run tests again with a more permissive exclude_regexp, which will
37 # Run tests again with a more permissive exclude_regexp, which will
41 # allow transformation of binary operations ('f -1' -> 'f(-1)').
38 # allow transformation of binary operations ('f -1' -> 'f(-1)').
@@ -47,8 +44,8 b' def test_autocall_binops():'
47 ac.exclude_regexp = r'^[,&^\|\*/]|^is |^not |^in |^and |^or '
44 ac.exclude_regexp = r'^[,&^\|\*/]|^is |^not |^in |^and |^or '
48 pm.sort_checkers()
45 pm.sort_checkers()
49
46
50 yield nt.assert_equal(ip.prefilter('f -1'), 'f(-1)')
47 nt.assert_equal(ip.prefilter('f -1'), 'f(-1)')
51 yield nt.assert_equal(ip.prefilter('f +1'), 'f(+1)')
48 nt.assert_equal(ip.prefilter('f +1'), 'f(+1)')
52 finally:
49 finally:
53 pm.unregister_checker(ac)
50 pm.unregister_checker(ac)
54 finally:
51 finally:
@@ -56,7 +53,6 b' def test_autocall_binops():'
56 del ip.user_ns['f']
53 del ip.user_ns['f']
57
54
58
55
59 @dec.parametric
60 def test_issue_114():
56 def test_issue_114():
61 """Check that multiline string literals don't expand as magic
57 """Check that multiline string literals don't expand as magic
62 see http://github.com/ipython/ipython/issues/114"""
58 see http://github.com/ipython/ipython/issues/114"""
@@ -70,7 +66,7 b' def test_issue_114():'
70 try:
66 try:
71 for mgk in ip.magics_manager.lsmagic()['line']:
67 for mgk in ip.magics_manager.lsmagic()['line']:
72 raw = template % mgk
68 raw = template % mgk
73 yield nt.assert_equal(ip.prefilter(raw), raw)
69 nt.assert_equal(ip.prefilter(raw), raw)
74 finally:
70 finally:
75 ip.prefilter_manager.multi_line_specials = msp
71 ip.prefilter_manager.multi_line_specials = msp
76
72
@@ -24,7 +24,6 b' import numpy as np'
24
24
25 # Our own imports
25 # Our own imports
26 from IPython.core.interactiveshell import InteractiveShell
26 from IPython.core.interactiveshell import InteractiveShell
27 from IPython.testing import decorators as dec
28 from .. import pylabtools as pt
27 from .. import pylabtools as pt
29
28
30 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
@@ -39,11 +38,10 b' from .. import pylabtools as pt'
39 # Classes and functions
38 # Classes and functions
40 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
41
40
42 @dec.parametric
43 def test_figure_to_svg():
41 def test_figure_to_svg():
44 # simple empty-figure test
42 # simple empty-figure test
45 fig = plt.figure()
43 fig = plt.figure()
46 yield nt.assert_equal(pt.print_figure(fig, 'svg'), None)
44 nt.assert_equal(pt.print_figure(fig, 'svg'), None)
47
45
48 plt.close('all')
46 plt.close('all')
49
47
@@ -53,7 +51,7 b' def test_figure_to_svg():'
53 ax.plot([1,2,3])
51 ax.plot([1,2,3])
54 plt.draw()
52 plt.draw()
55 svg = pt.print_figure(fig, 'svg')[:100].lower()
53 svg = pt.print_figure(fig, 'svg')[:100].lower()
56 yield nt.assert_true('doctype svg' in svg)
54 nt.assert_in('doctype svg', svg)
57
55
58
56
59 def test_import_pylab():
57 def test_import_pylab():
@@ -275,7 +275,7 b' def main() :'
275 if __name__ == '__main__' :
275 if __name__ == '__main__' :
276 sys.exit(main())
276 sys.exit(main())
277
277
278 __all__ = ['install_mathjax', 'main', 'dest']
278 __all__ = ['install_mathjax', 'main', 'default_dest']
279
279
280 """
280 """
281 Test notes:
281 Test notes:
@@ -20,14 +20,12 b' Authors'
20 import nose.tools as nt
20 import nose.tools as nt
21
21
22 # Our own imports
22 # Our own imports
23 from IPython.testing import decorators as dec
24 from IPython.kernel.launcher import swallow_argv
23 from IPython.kernel.launcher import swallow_argv
25
24
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27 # Classes and functions
26 # Classes and functions
28 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
29
28
30 @dec.parametric
31 def test_swallow_argv():
29 def test_swallow_argv():
32 tests = [
30 tests = [
33 # expected , argv , aliases, flags
31 # expected , argv , aliases, flags
@@ -56,5 +54,5 b' def test_swallow_argv():'
56 "expected : %r" % expected,
54 "expected : %r" % expected,
57 "returned : %r" % stripped,
55 "returned : %r" % stripped,
58 ])
56 ])
59 yield nt.assert_equal(expected, stripped, message)
57 nt.assert_equal(expected, stripped, message)
60
58
@@ -15,7 +15,6 b' import nose.tools as nt'
15
15
16 from IPython.kernel import KernelManager
16 from IPython.kernel import KernelManager
17
17
18 from IPython.testing import decorators as dec
19 from IPython.utils.traitlets import (
18 from IPython.utils.traitlets import (
20 HasTraits, TraitError, Bool, Unicode, Dict, Integer, List, Enum, Any,
19 HasTraits, TraitError, Bool, Unicode, Dict, Integer, List, Enum, Any,
21 )
20 )
@@ -60,7 +59,7 b' def flush_channels(kc=None):'
60 except Empty:
59 except Empty:
61 break
60 break
62 else:
61 else:
63 list(validate_message(msg))
62 validate_message(msg)
64
63
65
64
66 def execute(code='', kc=None, **kwargs):
65 def execute(code='', kc=None, **kwargs):
@@ -69,14 +68,14 b" def execute(code='', kc=None, **kwargs):"
69 kc = KC
68 kc = KC
70 msg_id = kc.execute(code=code, **kwargs)
69 msg_id = kc.execute(code=code, **kwargs)
71 reply = kc.get_shell_msg(timeout=TIMEOUT)
70 reply = kc.get_shell_msg(timeout=TIMEOUT)
72 list(validate_message(reply, 'execute_reply', msg_id))
71 validate_message(reply, 'execute_reply', msg_id)
73 busy = kc.get_iopub_msg(timeout=TIMEOUT)
72 busy = kc.get_iopub_msg(timeout=TIMEOUT)
74 list(validate_message(busy, 'status', msg_id))
73 validate_message(busy, 'status', msg_id)
75 nt.assert_equal(busy['content']['execution_state'], 'busy')
74 nt.assert_equal(busy['content']['execution_state'], 'busy')
76
75
77 if not kwargs.get('silent'):
76 if not kwargs.get('silent'):
78 pyin = kc.get_iopub_msg(timeout=TIMEOUT)
77 pyin = kc.get_iopub_msg(timeout=TIMEOUT)
79 list(validate_message(pyin, 'pyin', msg_id))
78 validate_message(pyin, 'pyin', msg_id)
80 nt.assert_equal(pyin['content']['code'], code)
79 nt.assert_equal(pyin['content']['code'], code)
81
80
82 return msg_id, reply['content']
81 return msg_id, reply['content']
@@ -101,14 +100,14 b' class Reference(HasTraits):'
101 def check(self, d):
100 def check(self, d):
102 """validate a dict against our traits"""
101 """validate a dict against our traits"""
103 for key in self.trait_names():
102 for key in self.trait_names():
104 yield nt.assert_true(key in d, "Missing key: %r, should be found in %s" % (key, d))
103 nt.assert_in(key, d)
105 # FIXME: always allow None, probably not a good idea
104 # FIXME: always allow None, probably not a good idea
106 if d[key] is None:
105 if d[key] is None:
107 continue
106 continue
108 try:
107 try:
109 setattr(self, key, d[key])
108 setattr(self, key, d[key])
110 except TraitError as e:
109 except TraitError as e:
111 yield nt.assert_true(False, str(e))
110 nt.assert_true(False, str(e))
112
111
113
112
114 class RMessage(Reference):
113 class RMessage(Reference):
@@ -133,14 +132,11 b' class ExecuteReply(Reference):'
133 status = Enum((u'ok', u'error'))
132 status = Enum((u'ok', u'error'))
134
133
135 def check(self, d):
134 def check(self, d):
136 for tst in Reference.check(self, d):
135 Reference.check(self, d)
137 yield tst
138 if d['status'] == 'ok':
136 if d['status'] == 'ok':
139 for tst in ExecuteReplyOkay().check(d):
137 ExecuteReplyOkay().check(d)
140 yield tst
141 elif d['status'] == 'error':
138 elif d['status'] == 'error':
142 for tst in ExecuteReplyError().check(d):
139 ExecuteReplyError().check(d)
143 yield tst
144
140
145
141
146 class ExecuteReplyOkay(Reference):
142 class ExecuteReplyOkay(Reference):
@@ -177,11 +173,9 b' class OInfoReply(Reference):'
177 source = Unicode()
173 source = Unicode()
178
174
179 def check(self, d):
175 def check(self, d):
180 for tst in Reference.check(self, d):
176 Reference.check(self, d)
181 yield tst
182 if d['argspec'] is not None:
177 if d['argspec'] is not None:
183 for tst in ArgSpec().check(d['argspec']):
178 ArgSpec().check(d['argspec'])
184 yield tst
185
179
186
180
187 class ArgSpec(Reference):
181 class ArgSpec(Reference):
@@ -212,10 +206,8 b' class KernelInfoReply(Reference):'
212
206
213 def _ipython_version_changed(self, name, old, new):
207 def _ipython_version_changed(self, name, old, new):
214 for v in new:
208 for v in new:
215 nt.assert_true(
209 assert isinstance(v, int) or isinstance(v, basestring), \
216 isinstance(v, int) or isinstance(v, basestring),
210 'expected int or string as version component, got {0!r}'.format(v)
217 'expected int or string as version component, got {0!r}'
218 .format(v))
219
211
220
212
221 # IOPub messages
213 # IOPub messages
@@ -241,8 +233,8 b' class DisplayData(Reference):'
241 data = Dict()
233 data = Dict()
242 def _data_changed(self, name, old, new):
234 def _data_changed(self, name, old, new):
243 for k,v in new.iteritems():
235 for k,v in new.iteritems():
244 nt.assert_true(mime_pat.match(k))
236 assert mime_pat.match(k)
245 nt.assert_true(isinstance(v, basestring), "expected string data, got %r" % v)
237 nt.assert_is_instance(v, basestring)
246
238
247
239
248 class PyOut(Reference):
240 class PyOut(Reference):
@@ -250,8 +242,8 b' class PyOut(Reference):'
250 data = Dict()
242 data = Dict()
251 def _data_changed(self, name, old, new):
243 def _data_changed(self, name, old, new):
252 for k,v in new.iteritems():
244 for k,v in new.iteritems():
253 nt.assert_true(mime_pat.match(k))
245 assert mime_pat.match(k)
254 nt.assert_true(isinstance(v, basestring), "expected string data, got %r" % v)
246 nt.assert_is_instance(v, basestring)
255
247
256
248
257 references = {
249 references = {
@@ -282,13 +274,12 b' def validate_message(msg, msg_type=None, parent=None):'
282 """
274 """
283 RMessage().check(msg)
275 RMessage().check(msg)
284 if msg_type:
276 if msg_type:
285 yield nt.assert_equal(msg['msg_type'], msg_type)
277 nt.assert_equal(msg['msg_type'], msg_type)
286 if parent:
278 if parent:
287 yield nt.assert_equal(msg['parent_header']['msg_id'], parent)
279 nt.assert_equal(msg['parent_header']['msg_id'], parent)
288 content = msg['content']
280 content = msg['content']
289 ref = references[msg['msg_type']]
281 ref = references[msg['msg_type']]
290 for tst in ref.check(content):
282 ref.check(content)
291 yield tst
292
283
293
284
294 #-----------------------------------------------------------------------------
285 #-----------------------------------------------------------------------------
@@ -297,54 +288,47 b' def validate_message(msg, msg_type=None, parent=None):'
297
288
298 # Shell channel
289 # Shell channel
299
290
300 @dec.parametric
301 def test_execute():
291 def test_execute():
302 flush_channels()
292 flush_channels()
303
293
304 msg_id = KC.execute(code='x=1')
294 msg_id = KC.execute(code='x=1')
305 reply = KC.get_shell_msg(timeout=TIMEOUT)
295 reply = KC.get_shell_msg(timeout=TIMEOUT)
306 for tst in validate_message(reply, 'execute_reply', msg_id):
296 validate_message(reply, 'execute_reply', msg_id)
307 yield tst
308
297
309
298
310 @dec.parametric
311 def test_execute_silent():
299 def test_execute_silent():
312 flush_channels()
300 flush_channels()
313 msg_id, reply = execute(code='x=1', silent=True)
301 msg_id, reply = execute(code='x=1', silent=True)
314
302
315 # flush status=idle
303 # flush status=idle
316 status = KC.iopub_channel.get_msg(timeout=TIMEOUT)
304 status = KC.iopub_channel.get_msg(timeout=TIMEOUT)
317 for tst in validate_message(status, 'status', msg_id):
305 validate_message(status, 'status', msg_id)
318 yield tst
319 nt.assert_equal(status['content']['execution_state'], 'idle')
306 nt.assert_equal(status['content']['execution_state'], 'idle')
320
307
321 yield nt.assert_raises(Empty, KC.iopub_channel.get_msg, timeout=0.1)
308 nt.assert_raises(Empty, KC.iopub_channel.get_msg, timeout=0.1)
322 count = reply['execution_count']
309 count = reply['execution_count']
323
310
324 msg_id, reply = execute(code='x=2', silent=True)
311 msg_id, reply = execute(code='x=2', silent=True)
325
312
326 # flush status=idle
313 # flush status=idle
327 status = KC.iopub_channel.get_msg(timeout=TIMEOUT)
314 status = KC.iopub_channel.get_msg(timeout=TIMEOUT)
328 for tst in validate_message(status, 'status', msg_id):
315 validate_message(status, 'status', msg_id)
329 yield tst
316 nt.assert_equal(status['content']['execution_state'], 'idle')
330 yield nt.assert_equal(status['content']['execution_state'], 'idle')
331
317
332 yield nt.assert_raises(Empty, KC.iopub_channel.get_msg, timeout=0.1)
318 nt.assert_raises(Empty, KC.iopub_channel.get_msg, timeout=0.1)
333 count_2 = reply['execution_count']
319 count_2 = reply['execution_count']
334 yield nt.assert_equal(count_2, count)
320 nt.assert_equal(count_2, count)
335
321
336
322
337 @dec.parametric
338 def test_execute_error():
323 def test_execute_error():
339 flush_channels()
324 flush_channels()
340
325
341 msg_id, reply = execute(code='1/0')
326 msg_id, reply = execute(code='1/0')
342 yield nt.assert_equal(reply['status'], 'error')
327 nt.assert_equal(reply['status'], 'error')
343 yield nt.assert_equal(reply['ename'], 'ZeroDivisionError')
328 nt.assert_equal(reply['ename'], 'ZeroDivisionError')
344
329
345 pyerr = KC.iopub_channel.get_msg(timeout=TIMEOUT)
330 pyerr = KC.iopub_channel.get_msg(timeout=TIMEOUT)
346 for tst in validate_message(pyerr, 'pyerr', msg_id):
331 validate_message(pyerr, 'pyerr', msg_id)
347 yield tst
348
332
349
333
350 def test_execute_inc():
334 def test_execute_inc():
@@ -405,17 +389,14 b' def test_user_expressions_fail():'
405 nt.assert_equal(foo['ename'], 'NameError')
389 nt.assert_equal(foo['ename'], 'NameError')
406
390
407
391
408 @dec.parametric
409 def test_oinfo():
392 def test_oinfo():
410 flush_channels()
393 flush_channels()
411
394
412 msg_id = KC.object_info('a')
395 msg_id = KC.object_info('a')
413 reply = KC.get_shell_msg(timeout=TIMEOUT)
396 reply = KC.get_shell_msg(timeout=TIMEOUT)
414 for tst in validate_message(reply, 'object_info_reply', msg_id):
397 validate_message(reply, 'object_info_reply', msg_id)
415 yield tst
416
398
417
399
418 @dec.parametric
419 def test_oinfo_found():
400 def test_oinfo_found():
420 flush_channels()
401 flush_channels()
421
402
@@ -423,15 +404,13 b' def test_oinfo_found():'
423
404
424 msg_id = KC.object_info('a')
405 msg_id = KC.object_info('a')
425 reply = KC.get_shell_msg(timeout=TIMEOUT)
406 reply = KC.get_shell_msg(timeout=TIMEOUT)
426 for tst in validate_message(reply, 'object_info_reply', msg_id):
407 validate_message(reply, 'object_info_reply', msg_id)
427 yield tst
428 content = reply['content']
408 content = reply['content']
429 yield nt.assert_true(content['found'])
409 assert content['found']
430 argspec = content['argspec']
410 argspec = content['argspec']
431 yield nt.assert_true(argspec is None, "didn't expect argspec dict, got %r" % argspec)
411 nt.assert_is(argspec, None)
432
412
433
413
434 @dec.parametric
435 def test_oinfo_detail():
414 def test_oinfo_detail():
436 flush_channels()
415 flush_channels()
437
416
@@ -439,28 +418,24 b' def test_oinfo_detail():'
439
418
440 msg_id = KC.object_info('ip.object_inspect', detail_level=2)
419 msg_id = KC.object_info('ip.object_inspect', detail_level=2)
441 reply = KC.get_shell_msg(timeout=TIMEOUT)
420 reply = KC.get_shell_msg(timeout=TIMEOUT)
442 for tst in validate_message(reply, 'object_info_reply', msg_id):
421 validate_message(reply, 'object_info_reply', msg_id)
443 yield tst
444 content = reply['content']
422 content = reply['content']
445 yield nt.assert_true(content['found'])
423 assert content['found']
446 argspec = content['argspec']
424 argspec = content['argspec']
447 yield nt.assert_true(isinstance(argspec, dict), "expected non-empty argspec dict, got %r" % argspec)
425 nt.assert_is_instance(argspec, dict, "expected non-empty argspec dict, got %r" % argspec)
448 yield nt.assert_equal(argspec['defaults'], [0])
426 nt.assert_equal(argspec['defaults'], [0])
449
427
450
428
451 @dec.parametric
452 def test_oinfo_not_found():
429 def test_oinfo_not_found():
453 flush_channels()
430 flush_channels()
454
431
455 msg_id = KC.object_info('dne')
432 msg_id = KC.object_info('dne')
456 reply = KC.get_shell_msg(timeout=TIMEOUT)
433 reply = KC.get_shell_msg(timeout=TIMEOUT)
457 for tst in validate_message(reply, 'object_info_reply', msg_id):
434 validate_message(reply, 'object_info_reply', msg_id)
458 yield tst
459 content = reply['content']
435 content = reply['content']
460 yield nt.assert_false(content['found'])
436 nt.assert_false(content['found'])
461
437
462
438
463 @dec.parametric
464 def test_complete():
439 def test_complete():
465 flush_channels()
440 flush_channels()
466
441
@@ -468,49 +443,42 b' def test_complete():'
468
443
469 msg_id = KC.complete('al', 'al', 2)
444 msg_id = KC.complete('al', 'al', 2)
470 reply = KC.get_shell_msg(timeout=TIMEOUT)
445 reply = KC.get_shell_msg(timeout=TIMEOUT)
471 for tst in validate_message(reply, 'complete_reply', msg_id):
446 validate_message(reply, 'complete_reply', msg_id)
472 yield tst
473 matches = reply['content']['matches']
447 matches = reply['content']['matches']
474 for name in ('alpha', 'albert'):
448 for name in ('alpha', 'albert'):
475 yield nt.assert_true(name in matches, "Missing match: %r" % name)
449 nt.assert_in(name, matches)
476
450
477
451
478 @dec.parametric
479 def test_kernel_info_request():
452 def test_kernel_info_request():
480 flush_channels()
453 flush_channels()
481
454
482 msg_id = KC.kernel_info()
455 msg_id = KC.kernel_info()
483 reply = KC.get_shell_msg(timeout=TIMEOUT)
456 reply = KC.get_shell_msg(timeout=TIMEOUT)
484 for tst in validate_message(reply, 'kernel_info_reply', msg_id):
457 validate_message(reply, 'kernel_info_reply', msg_id)
485 yield tst
486
458
487
459
488 # IOPub channel
460 # IOPub channel
489
461
490
462
491 @dec.parametric
492 def test_stream():
463 def test_stream():
493 flush_channels()
464 flush_channels()
494
465
495 msg_id, reply = execute("print('hi')")
466 msg_id, reply = execute("print('hi')")
496
467
497 stdout = KC.iopub_channel.get_msg(timeout=TIMEOUT)
468 stdout = KC.iopub_channel.get_msg(timeout=TIMEOUT)
498 for tst in validate_message(stdout, 'stream', msg_id):
469 validate_message(stdout, 'stream', msg_id)
499 yield tst
500 content = stdout['content']
470 content = stdout['content']
501 yield nt.assert_equal(content['name'], u'stdout')
471 nt.assert_equal(content['name'], u'stdout')
502 yield nt.assert_equal(content['data'], u'hi\n')
472 nt.assert_equal(content['data'], u'hi\n')
503
473
504
474
505 @dec.parametric
506 def test_display_data():
475 def test_display_data():
507 flush_channels()
476 flush_channels()
508
477
509 msg_id, reply = execute("from IPython.core.display import display; display(1)")
478 msg_id, reply = execute("from IPython.core.display import display; display(1)")
510
479
511 display = KC.iopub_channel.get_msg(timeout=TIMEOUT)
480 display = KC.iopub_channel.get_msg(timeout=TIMEOUT)
512 for tst in validate_message(display, 'display_data', parent=msg_id):
481 validate_message(display, 'display_data', parent=msg_id)
513 yield tst
514 data = display['content']['data']
482 data = display['content']['data']
515 yield nt.assert_equal(data['text/plain'], u'1')
483 nt.assert_equal(data['text/plain'], u'1')
516
484
@@ -14,8 +14,6 b' Authors'
14
14
15 import nose.tools as nt
15 import nose.tools as nt
16
16
17 from IPython.testing import decorators as dec
18
19 from IPython.kernel import launcher, connect
17 from IPython.kernel import launcher, connect
20 from IPython import kernel
18 from IPython import kernel
21
19
@@ -23,25 +21,21 b' from IPython import kernel'
23 # Classes and functions
21 # Classes and functions
24 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
25
23
26 @dec.parametric
27 def test_kms():
24 def test_kms():
28 for base in ("", "Multi"):
25 for base in ("", "Multi"):
29 KM = base + "KernelManager"
26 KM = base + "KernelManager"
30 yield nt.assert_true(KM in dir(kernel), KM)
27 nt.assert_in(KM, dir(kernel))
31
28
32 @dec.parametric
33 def test_kcs():
29 def test_kcs():
34 for base in ("", "Blocking"):
30 for base in ("", "Blocking"):
35 KM = base + "KernelClient"
31 KM = base + "KernelClient"
36 yield nt.assert_true(KM in dir(kernel), KM)
32 nt.assert_in(KM, dir(kernel))
37
33
38 @dec.parametric
39 def test_launcher():
34 def test_launcher():
40 for name in launcher.__all__:
35 for name in launcher.__all__:
41 yield nt.assert_true(name in dir(kernel), name)
36 nt.assert_in(name, dir(kernel))
42
37
43 @dec.parametric
44 def test_connect():
38 def test_connect():
45 for name in connect.__all__:
39 for name in connect.__all__:
46 yield nt.assert_true(name in dir(kernel), name)
40 nt.assert_in(name, dir(kernel))
47
41
@@ -46,7 +46,6 b" DTYPES = ('uint8', 'float64', 'int32', [('g', 'float32')], '|S10')"
46 # Tests
46 # Tests
47 #-------------------------------------------------------------------------------
47 #-------------------------------------------------------------------------------
48
48
49 @dec.parametric
50 def test_roundtrip_simple():
49 def test_roundtrip_simple():
51 for obj in [
50 for obj in [
52 'hello',
51 'hello',
@@ -55,18 +54,16 b' def test_roundtrip_simple():'
55 (b'123', 'hello'),
54 (b'123', 'hello'),
56 ]:
55 ]:
57 obj2 = roundtrip(obj)
56 obj2 = roundtrip(obj)
58 yield nt.assert_equals(obj, obj2)
57 nt.assert_equal(obj, obj2)
59
58
60 @dec.parametric
61 def test_roundtrip_nested():
59 def test_roundtrip_nested():
62 for obj in [
60 for obj in [
63 dict(a=range(5), b={1:b'hello'}),
61 dict(a=range(5), b={1:b'hello'}),
64 [range(5),[range(3),(1,[b'whoda'])]],
62 [range(5),[range(3),(1,[b'whoda'])]],
65 ]:
63 ]:
66 obj2 = roundtrip(obj)
64 obj2 = roundtrip(obj)
67 yield nt.assert_equals(obj, obj2)
65 nt.assert_equal(obj, obj2)
68
66
69 @dec.parametric
70 def test_roundtrip_buffered():
67 def test_roundtrip_buffered():
71 for obj in [
68 for obj in [
72 dict(a=b"x"*1025),
69 dict(a=b"x"*1025),
@@ -74,10 +71,10 b' def test_roundtrip_buffered():'
74 [b"hello"*501, 1,2,3]
71 [b"hello"*501, 1,2,3]
75 ]:
72 ]:
76 bufs = serialize_object(obj)
73 bufs = serialize_object(obj)
77 yield nt.assert_equals(len(bufs), 2)
74 nt.assert_equal(len(bufs), 2)
78 obj2, remainder = unserialize_object(bufs)
75 obj2, remainder = unserialize_object(bufs)
79 yield nt.assert_equals(remainder, [])
76 nt.assert_equal(remainder, [])
80 yield nt.assert_equals(obj, obj2)
77 nt.assert_equal(obj, obj2)
81
78
82 def _scrub_nan(A):
79 def _scrub_nan(A):
83 """scrub nans out of empty arrays
80 """scrub nans out of empty arrays
@@ -93,7 +90,6 b' def _scrub_nan(A):'
93 # e.g. str dtype
90 # e.g. str dtype
94 pass
91 pass
95
92
96 @dec.parametric
97 @dec.skip_without('numpy')
93 @dec.skip_without('numpy')
98 def test_numpy():
94 def test_numpy():
99 import numpy
95 import numpy
@@ -104,12 +100,11 b' def test_numpy():'
104 _scrub_nan(A)
100 _scrub_nan(A)
105 bufs = serialize_object(A)
101 bufs = serialize_object(A)
106 B, r = unserialize_object(bufs)
102 B, r = unserialize_object(bufs)
107 yield nt.assert_equals(r, [])
103 nt.assert_equal(r, [])
108 yield nt.assert_equals(A.shape, B.shape)
104 nt.assert_equal(A.shape, B.shape)
109 yield nt.assert_equals(A.dtype, B.dtype)
105 nt.assert_equal(A.dtype, B.dtype)
110 yield assert_array_equal(A,B)
106 assert_array_equal(A,B)
111
107
112 @dec.parametric
113 @dec.skip_without('numpy')
108 @dec.skip_without('numpy')
114 def test_recarray():
109 def test_recarray():
115 import numpy
110 import numpy
@@ -124,12 +119,11 b' def test_recarray():'
124
119
125 bufs = serialize_object(A)
120 bufs = serialize_object(A)
126 B, r = unserialize_object(bufs)
121 B, r = unserialize_object(bufs)
127 yield nt.assert_equals(r, [])
122 nt.assert_equal(r, [])
128 yield nt.assert_equals(A.shape, B.shape)
123 nt.assert_equal(A.shape, B.shape)
129 yield nt.assert_equals(A.dtype, B.dtype)
124 nt.assert_equal(A.dtype, B.dtype)
130 yield assert_array_equal(A,B)
125 assert_array_equal(A,B)
131
126
132 @dec.parametric
133 @dec.skip_without('numpy')
127 @dec.skip_without('numpy')
134 def test_numpy_in_seq():
128 def test_numpy_in_seq():
135 import numpy
129 import numpy
@@ -140,15 +134,14 b' def test_numpy_in_seq():'
140 _scrub_nan(A)
134 _scrub_nan(A)
141 bufs = serialize_object((A,1,2,b'hello'))
135 bufs = serialize_object((A,1,2,b'hello'))
142 canned = pickle.loads(bufs[0])
136 canned = pickle.loads(bufs[0])
143 yield nt.assert_true(canned[0], CannedArray)
137 nt.assert_is_instance(canned[0], CannedArray)
144 tup, r = unserialize_object(bufs)
138 tup, r = unserialize_object(bufs)
145 B = tup[0]
139 B = tup[0]
146 yield nt.assert_equals(r, [])
140 nt.assert_equal(r, [])
147 yield nt.assert_equals(A.shape, B.shape)
141 nt.assert_equal(A.shape, B.shape)
148 yield nt.assert_equals(A.dtype, B.dtype)
142 nt.assert_equal(A.dtype, B.dtype)
149 yield assert_array_equal(A,B)
143 assert_array_equal(A,B)
150
144
151 @dec.parametric
152 @dec.skip_without('numpy')
145 @dec.skip_without('numpy')
153 def test_numpy_in_dict():
146 def test_numpy_in_dict():
154 import numpy
147 import numpy
@@ -159,27 +152,25 b' def test_numpy_in_dict():'
159 _scrub_nan(A)
152 _scrub_nan(A)
160 bufs = serialize_object(dict(a=A,b=1,c=range(20)))
153 bufs = serialize_object(dict(a=A,b=1,c=range(20)))
161 canned = pickle.loads(bufs[0])
154 canned = pickle.loads(bufs[0])
162 yield nt.assert_true(canned['a'], CannedArray)
155 nt.assert_is_instance(canned['a'], CannedArray)
163 d, r = unserialize_object(bufs)
156 d, r = unserialize_object(bufs)
164 B = d['a']
157 B = d['a']
165 yield nt.assert_equals(r, [])
158 nt.assert_equal(r, [])
166 yield nt.assert_equals(A.shape, B.shape)
159 nt.assert_equal(A.shape, B.shape)
167 yield nt.assert_equals(A.dtype, B.dtype)
160 nt.assert_equal(A.dtype, B.dtype)
168 yield assert_array_equal(A,B)
161 assert_array_equal(A,B)
169
162
170 @dec.parametric
171 def test_class():
163 def test_class():
172 @interactive
164 @interactive
173 class C(object):
165 class C(object):
174 a=5
166 a=5
175 bufs = serialize_object(dict(C=C))
167 bufs = serialize_object(dict(C=C))
176 canned = pickle.loads(bufs[0])
168 canned = pickle.loads(bufs[0])
177 yield nt.assert_true(canned['C'], CannedClass)
169 nt.assert_is_instance(canned['C'], CannedClass)
178 d, r = unserialize_object(bufs)
170 d, r = unserialize_object(bufs)
179 C2 = d['C']
171 C2 = d['C']
180 yield nt.assert_equal(C2.a, C.a)
172 nt.assert_equal(C2.a, C.a)
181
173
182 @dec.parametric
183 def test_class_oldstyle():
174 def test_class_oldstyle():
184 @interactive
175 @interactive
185 class C:
176 class C:
@@ -187,42 +178,38 b' def test_class_oldstyle():'
187
178
188 bufs = serialize_object(dict(C=C))
179 bufs = serialize_object(dict(C=C))
189 canned = pickle.loads(bufs[0])
180 canned = pickle.loads(bufs[0])
190 yield nt.assert_true(isinstance(canned['C'], CannedClass))
181 nt.assert_is_instance(canned['C'], CannedClass)
191 d, r = unserialize_object(bufs)
182 d, r = unserialize_object(bufs)
192 C2 = d['C']
183 C2 = d['C']
193 yield nt.assert_equal(C2.a, C.a)
184 nt.assert_equal(C2.a, C.a)
194
185
195 @dec.parametric
196 def test_tuple():
186 def test_tuple():
197 tup = (lambda x:x, 1)
187 tup = (lambda x:x, 1)
198 bufs = serialize_object(tup)
188 bufs = serialize_object(tup)
199 canned = pickle.loads(bufs[0])
189 canned = pickle.loads(bufs[0])
200 yield nt.assert_true(isinstance(canned, tuple))
190 nt.assert_is_instance(canned, tuple)
201 t2, r = unserialize_object(bufs)
191 t2, r = unserialize_object(bufs)
202 yield nt.assert_equal(t2[0](t2[1]), tup[0](tup[1]))
192 nt.assert_equal(t2[0](t2[1]), tup[0](tup[1]))
203
193
204 point = namedtuple('point', 'x y')
194 point = namedtuple('point', 'x y')
205
195
206 @dec.parametric
207 def test_namedtuple():
196 def test_namedtuple():
208 p = point(1,2)
197 p = point(1,2)
209 bufs = serialize_object(p)
198 bufs = serialize_object(p)
210 canned = pickle.loads(bufs[0])
199 canned = pickle.loads(bufs[0])
211 yield nt.assert_true(isinstance(canned, point))
200 nt.assert_is_instance(canned, point)
212 p2, r = unserialize_object(bufs, globals())
201 p2, r = unserialize_object(bufs, globals())
213 yield nt.assert_equal(p2.x, p.x)
202 nt.assert_equal(p2.x, p.x)
214 yield nt.assert_equal(p2.y, p.y)
203 nt.assert_equal(p2.y, p.y)
215
204
216 @dec.parametric
217 def test_list():
205 def test_list():
218 lis = [lambda x:x, 1]
206 lis = [lambda x:x, 1]
219 bufs = serialize_object(lis)
207 bufs = serialize_object(lis)
220 canned = pickle.loads(bufs[0])
208 canned = pickle.loads(bufs[0])
221 yield nt.assert_true(isinstance(canned, list))
209 nt.assert_is_instance(canned, list)
222 l2, r = unserialize_object(bufs)
210 l2, r = unserialize_object(bufs)
223 yield nt.assert_equal(l2[0](l2[1]), lis[0](lis[1]))
211 nt.assert_equal(l2[0](l2[1]), lis[0](lis[1]))
224
212
225 @dec.parametric
226 def test_class_inheritance():
213 def test_class_inheritance():
227 @interactive
214 @interactive
228 class C(object):
215 class C(object):
@@ -234,8 +221,8 b' def test_class_inheritance():'
234
221
235 bufs = serialize_object(dict(D=D))
222 bufs = serialize_object(dict(D=D))
236 canned = pickle.loads(bufs[0])
223 canned = pickle.loads(bufs[0])
237 yield nt.assert_true(canned['D'], CannedClass)
224 nt.assert_is_instance(canned['D'], CannedClass)
238 d, r = unserialize_object(bufs)
225 d, r = unserialize_object(bufs)
239 D2 = d['D']
226 D2 = d['D']
240 yield nt.assert_equal(D2.a, D.a)
227 nt.assert_equal(D2.a, D.a)
241 yield nt.assert_equal(D2.b, D.b)
228 nt.assert_equal(D2.b, D.b)
@@ -39,7 +39,7 b' class TestAnsi(TestsBase):'
39 'hello' : 'hello'}
39 'hello' : 'hello'}
40
40
41 for inval, outval in correct_outputs.items():
41 for inval, outval in correct_outputs.items():
42 yield self._try_strip_ansi(inval, outval)
42 self._try_strip_ansi(inval, outval)
43
43
44
44
45 def _try_strip_ansi(self, inval, outval):
45 def _try_strip_ansi(self, inval, outval):
@@ -58,7 +58,7 b' class TestAnsi(TestsBase):'
58 'hello' : 'hello'}
58 'hello' : 'hello'}
59
59
60 for inval, outval in correct_outputs.items():
60 for inval, outval in correct_outputs.items():
61 yield self._try_ansi2html(inval, outval)
61 self._try_ansi2html(inval, outval)
62
62
63
63
64 def _try_ansi2html(self, inval, outval):
64 def _try_ansi2html(self, inval, outval):
@@ -77,7 +77,7 b' class TestAnsi(TestsBase):'
77 'hello' : 'hello'}
77 'hello' : 'hello'}
78
78
79 for inval, outval in correct_outputs.items():
79 for inval, outval in correct_outputs.items():
80 yield self._try_ansi2latex(inval, outval)
80 self._try_ansi2latex(inval, outval)
81
81
82
82
83 def _try_ansi2latex(self, inval, outval):
83 def _try_ansi2latex(self, inval, outval):
@@ -49,13 +49,13 b' class TestHighlight(TestsBase):'
49 def test_highlight2html(self):
49 def test_highlight2html(self):
50 """highlight2html test"""
50 """highlight2html test"""
51 for index, test in enumerate(self.tests):
51 for index, test in enumerate(self.tests):
52 yield self._try_highlight(highlight2html, test, self.tokens[index])
52 self._try_highlight(highlight2html, test, self.tokens[index])
53
53
54
54
55 def test_highlight2latex(self):
55 def test_highlight2latex(self):
56 """highlight2latex test"""
56 """highlight2latex test"""
57 for index, test in enumerate(self.tests):
57 for index, test in enumerate(self.tests):
58 yield self._try_highlight(highlight2latex, test, self.tokens[index])
58 self._try_highlight(highlight2latex, test, self.tokens[index])
59
59
60
60
61 def _try_highlight(self, method, test, tokens):
61 def _try_highlight(self, method, test, tokens):
@@ -35,7 +35,7 b' class TestLatex(TestsBase):'
35 ('','')]
35 ('','')]
36
36
37 for test in tests:
37 for test in tests:
38 yield self._try_escape_latex(test[0], test[1])
38 self._try_escape_latex(test[0], test[1])
39
39
40
40
41 def _try_escape_latex(self, test, result):
41 def _try_escape_latex(self, test, result):
@@ -56,7 +56,7 b' class TestLatex(TestsBase):'
56 ('','')]
56 ('','')]
57
57
58 for test in tests:
58 for test in tests:
59 yield self._try_strip_math_space(test[0], test[1])
59 self._try_strip_math_space(test[0], test[1])
60
60
61
61
62 def _try_strip_math_space(self, test, result):
62 def _try_strip_math_space(self, test, result):
@@ -61,14 +61,14 b' class TestMarkdown(TestsBase):'
61 def test_markdown2latex(self):
61 def test_markdown2latex(self):
62 """markdown2latex test"""
62 """markdown2latex test"""
63 for index, test in enumerate(self.tests):
63 for index, test in enumerate(self.tests):
64 yield self._try_markdown(markdown2latex, test, self.tokens[index])
64 self._try_markdown(markdown2latex, test, self.tokens[index])
65
65
66
66
67 @dec.onlyif_cmds_exist('pandoc')
67 @dec.onlyif_cmds_exist('pandoc')
68 def test_markdown2html(self):
68 def test_markdown2html(self):
69 """markdown2html test"""
69 """markdown2html test"""
70 for index, test in enumerate(self.tests):
70 for index, test in enumerate(self.tests):
71 yield self._try_markdown(markdown2html, test, self.tokens[index])
71 self._try_markdown(markdown2html, test, self.tokens[index])
72
72
73
73
74 @dec.onlyif_cmds_exist('pandoc')
74 @dec.onlyif_cmds_exist('pandoc')
@@ -81,7 +81,7 b' class TestMarkdown(TestsBase):'
81 tokens[1] = r'\*\*test'
81 tokens[1] = r'\*\*test'
82
82
83 for index, test in enumerate(self.tests):
83 for index, test in enumerate(self.tests):
84 yield self._try_markdown(markdown2rst, test, tokens[index])
84 self._try_markdown(markdown2rst, test, tokens[index])
85
85
86
86
87 def _try_markdown(self, method, test, tokens):
87 def _try_markdown(self, method, test, tokens):
@@ -15,7 +15,6 b' Module with tests for Strings'
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 import os
16 import os
17
17
18 from IPython.testing import decorators as dec
19 from ...tests.base import TestsBase
18 from ...tests.base import TestsBase
20 from ..strings import (wrap_text, html2text, add_anchor, strip_dollars,
19 from ..strings import (wrap_text, html2text, add_anchor, strip_dollars,
21 strip_files_prefix, get_lines, comment_lines, ipython2python, posix_path,
20 strip_files_prefix, get_lines, comment_lines, ipython2python, posix_path,
@@ -36,7 +35,7 b' class TestStrings(TestsBase):'
36 As if the strings were thine, shouldst know of this.
35 As if the strings were thine, shouldst know of this.
37 """
36 """
38 for length in [30,5,1]:
37 for length in [30,5,1]:
39 yield self._confirm_wrap_text(test_text, length)
38 self._confirm_wrap_text(test_text, length)
40
39
41
40
42 def _confirm_wrap_text(self, text, length):
41 def _confirm_wrap_text(self, text, length):
@@ -73,7 +72,7 b' class TestStrings(TestsBase):'
73 ('Hello', 'Hello'),
72 ('Hello', 'Hello'),
74 ('W$o$rld', 'W$o$rld')]
73 ('W$o$rld', 'W$o$rld')]
75 for test in tests:
74 for test in tests:
76 yield self._try_strip_dollars(test[0], test[1])
75 self._try_strip_dollars(test[0], test[1])
77
76
78
77
79 def _try_strip_dollars(self, test, result):
78 def _try_strip_dollars(self, test, result):
@@ -89,7 +88,7 b' class TestStrings(TestsBase):'
89 ('My files are in `files/`', 'My files are in `files/`'),
88 ('My files are in `files/`', 'My files are in `files/`'),
90 ('<a href="files/test.html">files/test.html</a>', '<a href="test.html">files/test.html</a>')]
89 ('<a href="files/test.html">files/test.html</a>', '<a href="test.html">files/test.html</a>')]
91 for test in tests:
90 for test in tests:
92 yield self._try_files_prefix(test[0], test[1])
91 self._try_files_prefix(test[0], test[1])
93
92
94
93
95 def _try_files_prefix(self, test, result):
94 def _try_files_prefix(self, test, result):
@@ -16,12 +16,12 b' Contains base test class for nbconvert'
16 import os
16 import os
17 import glob
17 import glob
18 import shutil
18 import shutil
19 import unittest
19
20
20 import IPython
21 import IPython
21 from IPython.utils.tempdir import TemporaryWorkingDirectory
22 from IPython.utils.tempdir import TemporaryWorkingDirectory
22 from IPython.utils.process import get_output_error_code
23 from IPython.utils.process import get_output_error_code
23 from IPython.testing.tools import get_ipython_cmd
24 from IPython.testing.tools import get_ipython_cmd
24 from IPython.testing.ipunittest import ParametricTestCase
25
25
26 # a trailing space allows for simpler concatenation with the other arguments
26 # a trailing space allows for simpler concatenation with the other arguments
27 ipy_cmd = get_ipython_cmd(as_string=True) + " "
27 ipy_cmd = get_ipython_cmd(as_string=True) + " "
@@ -31,7 +31,7 b' ipy_cmd = get_ipython_cmd(as_string=True) + " "'
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33
33
34 class TestsBase(ParametricTestCase):
34 class TestsBase(unittest.TestCase):
35 """Base tests class. Contains useful fuzzy comparison and nbconvert
35 """Base tests class. Contains useful fuzzy comparison and nbconvert
36 functions."""
36 functions."""
37
37
@@ -86,7 +86,7 b' class TestsBase(ParametricTestCase):'
86
86
87 For example:
87 For example:
88 Replace "ii" with "i" in the string "Hiiii" yields "Hii"
88 Replace "ii" with "i" in the string "Hiiii" yields "Hii"
89 Another replacement yields "Hi" (the desired output)
89 Another replacement cds "Hi" (the desired output)
90
90
91 Parameters:
91 Parameters:
92 -----------
92 -----------
@@ -17,20 +17,14 b' Authors:'
17 #-------------------------------------------------------------------------------
17 #-------------------------------------------------------------------------------
18
18
19 import re
19 import re
20 import sys
21 import time
20 import time
22
21
23 import zmq
24 from nose import SkipTest
25
22
26 from IPython.testing import decorators as dec
23 from IPython.testing import decorators as dec
27 from IPython.testing.ipunittest import ParametricTestCase
28 from IPython.utils.io import capture_output
24 from IPython.utils.io import capture_output
29
25
30 from IPython import parallel as pmod
26 from IPython import parallel as pmod
31 from IPython.parallel import error
32 from IPython.parallel import AsyncResult
27 from IPython.parallel import AsyncResult
33 from IPython.parallel.util import interactive
34
28
35 from IPython.parallel.tests import add_engines
29 from IPython.parallel.tests import add_engines
36
30
@@ -39,7 +33,7 b' from .clienttest import ClusterTestCase, generate_output'
39 def setup():
33 def setup():
40 add_engines(3, total=True)
34 add_engines(3, total=True)
41
35
42 class TestParallelMagics(ClusterTestCase, ParametricTestCase):
36 class TestParallelMagics(ClusterTestCase):
43
37
44 def test_px_blocking(self):
38 def test_px_blocking(self):
45 ip = get_ipython()
39 ip = get_ipython()
@@ -22,20 +22,16 b' import platform'
22 import time
22 import time
23 from collections import namedtuple
23 from collections import namedtuple
24 from tempfile import mktemp
24 from tempfile import mktemp
25 from StringIO import StringIO
26
25
27 import zmq
26 import zmq
28 from nose import SkipTest
29 from nose.plugins.attrib import attr
27 from nose.plugins.attrib import attr
30
28
31 from IPython.testing import decorators as dec
29 from IPython.testing import decorators as dec
32 from IPython.testing.ipunittest import ParametricTestCase
33 from IPython.utils.io import capture_output
30 from IPython.utils.io import capture_output
34
31
35 from IPython import parallel as pmod
32 from IPython import parallel as pmod
36 from IPython.parallel import error
33 from IPython.parallel import error
37 from IPython.parallel import AsyncResult, AsyncHubResult, AsyncMapResult
34 from IPython.parallel import AsyncResult, AsyncHubResult, AsyncMapResult
38 from IPython.parallel import DirectView
39 from IPython.parallel.util import interactive
35 from IPython.parallel.util import interactive
40
36
41 from IPython.parallel.tests import add_engines
37 from IPython.parallel.tests import add_engines
@@ -47,7 +43,7 b' def setup():'
47
43
48 point = namedtuple("point", "x y")
44 point = namedtuple("point", "x y")
49
45
50 class TestView(ClusterTestCase, ParametricTestCase):
46 class TestView(ClusterTestCase):
51
47
52 def setUp(self):
48 def setUp(self):
53 # On Win XP, wait for resource cleanup, else parallel test group fails
49 # On Win XP, wait for resource cleanup, else parallel test group fails
@@ -242,7 +238,7 b' class TestView(ClusterTestCase, ParametricTestCase):'
242 @skip_without('numpy')
238 @skip_without('numpy')
243 def test_scatter_gather_numpy(self):
239 def test_scatter_gather_numpy(self):
244 import numpy
240 import numpy
245 from numpy.testing.utils import assert_array_equal, assert_array_almost_equal
241 from numpy.testing.utils import assert_array_equal
246 view = self.client[:]
242 view = self.client[:]
247 a = numpy.arange(64)
243 a = numpy.arange(64)
248 view.scatter('a', a, block=True)
244 view.scatter('a', a, block=True)
@@ -280,7 +276,7 b' class TestView(ClusterTestCase, ParametricTestCase):'
280 def test_apply_numpy(self):
276 def test_apply_numpy(self):
281 """view.apply(f, ndarray)"""
277 """view.apply(f, ndarray)"""
282 import numpy
278 import numpy
283 from numpy.testing.utils import assert_array_equal, assert_array_almost_equal
279 from numpy.testing.utils import assert_array_equal
284
280
285 A = numpy.random.random((100,100))
281 A = numpy.random.random((100,100))
286 view = self.client[-1]
282 view = self.client[-1]
@@ -368,7 +364,7 b' class TestView(ClusterTestCase, ParametricTestCase):'
368 @skip_without('numpy')
364 @skip_without('numpy')
369 def test_scatter_gather_numpy_nonblocking(self):
365 def test_scatter_gather_numpy_nonblocking(self):
370 import numpy
366 import numpy
371 from numpy.testing.utils import assert_array_equal, assert_array_almost_equal
367 from numpy.testing.utils import assert_array_equal
372 a = numpy.arange(64)
368 a = numpy.arange(64)
373 view = self.client[:]
369 view = self.client[:]
374 ar = view.scatter('a', a, block=False)
370 ar = view.scatter('a', a, block=False)
@@ -512,19 +508,17 b' class TestView(ClusterTestCase, ParametricTestCase):'
512 def test_len(self):
508 def test_len(self):
513 """len(view) makes sense"""
509 """len(view) makes sense"""
514 e0 = self.client[self.client.ids[0]]
510 e0 = self.client[self.client.ids[0]]
515 yield self.assertEqual(len(e0), 1)
511 self.assertEqual(len(e0), 1)
516 v = self.client[:]
512 v = self.client[:]
517 yield self.assertEqual(len(v), len(self.client.ids))
513 self.assertEqual(len(v), len(self.client.ids))
518 v = self.client.direct_view('all')
514 v = self.client.direct_view('all')
519 yield self.assertEqual(len(v), len(self.client.ids))
515 self.assertEqual(len(v), len(self.client.ids))
520 v = self.client[:2]
516 v = self.client[:2]
521 yield self.assertEqual(len(v), 2)
517 self.assertEqual(len(v), 2)
522 v = self.client[:1]
518 v = self.client[:1]
523 yield self.assertEqual(len(v), 1)
519 self.assertEqual(len(v), 1)
524 v = self.client.load_balanced_view()
520 v = self.client.load_balanced_view()
525 yield self.assertEqual(len(v), len(self.client.ids))
521 self.assertEqual(len(v), len(self.client.ids))
526 # parametric tests seem to require manual closing?
527 self.client.close()
528
522
529
523
530 # begin execute tests
524 # begin execute tests
@@ -16,10 +16,6 b' Included decorators:'
16
16
17 Lightweight testing that remains unittest-compatible.
17 Lightweight testing that remains unittest-compatible.
18
18
19 - @parametric, for parametric test support that is vastly easier to use than
20 nose's for debugging. With ours, if a test fails, the stack under inspection
21 is that of the test and not that of the test framework.
22
23 - An @as_unittest decorator can be used to tag any normal parameter-less
19 - An @as_unittest decorator can be used to tag any normal parameter-less
24 function as a unittest TestCase. Then, both nose and normal unittest will
20 function as a unittest TestCase. Then, both nose and normal unittest will
25 recognize it as such. This will make it easier to migrate away from Nose if
21 recognize it as such. This will make it easier to migrate away from Nose if
@@ -58,12 +54,6 b' import unittest'
58 # This is Michele Simionato's decorator module, kept verbatim.
54 # This is Michele Simionato's decorator module, kept verbatim.
59 from IPython.external.decorator import decorator
55 from IPython.external.decorator import decorator
60
56
61 # We already have python3-compliant code for parametric tests
62 if sys.version[0]=='2':
63 from _paramtestpy2 import parametric
64 else:
65 from _paramtestpy3 import parametric
66
67 # Expose the unittest-driven decorators
57 # Expose the unittest-driven decorators
68 from ipunittest import ipdoctest, ipdocstring
58 from ipunittest import ipdoctest, ipdocstring
69
59
@@ -37,16 +37,9 b' from __future__ import absolute_import'
37
37
38 # Stdlib
38 # Stdlib
39 import re
39 import re
40 import sys
41 import unittest
40 import unittest
42 from doctest import DocTestFinder, DocTestRunner, TestResults
41 from doctest import DocTestFinder, DocTestRunner, TestResults
43
42
44 # We already have python3-compliant code for parametric tests
45 if sys.version[0]=='2':
46 from ._paramtestpy2 import ParametricTestCase
47 else:
48 from ._paramtestpy3 import ParametricTestCase
49
50 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
51 # Classes and functions
44 # Classes and functions
52 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
@@ -12,7 +12,6 b' import nose.tools as nt'
12 # Our own
12 # Our own
13 from IPython.testing import decorators as dec
13 from IPython.testing import decorators as dec
14 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.testing.skipdoctest import skip_doctest
15 from IPython.testing.ipunittest import ParametricTestCase
16
15
17 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
18 # Utilities
17 # Utilities
@@ -47,24 +46,6 b' def trivial():'
47 """A trivial test"""
46 """A trivial test"""
48 pass
47 pass
49
48
50 # Some examples of parametric tests.
51
52 def is_smaller(i,j):
53 assert i<j,"%s !< %s" % (i,j)
54
55 class Tester(ParametricTestCase):
56
57 def test_parametric(self):
58 yield is_smaller(3, 4)
59 x, y = 1, 2
60 yield is_smaller(x, y)
61
62 @dec.parametric
63 def test_par_standalone():
64 yield is_smaller(3, 4)
65 x, y = 1, 2
66 yield is_smaller(x, y)
67
68
49
69 @dec.skip
50 @dec.skip
70 def test_deliberately_broken():
51 def test_deliberately_broken():
@@ -51,26 +51,24 b' def test_full_path_win32():'
51 nt.assert_equal(result, ['c:\\a.txt'])
51 nt.assert_equal(result, ['c:\\a.txt'])
52
52
53
53
54 @dec.parametric
55 def test_parser():
54 def test_parser():
56 err = ("FAILED (errors=1)", 1, 0)
55 err = ("FAILED (errors=1)", 1, 0)
57 fail = ("FAILED (failures=1)", 0, 1)
56 fail = ("FAILED (failures=1)", 0, 1)
58 both = ("FAILED (errors=1, failures=1)", 1, 1)
57 both = ("FAILED (errors=1, failures=1)", 1, 1)
59 for txt, nerr, nfail in [err, fail, both]:
58 for txt, nerr, nfail in [err, fail, both]:
60 nerr1, nfail1 = tt.parse_test_output(txt)
59 nerr1, nfail1 = tt.parse_test_output(txt)
61 yield nt.assert_equal(nerr, nerr1)
60 nt.assert_equal(nerr, nerr1)
62 yield nt.assert_equal(nfail, nfail1)
61 nt.assert_equal(nfail, nfail1)
62
63
63
64
65 @dec.parametric
66 def test_temp_pyfile():
64 def test_temp_pyfile():
67 src = 'pass\n'
65 src = 'pass\n'
68 fname, fh = tt.temp_pyfile(src)
66 fname, fh = tt.temp_pyfile(src)
69 yield nt.assert_true(os.path.isfile(fname))
67 assert os.path.isfile(fname)
70 fh.close()
68 fh.close()
71 with open(fname) as fh2:
69 with open(fname) as fh2:
72 src2 = fh2.read()
70 src2 = fh2.read()
73 yield nt.assert_equal(src2, src)
71 nt.assert_equal(src2, src)
74
72
75 class TestAssertPrints(unittest.TestCase):
73 class TestAssertPrints(unittest.TestCase):
76 def test_passing(self):
74 def test_passing(self):
@@ -17,10 +17,10 b' import sys'
17
17
18 from StringIO import StringIO
18 from StringIO import StringIO
19 from subprocess import Popen, PIPE
19 from subprocess import Popen, PIPE
20 import unittest
20
21
21 import nose.tools as nt
22 import nose.tools as nt
22
23
23 from IPython.testing.ipunittest import ParametricTestCase
24 from IPython.utils.io import Tee, capture_output
24 from IPython.utils.io import Tee, capture_output
25 from IPython.utils.py3compat import doctest_refactor_print
25 from IPython.utils.py3compat import doctest_refactor_print
26
26
@@ -38,7 +38,7 b' def test_tee_simple():'
38 nt.assert_equal(chan.getvalue(), text+"\n")
38 nt.assert_equal(chan.getvalue(), text+"\n")
39
39
40
40
41 class TeeTestCase(ParametricTestCase):
41 class TeeTestCase(unittest.TestCase):
42
42
43 def tchan(self, channel, check='close'):
43 def tchan(self, channel, check='close'):
44 trap = StringIO()
44 trap = StringIO()
@@ -61,7 +61,7 b' class TeeTestCase(ParametricTestCase):'
61 def test(self):
61 def test(self):
62 for chan in ['stdout', 'stderr']:
62 for chan in ['stdout', 'stderr']:
63 for check in ['close', 'del']:
63 for check in ['close', 'del']:
64 yield self.tchan(chan, check)
64 self.tchan(chan, check)
65
65
66 def test_io_init():
66 def test_io_init():
67 """Test that io.stdin/out/err exist at startup"""
67 """Test that io.stdin/out/err exist at startup"""
@@ -19,7 +19,6 b' from base64 import decodestring'
19 import nose.tools as nt
19 import nose.tools as nt
20
20
21 # our own
21 # our own
22 from IPython.testing import decorators as dec
23 from IPython.utils import jsonutil, tz
22 from IPython.utils import jsonutil, tz
24 from ..jsonutil import json_clean, encode_images
23 from ..jsonutil import json_clean, encode_images
25 from ..py3compat import unicode_to_str, str_to_bytes
24 from ..py3compat import unicode_to_str, str_to_bytes
@@ -62,7 +61,6 b' def test():'
62
61
63
62
64
63
65 @dec.parametric
66 def test_encode_images():
64 def test_encode_images():
67 # invalid data, but the header and footer are from real files
65 # invalid data, but the header and footer are from real files
68 pngdata = b'\x89PNG\r\n\x1a\nblahblahnotactuallyvalidIEND\xaeB`\x82'
66 pngdata = b'\x89PNG\r\n\x1a\nblahblahnotactuallyvalidIEND\xaeB`\x82'
@@ -76,19 +74,19 b' def test_encode_images():'
76 for key, value in fmt.iteritems():
74 for key, value in fmt.iteritems():
77 # encoded has unicode, want bytes
75 # encoded has unicode, want bytes
78 decoded = decodestring(encoded[key].encode('ascii'))
76 decoded = decodestring(encoded[key].encode('ascii'))
79 yield nt.assert_equal(decoded, value)
77 nt.assert_equal(decoded, value)
80 encoded2 = encode_images(encoded)
78 encoded2 = encode_images(encoded)
81 yield nt.assert_equal(encoded, encoded2)
79 nt.assert_equal(encoded, encoded2)
82
80
83 b64_str = {}
81 b64_str = {}
84 for key, encoded in encoded.iteritems():
82 for key, encoded in encoded.iteritems():
85 b64_str[key] = unicode_to_str(encoded)
83 b64_str[key] = unicode_to_str(encoded)
86 encoded3 = encode_images(b64_str)
84 encoded3 = encode_images(b64_str)
87 yield nt.assert_equal(encoded3, b64_str)
85 nt.assert_equal(encoded3, b64_str)
88 for key, value in fmt.iteritems():
86 for key, value in fmt.iteritems():
89 # encoded3 has str, want bytes
87 # encoded3 has str, want bytes
90 decoded = decodestring(str_to_bytes(encoded3[key]))
88 decoded = decodestring(str_to_bytes(encoded3[key]))
91 yield nt.assert_equal(decoded, value)
89 nt.assert_equal(decoded, value)
92
90
93 def test_lambda():
91 def test_lambda():
94 jc = json_clean(lambda : 1)
92 jc = json_clean(lambda : 1)
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now