##// END OF EJS Templates
Fix a couple of core tests under Python 3.
Thomas Kluyver -
Show More
@@ -1,222 +1,222
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for the key interactiveshell module.
2 """Tests for the key interactiveshell module.
3
3
4 Historically the main classes in interactiveshell have been under-tested. This
4 Historically the main classes in interactiveshell have been under-tested. This
5 module should grow as many single-method tests as possible to trap many of the
5 module should grow as many single-method tests as possible to trap many of the
6 recurring bugs we seem to encounter with high-level interaction.
6 recurring bugs we seem to encounter with high-level interaction.
7
7
8 Authors
8 Authors
9 -------
9 -------
10 * Fernando Perez
10 * Fernando Perez
11 """
11 """
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2011 The IPython Development Team
13 # Copyright (C) 2011 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # stdlib
22 # stdlib
23 import os
23 import os
24 import shutil
24 import shutil
25 import tempfile
25 import tempfile
26 import unittest
26 import unittest
27 from os.path import join
27 from os.path import join
28 from StringIO import StringIO
28 from StringIO import StringIO
29
29
30 from IPython.testing import decorators as dec
30 from IPython.testing import decorators as dec
31 from IPython.utils import io
31 from IPython.utils import io
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Tests
34 # Tests
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37 class InteractiveShellTestCase(unittest.TestCase):
37 class InteractiveShellTestCase(unittest.TestCase):
38 def test_naked_string_cells(self):
38 def test_naked_string_cells(self):
39 """Test that cells with only naked strings are fully executed"""
39 """Test that cells with only naked strings are fully executed"""
40 ip = get_ipython()
40 ip = get_ipython()
41 # First, single-line inputs
41 # First, single-line inputs
42 ip.run_cell('"a"\n')
42 ip.run_cell('"a"\n')
43 self.assertEquals(ip.user_ns['_'], 'a')
43 self.assertEquals(ip.user_ns['_'], 'a')
44 # And also multi-line cells
44 # And also multi-line cells
45 ip.run_cell('"""a\nb"""\n')
45 ip.run_cell('"""a\nb"""\n')
46 self.assertEquals(ip.user_ns['_'], 'a\nb')
46 self.assertEquals(ip.user_ns['_'], 'a\nb')
47
47
48 def test_run_empty_cell(self):
48 def test_run_empty_cell(self):
49 """Just make sure we don't get a horrible error with a blank
49 """Just make sure we don't get a horrible error with a blank
50 cell of input. Yes, I did overlook that."""
50 cell of input. Yes, I did overlook that."""
51 ip = get_ipython()
51 ip = get_ipython()
52 old_xc = ip.execution_count
52 old_xc = ip.execution_count
53 ip.run_cell('')
53 ip.run_cell('')
54 self.assertEquals(ip.execution_count, old_xc)
54 self.assertEquals(ip.execution_count, old_xc)
55
55
56 def test_run_cell_multiline(self):
56 def test_run_cell_multiline(self):
57 """Multi-block, multi-line cells must execute correctly.
57 """Multi-block, multi-line cells must execute correctly.
58 """
58 """
59 ip = get_ipython()
59 ip = get_ipython()
60 src = '\n'.join(["x=1",
60 src = '\n'.join(["x=1",
61 "y=2",
61 "y=2",
62 "if 1:",
62 "if 1:",
63 " x += 1",
63 " x += 1",
64 " y += 1",])
64 " y += 1",])
65 ip.run_cell(src)
65 ip.run_cell(src)
66 self.assertEquals(ip.user_ns['x'], 2)
66 self.assertEquals(ip.user_ns['x'], 2)
67 self.assertEquals(ip.user_ns['y'], 3)
67 self.assertEquals(ip.user_ns['y'], 3)
68
68
69 def test_multiline_string_cells(self):
69 def test_multiline_string_cells(self):
70 "Code sprinkled with multiline strings should execute (GH-306)"
70 "Code sprinkled with multiline strings should execute (GH-306)"
71 ip = get_ipython()
71 ip = get_ipython()
72 ip.run_cell('tmp=0')
72 ip.run_cell('tmp=0')
73 self.assertEquals(ip.user_ns['tmp'], 0)
73 self.assertEquals(ip.user_ns['tmp'], 0)
74 ip.run_cell('tmp=1;"""a\nb"""\n')
74 ip.run_cell('tmp=1;"""a\nb"""\n')
75 self.assertEquals(ip.user_ns['tmp'], 1)
75 self.assertEquals(ip.user_ns['tmp'], 1)
76
76
77 def test_dont_cache_with_semicolon(self):
77 def test_dont_cache_with_semicolon(self):
78 "Ending a line with semicolon should not cache the returned object (GH-307)"
78 "Ending a line with semicolon should not cache the returned object (GH-307)"
79 ip = get_ipython()
79 ip = get_ipython()
80 oldlen = len(ip.user_ns['Out'])
80 oldlen = len(ip.user_ns['Out'])
81 a = ip.run_cell('1;', store_history=True)
81 a = ip.run_cell('1;', store_history=True)
82 newlen = len(ip.user_ns['Out'])
82 newlen = len(ip.user_ns['Out'])
83 self.assertEquals(oldlen, newlen)
83 self.assertEquals(oldlen, newlen)
84 #also test the default caching behavior
84 #also test the default caching behavior
85 ip.run_cell('1', store_history=True)
85 ip.run_cell('1', store_history=True)
86 newlen = len(ip.user_ns['Out'])
86 newlen = len(ip.user_ns['Out'])
87 self.assertEquals(oldlen+1, newlen)
87 self.assertEquals(oldlen+1, newlen)
88
88
89 def test_In_variable(self):
89 def test_In_variable(self):
90 "Verify that In variable grows with user input (GH-284)"
90 "Verify that In variable grows with user input (GH-284)"
91 ip = get_ipython()
91 ip = get_ipython()
92 oldlen = len(ip.user_ns['In'])
92 oldlen = len(ip.user_ns['In'])
93 ip.run_cell('1;', store_history=True)
93 ip.run_cell('1;', store_history=True)
94 newlen = len(ip.user_ns['In'])
94 newlen = len(ip.user_ns['In'])
95 self.assertEquals(oldlen+1, newlen)
95 self.assertEquals(oldlen+1, newlen)
96 self.assertEquals(ip.user_ns['In'][-1],'1;')
96 self.assertEquals(ip.user_ns['In'][-1],'1;')
97
97
98 def test_magic_names_in_string(self):
98 def test_magic_names_in_string(self):
99 ip = get_ipython()
99 ip = get_ipython()
100 ip.run_cell('a = """\n%exit\n"""')
100 ip.run_cell('a = """\n%exit\n"""')
101 self.assertEquals(ip.user_ns['a'], '\n%exit\n')
101 self.assertEquals(ip.user_ns['a'], '\n%exit\n')
102
102
103 def test_alias_crash(self):
103 def test_alias_crash(self):
104 """Errors in prefilter can't crash IPython"""
104 """Errors in prefilter can't crash IPython"""
105 ip = get_ipython()
105 ip = get_ipython()
106 ip.run_cell('%alias parts echo first %s second %s')
106 ip.run_cell('%alias parts echo first %s second %s')
107 # capture stderr:
107 # capture stderr:
108 save_err = io.stderr
108 save_err = io.stderr
109 io.stderr = StringIO()
109 io.stderr = StringIO()
110 ip.run_cell('parts 1')
110 ip.run_cell('parts 1')
111 err = io.stderr.getvalue()
111 err = io.stderr.getvalue()
112 io.stderr = save_err
112 io.stderr = save_err
113 self.assertEquals(err.split(':')[0], 'ERROR')
113 self.assertEquals(err.split(':')[0], 'ERROR')
114
114
115 def test_trailing_newline(self):
115 def test_trailing_newline(self):
116 """test that running !(command) does not raise a SyntaxError"""
116 """test that running !(command) does not raise a SyntaxError"""
117 ip = get_ipython()
117 ip = get_ipython()
118 ip.run_cell('!(true)\n', False)
118 ip.run_cell('!(true)\n', False)
119 ip.run_cell('!(true)\n\n\n', False)
119 ip.run_cell('!(true)\n\n\n', False)
120
120
121 def test_gh_597(self):
121 def test_gh_597(self):
122 """Pretty-printing lists of objects with non-ascii reprs may cause
122 """Pretty-printing lists of objects with non-ascii reprs may cause
123 problems."""
123 problems."""
124 class Spam(object):
124 class Spam(object):
125 def __repr__(self):
125 def __repr__(self):
126 return "\xe9"*50
126 return "\xe9"*50
127 import IPython.core.formatters
127 import IPython.core.formatters
128 f = IPython.core.formatters.PlainTextFormatter()
128 f = IPython.core.formatters.PlainTextFormatter()
129 f([Spam(),Spam()])
129 f([Spam(),Spam()])
130
130
131 def test_future_flags(self):
131 def test_future_flags(self):
132 """Check that future flags are used for parsing code (gh-777)"""
132 """Check that future flags are used for parsing code (gh-777)"""
133 ip = get_ipython()
133 ip = get_ipython()
134 ip.run_cell('from __future__ import print_function')
134 ip.run_cell('from __future__ import print_function')
135 try:
135 try:
136 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
136 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
137 assert 'prfunc_return_val' in ip.user_ns
137 assert 'prfunc_return_val' in ip.user_ns
138 finally:
138 finally:
139 # Reset compiler flags so we don't mess up other tests.
139 # Reset compiler flags so we don't mess up other tests.
140 ip.compile.reset_compiler_flags()
140 ip.compile.reset_compiler_flags()
141
141
142 def test_future_unicode(self):
142 def test_future_unicode(self):
143 """Check that unicode_literals is imported from __future__ (gh #786)"""
143 """Check that unicode_literals is imported from __future__ (gh #786)"""
144 ip = get_ipython()
144 ip = get_ipython()
145 try:
145 try:
146 ip.run_cell(u'byte_str = "a"')
146 ip.run_cell(u'byte_str = "a"')
147 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
147 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
148 ip.run_cell('from __future__ import unicode_literals')
148 ip.run_cell('from __future__ import unicode_literals')
149 ip.run_cell(u'unicode_str = "a"')
149 ip.run_cell(u'unicode_str = "a"')
150 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
150 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
151 finally:
151 finally:
152 # Reset compiler flags so we don't mess up other tests.
152 # Reset compiler flags so we don't mess up other tests.
153 ip.compile.reset_compiler_flags()
153 ip.compile.reset_compiler_flags()
154
154
155 def test_bad_custom_tb(self):
155 def test_bad_custom_tb(self):
156 """Check that InteractiveShell is protected from bad custom exception handlers"""
156 """Check that InteractiveShell is protected from bad custom exception handlers"""
157 ip = get_ipython()
157 ip = get_ipython()
158 from IPython.utils import io
158 from IPython.utils import io
159 save_stderr = io.stderr
159 save_stderr = io.stderr
160 try:
160 try:
161 # capture stderr
161 # capture stderr
162 io.stderr = StringIO()
162 io.stderr = StringIO()
163 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
163 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
164 self.assertEquals(ip.custom_exceptions, (IOError,))
164 self.assertEquals(ip.custom_exceptions, (IOError,))
165 ip.run_cell(u'raise IOError("foo")')
165 ip.run_cell(u'raise IOError("foo")')
166 self.assertEquals(ip.custom_exceptions, ())
166 self.assertEquals(ip.custom_exceptions, ())
167 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
167 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
168 finally:
168 finally:
169 io.stderr = save_stderr
169 io.stderr = save_stderr
170
170
171 def test_bad_custom_tb_return(self):
171 def test_bad_custom_tb_return(self):
172 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
172 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
173 ip = get_ipython()
173 ip = get_ipython()
174 from IPython.utils import io
174 from IPython.utils import io
175 save_stderr = io.stderr
175 save_stderr = io.stderr
176 try:
176 try:
177 # capture stderr
177 # capture stderr
178 io.stderr = StringIO()
178 io.stderr = StringIO()
179 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
179 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
180 self.assertEquals(ip.custom_exceptions, (NameError,))
180 self.assertEquals(ip.custom_exceptions, (NameError,))
181 ip.run_cell(u'a=abracadabra')
181 ip.run_cell(u'a=abracadabra')
182 self.assertEquals(ip.custom_exceptions, ())
182 self.assertEquals(ip.custom_exceptions, ())
183 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
183 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
184 finally:
184 finally:
185 io.stderr = save_stderr
185 io.stderr = save_stderr
186
186
187 def test_drop_by_id(self):
187 def test_drop_by_id(self):
188 ip = get_ipython()
188 ip = get_ipython()
189 myvars = {"a":object(), "b":object(), "c": object()}
189 myvars = {"a":object(), "b":object(), "c": object()}
190 ip.push(myvars, interactive=False)
190 ip.push(myvars, interactive=False)
191 for name in myvars:
191 for name in myvars:
192 assert name in ip.user_ns, name
192 assert name in ip.user_ns, name
193 assert name in ip.user_ns_hidden, name
193 assert name in ip.user_ns_hidden, name
194 ip.user_ns['b'] = 12
194 ip.user_ns['b'] = 12
195 ip.drop_by_id(myvars)
195 ip.drop_by_id(myvars)
196 for name in ["a", "c"]:
196 for name in ["a", "c"]:
197 assert name not in ip.user_ns, name
197 assert name not in ip.user_ns, name
198 assert name not in ip.user_ns_hidden, name
198 assert name not in ip.user_ns_hidden, name
199 assert ip.user_ns['b'] == 12
199 assert ip.user_ns['b'] == 12
200 ip.reset()
200 ip.reset()
201
201
202 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
202 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
203
203
204 def setUp(self):
204 def setUp(self):
205 self.BASETESTDIR = tempfile.mkdtemp()
205 self.BASETESTDIR = tempfile.mkdtemp()
206 self.TESTDIR = join(self.BASETESTDIR, u"åäö")
206 self.TESTDIR = join(self.BASETESTDIR, u"åäö")
207 os.mkdir(self.TESTDIR)
207 os.mkdir(self.TESTDIR)
208 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
208 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
209 sfile.write("pass\n")
209 sfile.write("pass\n")
210 self.oldpath = os.getcwdu()
210 self.oldpath = os.getcwdu()
211 os.chdir(self.TESTDIR)
211 os.chdir(self.TESTDIR)
212 self.fname = u"åäötestscript.py"
212 self.fname = u"åäötestscript.py"
213
213
214
214
215 def tearDown(self):
215 def tearDown(self):
216 os.chdir(self.oldpath)
216 os.chdir(self.oldpath)
217 shutil.rmtree(self.BASETESTDIR)
217 shutil.rmtree(self.BASETESTDIR)
218
218
219 def test_1(self):
219 def test_1(self):
220 """Test safe_execfile with non-ascii path
220 """Test safe_execfile with non-ascii path
221 """
221 """
222 _ip.shell.safe_execfile(self.fname, raise_exceptions=True)
222 _ip.shell.safe_execfile(self.fname, {}, raise_exceptions=True)
@@ -1,460 +1,463
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12 import sys
12 import sys
13 import tempfile
13 import tempfile
14 import types
14 import types
15 from StringIO import StringIO
15 from StringIO import StringIO
16
16
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 from IPython.utils.path import get_long_path_name
19 from IPython.utils.path import get_long_path_name
20 from IPython.testing import decorators as dec
20 from IPython.testing import decorators as dec
21 from IPython.testing import tools as tt
21 from IPython.testing import tools as tt
22 from IPython.utils import py3compat
22 from IPython.utils import py3compat
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Test functions begin
25 # Test functions begin
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 def test_rehashx():
27 def test_rehashx():
28 # clear up everything
28 # clear up everything
29 _ip = get_ipython()
29 _ip = get_ipython()
30 _ip.alias_manager.alias_table.clear()
30 _ip.alias_manager.alias_table.clear()
31 del _ip.db['syscmdlist']
31 del _ip.db['syscmdlist']
32
32
33 _ip.magic('rehashx')
33 _ip.magic('rehashx')
34 # Practically ALL ipython development systems will have more than 10 aliases
34 # Practically ALL ipython development systems will have more than 10 aliases
35
35
36 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
36 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
37 for key, val in _ip.alias_manager.alias_table.iteritems():
37 for key, val in _ip.alias_manager.alias_table.iteritems():
38 # we must strip dots from alias names
38 # we must strip dots from alias names
39 nt.assert_true('.' not in key)
39 nt.assert_true('.' not in key)
40
40
41 # rehashx must fill up syscmdlist
41 # rehashx must fill up syscmdlist
42 scoms = _ip.db['syscmdlist']
42 scoms = _ip.db['syscmdlist']
43 yield (nt.assert_true, len(scoms) > 10)
43 yield (nt.assert_true, len(scoms) > 10)
44
44
45
45
46 def test_magic_parse_options():
46 def test_magic_parse_options():
47 """Test that we don't mangle paths when parsing magic options."""
47 """Test that we don't mangle paths when parsing magic options."""
48 ip = get_ipython()
48 ip = get_ipython()
49 path = 'c:\\x'
49 path = 'c:\\x'
50 opts = ip.parse_options('-f %s' % path,'f:')[0]
50 opts = ip.parse_options('-f %s' % path,'f:')[0]
51 # argv splitting is os-dependent
51 # argv splitting is os-dependent
52 if os.name == 'posix':
52 if os.name == 'posix':
53 expected = 'c:x'
53 expected = 'c:x'
54 else:
54 else:
55 expected = path
55 expected = path
56 nt.assert_equals(opts['f'], expected)
56 nt.assert_equals(opts['f'], expected)
57
57
58
58
59 @dec.skip_without('sqlite3')
59 @dec.skip_without('sqlite3')
60 def doctest_hist_f():
60 def doctest_hist_f():
61 """Test %hist -f with temporary filename.
61 """Test %hist -f with temporary filename.
62
62
63 In [9]: import tempfile
63 In [9]: import tempfile
64
64
65 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
65 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
66
66
67 In [11]: %hist -nl -f $tfile 3
67 In [11]: %hist -nl -f $tfile 3
68
68
69 In [13]: import os; os.unlink(tfile)
69 In [13]: import os; os.unlink(tfile)
70 """
70 """
71
71
72
72
73 @dec.skip_without('sqlite3')
73 @dec.skip_without('sqlite3')
74 def doctest_hist_r():
74 def doctest_hist_r():
75 """Test %hist -r
75 """Test %hist -r
76
76
77 XXX - This test is not recording the output correctly. For some reason, in
77 XXX - This test is not recording the output correctly. For some reason, in
78 testing mode the raw history isn't getting populated. No idea why.
78 testing mode the raw history isn't getting populated. No idea why.
79 Disabling the output checking for now, though at least we do run it.
79 Disabling the output checking for now, though at least we do run it.
80
80
81 In [1]: 'hist' in _ip.lsmagic()
81 In [1]: 'hist' in _ip.lsmagic()
82 Out[1]: True
82 Out[1]: True
83
83
84 In [2]: x=1
84 In [2]: x=1
85
85
86 In [3]: %hist -rl 2
86 In [3]: %hist -rl 2
87 x=1 # random
87 x=1 # random
88 %hist -r 2
88 %hist -r 2
89 """
89 """
90
90
91
91
92 @dec.skip_without('sqlite3')
92 @dec.skip_without('sqlite3')
93 def doctest_hist_op():
93 def doctest_hist_op():
94 """Test %hist -op
94 """Test %hist -op
95
95
96 In [1]: class b(float):
96 In [1]: class b(float):
97 ...: pass
97 ...: pass
98 ...:
98 ...:
99
99
100 In [2]: class s(object):
100 In [2]: class s(object):
101 ...: def __str__(self):
101 ...: def __str__(self):
102 ...: return 's'
102 ...: return 's'
103 ...:
103 ...:
104
104
105 In [3]:
105 In [3]:
106
106
107 In [4]: class r(b):
107 In [4]: class r(b):
108 ...: def __repr__(self):
108 ...: def __repr__(self):
109 ...: return 'r'
109 ...: return 'r'
110 ...:
110 ...:
111
111
112 In [5]: class sr(s,r): pass
112 In [5]: class sr(s,r): pass
113 ...:
113 ...:
114
114
115 In [6]:
115 In [6]:
116
116
117 In [7]: bb=b()
117 In [7]: bb=b()
118
118
119 In [8]: ss=s()
119 In [8]: ss=s()
120
120
121 In [9]: rr=r()
121 In [9]: rr=r()
122
122
123 In [10]: ssrr=sr()
123 In [10]: ssrr=sr()
124
124
125 In [11]: 4.5
125 In [11]: 4.5
126 Out[11]: 4.5
126 Out[11]: 4.5
127
127
128 In [12]: str(ss)
128 In [12]: str(ss)
129 Out[12]: 's'
129 Out[12]: 's'
130
130
131 In [13]:
131 In [13]:
132
132
133 In [14]: %hist -op
133 In [14]: %hist -op
134 >>> class b:
134 >>> class b:
135 ... pass
135 ... pass
136 ...
136 ...
137 >>> class s(b):
137 >>> class s(b):
138 ... def __str__(self):
138 ... def __str__(self):
139 ... return 's'
139 ... return 's'
140 ...
140 ...
141 >>>
141 >>>
142 >>> class r(b):
142 >>> class r(b):
143 ... def __repr__(self):
143 ... def __repr__(self):
144 ... return 'r'
144 ... return 'r'
145 ...
145 ...
146 >>> class sr(s,r): pass
146 >>> class sr(s,r): pass
147 >>>
147 >>>
148 >>> bb=b()
148 >>> bb=b()
149 >>> ss=s()
149 >>> ss=s()
150 >>> rr=r()
150 >>> rr=r()
151 >>> ssrr=sr()
151 >>> ssrr=sr()
152 >>> 4.5
152 >>> 4.5
153 4.5
153 4.5
154 >>> str(ss)
154 >>> str(ss)
155 's'
155 's'
156 >>>
156 >>>
157 """
157 """
158
158
159
159
160 @dec.skip_without('sqlite3')
160 @dec.skip_without('sqlite3')
161 def test_macro():
161 def test_macro():
162 ip = get_ipython()
162 ip = get_ipython()
163 ip.history_manager.reset() # Clear any existing history.
163 ip.history_manager.reset() # Clear any existing history.
164 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
164 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
165 for i, cmd in enumerate(cmds, start=1):
165 for i, cmd in enumerate(cmds, start=1):
166 ip.history_manager.store_inputs(i, cmd)
166 ip.history_manager.store_inputs(i, cmd)
167 ip.magic("macro test 1-3")
167 ip.magic("macro test 1-3")
168 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
168 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
169
169
170 # List macros.
170 # List macros.
171 assert "test" in ip.magic("macro")
171 assert "test" in ip.magic("macro")
172
172
173
173
174 @dec.skip_without('sqlite3')
174 @dec.skip_without('sqlite3')
175 def test_macro_run():
175 def test_macro_run():
176 """Test that we can run a multi-line macro successfully."""
176 """Test that we can run a multi-line macro successfully."""
177 ip = get_ipython()
177 ip = get_ipython()
178 ip.history_manager.reset()
178 ip.history_manager.reset()
179 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
179 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
180 "%macro test 2-3"]
180 "%macro test 2-3"]
181 for cmd in cmds:
181 for cmd in cmds:
182 ip.run_cell(cmd, store_history=True)
182 ip.run_cell(cmd, store_history=True)
183 nt.assert_equal(ip.user_ns["test"].value,
183 nt.assert_equal(ip.user_ns["test"].value,
184 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
184 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
185 with tt.AssertPrints("12"):
185 with tt.AssertPrints("12"):
186 ip.run_cell("test")
186 ip.run_cell("test")
187 with tt.AssertPrints("13"):
187 with tt.AssertPrints("13"):
188 ip.run_cell("test")
188 ip.run_cell("test")
189
189
190
190
191 # XXX failing for now, until we get clearcmd out of quarantine. But we should
191 # XXX failing for now, until we get clearcmd out of quarantine. But we should
192 # fix this and revert the skip to happen only if numpy is not around.
192 # fix this and revert the skip to happen only if numpy is not around.
193 #@dec.skipif_not_numpy
193 #@dec.skipif_not_numpy
194 @dec.skip_known_failure
194 @dec.skip_known_failure
195 def test_numpy_clear_array_undec():
195 def test_numpy_clear_array_undec():
196 from IPython.extensions import clearcmd
196 from IPython.extensions import clearcmd
197
197
198 _ip.ex('import numpy as np')
198 _ip.ex('import numpy as np')
199 _ip.ex('a = np.empty(2)')
199 _ip.ex('a = np.empty(2)')
200 yield (nt.assert_true, 'a' in _ip.user_ns)
200 yield (nt.assert_true, 'a' in _ip.user_ns)
201 _ip.magic('clear array')
201 _ip.magic('clear array')
202 yield (nt.assert_false, 'a' in _ip.user_ns)
202 yield (nt.assert_false, 'a' in _ip.user_ns)
203
203
204
204
205 # Multiple tests for clipboard pasting
205 # Multiple tests for clipboard pasting
206 @dec.parametric
206 @dec.parametric
207 def test_paste():
207 def test_paste():
208 _ip = get_ipython()
208 _ip = get_ipython()
209 def paste(txt, flags='-q'):
209 def paste(txt, flags='-q'):
210 """Paste input text, by default in quiet mode"""
210 """Paste input text, by default in quiet mode"""
211 hooks.clipboard_get = lambda : txt
211 hooks.clipboard_get = lambda : txt
212 _ip.magic('paste '+flags)
212 _ip.magic('paste '+flags)
213
213
214 # Inject fake clipboard hook but save original so we can restore it later
214 # Inject fake clipboard hook but save original so we can restore it later
215 hooks = _ip.hooks
215 hooks = _ip.hooks
216 user_ns = _ip.user_ns
216 user_ns = _ip.user_ns
217 original_clip = hooks.clipboard_get
217 original_clip = hooks.clipboard_get
218
218
219 try:
219 try:
220 # Run tests with fake clipboard function
220 # Run tests with fake clipboard function
221 user_ns.pop('x', None)
221 user_ns.pop('x', None)
222 paste('x=1')
222 paste('x=1')
223 yield nt.assert_equal(user_ns['x'], 1)
223 yield nt.assert_equal(user_ns['x'], 1)
224
224
225 user_ns.pop('x', None)
225 user_ns.pop('x', None)
226 paste('>>> x=2')
226 paste('>>> x=2')
227 yield nt.assert_equal(user_ns['x'], 2)
227 yield nt.assert_equal(user_ns['x'], 2)
228
228
229 paste("""
229 paste("""
230 >>> x = [1,2,3]
230 >>> x = [1,2,3]
231 >>> y = []
231 >>> y = []
232 >>> for i in x:
232 >>> for i in x:
233 ... y.append(i**2)
233 ... y.append(i**2)
234 ...
234 ...
235 """)
235 """)
236 yield nt.assert_equal(user_ns['x'], [1,2,3])
236 yield nt.assert_equal(user_ns['x'], [1,2,3])
237 yield nt.assert_equal(user_ns['y'], [1,4,9])
237 yield nt.assert_equal(user_ns['y'], [1,4,9])
238
238
239 # Now, test that paste -r works
239 # Now, test that paste -r works
240 user_ns.pop('x', None)
240 user_ns.pop('x', None)
241 yield nt.assert_false('x' in user_ns)
241 yield nt.assert_false('x' in user_ns)
242 _ip.magic('paste -r')
242 _ip.magic('paste -r')
243 yield nt.assert_equal(user_ns['x'], [1,2,3])
243 yield nt.assert_equal(user_ns['x'], [1,2,3])
244
244
245 # Also test paste echoing, by temporarily faking the writer
245 # Also test paste echoing, by temporarily faking the writer
246 w = StringIO()
246 w = StringIO()
247 writer = _ip.write
247 writer = _ip.write
248 _ip.write = w.write
248 _ip.write = w.write
249 code = """
249 code = """
250 a = 100
250 a = 100
251 b = 200"""
251 b = 200"""
252 try:
252 try:
253 paste(code,'')
253 paste(code,'')
254 out = w.getvalue()
254 out = w.getvalue()
255 finally:
255 finally:
256 _ip.write = writer
256 _ip.write = writer
257 yield nt.assert_equal(user_ns['a'], 100)
257 yield nt.assert_equal(user_ns['a'], 100)
258 yield nt.assert_equal(user_ns['b'], 200)
258 yield nt.assert_equal(user_ns['b'], 200)
259 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
259 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
260
260
261 finally:
261 finally:
262 # Restore original hook
262 # Restore original hook
263 hooks.clipboard_get = original_clip
263 hooks.clipboard_get = original_clip
264
264
265
265
266 def test_time():
266 def test_time():
267 _ip.magic('time None')
267 _ip.magic('time None')
268
268
269
269
270 @py3compat.doctest_refactor_print
270 @py3compat.doctest_refactor_print
271 def doctest_time():
271 def doctest_time():
272 """
272 """
273 In [10]: %time None
273 In [10]: %time None
274 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
274 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 Wall time: 0.00 s
275 Wall time: 0.00 s
276
276
277 In [11]: def f(kmjy):
277 In [11]: def f(kmjy):
278 ....: %time print 2*kmjy
278 ....: %time print 2*kmjy
279
279
280 In [12]: f(3)
280 In [12]: f(3)
281 6
281 6
282 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
282 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
283 Wall time: 0.00 s
283 Wall time: 0.00 s
284 """
284 """
285
285
286
286
287 def test_doctest_mode():
287 def test_doctest_mode():
288 "Toggle doctest_mode twice, it should be a no-op and run without error"
288 "Toggle doctest_mode twice, it should be a no-op and run without error"
289 _ip.magic('doctest_mode')
289 _ip.magic('doctest_mode')
290 _ip.magic('doctest_mode')
290 _ip.magic('doctest_mode')
291
291
292
292
293 def test_parse_options():
293 def test_parse_options():
294 """Tests for basic options parsing in magics."""
294 """Tests for basic options parsing in magics."""
295 # These are only the most minimal of tests, more should be added later. At
295 # These are only the most minimal of tests, more should be added later. At
296 # the very least we check that basic text/unicode calls work OK.
296 # the very least we check that basic text/unicode calls work OK.
297 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
297 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
298 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
298 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
299
299
300
300
301 def test_dirops():
301 def test_dirops():
302 """Test various directory handling operations."""
302 """Test various directory handling operations."""
303 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
303 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
304 curpath = os.getcwdu
304 curpath = os.getcwdu
305 startdir = os.getcwdu()
305 startdir = os.getcwdu()
306 ipdir = _ip.ipython_dir
306 ipdir = _ip.ipython_dir
307 try:
307 try:
308 _ip.magic('cd "%s"' % ipdir)
308 _ip.magic('cd "%s"' % ipdir)
309 nt.assert_equal(curpath(), ipdir)
309 nt.assert_equal(curpath(), ipdir)
310 _ip.magic('cd -')
310 _ip.magic('cd -')
311 nt.assert_equal(curpath(), startdir)
311 nt.assert_equal(curpath(), startdir)
312 _ip.magic('pushd "%s"' % ipdir)
312 _ip.magic('pushd "%s"' % ipdir)
313 nt.assert_equal(curpath(), ipdir)
313 nt.assert_equal(curpath(), ipdir)
314 _ip.magic('popd')
314 _ip.magic('popd')
315 nt.assert_equal(curpath(), startdir)
315 nt.assert_equal(curpath(), startdir)
316 finally:
316 finally:
317 os.chdir(startdir)
317 os.chdir(startdir)
318
318
319
319
320 def check_cpaste(code, should_fail=False):
320 def check_cpaste(code, should_fail=False):
321 """Execute code via 'cpaste' and ensure it was executed, unless
321 """Execute code via 'cpaste' and ensure it was executed, unless
322 should_fail is set.
322 should_fail is set.
323 """
323 """
324 _ip.user_ns['code_ran'] = False
324 _ip.user_ns['code_ran'] = False
325
325
326 src = StringIO()
326 src = StringIO()
327 src.encoding = None # IPython expects stdin to have an encoding attribute
327 try:
328 src.encoding = None # IPython expects stdin to have an encoding attribute
329 except Exception:
330 pass # ...but it's a read-only attribute in Python 3
328 src.write('\n')
331 src.write('\n')
329 src.write(code)
332 src.write(code)
330 src.write('\n--\n')
333 src.write('\n--\n')
331 src.seek(0)
334 src.seek(0)
332
335
333 stdin_save = sys.stdin
336 stdin_save = sys.stdin
334 sys.stdin = src
337 sys.stdin = src
335
338
336 try:
339 try:
337 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
340 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
338 with context("Traceback (most recent call last)"):
341 with context("Traceback (most recent call last)"):
339 _ip.magic('cpaste')
342 _ip.magic('cpaste')
340
343
341 if not should_fail:
344 if not should_fail:
342 assert _ip.user_ns['code_ran']
345 assert _ip.user_ns['code_ran']
343 finally:
346 finally:
344 sys.stdin = stdin_save
347 sys.stdin = stdin_save
345
348
346
349
347 def test_cpaste():
350 def test_cpaste():
348 """Test cpaste magic"""
351 """Test cpaste magic"""
349
352
350 def run():
353 def run():
351 """Marker function: sets a flag when executed.
354 """Marker function: sets a flag when executed.
352 """
355 """
353 _ip.user_ns['code_ran'] = True
356 _ip.user_ns['code_ran'] = True
354 return 'run' # return string so '+ run()' doesn't result in success
357 return 'run' # return string so '+ run()' doesn't result in success
355
358
356 tests = {'pass': ["> > > run()",
359 tests = {'pass': ["> > > run()",
357 ">>> > run()",
360 ">>> > run()",
358 "+++ run()",
361 "+++ run()",
359 "++ run()",
362 "++ run()",
360 " >>> run()"],
363 " >>> run()"],
361
364
362 'fail': ["+ + run()",
365 'fail': ["+ + run()",
363 " ++ run()"]}
366 " ++ run()"]}
364
367
365 _ip.user_ns['run'] = run
368 _ip.user_ns['run'] = run
366
369
367 for code in tests['pass']:
370 for code in tests['pass']:
368 check_cpaste(code)
371 check_cpaste(code)
369
372
370 for code in tests['fail']:
373 for code in tests['fail']:
371 check_cpaste(code, should_fail=True)
374 check_cpaste(code, should_fail=True)
372
375
373 def test_xmode():
376 def test_xmode():
374 # Calling xmode three times should be a no-op
377 # Calling xmode three times should be a no-op
375 xmode = _ip.InteractiveTB.mode
378 xmode = _ip.InteractiveTB.mode
376 for i in range(3):
379 for i in range(3):
377 _ip.magic("xmode")
380 _ip.magic("xmode")
378 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
381 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
379
382
380 def test_reset_hard():
383 def test_reset_hard():
381 monitor = []
384 monitor = []
382 class A(object):
385 class A(object):
383 def __del__(self):
386 def __del__(self):
384 monitor.append(1)
387 monitor.append(1)
385 def __repr__(self):
388 def __repr__(self):
386 return "<A instance>"
389 return "<A instance>"
387
390
388 _ip.user_ns["a"] = A()
391 _ip.user_ns["a"] = A()
389 _ip.run_cell("a")
392 _ip.run_cell("a")
390
393
391 nt.assert_equal(monitor, [])
394 nt.assert_equal(monitor, [])
392 _ip.magic_reset("-f")
395 _ip.magic_reset("-f")
393 nt.assert_equal(monitor, [1])
396 nt.assert_equal(monitor, [1])
394
397
395 class TestXdel(tt.TempFileMixin):
398 class TestXdel(tt.TempFileMixin):
396 def test_xdel(self):
399 def test_xdel(self):
397 """Test that references from %run are cleared by xdel."""
400 """Test that references from %run are cleared by xdel."""
398 src = ("class A(object):\n"
401 src = ("class A(object):\n"
399 " monitor = []\n"
402 " monitor = []\n"
400 " def __del__(self):\n"
403 " def __del__(self):\n"
401 " self.monitor.append(1)\n"
404 " self.monitor.append(1)\n"
402 "a = A()\n")
405 "a = A()\n")
403 self.mktmp(src)
406 self.mktmp(src)
404 # %run creates some hidden references...
407 # %run creates some hidden references...
405 _ip.magic("run %s" % self.fname)
408 _ip.magic("run %s" % self.fname)
406 # ... as does the displayhook.
409 # ... as does the displayhook.
407 _ip.run_cell("a")
410 _ip.run_cell("a")
408
411
409 monitor = _ip.user_ns["A"].monitor
412 monitor = _ip.user_ns["A"].monitor
410 nt.assert_equal(monitor, [])
413 nt.assert_equal(monitor, [])
411
414
412 _ip.magic("xdel a")
415 _ip.magic("xdel a")
413
416
414 # Check that a's __del__ method has been called.
417 # Check that a's __del__ method has been called.
415 nt.assert_equal(monitor, [1])
418 nt.assert_equal(monitor, [1])
416
419
417 def doctest_who():
420 def doctest_who():
418 """doctest for %who
421 """doctest for %who
419
422
420 In [1]: %reset -f
423 In [1]: %reset -f
421
424
422 In [2]: alpha = 123
425 In [2]: alpha = 123
423
426
424 In [3]: beta = 'beta'
427 In [3]: beta = 'beta'
425
428
426 In [4]: %who int
429 In [4]: %who int
427 alpha
430 alpha
428
431
429 In [5]: %who str
432 In [5]: %who str
430 beta
433 beta
431
434
432 In [6]: %whos
435 In [6]: %whos
433 Variable Type Data/Info
436 Variable Type Data/Info
434 ----------------------------
437 ----------------------------
435 alpha int 123
438 alpha int 123
436 beta str beta
439 beta str beta
437
440
438 In [7]: %who_ls
441 In [7]: %who_ls
439 Out[7]: ['alpha', 'beta']
442 Out[7]: ['alpha', 'beta']
440 """
443 """
441
444
442 @py3compat.u_format
445 @py3compat.u_format
443 def doctest_precision():
446 def doctest_precision():
444 """doctest for %precision
447 """doctest for %precision
445
448
446 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
449 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
447
450
448 In [2]: %precision 5
451 In [2]: %precision 5
449 Out[2]: {u}'%.5f'
452 Out[2]: {u}'%.5f'
450
453
451 In [3]: f.float_format
454 In [3]: f.float_format
452 Out[3]: {u}'%.5f'
455 Out[3]: {u}'%.5f'
453
456
454 In [4]: %precision %e
457 In [4]: %precision %e
455 Out[4]: {u}'%e'
458 Out[4]: {u}'%e'
456
459
457 In [5]: f(3.1415927)
460 In [5]: f(3.1415927)
458 Out[5]: {u}'3.141593e+00'
461 Out[5]: {u}'3.141593e+00'
459 """
462 """
460
463
General Comments 0
You need to be logged in to leave comments. Login now