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