##// END OF EJS Templates
Remove uses of @parametric decorator
Thomas Kluyver -
Show More
@@ -1,121 +1,118 b''
1 #-----------------------------------------------------------------------------
1 #-----------------------------------------------------------------------------
2 # Copyright (C) 2010-2011, IPython Development Team.
2 # Copyright (C) 2010-2011, IPython Development Team.
3 #
3 #
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5 #
5 #
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()
18 @argument('-f', '--foo', help="an argument")
17 @argument('-f', '--foo', help="an argument")
19 def magic_foo1(self, args):
18 def magic_foo1(self, args):
20 """ A docstring.
19 """ A docstring.
21 """
20 """
22 return parse_argstring(magic_foo1, args)
21 return parse_argstring(magic_foo1, args)
23
22
24
23
25 @magic_arguments()
24 @magic_arguments()
26 def magic_foo2(self, args):
25 def magic_foo2(self, args):
27 """ A docstring.
26 """ A docstring.
28 """
27 """
29 return parse_argstring(magic_foo2, args)
28 return parse_argstring(magic_foo2, args)
30
29
31
30
32 @magic_arguments()
31 @magic_arguments()
33 @argument('-f', '--foo', help="an argument")
32 @argument('-f', '--foo', help="an argument")
34 @argument_group('Group')
33 @argument_group('Group')
35 @argument('-b', '--bar', help="a grouped argument")
34 @argument('-b', '--bar', help="a grouped argument")
36 @argument_group('Second Group')
35 @argument_group('Second Group')
37 @argument('-z', '--baz', help="another grouped argument")
36 @argument('-z', '--baz', help="another grouped argument")
38 def magic_foo3(self, args):
37 def magic_foo3(self, args):
39 """ A docstring.
38 """ A docstring.
40 """
39 """
41 return parse_argstring(magic_foo3, args)
40 return parse_argstring(magic_foo3, args)
42
41
43
42
44 @magic_arguments()
43 @magic_arguments()
45 @kwds(argument_default=argparse.SUPPRESS)
44 @kwds(argument_default=argparse.SUPPRESS)
46 @argument('-f', '--foo', help="an argument")
45 @argument('-f', '--foo', help="an argument")
47 def magic_foo4(self, args):
46 def magic_foo4(self, args):
48 """ A docstring.
47 """ A docstring.
49 """
48 """
50 return parse_argstring(magic_foo4, args)
49 return parse_argstring(magic_foo4, args)
51
50
52
51
53 @magic_arguments('frobnicate')
52 @magic_arguments('frobnicate')
54 @argument('-f', '--foo', help="an argument")
53 @argument('-f', '--foo', help="an argument")
55 def magic_foo5(self, args):
54 def magic_foo5(self, args):
56 """ A docstring.
55 """ A docstring.
57 """
56 """
58 return parse_argstring(magic_foo5, args)
57 return parse_argstring(magic_foo5, args)
59
58
60
59
61 @magic_arguments()
60 @magic_arguments()
62 @argument('-f', '--foo', help="an argument")
61 @argument('-f', '--foo', help="an argument")
63 def magic_magic_foo(self, args):
62 def magic_magic_foo(self, args):
64 """ A docstring.
63 """ A docstring.
65 """
64 """
66 return parse_argstring(magic_magic_foo, args)
65 return parse_argstring(magic_magic_foo, args)
67
66
68
67
69 @magic_arguments()
68 @magic_arguments()
70 @argument('-f', '--foo', help="an argument")
69 @argument('-f', '--foo', help="an argument")
71 def foo(self, args):
70 def foo(self, args):
72 """ A docstring.
71 """ A docstring.
73 """
72 """
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')
@@ -1,99 +1,96 b''
1 """Tests for input manipulation machinery."""
1 """Tests for input manipulation machinery."""
2
2
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Imports
4 # Imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
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
9 from IPython.testing import decorators as dec
10 from IPython.testing.globalipapp import get_ipython
10 from IPython.testing.globalipapp import get_ipython
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Tests
13 # Tests
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 ip = get_ipython()
15 ip = get_ipython()
16
16
17 @dec.parametric
18 def test_prefilter():
17 def test_prefilter():
19 """Test user input conversions"""
18 """Test user input conversions"""
20
19
21 # pairs of (raw, expected correct) input
20 # pairs of (raw, expected correct) input
22 pairs = [ ('2+2','2+2'),
21 pairs = [ ('2+2','2+2'),
23 ]
22 ]
24
23
25 for raw, correct in pairs:
24 for raw, correct in pairs:
26 yield nt.assert_equal(ip.prefilter(raw), correct)
25 nt.assert_equal(ip.prefilter(raw), correct)
27
26
28
27
29 @dec.parametric
30 def test_autocall_binops():
28 def test_autocall_binops():
31 """See https://github.com/ipython/ipython/issues/81"""
29 """See https://github.com/ipython/ipython/issues/81"""
32 ip.magic('autocall 2')
30 ip.magic('autocall 2')
33 f = lambda x: x
31 f = lambda x: x
34 ip.user_ns['f'] = f
32 ip.user_ns['f'] = f
35 try:
33 try:
36 yield nt.assert_equal(ip.prefilter('f 1'),'f(1)')
34 nt.assert_equal(ip.prefilter('f 1'),'f(1)')
37 for t in ['f +1', 'f -1']:
35 for t in ['f +1', 'f -1']:
38 yield nt.assert_equal(ip.prefilter(t), t)
36 nt.assert_equal(ip.prefilter(t), t)
39
37
40 # Run tests again with a more permissive exclude_regexp, which will
38 # Run tests again with a more permissive exclude_regexp, which will
41 # allow transformation of binary operations ('f -1' -> 'f(-1)').
39 # allow transformation of binary operations ('f -1' -> 'f(-1)').
42 pm = ip.prefilter_manager
40 pm = ip.prefilter_manager
43 ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm,
41 ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm,
44 config=pm.config)
42 config=pm.config)
45 try:
43 try:
46 ac.priority = 1
44 ac.priority = 1
47 ac.exclude_regexp = r'^[,&^\|\*/]|^is |^not |^in |^and |^or '
45 ac.exclude_regexp = r'^[,&^\|\*/]|^is |^not |^in |^and |^or '
48 pm.sort_checkers()
46 pm.sort_checkers()
49
47
50 yield nt.assert_equal(ip.prefilter('f -1'), 'f(-1)')
48 nt.assert_equal(ip.prefilter('f -1'), 'f(-1)')
51 yield nt.assert_equal(ip.prefilter('f +1'), 'f(+1)')
49 nt.assert_equal(ip.prefilter('f +1'), 'f(+1)')
52 finally:
50 finally:
53 pm.unregister_checker(ac)
51 pm.unregister_checker(ac)
54 finally:
52 finally:
55 ip.magic('autocall 0')
53 ip.magic('autocall 0')
56 del ip.user_ns['f']
54 del ip.user_ns['f']
57
55
58
56
59 @dec.parametric
60 def test_issue_114():
57 def test_issue_114():
61 """Check that multiline string literals don't expand as magic
58 """Check that multiline string literals don't expand as magic
62 see http://github.com/ipython/ipython/issues/114"""
59 see http://github.com/ipython/ipython/issues/114"""
63
60
64 template = '"""\n%s\n"""'
61 template = '"""\n%s\n"""'
65 # Store the current value of multi_line_specials and turn it off before
62 # Store the current value of multi_line_specials and turn it off before
66 # running test, since it could be true (case in which the test doesn't make
63 # running test, since it could be true (case in which the test doesn't make
67 # sense, as multiline string literals *will* expand as magic in that case).
64 # sense, as multiline string literals *will* expand as magic in that case).
68 msp = ip.prefilter_manager.multi_line_specials
65 msp = ip.prefilter_manager.multi_line_specials
69 ip.prefilter_manager.multi_line_specials = False
66 ip.prefilter_manager.multi_line_specials = False
70 try:
67 try:
71 for mgk in ip.magics_manager.lsmagic()['line']:
68 for mgk in ip.magics_manager.lsmagic()['line']:
72 raw = template % mgk
69 raw = template % mgk
73 yield nt.assert_equal(ip.prefilter(raw), raw)
70 nt.assert_equal(ip.prefilter(raw), raw)
74 finally:
71 finally:
75 ip.prefilter_manager.multi_line_specials = msp
72 ip.prefilter_manager.multi_line_specials = msp
76
73
77
74
78 def test_prefilter_attribute_errors():
75 def test_prefilter_attribute_errors():
79 """Capture exceptions thrown by user objects on attribute access.
76 """Capture exceptions thrown by user objects on attribute access.
80
77
81 See http://github.com/ipython/ipython/issues/988."""
78 See http://github.com/ipython/ipython/issues/988."""
82
79
83 class X(object):
80 class X(object):
84 def __getattr__(self, k):
81 def __getattr__(self, k):
85 raise ValueError('broken object')
82 raise ValueError('broken object')
86 def __call__(self, x):
83 def __call__(self, x):
87 return x
84 return x
88
85
89 # Create a callable broken object
86 # Create a callable broken object
90 ip.user_ns['x'] = X()
87 ip.user_ns['x'] = X()
91 ip.magic('autocall 2')
88 ip.magic('autocall 2')
92 try:
89 try:
93 # Even if x throws an attribute error when looking at its rewrite
90 # Even if x throws an attribute error when looking at its rewrite
94 # attribute, we should not crash. So the test here is simply making
91 # attribute, we should not crash. So the test here is simply making
95 # the prefilter call and not having an exception.
92 # the prefilter call and not having an exception.
96 ip.prefilter('x 1')
93 ip.prefilter('x 1')
97 finally:
94 finally:
98 del ip.user_ns['x']
95 del ip.user_ns['x']
99 ip.magic('autocall 0')
96 ip.magic('autocall 0')
@@ -1,140 +1,138 b''
1 """Tests for pylab tools module.
1 """Tests for pylab tools module.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2011, the IPython Development Team.
4 # Copyright (c) 2011, the IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
14 from __future__ import print_function
15
15
16 # Stdlib imports
16 # Stdlib imports
17
17
18 # Third-party imports
18 # Third-party imports
19 import matplotlib; matplotlib.use('Agg')
19 import matplotlib; matplotlib.use('Agg')
20 import nose.tools as nt
20 import nose.tools as nt
21
21
22 from matplotlib import pyplot as plt
22 from matplotlib import pyplot as plt
23 import numpy as np
23 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 #-----------------------------------------------------------------------------
31 # Globals and constants
30 # Globals and constants
32 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
33
32
34 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
35 # Local utilities
34 # Local utilities
36 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
37
36
38 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
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
50 # simple check for at least svg-looking output
48 # simple check for at least svg-looking output
51 fig = plt.figure()
49 fig = plt.figure()
52 ax = fig.add_subplot(1,1,1)
50 ax = fig.add_subplot(1,1,1)
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():
60 ip = get_ipython()
58 ip = get_ipython()
61 ns = {}
59 ns = {}
62 pt.import_pylab(ns, import_all=False)
60 pt.import_pylab(ns, import_all=False)
63 nt.assert_true('plt' in ns)
61 nt.assert_true('plt' in ns)
64 nt.assert_equal(ns['np'], np)
62 nt.assert_equal(ns['np'], np)
65
63
66 class TestPylabSwitch(object):
64 class TestPylabSwitch(object):
67 class Shell(InteractiveShell):
65 class Shell(InteractiveShell):
68 def enable_gui(self, gui):
66 def enable_gui(self, gui):
69 pass
67 pass
70
68
71 def setup(self):
69 def setup(self):
72 import matplotlib
70 import matplotlib
73 def act_mpl(backend):
71 def act_mpl(backend):
74 matplotlib.rcParams['backend'] = backend
72 matplotlib.rcParams['backend'] = backend
75
73
76 # Save rcParams since they get modified
74 # Save rcParams since they get modified
77 self._saved_rcParams = matplotlib.rcParams
75 self._saved_rcParams = matplotlib.rcParams
78 matplotlib.rcParams = dict(backend='Qt4Agg')
76 matplotlib.rcParams = dict(backend='Qt4Agg')
79
77
80 # Mock out functions
78 # Mock out functions
81 self._save_am = pt.activate_matplotlib
79 self._save_am = pt.activate_matplotlib
82 pt.activate_matplotlib = act_mpl
80 pt.activate_matplotlib = act_mpl
83 self._save_ip = pt.import_pylab
81 self._save_ip = pt.import_pylab
84 pt.import_pylab = lambda *a,**kw:None
82 pt.import_pylab = lambda *a,**kw:None
85 self._save_cis = pt.configure_inline_support
83 self._save_cis = pt.configure_inline_support
86 pt.configure_inline_support = lambda *a,**kw:None
84 pt.configure_inline_support = lambda *a,**kw:None
87
85
88 def teardown(self):
86 def teardown(self):
89 pt.activate_matplotlib = self._save_am
87 pt.activate_matplotlib = self._save_am
90 pt.import_pylab = self._save_ip
88 pt.import_pylab = self._save_ip
91 pt.configure_inline_support = self._save_cis
89 pt.configure_inline_support = self._save_cis
92 import matplotlib
90 import matplotlib
93 matplotlib.rcParams = self._saved_rcParams
91 matplotlib.rcParams = self._saved_rcParams
94
92
95 def test_qt(self):
93 def test_qt(self):
96 s = self.Shell()
94 s = self.Shell()
97 gui, backend = s.enable_matplotlib(None)
95 gui, backend = s.enable_matplotlib(None)
98 nt.assert_equal(gui, 'qt')
96 nt.assert_equal(gui, 'qt')
99 nt.assert_equal(s.pylab_gui_select, 'qt')
97 nt.assert_equal(s.pylab_gui_select, 'qt')
100
98
101 gui, backend = s.enable_matplotlib('inline')
99 gui, backend = s.enable_matplotlib('inline')
102 nt.assert_equal(gui, 'inline')
100 nt.assert_equal(gui, 'inline')
103 nt.assert_equal(s.pylab_gui_select, 'qt')
101 nt.assert_equal(s.pylab_gui_select, 'qt')
104
102
105 gui, backend = s.enable_matplotlib('qt')
103 gui, backend = s.enable_matplotlib('qt')
106 nt.assert_equal(gui, 'qt')
104 nt.assert_equal(gui, 'qt')
107 nt.assert_equal(s.pylab_gui_select, 'qt')
105 nt.assert_equal(s.pylab_gui_select, 'qt')
108
106
109 gui, backend = s.enable_matplotlib('inline')
107 gui, backend = s.enable_matplotlib('inline')
110 nt.assert_equal(gui, 'inline')
108 nt.assert_equal(gui, 'inline')
111 nt.assert_equal(s.pylab_gui_select, 'qt')
109 nt.assert_equal(s.pylab_gui_select, 'qt')
112
110
113 gui, backend = s.enable_matplotlib()
111 gui, backend = s.enable_matplotlib()
114 nt.assert_equal(gui, 'qt')
112 nt.assert_equal(gui, 'qt')
115 nt.assert_equal(s.pylab_gui_select, 'qt')
113 nt.assert_equal(s.pylab_gui_select, 'qt')
116
114
117 def test_inline(self):
115 def test_inline(self):
118 s = self.Shell()
116 s = self.Shell()
119 gui, backend = s.enable_matplotlib('inline')
117 gui, backend = s.enable_matplotlib('inline')
120 nt.assert_equal(gui, 'inline')
118 nt.assert_equal(gui, 'inline')
121 nt.assert_equal(s.pylab_gui_select, None)
119 nt.assert_equal(s.pylab_gui_select, None)
122
120
123 gui, backend = s.enable_matplotlib('inline')
121 gui, backend = s.enable_matplotlib('inline')
124 nt.assert_equal(gui, 'inline')
122 nt.assert_equal(gui, 'inline')
125 nt.assert_equal(s.pylab_gui_select, None)
123 nt.assert_equal(s.pylab_gui_select, None)
126
124
127 gui, backend = s.enable_matplotlib('qt')
125 gui, backend = s.enable_matplotlib('qt')
128 nt.assert_equal(gui, 'qt')
126 nt.assert_equal(gui, 'qt')
129 nt.assert_equal(s.pylab_gui_select, 'qt')
127 nt.assert_equal(s.pylab_gui_select, 'qt')
130
128
131 def test_qt_gtk(self):
129 def test_qt_gtk(self):
132 s = self.Shell()
130 s = self.Shell()
133 gui, backend = s.enable_matplotlib('qt')
131 gui, backend = s.enable_matplotlib('qt')
134 nt.assert_equal(gui, 'qt')
132 nt.assert_equal(gui, 'qt')
135 nt.assert_equal(s.pylab_gui_select, 'qt')
133 nt.assert_equal(s.pylab_gui_select, 'qt')
136
134
137 gui, backend = s.enable_matplotlib('gtk')
135 gui, backend = s.enable_matplotlib('gtk')
138 nt.assert_equal(gui, 'qt')
136 nt.assert_equal(gui, 'qt')
139 nt.assert_equal(s.pylab_gui_select, 'qt')
137 nt.assert_equal(s.pylab_gui_select, 'qt')
140
138
@@ -1,60 +1,59 b''
1 """Tests for kernel utility functions
1 """Tests for kernel utility functions
2
2
3 Authors
3 Authors
4 -------
4 -------
5 * MinRK
5 * MinRK
6 """
6 """
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (c) 2011, the IPython Development Team.
8 # Copyright (c) 2011, the IPython Development Team.
9 #
9 #
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11 #
11 #
12 # The full license is in the file COPYING.txt, distributed with this software.
12 # The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 # Third-party imports
19 # Third-party imports
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
23 from IPython.testing import decorators as dec
24 from IPython.kernel.launcher import swallow_argv
24 from IPython.kernel.launcher import swallow_argv
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Classes and functions
27 # Classes and functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 @dec.parametric
31 def test_swallow_argv():
30 def test_swallow_argv():
32 tests = [
31 tests = [
33 # expected , argv , aliases, flags
32 # expected , argv , aliases, flags
34 (['-a', '5'], ['-a', '5'], None, None),
33 (['-a', '5'], ['-a', '5'], None, None),
35 (['5'], ['-a', '5'], None, ['a']),
34 (['5'], ['-a', '5'], None, ['a']),
36 ([], ['-a', '5'], ['a'], None),
35 ([], ['-a', '5'], ['a'], None),
37 ([], ['-a', '5'], ['a'], ['a']),
36 ([], ['-a', '5'], ['a'], ['a']),
38 ([], ['--foo'], None, ['foo']),
37 ([], ['--foo'], None, ['foo']),
39 ([], ['--foo'], ['foobar'], []),
38 ([], ['--foo'], ['foobar'], []),
40 ([], ['--foo', '5'], ['foo'], []),
39 ([], ['--foo', '5'], ['foo'], []),
41 ([], ['--foo=5'], ['foo'], []),
40 ([], ['--foo=5'], ['foo'], []),
42 (['--foo=5'], ['--foo=5'], [], ['foo']),
41 (['--foo=5'], ['--foo=5'], [], ['foo']),
43 (['5'], ['--foo', '5'], [], ['foo']),
42 (['5'], ['--foo', '5'], [], ['foo']),
44 (['bar'], ['--foo', '5', 'bar'], ['foo'], ['foo']),
43 (['bar'], ['--foo', '5', 'bar'], ['foo'], ['foo']),
45 (['bar'], ['--foo=5', 'bar'], ['foo'], ['foo']),
44 (['bar'], ['--foo=5', 'bar'], ['foo'], ['foo']),
46 (['5','bar'], ['--foo', '5', 'bar'], None, ['foo']),
45 (['5','bar'], ['--foo', '5', 'bar'], None, ['foo']),
47 (['bar'], ['--foo', '5', 'bar'], ['foo'], None),
46 (['bar'], ['--foo', '5', 'bar'], ['foo'], None),
48 (['bar'], ['--foo=5', 'bar'], ['foo'], None),
47 (['bar'], ['--foo=5', 'bar'], ['foo'], None),
49 ]
48 ]
50 for expected, argv, aliases, flags in tests:
49 for expected, argv, aliases, flags in tests:
51 stripped = swallow_argv(argv, aliases=aliases, flags=flags)
50 stripped = swallow_argv(argv, aliases=aliases, flags=flags)
52 message = '\n'.join(['',
51 message = '\n'.join(['',
53 "argv: %r" % argv,
52 "argv: %r" % argv,
54 "aliases: %r" % aliases,
53 "aliases: %r" % aliases,
55 "flags : %r" % flags,
54 "flags : %r" % flags,
56 "expected : %r" % expected,
55 "expected : %r" % expected,
57 "returned : %r" % stripped,
56 "returned : %r" % stripped,
58 ])
57 ])
59 yield nt.assert_equal(expected, stripped, message)
58 nt.assert_equal(expected, stripped, message)
60
59
@@ -1,516 +1,484 b''
1 """Test suite for our zeromq-based messaging specification.
1 """Test suite for our zeromq-based messaging specification.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (C) 2010-2011 The IPython Development Team
4 # Copyright (C) 2010-2011 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.txt, distributed as part of this software.
7 # the file COPYING.txt, distributed as part of this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 import re
10 import re
11 from subprocess import PIPE
11 from subprocess import PIPE
12 from Queue import Empty
12 from Queue import Empty
13
13
14 import nose.tools as nt
14 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 )
22
21
23 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
24 # Global setup and utilities
23 # Global setup and utilities
25 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
26
25
27 STARTUP_TIMEOUT = 60
26 STARTUP_TIMEOUT = 60
28 TIMEOUT = 15
27 TIMEOUT = 15
29
28
30 def setup():
29 def setup():
31 global KM, KC
30 global KM, KC
32 KM = KernelManager()
31 KM = KernelManager()
33 KM.start_kernel(stdout=PIPE, stderr=PIPE)
32 KM.start_kernel(stdout=PIPE, stderr=PIPE)
34 KC = KM.client()
33 KC = KM.client()
35 KC.start_channels()
34 KC.start_channels()
36
35
37 # wait for kernel to be ready
36 # wait for kernel to be ready
38 try:
37 try:
39 msg = KC.iopub_channel.get_msg(block=True, timeout=STARTUP_TIMEOUT)
38 msg = KC.iopub_channel.get_msg(block=True, timeout=STARTUP_TIMEOUT)
40 except Empty:
39 except Empty:
41 pass
40 pass
42 msg_id = KC.kernel_info()
41 msg_id = KC.kernel_info()
43 KC.get_shell_msg(block=True, timeout=STARTUP_TIMEOUT)
42 KC.get_shell_msg(block=True, timeout=STARTUP_TIMEOUT)
44 flush_channels()
43 flush_channels()
45
44
46
45
47 def teardown():
46 def teardown():
48 KC.stop_channels()
47 KC.stop_channels()
49 KM.shutdown_kernel()
48 KM.shutdown_kernel()
50
49
51
50
52 def flush_channels(kc=None):
51 def flush_channels(kc=None):
53 """flush any messages waiting on the queue"""
52 """flush any messages waiting on the queue"""
54 if kc is None:
53 if kc is None:
55 kc = KC
54 kc = KC
56 for channel in (kc.shell_channel, kc.iopub_channel):
55 for channel in (kc.shell_channel, kc.iopub_channel):
57 while True:
56 while True:
58 try:
57 try:
59 msg = channel.get_msg(block=True, timeout=0.1)
58 msg = channel.get_msg(block=True, timeout=0.1)
60 except Empty:
59 except Empty:
61 break
60 break
62 else:
61 else:
63 list(validate_message(msg))
62 list(validate_message(msg))
64
63
65
64
66 def execute(code='', kc=None, **kwargs):
65 def execute(code='', kc=None, **kwargs):
67 """wrapper for doing common steps for validating an execution request"""
66 """wrapper for doing common steps for validating an execution request"""
68 if kc is None:
67 if kc is None:
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 list(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 list(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 list(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']
83
82
84 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
85 # MSG Spec References
84 # MSG Spec References
86 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
87
86
88
87
89 class Reference(HasTraits):
88 class Reference(HasTraits):
90
89
91 """
90 """
92 Base class for message spec specification testing.
91 Base class for message spec specification testing.
93
92
94 This class is the core of the message specification test. The
93 This class is the core of the message specification test. The
95 idea is that child classes implement trait attributes for each
94 idea is that child classes implement trait attributes for each
96 message keys, so that message keys can be tested against these
95 message keys, so that message keys can be tested against these
97 traits using :meth:`check` method.
96 traits using :meth:`check` method.
98
97
99 """
98 """
100
99
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):
115 msg_id = Unicode()
114 msg_id = Unicode()
116 msg_type = Unicode()
115 msg_type = Unicode()
117 header = Dict()
116 header = Dict()
118 parent_header = Dict()
117 parent_header = Dict()
119 content = Dict()
118 content = Dict()
120
119
121 class RHeader(Reference):
120 class RHeader(Reference):
122 msg_id = Unicode()
121 msg_id = Unicode()
123 msg_type = Unicode()
122 msg_type = Unicode()
124 session = Unicode()
123 session = Unicode()
125 username = Unicode()
124 username = Unicode()
126
125
127 class RContent(Reference):
126 class RContent(Reference):
128 status = Enum((u'ok', u'error'))
127 status = Enum((u'ok', u'error'))
129
128
130
129
131 class ExecuteReply(Reference):
130 class ExecuteReply(Reference):
132 execution_count = Integer()
131 execution_count = Integer()
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):
147 payload = List(Dict)
143 payload = List(Dict)
148 user_variables = Dict()
144 user_variables = Dict()
149 user_expressions = Dict()
145 user_expressions = Dict()
150
146
151
147
152 class ExecuteReplyError(Reference):
148 class ExecuteReplyError(Reference):
153 ename = Unicode()
149 ename = Unicode()
154 evalue = Unicode()
150 evalue = Unicode()
155 traceback = List(Unicode)
151 traceback = List(Unicode)
156
152
157
153
158 class OInfoReply(Reference):
154 class OInfoReply(Reference):
159 name = Unicode()
155 name = Unicode()
160 found = Bool()
156 found = Bool()
161 ismagic = Bool()
157 ismagic = Bool()
162 isalias = Bool()
158 isalias = Bool()
163 namespace = Enum((u'builtin', u'magics', u'alias', u'Interactive'))
159 namespace = Enum((u'builtin', u'magics', u'alias', u'Interactive'))
164 type_name = Unicode()
160 type_name = Unicode()
165 string_form = Unicode()
161 string_form = Unicode()
166 base_class = Unicode()
162 base_class = Unicode()
167 length = Integer()
163 length = Integer()
168 file = Unicode()
164 file = Unicode()
169 definition = Unicode()
165 definition = Unicode()
170 argspec = Dict()
166 argspec = Dict()
171 init_definition = Unicode()
167 init_definition = Unicode()
172 docstring = Unicode()
168 docstring = Unicode()
173 init_docstring = Unicode()
169 init_docstring = Unicode()
174 class_docstring = Unicode()
170 class_docstring = Unicode()
175 call_def = Unicode()
171 call_def = Unicode()
176 call_docstring = Unicode()
172 call_docstring = Unicode()
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):
188 args = List(Unicode)
182 args = List(Unicode)
189 varargs = Unicode()
183 varargs = Unicode()
190 varkw = Unicode()
184 varkw = Unicode()
191 defaults = List()
185 defaults = List()
192
186
193
187
194 class Status(Reference):
188 class Status(Reference):
195 execution_state = Enum((u'busy', u'idle', u'starting'))
189 execution_state = Enum((u'busy', u'idle', u'starting'))
196
190
197
191
198 class CompleteReply(Reference):
192 class CompleteReply(Reference):
199 matches = List(Unicode)
193 matches = List(Unicode)
200
194
201
195
202 def Version(num, trait=Integer):
196 def Version(num, trait=Integer):
203 return List(trait, default_value=[0] * num, minlen=num, maxlen=num)
197 return List(trait, default_value=[0] * num, minlen=num, maxlen=num)
204
198
205
199
206 class KernelInfoReply(Reference):
200 class KernelInfoReply(Reference):
207
201
208 protocol_version = Version(2)
202 protocol_version = Version(2)
209 ipython_version = Version(4, Any)
203 ipython_version = Version(4, Any)
210 language_version = Version(3)
204 language_version = Version(3)
211 language = Unicode()
205 language = Unicode()
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
222
214
223 class PyIn(Reference):
215 class PyIn(Reference):
224 code = Unicode()
216 code = Unicode()
225 execution_count = Integer()
217 execution_count = Integer()
226
218
227
219
228 PyErr = ExecuteReplyError
220 PyErr = ExecuteReplyError
229
221
230
222
231 class Stream(Reference):
223 class Stream(Reference):
232 name = Enum((u'stdout', u'stderr'))
224 name = Enum((u'stdout', u'stderr'))
233 data = Unicode()
225 data = Unicode()
234
226
235
227
236 mime_pat = re.compile(r'\w+/\w+')
228 mime_pat = re.compile(r'\w+/\w+')
237
229
238 class DisplayData(Reference):
230 class DisplayData(Reference):
239 source = Unicode()
231 source = Unicode()
240 metadata = Dict()
232 metadata = Dict()
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):
249 execution_count = Integer()
241 execution_count = Integer()
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 = {
258 'execute_reply' : ExecuteReply(),
250 'execute_reply' : ExecuteReply(),
259 'object_info_reply' : OInfoReply(),
251 'object_info_reply' : OInfoReply(),
260 'status' : Status(),
252 'status' : Status(),
261 'complete_reply' : CompleteReply(),
253 'complete_reply' : CompleteReply(),
262 'kernel_info_reply': KernelInfoReply(),
254 'kernel_info_reply': KernelInfoReply(),
263 'pyin' : PyIn(),
255 'pyin' : PyIn(),
264 'pyout' : PyOut(),
256 'pyout' : PyOut(),
265 'pyerr' : PyErr(),
257 'pyerr' : PyErr(),
266 'stream' : Stream(),
258 'stream' : Stream(),
267 'display_data' : DisplayData(),
259 'display_data' : DisplayData(),
268 }
260 }
269 """
261 """
270 Specifications of `content` part of the reply messages.
262 Specifications of `content` part of the reply messages.
271 """
263 """
272
264
273
265
274 def validate_message(msg, msg_type=None, parent=None):
266 def validate_message(msg, msg_type=None, parent=None):
275 """validate a message
267 """validate a message
276
268
277 This is a generator, and must be iterated through to actually
269 This is a generator, and must be iterated through to actually
278 trigger each test.
270 trigger each test.
279
271
280 If msg_type and/or parent are given, the msg_type and/or parent msg_id
272 If msg_type and/or parent are given, the msg_type and/or parent msg_id
281 are compared with the given values.
273 are compared with the given values.
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 #-----------------------------------------------------------------------------
295 # Tests
286 # Tests
296 #-----------------------------------------------------------------------------
287 #-----------------------------------------------------------------------------
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():
351 """execute request should increment execution_count"""
335 """execute request should increment execution_count"""
352 flush_channels()
336 flush_channels()
353
337
354 msg_id, reply = execute(code='x=1')
338 msg_id, reply = execute(code='x=1')
355 count = reply['execution_count']
339 count = reply['execution_count']
356
340
357 flush_channels()
341 flush_channels()
358
342
359 msg_id, reply = execute(code='x=2')
343 msg_id, reply = execute(code='x=2')
360 count_2 = reply['execution_count']
344 count_2 = reply['execution_count']
361 nt.assert_equal(count_2, count+1)
345 nt.assert_equal(count_2, count+1)
362
346
363
347
364 def test_user_variables():
348 def test_user_variables():
365 flush_channels()
349 flush_channels()
366
350
367 msg_id, reply = execute(code='x=1', user_variables=['x'])
351 msg_id, reply = execute(code='x=1', user_variables=['x'])
368 user_variables = reply['user_variables']
352 user_variables = reply['user_variables']
369 nt.assert_equal(user_variables, {u'x': {
353 nt.assert_equal(user_variables, {u'x': {
370 u'status': u'ok',
354 u'status': u'ok',
371 u'data': {u'text/plain': u'1'},
355 u'data': {u'text/plain': u'1'},
372 u'metadata': {},
356 u'metadata': {},
373 }})
357 }})
374
358
375
359
376 def test_user_variables_fail():
360 def test_user_variables_fail():
377 flush_channels()
361 flush_channels()
378
362
379 msg_id, reply = execute(code='x=1', user_variables=['nosuchname'])
363 msg_id, reply = execute(code='x=1', user_variables=['nosuchname'])
380 user_variables = reply['user_variables']
364 user_variables = reply['user_variables']
381 foo = user_variables['nosuchname']
365 foo = user_variables['nosuchname']
382 nt.assert_equal(foo['status'], 'error')
366 nt.assert_equal(foo['status'], 'error')
383 nt.assert_equal(foo['ename'], 'KeyError')
367 nt.assert_equal(foo['ename'], 'KeyError')
384
368
385
369
386 def test_user_expressions():
370 def test_user_expressions():
387 flush_channels()
371 flush_channels()
388
372
389 msg_id, reply = execute(code='x=1', user_expressions=dict(foo='x+1'))
373 msg_id, reply = execute(code='x=1', user_expressions=dict(foo='x+1'))
390 user_expressions = reply['user_expressions']
374 user_expressions = reply['user_expressions']
391 nt.assert_equal(user_expressions, {u'foo': {
375 nt.assert_equal(user_expressions, {u'foo': {
392 u'status': u'ok',
376 u'status': u'ok',
393 u'data': {u'text/plain': u'2'},
377 u'data': {u'text/plain': u'2'},
394 u'metadata': {},
378 u'metadata': {},
395 }})
379 }})
396
380
397
381
398 def test_user_expressions_fail():
382 def test_user_expressions_fail():
399 flush_channels()
383 flush_channels()
400
384
401 msg_id, reply = execute(code='x=0', user_expressions=dict(foo='nosuchname'))
385 msg_id, reply = execute(code='x=0', user_expressions=dict(foo='nosuchname'))
402 user_expressions = reply['user_expressions']
386 user_expressions = reply['user_expressions']
403 foo = user_expressions['foo']
387 foo = user_expressions['foo']
404 nt.assert_equal(foo['status'], 'error')
388 nt.assert_equal(foo['status'], 'error')
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
422 msg_id, reply = execute(code='a=5')
403 msg_id, reply = execute(code='a=5')
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
438 msg_id, reply = execute(code='ip=get_ipython()')
417 msg_id, reply = execute(code='ip=get_ipython()')
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
467 msg_id, reply = execute(code="alpha = albert = 5")
442 msg_id, reply = execute(code="alpha = albert = 5")
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
@@ -1,47 +1,41 b''
1 """Test the IPython.kernel public API
1 """Test the IPython.kernel public API
2
2
3 Authors
3 Authors
4 -------
4 -------
5 * MinRK
5 * MinRK
6 """
6 """
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (c) 2013, the IPython Development Team.
8 # Copyright (c) 2013, the IPython Development Team.
9 #
9 #
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11 #
11 #
12 # The full license is in the file COPYING.txt, distributed with this software.
12 # The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
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
22 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
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
@@ -1,241 +1,228 b''
1 """test serialization tools"""
1 """test serialization tools"""
2
2
3 #-------------------------------------------------------------------------------
3 #-------------------------------------------------------------------------------
4 # Copyright (C) 2011 The IPython Development Team
4 # Copyright (C) 2011 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 pickle
14 import pickle
15 from collections import namedtuple
15 from collections import namedtuple
16
16
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 # from unittest import TestCaes
19 # from unittest import TestCaes
20 from IPython.kernel.zmq.serialize import serialize_object, unserialize_object
20 from IPython.kernel.zmq.serialize import serialize_object, unserialize_object
21 from IPython.testing import decorators as dec
21 from IPython.testing import decorators as dec
22 from IPython.utils.pickleutil import CannedArray, CannedClass
22 from IPython.utils.pickleutil import CannedArray, CannedClass
23 from IPython.parallel import interactive
23 from IPython.parallel import interactive
24
24
25 #-------------------------------------------------------------------------------
25 #-------------------------------------------------------------------------------
26 # Globals and Utilities
26 # Globals and Utilities
27 #-------------------------------------------------------------------------------
27 #-------------------------------------------------------------------------------
28
28
29 def roundtrip(obj):
29 def roundtrip(obj):
30 """roundtrip an object through serialization"""
30 """roundtrip an object through serialization"""
31 bufs = serialize_object(obj)
31 bufs = serialize_object(obj)
32 obj2, remainder = unserialize_object(bufs)
32 obj2, remainder = unserialize_object(bufs)
33 nt.assert_equals(remainder, [])
33 nt.assert_equals(remainder, [])
34 return obj2
34 return obj2
35
35
36 class C(object):
36 class C(object):
37 """dummy class for """
37 """dummy class for """
38
38
39 def __init__(self, **kwargs):
39 def __init__(self, **kwargs):
40 for key,value in kwargs.iteritems():
40 for key,value in kwargs.iteritems():
41 setattr(self, key, value)
41 setattr(self, key, value)
42
42
43 SHAPES = ((100,), (1024,10), (10,8,6,5), (), (0,))
43 SHAPES = ((100,), (1024,10), (10,8,6,5), (), (0,))
44 DTYPES = ('uint8', 'float64', 'int32', [('g', 'float32')], '|S10')
44 DTYPES = ('uint8', 'float64', 'int32', [('g', 'float32')], '|S10')
45 #-------------------------------------------------------------------------------
45 #-------------------------------------------------------------------------------
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',
53 dict(a='b', b=10),
52 dict(a='b', b=10),
54 [1,2,'hi'],
53 [1,2,'hi'],
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),
73 b"hello"*500,
70 b"hello"*500,
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
84
81
85 since nan != nan
82 since nan != nan
86 """
83 """
87 import numpy
84 import numpy
88 if A.dtype.fields and A.shape:
85 if A.dtype.fields and A.shape:
89 for field in A.dtype.fields.keys():
86 for field in A.dtype.fields.keys():
90 try:
87 try:
91 A[field][numpy.isnan(A[field])] = 0
88 A[field][numpy.isnan(A[field])] = 0
92 except (TypeError, NotImplementedError):
89 except (TypeError, NotImplementedError):
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
100 from numpy.testing.utils import assert_array_equal
96 from numpy.testing.utils import assert_array_equal
101 for shape in SHAPES:
97 for shape in SHAPES:
102 for dtype in DTYPES:
98 for dtype in DTYPES:
103 A = numpy.empty(shape, dtype=dtype)
99 A = numpy.empty(shape, dtype=dtype)
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
116 from numpy.testing.utils import assert_array_equal
111 from numpy.testing.utils import assert_array_equal
117 for shape in SHAPES:
112 for shape in SHAPES:
118 for dtype in [
113 for dtype in [
119 [('f', float), ('s', '|S10')],
114 [('f', float), ('s', '|S10')],
120 [('n', int), ('s', '|S1'), ('u', 'uint32')],
115 [('n', int), ('s', '|S1'), ('u', 'uint32')],
121 ]:
116 ]:
122 A = numpy.empty(shape, dtype=dtype)
117 A = numpy.empty(shape, dtype=dtype)
123 _scrub_nan(A)
118 _scrub_nan(A)
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
136 from numpy.testing.utils import assert_array_equal
130 from numpy.testing.utils import assert_array_equal
137 for shape in SHAPES:
131 for shape in SHAPES:
138 for dtype in DTYPES:
132 for dtype in DTYPES:
139 A = numpy.empty(shape, dtype=dtype)
133 A = numpy.empty(shape, dtype=dtype)
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
155 from numpy.testing.utils import assert_array_equal
148 from numpy.testing.utils import assert_array_equal
156 for shape in SHAPES:
149 for shape in SHAPES:
157 for dtype in DTYPES:
150 for dtype in DTYPES:
158 A = numpy.empty(shape, dtype=dtype)
151 A = numpy.empty(shape, dtype=dtype)
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:
186 a=5
177 a=5
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):
229 a=5
216 a=5
230
217
231 @interactive
218 @interactive
232 class D(C):
219 class D(C):
233 b=10
220 b=10
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)
@@ -1,133 +1,131 b''
1 """Test suite for our JSON utilities.
1 """Test suite for our JSON utilities.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (C) 2010-2011 The IPython Development Team
4 # Copyright (C) 2010-2011 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.txt, distributed as part of this software.
7 # the file COPYING.txt, distributed as part of this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # stdlib
13 # stdlib
14 import datetime
14 import datetime
15 import json
15 import json
16 from base64 import decodestring
16 from base64 import decodestring
17
17
18 # third party
18 # third party
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
26
25
27 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
28 # Test functions
27 # Test functions
29 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
30
29
31 def test():
30 def test():
32 # list of input/expected output. Use None for the expected output if it
31 # list of input/expected output. Use None for the expected output if it
33 # can be the same as the input.
32 # can be the same as the input.
34 pairs = [(1, None), # start with scalars
33 pairs = [(1, None), # start with scalars
35 (1.0, None),
34 (1.0, None),
36 ('a', None),
35 ('a', None),
37 (True, None),
36 (True, None),
38 (False, None),
37 (False, None),
39 (None, None),
38 (None, None),
40 # complex numbers for now just go to strings, as otherwise they
39 # complex numbers for now just go to strings, as otherwise they
41 # are unserializable
40 # are unserializable
42 (1j, '1j'),
41 (1j, '1j'),
43 # Containers
42 # Containers
44 ([1, 2], None),
43 ([1, 2], None),
45 ((1, 2), [1, 2]),
44 ((1, 2), [1, 2]),
46 (set([1, 2]), [1, 2]),
45 (set([1, 2]), [1, 2]),
47 (dict(x=1), None),
46 (dict(x=1), None),
48 ({'x': 1, 'y':[1,2,3], '1':'int'}, None),
47 ({'x': 1, 'y':[1,2,3], '1':'int'}, None),
49 # More exotic objects
48 # More exotic objects
50 ((x for x in range(3)), [0, 1, 2]),
49 ((x for x in range(3)), [0, 1, 2]),
51 (iter([1, 2]), [1, 2]),
50 (iter([1, 2]), [1, 2]),
52 ]
51 ]
53
52
54 for val, jval in pairs:
53 for val, jval in pairs:
55 if jval is None:
54 if jval is None:
56 jval = val
55 jval = val
57 out = json_clean(val)
56 out = json_clean(val)
58 # validate our cleanup
57 # validate our cleanup
59 nt.assert_equal(out, jval)
58 nt.assert_equal(out, jval)
60 # and ensure that what we return, indeed encodes cleanly
59 # and ensure that what we return, indeed encodes cleanly
61 json.loads(json.dumps(out))
60 json.loads(json.dumps(out))
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'
69 jpegdata = b'\xff\xd8\xff\xe0\x00\x10JFIFblahblahjpeg(\xa0\x0f\xff\xd9'
67 jpegdata = b'\xff\xd8\xff\xe0\x00\x10JFIFblahblahjpeg(\xa0\x0f\xff\xd9'
70
68
71 fmt = {
69 fmt = {
72 'image/png' : pngdata,
70 'image/png' : pngdata,
73 'image/jpeg' : jpegdata,
71 'image/jpeg' : jpegdata,
74 }
72 }
75 encoded = encode_images(fmt)
73 encoded = encode_images(fmt)
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)
95 assert isinstance(jc, str)
93 assert isinstance(jc, str)
96 assert '<lambda>' in jc
94 assert '<lambda>' in jc
97 json.dumps(jc)
95 json.dumps(jc)
98
96
99 def test_extract_dates():
97 def test_extract_dates():
100 timestamps = [
98 timestamps = [
101 '2013-07-03T16:34:52.249482',
99 '2013-07-03T16:34:52.249482',
102 '2013-07-03T16:34:52.249482Z',
100 '2013-07-03T16:34:52.249482Z',
103 '2013-07-03T16:34:52.249482Z-0800',
101 '2013-07-03T16:34:52.249482Z-0800',
104 '2013-07-03T16:34:52.249482Z+0800',
102 '2013-07-03T16:34:52.249482Z+0800',
105 '2013-07-03T16:34:52.249482Z+08:00',
103 '2013-07-03T16:34:52.249482Z+08:00',
106 '2013-07-03T16:34:52.249482Z-08:00',
104 '2013-07-03T16:34:52.249482Z-08:00',
107 '2013-07-03T16:34:52.249482-0800',
105 '2013-07-03T16:34:52.249482-0800',
108 '2013-07-03T16:34:52.249482+0800',
106 '2013-07-03T16:34:52.249482+0800',
109 '2013-07-03T16:34:52.249482+08:00',
107 '2013-07-03T16:34:52.249482+08:00',
110 '2013-07-03T16:34:52.249482-08:00',
108 '2013-07-03T16:34:52.249482-08:00',
111 ]
109 ]
112 extracted = jsonutil.extract_dates(timestamps)
110 extracted = jsonutil.extract_dates(timestamps)
113 ref = extracted[0]
111 ref = extracted[0]
114 for dt in extracted:
112 for dt in extracted:
115 nt.assert_true(isinstance(dt, datetime.datetime))
113 nt.assert_true(isinstance(dt, datetime.datetime))
116 nt.assert_equal(dt, ref)
114 nt.assert_equal(dt, ref)
117
115
118 def test_date_default():
116 def test_date_default():
119 data = dict(today=datetime.datetime.now(), utcnow=tz.utcnow())
117 data = dict(today=datetime.datetime.now(), utcnow=tz.utcnow())
120 jsondata = json.dumps(data, default=jsonutil.date_default)
118 jsondata = json.dumps(data, default=jsonutil.date_default)
121 nt.assert_in("+00", jsondata)
119 nt.assert_in("+00", jsondata)
122 nt.assert_equal(jsondata.count("+00"), 1)
120 nt.assert_equal(jsondata.count("+00"), 1)
123 extracted = jsonutil.extract_dates(json.loads(jsondata))
121 extracted = jsonutil.extract_dates(json.loads(jsondata))
124 for dt in extracted.values():
122 for dt in extracted.values():
125 nt.assert_true(isinstance(dt, datetime.datetime))
123 nt.assert_true(isinstance(dt, datetime.datetime))
126
124
127 def test_exception():
125 def test_exception():
128 bad_dicts = [{1:'number', '1':'string'},
126 bad_dicts = [{1:'number', '1':'string'},
129 {True:'bool', 'True':'string'},
127 {True:'bool', 'True':'string'},
130 ]
128 ]
131 for d in bad_dicts:
129 for d in bad_dicts:
132 nt.assert_raises(ValueError, json_clean, d)
130 nt.assert_raises(ValueError, json_clean, d)
133
131
General Comments 0
You need to be logged in to leave comments. Login now