Show More
@@ -1,312 +1,311 b'' | |||||
1 | """ |
|
1 | """ | |
2 | Test for async helpers. |
|
2 | Test for async helpers. | |
3 |
|
3 | |||
4 | Should only trigger on python 3.5+ or will have syntax errors. |
|
4 | Should only trigger on python 3.5+ or will have syntax errors. | |
5 | """ |
|
5 | """ | |
6 |
|
||||
7 | import sys |
|
6 | import sys | |
8 | from itertools import chain, repeat |
|
7 | from itertools import chain, repeat | |
9 | import nose.tools as nt |
|
8 | import nose.tools as nt | |
10 | from textwrap import dedent, indent |
|
9 | from textwrap import dedent, indent | |
11 | from unittest import TestCase |
|
10 | from unittest import TestCase | |
12 | from IPython.testing.decorators import skip_without |
|
11 | from IPython.testing.decorators import skip_without | |
13 |
|
12 | |||
14 | ip = get_ipython() |
|
13 | ||
15 | iprc = lambda x: ip.run_cell(dedent(x)).raise_error() |
|
14 | iprc = lambda x: ip.run_cell(dedent(x)).raise_error() | |
16 | iprc_nr = lambda x: ip.run_cell(dedent(x)) |
|
15 | iprc_nr = lambda x: ip.run_cell(dedent(x)) | |
17 |
|
16 | |||
18 | if sys.version_info > (3, 5): |
|
17 | if sys.version_info > (3, 5): | |
19 | from IPython.core.async_helpers import _should_be_async |
|
18 | from IPython.core.async_helpers import _should_be_async | |
20 |
|
19 | |||
21 | class AsyncTest(TestCase): |
|
20 | class AsyncTest(TestCase): | |
22 | def test_should_be_async(self): |
|
21 | def test_should_be_async(self): | |
23 | nt.assert_false(_should_be_async("False")) |
|
22 | nt.assert_false(_should_be_async("False")) | |
24 | nt.assert_true(_should_be_async("await bar()")) |
|
23 | nt.assert_true(_should_be_async("await bar()")) | |
25 | nt.assert_true(_should_be_async("x = await bar()")) |
|
24 | nt.assert_true(_should_be_async("x = await bar()")) | |
26 | nt.assert_false( |
|
25 | nt.assert_false( | |
27 | _should_be_async( |
|
26 | _should_be_async( | |
28 | dedent( |
|
27 | dedent( | |
29 | """ |
|
28 | """ | |
30 | async def awaitable(): |
|
29 | async def awaitable(): | |
31 | pass |
|
30 | pass | |
32 | """ |
|
31 | """ | |
33 | ) |
|
32 | ) | |
34 | ) |
|
33 | ) | |
35 | ) |
|
34 | ) | |
36 |
|
35 | |||
37 | def _get_top_level_cases(self): |
|
36 | def _get_top_level_cases(self): | |
38 | # These are test cases that should be valid in a function |
|
37 | # These are test cases that should be valid in a function | |
39 | # but invalid outside of a function. |
|
38 | # but invalid outside of a function. | |
40 | test_cases = [] |
|
39 | test_cases = [] | |
41 | test_cases.append(('basic', "{val}")) |
|
40 | test_cases.append(('basic', "{val}")) | |
42 |
|
41 | |||
43 | # Note, in all conditional cases, I use True instead of |
|
42 | # Note, in all conditional cases, I use True instead of | |
44 | # False so that the peephole optimizer won't optimize away |
|
43 | # False so that the peephole optimizer won't optimize away | |
45 | # the return, so CPython will see this as a syntax error: |
|
44 | # the return, so CPython will see this as a syntax error: | |
46 | # |
|
45 | # | |
47 | # while True: |
|
46 | # while True: | |
48 | # break |
|
47 | # break | |
49 | # return |
|
48 | # return | |
50 | # |
|
49 | # | |
51 | # But not this: |
|
50 | # But not this: | |
52 | # |
|
51 | # | |
53 | # while False: |
|
52 | # while False: | |
54 | # return |
|
53 | # return | |
55 | # |
|
54 | # | |
56 | # See https://bugs.python.org/issue1875 |
|
55 | # See https://bugs.python.org/issue1875 | |
57 |
|
56 | |||
58 | test_cases.append(('if', dedent(""" |
|
57 | test_cases.append(('if', dedent(""" | |
59 | if True: |
|
58 | if True: | |
60 | {val} |
|
59 | {val} | |
61 | """))) |
|
60 | """))) | |
62 |
|
61 | |||
63 | test_cases.append(('while', dedent(""" |
|
62 | test_cases.append(('while', dedent(""" | |
64 | while True: |
|
63 | while True: | |
65 | {val} |
|
64 | {val} | |
66 | break |
|
65 | break | |
67 | """))) |
|
66 | """))) | |
68 |
|
67 | |||
69 | test_cases.append(('try', dedent(""" |
|
68 | test_cases.append(('try', dedent(""" | |
70 | try: |
|
69 | try: | |
71 | {val} |
|
70 | {val} | |
72 | except: |
|
71 | except: | |
73 | pass |
|
72 | pass | |
74 | """))) |
|
73 | """))) | |
75 |
|
74 | |||
76 | test_cases.append(('except', dedent(""" |
|
75 | test_cases.append(('except', dedent(""" | |
77 | try: |
|
76 | try: | |
78 | pass |
|
77 | pass | |
79 | except: |
|
78 | except: | |
80 | {val} |
|
79 | {val} | |
81 | """))) |
|
80 | """))) | |
82 |
|
81 | |||
83 | test_cases.append(('finally', dedent(""" |
|
82 | test_cases.append(('finally', dedent(""" | |
84 | try: |
|
83 | try: | |
85 | pass |
|
84 | pass | |
86 | except: |
|
85 | except: | |
87 | pass |
|
86 | pass | |
88 | finally: |
|
87 | finally: | |
89 | {val} |
|
88 | {val} | |
90 | """))) |
|
89 | """))) | |
91 |
|
90 | |||
92 | test_cases.append(('for', dedent(""" |
|
91 | test_cases.append(('for', dedent(""" | |
93 | for _ in range(4): |
|
92 | for _ in range(4): | |
94 | {val} |
|
93 | {val} | |
95 | """))) |
|
94 | """))) | |
96 |
|
95 | |||
97 |
|
96 | |||
98 | test_cases.append(('nested', dedent(""" |
|
97 | test_cases.append(('nested', dedent(""" | |
99 | if True: |
|
98 | if True: | |
100 | while True: |
|
99 | while True: | |
101 | {val} |
|
100 | {val} | |
102 | break |
|
101 | break | |
103 | """))) |
|
102 | """))) | |
104 |
|
103 | |||
105 | test_cases.append(('deep-nested', dedent(""" |
|
104 | test_cases.append(('deep-nested', dedent(""" | |
106 | if True: |
|
105 | if True: | |
107 | while True: |
|
106 | while True: | |
108 | break |
|
107 | break | |
109 | for x in range(3): |
|
108 | for x in range(3): | |
110 | if True: |
|
109 | if True: | |
111 | while True: |
|
110 | while True: | |
112 | for x in range(3): |
|
111 | for x in range(3): | |
113 | {val} |
|
112 | {val} | |
114 | """))) |
|
113 | """))) | |
115 |
|
114 | |||
116 | return test_cases |
|
115 | return test_cases | |
117 |
|
116 | |||
118 | def _get_ry_syntax_errors(self): |
|
117 | def _get_ry_syntax_errors(self): | |
119 | # This is a mix of tests that should be a syntax error if |
|
118 | # This is a mix of tests that should be a syntax error if | |
120 | # return or yield whether or not they are in a function |
|
119 | # return or yield whether or not they are in a function | |
121 |
|
120 | |||
122 | test_cases = [] |
|
121 | test_cases = [] | |
123 |
|
122 | |||
124 | test_cases.append(('class', dedent(""" |
|
123 | test_cases.append(('class', dedent(""" | |
125 | class V: |
|
124 | class V: | |
126 | {val} |
|
125 | {val} | |
127 | """))) |
|
126 | """))) | |
128 |
|
127 | |||
129 | test_cases.append(('nested-class', dedent(""" |
|
128 | test_cases.append(('nested-class', dedent(""" | |
130 | class V: |
|
129 | class V: | |
131 | class C: |
|
130 | class C: | |
132 | {val} |
|
131 | {val} | |
133 | """))) |
|
132 | """))) | |
134 |
|
133 | |||
135 | return test_cases |
|
134 | return test_cases | |
136 |
|
135 | |||
137 |
|
136 | |||
138 | def test_top_level_return_error(self): |
|
137 | def test_top_level_return_error(self): | |
139 | tl_err_test_cases = self._get_top_level_cases() |
|
138 | tl_err_test_cases = self._get_top_level_cases() | |
140 | tl_err_test_cases.extend(self._get_ry_syntax_errors()) |
|
139 | tl_err_test_cases.extend(self._get_ry_syntax_errors()) | |
141 |
|
140 | |||
142 | vals = ('return', 'yield', 'yield from (_ for _ in range(3))', |
|
141 | vals = ('return', 'yield', 'yield from (_ for _ in range(3))', | |
143 | dedent(''' |
|
142 | dedent(''' | |
144 | def f(): |
|
143 | def f(): | |
145 | pass |
|
144 | pass | |
146 | return |
|
145 | return | |
147 | '''), |
|
146 | '''), | |
148 | ) |
|
147 | ) | |
149 |
|
148 | |||
150 | for test_name, test_case in tl_err_test_cases: |
|
149 | for test_name, test_case in tl_err_test_cases: | |
151 | # This example should work if 'pass' is used as the value |
|
150 | # This example should work if 'pass' is used as the value | |
152 | with self.subTest((test_name, 'pass')): |
|
151 | with self.subTest((test_name, 'pass')): | |
153 | iprc(test_case.format(val='pass')) |
|
152 | iprc(test_case.format(val='pass')) | |
154 |
|
153 | |||
155 | # It should fail with all the values |
|
154 | # It should fail with all the values | |
156 | for val in vals: |
|
155 | for val in vals: | |
157 | with self.subTest((test_name, val)): |
|
156 | with self.subTest((test_name, val)): | |
158 | msg = "Syntax error not raised for %s, %s" % (test_name, val) |
|
157 | msg = "Syntax error not raised for %s, %s" % (test_name, val) | |
159 | with self.assertRaises(SyntaxError, msg=msg): |
|
158 | with self.assertRaises(SyntaxError, msg=msg): | |
160 | iprc(test_case.format(val=val)) |
|
159 | iprc(test_case.format(val=val)) | |
161 |
|
160 | |||
162 | def test_in_func_no_error(self): |
|
161 | def test_in_func_no_error(self): | |
163 | # Test that the implementation of top-level return/yield |
|
162 | # Test that the implementation of top-level return/yield | |
164 | # detection isn't *too* aggressive, and works inside a function |
|
163 | # detection isn't *too* aggressive, and works inside a function | |
165 | func_contexts = [] |
|
164 | func_contexts = [] | |
166 |
|
165 | |||
167 | func_contexts.append(('func', False, dedent(""" |
|
166 | func_contexts.append(('func', False, dedent(""" | |
168 | def f():"""))) |
|
167 | def f():"""))) | |
169 |
|
168 | |||
170 | func_contexts.append(('method', False, dedent(""" |
|
169 | func_contexts.append(('method', False, dedent(""" | |
171 | class MyClass: |
|
170 | class MyClass: | |
172 | def __init__(self): |
|
171 | def __init__(self): | |
173 | """))) |
|
172 | """))) | |
174 |
|
173 | |||
175 | func_contexts.append(('async-func', True, dedent(""" |
|
174 | func_contexts.append(('async-func', True, dedent(""" | |
176 | async def f():"""))) |
|
175 | async def f():"""))) | |
177 |
|
176 | |||
178 | func_contexts.append(('async-method', True, dedent(""" |
|
177 | func_contexts.append(('async-method', True, dedent(""" | |
179 | class MyClass: |
|
178 | class MyClass: | |
180 | async def f(self):"""))) |
|
179 | async def f(self):"""))) | |
181 |
|
180 | |||
182 | func_contexts.append(('closure', False, dedent(""" |
|
181 | func_contexts.append(('closure', False, dedent(""" | |
183 | def f(): |
|
182 | def f(): | |
184 | def g(): |
|
183 | def g(): | |
185 | """))) |
|
184 | """))) | |
186 |
|
185 | |||
187 | def nest_case(context, case): |
|
186 | def nest_case(context, case): | |
188 | # Detect indentation |
|
187 | # Detect indentation | |
189 | lines = context.strip().splitlines() |
|
188 | lines = context.strip().splitlines() | |
190 | prefix_len = 0 |
|
189 | prefix_len = 0 | |
191 | for c in lines[-1]: |
|
190 | for c in lines[-1]: | |
192 | if c != ' ': |
|
191 | if c != ' ': | |
193 | break |
|
192 | break | |
194 | prefix_len += 1 |
|
193 | prefix_len += 1 | |
195 |
|
194 | |||
196 | indented_case = indent(case, ' ' * (prefix_len + 4)) |
|
195 | indented_case = indent(case, ' ' * (prefix_len + 4)) | |
197 | return context + '\n' + indented_case |
|
196 | return context + '\n' + indented_case | |
198 |
|
197 | |||
199 | # Gather and run the tests |
|
198 | # Gather and run the tests | |
200 |
|
199 | |||
201 | # yield is allowed in async functions, starting in Python 3.6, |
|
200 | # yield is allowed in async functions, starting in Python 3.6, | |
202 | # and yield from is not allowed in any version |
|
201 | # and yield from is not allowed in any version | |
203 | vals = ('return', 'yield', 'yield from (_ for _ in range(3))') |
|
202 | vals = ('return', 'yield', 'yield from (_ for _ in range(3))') | |
204 | async_safe = (True, |
|
203 | async_safe = (True, | |
205 | sys.version_info >= (3, 6), |
|
204 | sys.version_info >= (3, 6), | |
206 | False) |
|
205 | False) | |
207 | vals = tuple(zip(vals, async_safe)) |
|
206 | vals = tuple(zip(vals, async_safe)) | |
208 |
|
207 | |||
209 | success_tests = zip(self._get_top_level_cases(), repeat(False)) |
|
208 | success_tests = zip(self._get_top_level_cases(), repeat(False)) | |
210 | failure_tests = zip(self._get_ry_syntax_errors(), repeat(True)) |
|
209 | failure_tests = zip(self._get_ry_syntax_errors(), repeat(True)) | |
211 |
|
210 | |||
212 | tests = chain(success_tests, failure_tests) |
|
211 | tests = chain(success_tests, failure_tests) | |
213 |
|
212 | |||
214 | for context_name, async_func, context in func_contexts: |
|
213 | for context_name, async_func, context in func_contexts: | |
215 | for (test_name, test_case), should_fail in tests: |
|
214 | for (test_name, test_case), should_fail in tests: | |
216 | nested_case = nest_case(context, test_case) |
|
215 | nested_case = nest_case(context, test_case) | |
217 |
|
216 | |||
218 | for val, async_safe in vals: |
|
217 | for val, async_safe in vals: | |
219 | val_should_fail = (should_fail or |
|
218 | val_should_fail = (should_fail or | |
220 | (async_func and not async_safe)) |
|
219 | (async_func and not async_safe)) | |
221 |
|
220 | |||
222 | test_id = (context_name, test_name, val) |
|
221 | test_id = (context_name, test_name, val) | |
223 | cell = nested_case.format(val=val) |
|
222 | cell = nested_case.format(val=val) | |
224 |
|
223 | |||
225 | with self.subTest(test_id): |
|
224 | with self.subTest(test_id): | |
226 | if val_should_fail: |
|
225 | if val_should_fail: | |
227 | msg = ("SyntaxError not raised for %s" % |
|
226 | msg = ("SyntaxError not raised for %s" % | |
228 | str(test_id)) |
|
227 | str(test_id)) | |
229 | with self.assertRaises(SyntaxError, msg=msg): |
|
228 | with self.assertRaises(SyntaxError, msg=msg): | |
230 | iprc(cell) |
|
229 | iprc(cell) | |
231 |
|
230 | |||
232 | print(cell) |
|
231 | print(cell) | |
233 | else: |
|
232 | else: | |
234 | iprc(cell) |
|
233 | iprc(cell) | |
235 |
|
234 | |||
236 | def test_nonlocal(self): |
|
235 | def test_nonlocal(self): | |
237 | # fails if outer scope is not a function scope or if var not defined |
|
236 | # fails if outer scope is not a function scope or if var not defined | |
238 | with self.assertRaises(SyntaxError): |
|
237 | with self.assertRaises(SyntaxError): | |
239 | iprc("nonlocal x") |
|
238 | iprc("nonlocal x") | |
240 | iprc(""" |
|
239 | iprc(""" | |
241 | x = 1 |
|
240 | x = 1 | |
242 | def f(): |
|
241 | def f(): | |
243 | nonlocal x |
|
242 | nonlocal x | |
244 | x = 10000 |
|
243 | x = 10000 | |
245 | yield x |
|
244 | yield x | |
246 | """) |
|
245 | """) | |
247 | iprc(""" |
|
246 | iprc(""" | |
248 | def f(): |
|
247 | def f(): | |
249 | def g(): |
|
248 | def g(): | |
250 | nonlocal x |
|
249 | nonlocal x | |
251 | x = 10000 |
|
250 | x = 10000 | |
252 | yield x |
|
251 | yield x | |
253 | """) |
|
252 | """) | |
254 |
|
253 | |||
255 | # works if outer scope is a function scope and var exists |
|
254 | # works if outer scope is a function scope and var exists | |
256 | iprc(""" |
|
255 | iprc(""" | |
257 | def f(): |
|
256 | def f(): | |
258 | x = 20 |
|
257 | x = 20 | |
259 | def g(): |
|
258 | def g(): | |
260 | nonlocal x |
|
259 | nonlocal x | |
261 | x = 10000 |
|
260 | x = 10000 | |
262 | yield x |
|
261 | yield x | |
263 | """) |
|
262 | """) | |
264 |
|
263 | |||
265 |
|
264 | |||
266 | def test_execute(self): |
|
265 | def test_execute(self): | |
267 | iprc(""" |
|
266 | iprc(""" | |
268 | import asyncio |
|
267 | import asyncio | |
269 | await asyncio.sleep(0.001) |
|
268 | await asyncio.sleep(0.001) | |
270 | """ |
|
269 | """ | |
271 | ) |
|
270 | ) | |
272 |
|
271 | |||
273 | def test_autoawait(self): |
|
272 | def test_autoawait(self): | |
274 | iprc("%autoawait False") |
|
273 | iprc("%autoawait False") | |
275 | iprc("%autoawait True") |
|
274 | iprc("%autoawait True") | |
276 | iprc(""" |
|
275 | iprc(""" | |
277 | from asyncio import sleep |
|
276 | from asyncio import sleep | |
278 | await sleep(0.1) |
|
277 | await sleep(0.1) | |
279 | """ |
|
278 | """ | |
280 | ) |
|
279 | ) | |
281 |
|
280 | |||
282 | @skip_without('curio') |
|
281 | @skip_without('curio') | |
283 | def test_autoawait_curio(self): |
|
282 | def test_autoawait_curio(self): | |
284 | iprc("%autoawait curio") |
|
283 | iprc("%autoawait curio") | |
285 |
|
284 | |||
286 | @skip_without('trio') |
|
285 | @skip_without('trio') | |
287 | def test_autoawait_trio(self): |
|
286 | def test_autoawait_trio(self): | |
288 | iprc("%autoawait trio") |
|
287 | iprc("%autoawait trio") | |
289 |
|
288 | |||
290 | @skip_without('trio') |
|
289 | @skip_without('trio') | |
291 | def test_autoawait_trio_wrong_sleep(self): |
|
290 | def test_autoawait_trio_wrong_sleep(self): | |
292 | iprc("%autoawait trio") |
|
291 | iprc("%autoawait trio") | |
293 | res = iprc_nr(""" |
|
292 | res = iprc_nr(""" | |
294 | import asyncio |
|
293 | import asyncio | |
295 | await asyncio.sleep(0) |
|
294 | await asyncio.sleep(0) | |
296 | """) |
|
295 | """) | |
297 | with nt.assert_raises(TypeError): |
|
296 | with nt.assert_raises(TypeError): | |
298 | res.raise_error() |
|
297 | res.raise_error() | |
299 |
|
298 | |||
300 | @skip_without('trio') |
|
299 | @skip_without('trio') | |
301 | def test_autoawait_asyncio_wrong_sleep(self): |
|
300 | def test_autoawait_asyncio_wrong_sleep(self): | |
302 | iprc("%autoawait asyncio") |
|
301 | iprc("%autoawait asyncio") | |
303 | res = iprc_nr(""" |
|
302 | res = iprc_nr(""" | |
304 | import trio |
|
303 | import trio | |
305 | await trio.sleep(0) |
|
304 | await trio.sleep(0) | |
306 | """) |
|
305 | """) | |
307 | with nt.assert_raises(RuntimeError): |
|
306 | with nt.assert_raises(RuntimeError): | |
308 | res.raise_error() |
|
307 | res.raise_error() | |
309 |
|
308 | |||
310 |
|
309 | |||
311 | def tearDown(self): |
|
310 | def tearDown(self): | |
312 | ip.loop_runner = "asyncio" |
|
311 | ip.loop_runner = "asyncio" |
@@ -1,72 +1,67 b'' | |||||
1 | """These kinds of tests are less than ideal, but at least they run. |
|
1 | """These kinds of tests are less than ideal, but at least they run. | |
2 |
|
2 | |||
3 | This was an old test that was being run interactively in the top-level tests/ |
|
3 | This was an old test that was being run interactively in the top-level tests/ | |
4 | directory, which we are removing. For now putting this here ensures at least |
|
4 | directory, which we are removing. For now putting this here ensures at least | |
5 | we do run the test, though ultimately this functionality should all be tested |
|
5 | we do run the test, though ultimately this functionality should all be tested | |
6 | with better-isolated tests that don't rely on the global instance in iptest. |
|
6 | with better-isolated tests that don't rely on the global instance in iptest. | |
7 | """ |
|
7 | """ | |
8 | from IPython.core.splitinput import LineInfo |
|
8 | from IPython.core.splitinput import LineInfo | |
9 | from IPython.core.prefilter import AutocallChecker |
|
9 | from IPython.core.prefilter import AutocallChecker | |
10 | from IPython.utils import py3compat |
|
10 | from IPython.utils import py3compat | |
11 | from IPython.testing.globalipapp import get_ipython |
|
|||
12 |
|
||||
13 |
|
||||
14 | ip = get_ipython() |
|
|||
15 |
|
||||
16 |
|
11 | |||
17 | def doctest_autocall(): |
|
12 | def doctest_autocall(): | |
18 | """ |
|
13 | """ | |
19 | In [1]: def f1(a,b,c): |
|
14 | In [1]: def f1(a,b,c): | |
20 | ...: return a+b+c |
|
15 | ...: return a+b+c | |
21 | ...: |
|
16 | ...: | |
22 |
|
17 | |||
23 | In [2]: def f2(a): |
|
18 | In [2]: def f2(a): | |
24 | ...: return a + a |
|
19 | ...: return a + a | |
25 | ...: |
|
20 | ...: | |
26 |
|
21 | |||
27 | In [3]: def r(x): |
|
22 | In [3]: def r(x): | |
28 | ...: return True |
|
23 | ...: return True | |
29 | ...: |
|
24 | ...: | |
30 |
|
25 | |||
31 | In [4]: ;f2 a b c |
|
26 | In [4]: ;f2 a b c | |
32 | Out[4]: 'a b ca b c' |
|
27 | Out[4]: 'a b ca b c' | |
33 |
|
28 | |||
34 | In [5]: assert _ == "a b ca b c" |
|
29 | In [5]: assert _ == "a b ca b c" | |
35 |
|
30 | |||
36 | In [6]: ,f1 a b c |
|
31 | In [6]: ,f1 a b c | |
37 | Out[6]: 'abc' |
|
32 | Out[6]: 'abc' | |
38 |
|
33 | |||
39 | In [7]: assert _ == 'abc' |
|
34 | In [7]: assert _ == 'abc' | |
40 |
|
35 | |||
41 | In [8]: print(_) |
|
36 | In [8]: print(_) | |
42 | abc |
|
37 | abc | |
43 |
|
38 | |||
44 | In [9]: /f1 1,2,3 |
|
39 | In [9]: /f1 1,2,3 | |
45 | Out[9]: 6 |
|
40 | Out[9]: 6 | |
46 |
|
41 | |||
47 | In [10]: assert _ == 6 |
|
42 | In [10]: assert _ == 6 | |
48 |
|
43 | |||
49 | In [11]: /f2 4 |
|
44 | In [11]: /f2 4 | |
50 | Out[11]: 8 |
|
45 | Out[11]: 8 | |
51 |
|
46 | |||
52 | In [12]: assert _ == 8 |
|
47 | In [12]: assert _ == 8 | |
53 |
|
48 | |||
54 | In [12]: del f1, f2 |
|
49 | In [12]: del f1, f2 | |
55 |
|
50 | |||
56 | In [13]: ,r a |
|
51 | In [13]: ,r a | |
57 | Out[13]: True |
|
52 | Out[13]: True | |
58 |
|
53 | |||
59 | In [14]: assert _ == True |
|
54 | In [14]: assert _ == True | |
60 |
|
55 | |||
61 | In [15]: r'a' |
|
56 | In [15]: r'a' | |
62 | Out[15]: 'a' |
|
57 | Out[15]: 'a' | |
63 |
|
58 | |||
64 | In [16]: assert _ == 'a' |
|
59 | In [16]: assert _ == 'a' | |
65 | """ |
|
60 | """ | |
66 |
|
61 | |||
67 |
|
62 | |||
68 | def test_autocall_should_ignore_raw_strings(): |
|
63 | def test_autocall_should_ignore_raw_strings(): | |
69 | line_info = LineInfo("r'a'") |
|
64 | line_info = LineInfo("r'a'") | |
70 | pm = ip.prefilter_manager |
|
65 | pm = ip.prefilter_manager | |
71 | ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, config=pm.config) |
|
66 | ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, config=pm.config) | |
72 | assert ac.check(line_info) is None |
|
67 | assert ac.check(line_info) is None |
@@ -1,114 +1,112 b'' | |||||
1 | import sys |
|
1 | import sys | |
2 | from IPython.testing.tools import AssertPrints, AssertNotPrints |
|
2 | from IPython.testing.tools import AssertPrints, AssertNotPrints | |
3 | from IPython.core.displayhook import CapturingDisplayHook |
|
3 | from IPython.core.displayhook import CapturingDisplayHook | |
4 | from IPython.utils.capture import CapturedIO |
|
4 | from IPython.utils.capture import CapturedIO | |
5 |
|
5 | |||
6 | ip = get_ipython() |
|
|||
7 |
|
||||
8 | def test_output_displayed(): |
|
6 | def test_output_displayed(): | |
9 | """Checking to make sure that output is displayed""" |
|
7 | """Checking to make sure that output is displayed""" | |
10 |
|
8 | |||
11 | with AssertPrints('2'): |
|
9 | with AssertPrints('2'): | |
12 | ip.run_cell('1+1', store_history=True) |
|
10 | ip.run_cell('1+1', store_history=True) | |
13 |
|
11 | |||
14 | with AssertPrints('2'): |
|
12 | with AssertPrints('2'): | |
15 | ip.run_cell('1+1 # comment with a semicolon;', store_history=True) |
|
13 | ip.run_cell('1+1 # comment with a semicolon;', store_history=True) | |
16 |
|
14 | |||
17 | with AssertPrints('2'): |
|
15 | with AssertPrints('2'): | |
18 | ip.run_cell('1+1\n#commented_out_function();', store_history=True) |
|
16 | ip.run_cell('1+1\n#commented_out_function();', store_history=True) | |
19 |
|
17 | |||
20 |
|
18 | |||
21 | def test_output_quiet(): |
|
19 | def test_output_quiet(): | |
22 | """Checking to make sure that output is quiet""" |
|
20 | """Checking to make sure that output is quiet""" | |
23 |
|
21 | |||
24 | with AssertNotPrints('2'): |
|
22 | with AssertNotPrints('2'): | |
25 | ip.run_cell('1+1;', store_history=True) |
|
23 | ip.run_cell('1+1;', store_history=True) | |
26 |
|
24 | |||
27 | with AssertNotPrints('2'): |
|
25 | with AssertNotPrints('2'): | |
28 | ip.run_cell('1+1; # comment with a semicolon', store_history=True) |
|
26 | ip.run_cell('1+1; # comment with a semicolon', store_history=True) | |
29 |
|
27 | |||
30 | with AssertNotPrints('2'): |
|
28 | with AssertNotPrints('2'): | |
31 | ip.run_cell('1+1;\n#commented_out_function()', store_history=True) |
|
29 | ip.run_cell('1+1;\n#commented_out_function()', store_history=True) | |
32 |
|
30 | |||
33 | def test_underscore_no_overrite_user(): |
|
31 | def test_underscore_no_overrite_user(): | |
34 | ip.run_cell('_ = 42', store_history=True) |
|
32 | ip.run_cell('_ = 42', store_history=True) | |
35 | ip.run_cell('1+1', store_history=True) |
|
33 | ip.run_cell('1+1', store_history=True) | |
36 |
|
34 | |||
37 | with AssertPrints('42'): |
|
35 | with AssertPrints('42'): | |
38 | ip.run_cell('print(_)', store_history=True) |
|
36 | ip.run_cell('print(_)', store_history=True) | |
39 |
|
37 | |||
40 | ip.run_cell('del _', store_history=True) |
|
38 | ip.run_cell('del _', store_history=True) | |
41 | ip.run_cell('6+6', store_history=True) |
|
39 | ip.run_cell('6+6', store_history=True) | |
42 | with AssertPrints('12'): |
|
40 | with AssertPrints('12'): | |
43 | ip.run_cell('_', store_history=True) |
|
41 | ip.run_cell('_', store_history=True) | |
44 |
|
42 | |||
45 |
|
43 | |||
46 | def test_underscore_no_overrite_builtins(): |
|
44 | def test_underscore_no_overrite_builtins(): | |
47 | ip.run_cell("import gettext ; gettext.install('foo')", store_history=True) |
|
45 | ip.run_cell("import gettext ; gettext.install('foo')", store_history=True) | |
48 | ip.run_cell('3+3', store_history=True) |
|
46 | ip.run_cell('3+3', store_history=True) | |
49 |
|
47 | |||
50 | with AssertPrints('gettext'): |
|
48 | with AssertPrints('gettext'): | |
51 | ip.run_cell('print(_)', store_history=True) |
|
49 | ip.run_cell('print(_)', store_history=True) | |
52 |
|
50 | |||
53 | ip.run_cell('_ = "userset"', store_history=True) |
|
51 | ip.run_cell('_ = "userset"', store_history=True) | |
54 |
|
52 | |||
55 | with AssertPrints('userset'): |
|
53 | with AssertPrints('userset'): | |
56 | ip.run_cell('print(_)', store_history=True) |
|
54 | ip.run_cell('print(_)', store_history=True) | |
57 | ip.run_cell('import builtins; del builtins._') |
|
55 | ip.run_cell('import builtins; del builtins._') | |
58 |
|
56 | |||
59 |
|
57 | |||
60 | def test_interactivehooks_ast_modes(): |
|
58 | def test_interactivehooks_ast_modes(): | |
61 | """ |
|
59 | """ | |
62 | Test that ast nodes can be triggered with different modes |
|
60 | Test that ast nodes can be triggered with different modes | |
63 | """ |
|
61 | """ | |
64 | saved_mode = ip.ast_node_interactivity |
|
62 | saved_mode = ip.ast_node_interactivity | |
65 | ip.ast_node_interactivity = 'last_expr_or_assign' |
|
63 | ip.ast_node_interactivity = 'last_expr_or_assign' | |
66 |
|
64 | |||
67 | try: |
|
65 | try: | |
68 | with AssertPrints('2'): |
|
66 | with AssertPrints('2'): | |
69 | ip.run_cell('a = 1+1', store_history=True) |
|
67 | ip.run_cell('a = 1+1', store_history=True) | |
70 |
|
68 | |||
71 | with AssertPrints('9'): |
|
69 | with AssertPrints('9'): | |
72 | ip.run_cell('b = 1+8 # comment with a semicolon;', store_history=False) |
|
70 | ip.run_cell('b = 1+8 # comment with a semicolon;', store_history=False) | |
73 |
|
71 | |||
74 | with AssertPrints('7'): |
|
72 | with AssertPrints('7'): | |
75 | ip.run_cell('c = 1+6\n#commented_out_function();', store_history=True) |
|
73 | ip.run_cell('c = 1+6\n#commented_out_function();', store_history=True) | |
76 |
|
74 | |||
77 | ip.run_cell('d = 11', store_history=True) |
|
75 | ip.run_cell('d = 11', store_history=True) | |
78 | with AssertPrints('12'): |
|
76 | with AssertPrints('12'): | |
79 | ip.run_cell('d += 1', store_history=True) |
|
77 | ip.run_cell('d += 1', store_history=True) | |
80 |
|
78 | |||
81 | with AssertNotPrints('42'): |
|
79 | with AssertNotPrints('42'): | |
82 | ip.run_cell('(u,v) = (41+1, 43-1)') |
|
80 | ip.run_cell('(u,v) = (41+1, 43-1)') | |
83 |
|
81 | |||
84 | finally: |
|
82 | finally: | |
85 | ip.ast_node_interactivity = saved_mode |
|
83 | ip.ast_node_interactivity = saved_mode | |
86 |
|
84 | |||
87 | def test_interactivehooks_ast_modes_semi_supress(): |
|
85 | def test_interactivehooks_ast_modes_semi_supress(): | |
88 | """ |
|
86 | """ | |
89 | Test that ast nodes can be triggered with different modes and suppressed |
|
87 | Test that ast nodes can be triggered with different modes and suppressed | |
90 | by semicolon |
|
88 | by semicolon | |
91 | """ |
|
89 | """ | |
92 | saved_mode = ip.ast_node_interactivity |
|
90 | saved_mode = ip.ast_node_interactivity | |
93 | ip.ast_node_interactivity = 'last_expr_or_assign' |
|
91 | ip.ast_node_interactivity = 'last_expr_or_assign' | |
94 |
|
92 | |||
95 | try: |
|
93 | try: | |
96 | with AssertNotPrints('2'): |
|
94 | with AssertNotPrints('2'): | |
97 | ip.run_cell('x = 1+1;', store_history=True) |
|
95 | ip.run_cell('x = 1+1;', store_history=True) | |
98 |
|
96 | |||
99 | with AssertNotPrints('7'): |
|
97 | with AssertNotPrints('7'): | |
100 | ip.run_cell('y = 1+6; # comment with a semicolon', store_history=True) |
|
98 | ip.run_cell('y = 1+6; # comment with a semicolon', store_history=True) | |
101 |
|
99 | |||
102 | with AssertNotPrints('9'): |
|
100 | with AssertNotPrints('9'): | |
103 | ip.run_cell('z = 1+8;\n#commented_out_function()', store_history=True) |
|
101 | ip.run_cell('z = 1+8;\n#commented_out_function()', store_history=True) | |
104 |
|
102 | |||
105 | finally: |
|
103 | finally: | |
106 | ip.ast_node_interactivity = saved_mode |
|
104 | ip.ast_node_interactivity = saved_mode | |
107 |
|
105 | |||
108 | def test_capture_display_hook_format(): |
|
106 | def test_capture_display_hook_format(): | |
109 | """Tests that the capture display hook conforms to the CapturedIO output format""" |
|
107 | """Tests that the capture display hook conforms to the CapturedIO output format""" | |
110 | hook = CapturingDisplayHook(ip) |
|
108 | hook = CapturingDisplayHook(ip) | |
111 | hook({"foo": "bar"}) |
|
109 | hook({"foo": "bar"}) | |
112 | captured = CapturedIO(sys.stdout, sys.stderr, hook.outputs) |
|
110 | captured = CapturedIO(sys.stdout, sys.stderr, hook.outputs) | |
113 | # Should not raise with RichOutput transformation error |
|
111 | # Should not raise with RichOutput transformation error | |
114 | captured.outputs |
|
112 | captured.outputs |
@@ -1,97 +1,95 b'' | |||||
1 | """Tests for input handlers. |
|
1 | """Tests for input handlers. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Module imports |
|
4 | # Module imports | |
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 |
|
6 | |||
7 | # third party |
|
7 | # third party | |
8 | import nose.tools as nt |
|
8 | import nose.tools as nt | |
9 |
|
9 | |||
10 | # our own packages |
|
10 | # our own packages | |
11 | from IPython.core import autocall |
|
11 | from IPython.core import autocall | |
12 | from IPython.testing import tools as tt |
|
12 | from IPython.testing import tools as tt | |
13 | from IPython.testing.globalipapp import get_ipython |
|
|||
14 | from IPython.utils import py3compat |
|
13 | from IPython.utils import py3compat | |
15 |
|
14 | |||
16 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
17 | # Globals |
|
16 | # Globals | |
18 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
19 |
|
18 | |||
20 | # Get the public instance of IPython |
|
19 | # Get the public instance of IPython | |
21 | ip = get_ipython() |
|
|||
22 |
|
20 | |||
23 | failures = [] |
|
21 | failures = [] | |
24 | num_tests = 0 |
|
22 | num_tests = 0 | |
25 |
|
23 | |||
26 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
27 | # Test functions |
|
25 | # Test functions | |
28 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
29 |
|
27 | |||
30 | class CallableIndexable(object): |
|
28 | class CallableIndexable(object): | |
31 | def __getitem__(self, idx): return True |
|
29 | def __getitem__(self, idx): return True | |
32 | def __call__(self, *args, **kws): return True |
|
30 | def __call__(self, *args, **kws): return True | |
33 |
|
31 | |||
34 |
|
32 | |||
35 | class Autocallable(autocall.IPyAutocall): |
|
33 | class Autocallable(autocall.IPyAutocall): | |
36 | def __call__(self): |
|
34 | def __call__(self): | |
37 | return "called" |
|
35 | return "called" | |
38 |
|
36 | |||
39 |
|
37 | |||
40 | def run(tests): |
|
38 | def run(tests): | |
41 | """Loop through a list of (pre, post) inputs, where pre is the string |
|
39 | """Loop through a list of (pre, post) inputs, where pre is the string | |
42 | handed to ipython, and post is how that string looks after it's been |
|
40 | handed to ipython, and post is how that string looks after it's been | |
43 | transformed (i.e. ipython's notion of _i)""" |
|
41 | transformed (i.e. ipython's notion of _i)""" | |
44 | tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests) |
|
42 | tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests) | |
45 |
|
43 | |||
46 |
|
44 | |||
47 | def test_handlers(): |
|
45 | def test_handlers(): | |
48 | call_idx = CallableIndexable() |
|
46 | call_idx = CallableIndexable() | |
49 | ip.user_ns['call_idx'] = call_idx |
|
47 | ip.user_ns['call_idx'] = call_idx | |
50 |
|
48 | |||
51 | # For many of the below, we're also checking that leading whitespace |
|
49 | # For many of the below, we're also checking that leading whitespace | |
52 | # turns off the esc char, which it should unless there is a continuation |
|
50 | # turns off the esc char, which it should unless there is a continuation | |
53 | # line. |
|
51 | # line. | |
54 | run([(i,py3compat.u_format(o)) for i,o in \ |
|
52 | run([(i,py3compat.u_format(o)) for i,o in \ | |
55 | [('"no change"', '"no change"'), # normal |
|
53 | [('"no change"', '"no change"'), # normal | |
56 | (u"lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic |
|
54 | (u"lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic | |
57 | #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache |
|
55 | #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache | |
58 | ]]) |
|
56 | ]]) | |
59 |
|
57 | |||
60 | # Objects which are instances of IPyAutocall are *always* autocalled |
|
58 | # Objects which are instances of IPyAutocall are *always* autocalled | |
61 | autocallable = Autocallable() |
|
59 | autocallable = Autocallable() | |
62 | ip.user_ns['autocallable'] = autocallable |
|
60 | ip.user_ns['autocallable'] = autocallable | |
63 |
|
61 | |||
64 | # auto |
|
62 | # auto | |
65 | ip.magic('autocall 0') |
|
63 | ip.magic('autocall 0') | |
66 | # Only explicit escapes or instances of IPyAutocallable should get |
|
64 | # Only explicit escapes or instances of IPyAutocallable should get | |
67 | # expanded |
|
65 | # expanded | |
68 | run([ |
|
66 | run([ | |
69 | ('len "abc"', 'len "abc"'), |
|
67 | ('len "abc"', 'len "abc"'), | |
70 | ('autocallable', 'autocallable()'), |
|
68 | ('autocallable', 'autocallable()'), | |
71 | # Don't add extra brackets (gh-1117) |
|
69 | # Don't add extra brackets (gh-1117) | |
72 | ('autocallable()', 'autocallable()'), |
|
70 | ('autocallable()', 'autocallable()'), | |
73 | ]) |
|
71 | ]) | |
74 | ip.magic('autocall 1') |
|
72 | ip.magic('autocall 1') | |
75 | run([ |
|
73 | run([ | |
76 | ('len "abc"', 'len("abc")'), |
|
74 | ('len "abc"', 'len("abc")'), | |
77 | ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens |
|
75 | ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens | |
78 | # Autocall is turned off if first arg is [] and the object |
|
76 | # Autocall is turned off if first arg is [] and the object | |
79 | # is both callable and indexable. Like so: |
|
77 | # is both callable and indexable. Like so: | |
80 | ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__... |
|
78 | ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__... | |
81 | ('call_idx [1]', 'call_idx [1]'), # call_idx *does*.. |
|
79 | ('call_idx [1]', 'call_idx [1]'), # call_idx *does*.. | |
82 | ('call_idx 1', 'call_idx(1)'), |
|
80 | ('call_idx 1', 'call_idx(1)'), | |
83 | ('len', 'len'), # only at 2 does it auto-call on single args |
|
81 | ('len', 'len'), # only at 2 does it auto-call on single args | |
84 | ]) |
|
82 | ]) | |
85 | ip.magic('autocall 2') |
|
83 | ip.magic('autocall 2') | |
86 | run([ |
|
84 | run([ | |
87 | ('len "abc"', 'len("abc")'), |
|
85 | ('len "abc"', 'len("abc")'), | |
88 | ('len "abc";', 'len("abc");'), |
|
86 | ('len "abc";', 'len("abc");'), | |
89 | ('len [1,2]', 'len([1,2])'), |
|
87 | ('len [1,2]', 'len([1,2])'), | |
90 | ('call_idx [1]', 'call_idx [1]'), |
|
88 | ('call_idx [1]', 'call_idx [1]'), | |
91 | ('call_idx 1', 'call_idx(1)'), |
|
89 | ('call_idx 1', 'call_idx(1)'), | |
92 | # This is what's different: |
|
90 | # This is what's different: | |
93 | ('len', 'len()'), # only at 2 does it auto-call on single args |
|
91 | ('len', 'len()'), # only at 2 does it auto-call on single args | |
94 | ]) |
|
92 | ]) | |
95 | ip.magic('autocall 1') |
|
93 | ip.magic('autocall 1') | |
96 |
|
94 | |||
97 | nt.assert_equal(failures, []) |
|
95 | nt.assert_equal(failures, []) |
@@ -1,254 +1,246 b'' | |||||
1 | """Tests for the key interactiveshell module, where the main ipython class is defined. |
|
1 | """Tests for the key interactiveshell module, where the main ipython class is defined. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Module imports |
|
4 | # Module imports | |
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 |
|
6 | |||
7 | # third party |
|
7 | # third party | |
8 | import nose.tools as nt |
|
8 | import nose.tools as nt | |
9 |
|
9 | |||
10 | # our own packages |
|
10 | # our own packages | |
11 | from IPython.testing.globalipapp import get_ipython |
|
|||
12 |
|
||||
13 | #----------------------------------------------------------------------------- |
|
|||
14 | # Globals |
|
|||
15 | #----------------------------------------------------------------------------- |
|
|||
16 |
|
||||
17 | # Get the public instance of IPython |
|
|||
18 | ip = get_ipython() |
|
|||
19 |
|
11 | |||
20 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
21 | # Test functions |
|
13 | # Test functions | |
22 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
23 |
|
15 | |||
24 | def test_reset(): |
|
16 | def test_reset(): | |
25 | """reset must clear most namespaces.""" |
|
17 | """reset must clear most namespaces.""" | |
26 |
|
18 | |||
27 | # Check that reset runs without error |
|
19 | # Check that reset runs without error | |
28 | ip.reset() |
|
20 | ip.reset() | |
29 |
|
21 | |||
30 | # Once we've reset it (to clear of any junk that might have been there from |
|
22 | # Once we've reset it (to clear of any junk that might have been there from | |
31 | # other tests, we can count how many variables are in the user's namespace |
|
23 | # other tests, we can count how many variables are in the user's namespace | |
32 | nvars_user_ns = len(ip.user_ns) |
|
24 | nvars_user_ns = len(ip.user_ns) | |
33 | nvars_hidden = len(ip.user_ns_hidden) |
|
25 | nvars_hidden = len(ip.user_ns_hidden) | |
34 |
|
26 | |||
35 | # Now add a few variables to user_ns, and check that reset clears them |
|
27 | # Now add a few variables to user_ns, and check that reset clears them | |
36 | ip.user_ns['x'] = 1 |
|
28 | ip.user_ns['x'] = 1 | |
37 | ip.user_ns['y'] = 1 |
|
29 | ip.user_ns['y'] = 1 | |
38 | ip.reset() |
|
30 | ip.reset() | |
39 |
|
31 | |||
40 | # Finally, check that all namespaces have only as many variables as we |
|
32 | # Finally, check that all namespaces have only as many variables as we | |
41 | # expect to find in them: |
|
33 | # expect to find in them: | |
42 | nt.assert_equal(len(ip.user_ns), nvars_user_ns) |
|
34 | nt.assert_equal(len(ip.user_ns), nvars_user_ns) | |
43 | nt.assert_equal(len(ip.user_ns_hidden), nvars_hidden) |
|
35 | nt.assert_equal(len(ip.user_ns_hidden), nvars_hidden) | |
44 |
|
36 | |||
45 |
|
37 | |||
46 | # Tests for reporting of exceptions in various modes, handling of SystemExit, |
|
38 | # Tests for reporting of exceptions in various modes, handling of SystemExit, | |
47 | # and %tb functionality. This is really a mix of testing ultraTB and interactiveshell. |
|
39 | # and %tb functionality. This is really a mix of testing ultraTB and interactiveshell. | |
48 |
|
40 | |||
49 | def doctest_tb_plain(): |
|
41 | def doctest_tb_plain(): | |
50 | """ |
|
42 | """ | |
51 | In [18]: xmode plain |
|
43 | In [18]: xmode plain | |
52 | Exception reporting mode: Plain |
|
44 | Exception reporting mode: Plain | |
53 |
|
45 | |||
54 | In [19]: run simpleerr.py |
|
46 | In [19]: run simpleerr.py | |
55 | Traceback (most recent call last): |
|
47 | Traceback (most recent call last): | |
56 | ...line 32, in <module> |
|
48 | ...line 32, in <module> | |
57 | bar(mode) |
|
49 | bar(mode) | |
58 | ...line 16, in bar |
|
50 | ...line 16, in bar | |
59 | div0() |
|
51 | div0() | |
60 | ...line 8, in div0 |
|
52 | ...line 8, in div0 | |
61 | x/y |
|
53 | x/y | |
62 | ZeroDivisionError: ... |
|
54 | ZeroDivisionError: ... | |
63 | """ |
|
55 | """ | |
64 |
|
56 | |||
65 |
|
57 | |||
66 | def doctest_tb_context(): |
|
58 | def doctest_tb_context(): | |
67 | """ |
|
59 | """ | |
68 | In [3]: xmode context |
|
60 | In [3]: xmode context | |
69 | Exception reporting mode: Context |
|
61 | Exception reporting mode: Context | |
70 |
|
62 | |||
71 | In [4]: run simpleerr.py |
|
63 | In [4]: run simpleerr.py | |
72 | --------------------------------------------------------------------------- |
|
64 | --------------------------------------------------------------------------- | |
73 | ZeroDivisionError Traceback (most recent call last) |
|
65 | ZeroDivisionError Traceback (most recent call last) | |
74 | <BLANKLINE> |
|
66 | <BLANKLINE> | |
75 | ... in <module> |
|
67 | ... in <module> | |
76 | 30 mode = 'div' |
|
68 | 30 mode = 'div' | |
77 | 31 |
|
69 | 31 | |
78 | ---> 32 bar(mode) |
|
70 | ---> 32 bar(mode) | |
79 | <BLANKLINE> |
|
71 | <BLANKLINE> | |
80 | ... in bar(mode) |
|
72 | ... in bar(mode) | |
81 | 14 "bar" |
|
73 | 14 "bar" | |
82 | 15 if mode=='div': |
|
74 | 15 if mode=='div': | |
83 | ---> 16 div0() |
|
75 | ---> 16 div0() | |
84 | 17 elif mode=='exit': |
|
76 | 17 elif mode=='exit': | |
85 | 18 try: |
|
77 | 18 try: | |
86 | <BLANKLINE> |
|
78 | <BLANKLINE> | |
87 | ... in div0() |
|
79 | ... in div0() | |
88 | 6 x = 1 |
|
80 | 6 x = 1 | |
89 | 7 y = 0 |
|
81 | 7 y = 0 | |
90 | ----> 8 x/y |
|
82 | ----> 8 x/y | |
91 | 9 |
|
83 | 9 | |
92 | 10 def sysexit(stat, mode): |
|
84 | 10 def sysexit(stat, mode): | |
93 | <BLANKLINE> |
|
85 | <BLANKLINE> | |
94 | ZeroDivisionError: ... |
|
86 | ZeroDivisionError: ... | |
95 | """ |
|
87 | """ | |
96 |
|
88 | |||
97 |
|
89 | |||
98 | def doctest_tb_verbose(): |
|
90 | def doctest_tb_verbose(): | |
99 | """ |
|
91 | """ | |
100 | In [5]: xmode verbose |
|
92 | In [5]: xmode verbose | |
101 | Exception reporting mode: Verbose |
|
93 | Exception reporting mode: Verbose | |
102 |
|
94 | |||
103 | In [6]: run simpleerr.py |
|
95 | In [6]: run simpleerr.py | |
104 | --------------------------------------------------------------------------- |
|
96 | --------------------------------------------------------------------------- | |
105 | ZeroDivisionError Traceback (most recent call last) |
|
97 | ZeroDivisionError Traceback (most recent call last) | |
106 | <BLANKLINE> |
|
98 | <BLANKLINE> | |
107 | ... in <module> |
|
99 | ... in <module> | |
108 | 30 mode = 'div' |
|
100 | 30 mode = 'div' | |
109 | 31 |
|
101 | 31 | |
110 | ---> 32 bar(mode) |
|
102 | ---> 32 bar(mode) | |
111 | global bar = <function bar at ...> |
|
103 | global bar = <function bar at ...> | |
112 | global mode = 'div' |
|
104 | global mode = 'div' | |
113 | <BLANKLINE> |
|
105 | <BLANKLINE> | |
114 | ... in bar(mode='div') |
|
106 | ... in bar(mode='div') | |
115 | 14 "bar" |
|
107 | 14 "bar" | |
116 | 15 if mode=='div': |
|
108 | 15 if mode=='div': | |
117 | ---> 16 div0() |
|
109 | ---> 16 div0() | |
118 | global div0 = <function div0 at ...> |
|
110 | global div0 = <function div0 at ...> | |
119 | 17 elif mode=='exit': |
|
111 | 17 elif mode=='exit': | |
120 | 18 try: |
|
112 | 18 try: | |
121 | <BLANKLINE> |
|
113 | <BLANKLINE> | |
122 | ... in div0() |
|
114 | ... in div0() | |
123 | 6 x = 1 |
|
115 | 6 x = 1 | |
124 | 7 y = 0 |
|
116 | 7 y = 0 | |
125 | ----> 8 x/y |
|
117 | ----> 8 x/y | |
126 | x = 1 |
|
118 | x = 1 | |
127 | y = 0 |
|
119 | y = 0 | |
128 | 9 |
|
120 | 9 | |
129 | 10 def sysexit(stat, mode): |
|
121 | 10 def sysexit(stat, mode): | |
130 | <BLANKLINE> |
|
122 | <BLANKLINE> | |
131 | ZeroDivisionError: ... |
|
123 | ZeroDivisionError: ... | |
132 | """ |
|
124 | """ | |
133 |
|
125 | |||
134 | def doctest_tb_sysexit(): |
|
126 | def doctest_tb_sysexit(): | |
135 | """ |
|
127 | """ | |
136 | In [17]: %xmode plain |
|
128 | In [17]: %xmode plain | |
137 | Exception reporting mode: Plain |
|
129 | Exception reporting mode: Plain | |
138 |
|
130 | |||
139 | In [18]: %run simpleerr.py exit |
|
131 | In [18]: %run simpleerr.py exit | |
140 | An exception has occurred, use %tb to see the full traceback. |
|
132 | An exception has occurred, use %tb to see the full traceback. | |
141 | SystemExit: (1, 'Mode = exit') |
|
133 | SystemExit: (1, 'Mode = exit') | |
142 |
|
134 | |||
143 | In [19]: %run simpleerr.py exit 2 |
|
135 | In [19]: %run simpleerr.py exit 2 | |
144 | An exception has occurred, use %tb to see the full traceback. |
|
136 | An exception has occurred, use %tb to see the full traceback. | |
145 | SystemExit: (2, 'Mode = exit') |
|
137 | SystemExit: (2, 'Mode = exit') | |
146 |
|
138 | |||
147 | In [20]: %tb |
|
139 | In [20]: %tb | |
148 | Traceback (most recent call last): |
|
140 | Traceback (most recent call last): | |
149 | File ... in <module> |
|
141 | File ... in <module> | |
150 | bar(mode) |
|
142 | bar(mode) | |
151 | File ... line 22, in bar |
|
143 | File ... line 22, in bar | |
152 | sysexit(stat, mode) |
|
144 | sysexit(stat, mode) | |
153 | File ... line 11, in sysexit |
|
145 | File ... line 11, in sysexit | |
154 | raise SystemExit(stat, 'Mode = %s' % mode) |
|
146 | raise SystemExit(stat, 'Mode = %s' % mode) | |
155 | SystemExit: (2, 'Mode = exit') |
|
147 | SystemExit: (2, 'Mode = exit') | |
156 |
|
148 | |||
157 | In [21]: %xmode context |
|
149 | In [21]: %xmode context | |
158 | Exception reporting mode: Context |
|
150 | Exception reporting mode: Context | |
159 |
|
151 | |||
160 | In [22]: %tb |
|
152 | In [22]: %tb | |
161 | --------------------------------------------------------------------------- |
|
153 | --------------------------------------------------------------------------- | |
162 | SystemExit Traceback (most recent call last) |
|
154 | SystemExit Traceback (most recent call last) | |
163 | <BLANKLINE> |
|
155 | <BLANKLINE> | |
164 | ...<module> |
|
156 | ...<module> | |
165 | 30 mode = 'div' |
|
157 | 30 mode = 'div' | |
166 | 31 |
|
158 | 31 | |
167 | ---> 32 bar(mode) |
|
159 | ---> 32 bar(mode) | |
168 | <BLANKLINE> |
|
160 | <BLANKLINE> | |
169 | ...bar(mode) |
|
161 | ...bar(mode) | |
170 | 20 except: |
|
162 | 20 except: | |
171 | 21 stat = 1 |
|
163 | 21 stat = 1 | |
172 | ---> 22 sysexit(stat, mode) |
|
164 | ---> 22 sysexit(stat, mode) | |
173 | 23 else: |
|
165 | 23 else: | |
174 | 24 raise ValueError('Unknown mode') |
|
166 | 24 raise ValueError('Unknown mode') | |
175 | <BLANKLINE> |
|
167 | <BLANKLINE> | |
176 | ...sysexit(stat, mode) |
|
168 | ...sysexit(stat, mode) | |
177 | 9 |
|
169 | 9 | |
178 | 10 def sysexit(stat, mode): |
|
170 | 10 def sysexit(stat, mode): | |
179 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) |
|
171 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) | |
180 | 12 |
|
172 | 12 | |
181 | 13 def bar(mode): |
|
173 | 13 def bar(mode): | |
182 | <BLANKLINE> |
|
174 | <BLANKLINE> | |
183 | SystemExit: (2, 'Mode = exit') |
|
175 | SystemExit: (2, 'Mode = exit') | |
184 |
|
176 | |||
185 | In [23]: %xmode verbose |
|
177 | In [23]: %xmode verbose | |
186 | Exception reporting mode: Verbose |
|
178 | Exception reporting mode: Verbose | |
187 |
|
179 | |||
188 | In [24]: %tb |
|
180 | In [24]: %tb | |
189 | --------------------------------------------------------------------------- |
|
181 | --------------------------------------------------------------------------- | |
190 | SystemExit Traceback (most recent call last) |
|
182 | SystemExit Traceback (most recent call last) | |
191 | <BLANKLINE> |
|
183 | <BLANKLINE> | |
192 | ... in <module> |
|
184 | ... in <module> | |
193 | 30 mode = 'div' |
|
185 | 30 mode = 'div' | |
194 | 31 |
|
186 | 31 | |
195 | ---> 32 bar(mode) |
|
187 | ---> 32 bar(mode) | |
196 | global bar = <function bar at ...> |
|
188 | global bar = <function bar at ...> | |
197 | global mode = 'exit' |
|
189 | global mode = 'exit' | |
198 | <BLANKLINE> |
|
190 | <BLANKLINE> | |
199 | ... in bar(mode='exit') |
|
191 | ... in bar(mode='exit') | |
200 | 20 except: |
|
192 | 20 except: | |
201 | 21 stat = 1 |
|
193 | 21 stat = 1 | |
202 | ---> 22 sysexit(stat, mode) |
|
194 | ---> 22 sysexit(stat, mode) | |
203 | global sysexit = <function sysexit at ...> |
|
195 | global sysexit = <function sysexit at ...> | |
204 | stat = 2 |
|
196 | stat = 2 | |
205 | mode = 'exit' |
|
197 | mode = 'exit' | |
206 | 23 else: |
|
198 | 23 else: | |
207 | 24 raise ValueError('Unknown mode') |
|
199 | 24 raise ValueError('Unknown mode') | |
208 | <BLANKLINE> |
|
200 | <BLANKLINE> | |
209 | ... in sysexit(stat=2, mode='exit') |
|
201 | ... in sysexit(stat=2, mode='exit') | |
210 | 9 |
|
202 | 9 | |
211 | 10 def sysexit(stat, mode): |
|
203 | 10 def sysexit(stat, mode): | |
212 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) |
|
204 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) | |
213 | global SystemExit = undefined |
|
205 | global SystemExit = undefined | |
214 | stat = 2 |
|
206 | stat = 2 | |
215 | mode = 'exit' |
|
207 | mode = 'exit' | |
216 | 12 |
|
208 | 12 | |
217 | 13 def bar(mode): |
|
209 | 13 def bar(mode): | |
218 | <BLANKLINE> |
|
210 | <BLANKLINE> | |
219 | SystemExit: (2, 'Mode = exit') |
|
211 | SystemExit: (2, 'Mode = exit') | |
220 | """ |
|
212 | """ | |
221 |
|
213 | |||
222 |
|
214 | |||
223 | def test_run_cell(): |
|
215 | def test_run_cell(): | |
224 | import textwrap |
|
216 | import textwrap | |
225 | ip.run_cell('a = 10\na+=1') |
|
217 | ip.run_cell('a = 10\na+=1') | |
226 | ip.run_cell('assert a == 11\nassert 1') |
|
218 | ip.run_cell('assert a == 11\nassert 1') | |
227 |
|
219 | |||
228 | nt.assert_equal(ip.user_ns['a'], 11) |
|
220 | nt.assert_equal(ip.user_ns['a'], 11) | |
229 | complex = textwrap.dedent(""" |
|
221 | complex = textwrap.dedent(""" | |
230 | if 1: |
|
222 | if 1: | |
231 | print "hello" |
|
223 | print "hello" | |
232 | if 1: |
|
224 | if 1: | |
233 | print "world" |
|
225 | print "world" | |
234 |
|
226 | |||
235 | if 2: |
|
227 | if 2: | |
236 | print "foo" |
|
228 | print "foo" | |
237 |
|
229 | |||
238 | if 3: |
|
230 | if 3: | |
239 | print "bar" |
|
231 | print "bar" | |
240 |
|
232 | |||
241 | if 4: |
|
233 | if 4: | |
242 | print "bar" |
|
234 | print "bar" | |
243 |
|
235 | |||
244 | """) |
|
236 | """) | |
245 | # Simply verifies that this kind of input is run |
|
237 | # Simply verifies that this kind of input is run | |
246 | ip.run_cell(complex) |
|
238 | ip.run_cell(complex) | |
247 |
|
239 | |||
248 |
|
240 | |||
249 | def test_db(): |
|
241 | def test_db(): | |
250 | """Test the internal database used for variable persistence.""" |
|
242 | """Test the internal database used for variable persistence.""" | |
251 | ip.db['__unittest_'] = 12 |
|
243 | ip.db['__unittest_'] = 12 | |
252 | nt.assert_equal(ip.db['__unittest_'], 12) |
|
244 | nt.assert_equal(ip.db['__unittest_'], 12) | |
253 | del ip.db['__unittest_'] |
|
245 | del ip.db['__unittest_'] | |
254 | assert '__unittest_' not in ip.db |
|
246 | assert '__unittest_' not in ip.db |
@@ -1,32 +1,30 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Test IPython.core.logger""" |
|
2 | """Test IPython.core.logger""" | |
3 |
|
3 | |||
4 | import os.path |
|
4 | import os.path | |
5 |
|
5 | |||
6 | import nose.tools as nt |
|
6 | import nose.tools as nt | |
7 | from IPython.utils.tempdir import TemporaryDirectory |
|
7 | from IPython.utils.tempdir import TemporaryDirectory | |
8 |
|
8 | |||
9 | _ip = get_ipython() |
|
|||
10 |
|
||||
11 | def test_logstart_inaccessible_file(): |
|
9 | def test_logstart_inaccessible_file(): | |
12 | try: |
|
10 | try: | |
13 | _ip.logger.logstart(logfname="/") # Opening that filename will fail. |
|
11 | _ip.logger.logstart(logfname="/") # Opening that filename will fail. | |
14 | except IOError: |
|
12 | except IOError: | |
15 | pass |
|
13 | pass | |
16 | else: |
|
14 | else: | |
17 | nt.assert_true(False) # The try block should never pass. |
|
15 | nt.assert_true(False) # The try block should never pass. | |
18 |
|
16 | |||
19 | try: |
|
17 | try: | |
20 | _ip.run_cell("a=1") # Check it doesn't try to log this |
|
18 | _ip.run_cell("a=1") # Check it doesn't try to log this | |
21 | finally: |
|
19 | finally: | |
22 | _ip.logger.log_active = False # If this fails, don't let later tests fail |
|
20 | _ip.logger.log_active = False # If this fails, don't let later tests fail | |
23 |
|
21 | |||
24 | def test_logstart_unicode(): |
|
22 | def test_logstart_unicode(): | |
25 | with TemporaryDirectory() as tdir: |
|
23 | with TemporaryDirectory() as tdir: | |
26 | logfname = os.path.join(tdir, "test_unicode.log") |
|
24 | logfname = os.path.join(tdir, "test_unicode.log") | |
27 | _ip.run_cell("'abc€'") |
|
25 | _ip.run_cell("'abc€'") | |
28 | try: |
|
26 | try: | |
29 | _ip.magic("logstart -to %s" % logfname) |
|
27 | _ip.magic("logstart -to %s" % logfname) | |
30 | _ip.run_cell("'abc€'") |
|
28 | _ip.run_cell("'abc€'") | |
31 | finally: |
|
29 | finally: | |
32 | _ip.logger.logstop() |
|
30 | _ip.logger.logstop() |
@@ -1,119 +1,117 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.globalipapp import get_ipython |
|
|||
10 |
|
9 | |||
11 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
12 | # Tests |
|
11 | # Tests | |
13 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
14 | ip = get_ipython() |
|
|||
15 |
|
13 | |||
16 | def test_prefilter(): |
|
14 | def test_prefilter(): | |
17 | """Test user input conversions""" |
|
15 | """Test user input conversions""" | |
18 |
|
16 | |||
19 | # pairs of (raw, expected correct) input |
|
17 | # pairs of (raw, expected correct) input | |
20 | pairs = [ ('2+2','2+2'), |
|
18 | pairs = [ ('2+2','2+2'), | |
21 | ] |
|
19 | ] | |
22 |
|
20 | |||
23 | for raw, correct in pairs: |
|
21 | for raw, correct in pairs: | |
24 | nt.assert_equal(ip.prefilter(raw), correct) |
|
22 | nt.assert_equal(ip.prefilter(raw), correct) | |
25 |
|
23 | |||
26 | def test_prefilter_shadowed(): |
|
24 | def test_prefilter_shadowed(): | |
27 | def dummy_magic(line): pass |
|
25 | def dummy_magic(line): pass | |
28 |
|
26 | |||
29 | prev_automagic_state = ip.automagic |
|
27 | prev_automagic_state = ip.automagic | |
30 | ip.automagic = True |
|
28 | ip.automagic = True | |
31 | ip.autocall = 0 |
|
29 | ip.autocall = 0 | |
32 |
|
30 | |||
33 | try: |
|
31 | try: | |
34 | # These should not be transformed - they are shadowed by other names |
|
32 | # These should not be transformed - they are shadowed by other names | |
35 | for name in ['if', 'zip', 'get_ipython']: # keyword, builtin, global |
|
33 | for name in ['if', 'zip', 'get_ipython']: # keyword, builtin, global | |
36 | ip.register_magic_function(dummy_magic, magic_name=name) |
|
34 | ip.register_magic_function(dummy_magic, magic_name=name) | |
37 | res = ip.prefilter(name+' foo') |
|
35 | res = ip.prefilter(name+' foo') | |
38 | nt.assert_equal(res, name+' foo') |
|
36 | nt.assert_equal(res, name+' foo') | |
39 | del ip.magics_manager.magics['line'][name] |
|
37 | del ip.magics_manager.magics['line'][name] | |
40 |
|
38 | |||
41 | # These should be transformed |
|
39 | # These should be transformed | |
42 | for name in ['fi', 'piz', 'nohtypi_teg']: |
|
40 | for name in ['fi', 'piz', 'nohtypi_teg']: | |
43 | ip.register_magic_function(dummy_magic, magic_name=name) |
|
41 | ip.register_magic_function(dummy_magic, magic_name=name) | |
44 | res = ip.prefilter(name+' foo') |
|
42 | res = ip.prefilter(name+' foo') | |
45 | nt.assert_not_equal(res, name+' foo') |
|
43 | nt.assert_not_equal(res, name+' foo') | |
46 | del ip.magics_manager.magics['line'][name] |
|
44 | del ip.magics_manager.magics['line'][name] | |
47 |
|
45 | |||
48 | finally: |
|
46 | finally: | |
49 | ip.automagic = prev_automagic_state |
|
47 | ip.automagic = prev_automagic_state | |
50 |
|
48 | |||
51 | def test_autocall_binops(): |
|
49 | def test_autocall_binops(): | |
52 | """See https://github.com/ipython/ipython/issues/81""" |
|
50 | """See https://github.com/ipython/ipython/issues/81""" | |
53 | ip.magic('autocall 2') |
|
51 | ip.magic('autocall 2') | |
54 | f = lambda x: x |
|
52 | f = lambda x: x | |
55 | ip.user_ns['f'] = f |
|
53 | ip.user_ns['f'] = f | |
56 | try: |
|
54 | try: | |
57 | nt.assert_equal(ip.prefilter('f 1'),'f(1)') |
|
55 | nt.assert_equal(ip.prefilter('f 1'),'f(1)') | |
58 | for t in ['f +1', 'f -1']: |
|
56 | for t in ['f +1', 'f -1']: | |
59 | nt.assert_equal(ip.prefilter(t), t) |
|
57 | nt.assert_equal(ip.prefilter(t), t) | |
60 |
|
58 | |||
61 | # Run tests again with a more permissive exclude_regexp, which will |
|
59 | # Run tests again with a more permissive exclude_regexp, which will | |
62 | # allow transformation of binary operations ('f -1' -> 'f(-1)'). |
|
60 | # allow transformation of binary operations ('f -1' -> 'f(-1)'). | |
63 | pm = ip.prefilter_manager |
|
61 | pm = ip.prefilter_manager | |
64 | ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, |
|
62 | ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, | |
65 | config=pm.config) |
|
63 | config=pm.config) | |
66 | try: |
|
64 | try: | |
67 | ac.priority = 1 |
|
65 | ac.priority = 1 | |
68 | ac.exclude_regexp = r'^[,&^\|\*/]|^is |^not |^in |^and |^or ' |
|
66 | ac.exclude_regexp = r'^[,&^\|\*/]|^is |^not |^in |^and |^or ' | |
69 | pm.sort_checkers() |
|
67 | pm.sort_checkers() | |
70 |
|
68 | |||
71 | nt.assert_equal(ip.prefilter('f -1'), 'f(-1)') |
|
69 | nt.assert_equal(ip.prefilter('f -1'), 'f(-1)') | |
72 | nt.assert_equal(ip.prefilter('f +1'), 'f(+1)') |
|
70 | nt.assert_equal(ip.prefilter('f +1'), 'f(+1)') | |
73 | finally: |
|
71 | finally: | |
74 | pm.unregister_checker(ac) |
|
72 | pm.unregister_checker(ac) | |
75 | finally: |
|
73 | finally: | |
76 | ip.magic('autocall 0') |
|
74 | ip.magic('autocall 0') | |
77 | del ip.user_ns['f'] |
|
75 | del ip.user_ns['f'] | |
78 |
|
76 | |||
79 |
|
77 | |||
80 | def test_issue_114(): |
|
78 | def test_issue_114(): | |
81 | """Check that multiline string literals don't expand as magic |
|
79 | """Check that multiline string literals don't expand as magic | |
82 | see http://github.com/ipython/ipython/issues/114""" |
|
80 | see http://github.com/ipython/ipython/issues/114""" | |
83 |
|
81 | |||
84 | template = '"""\n%s\n"""' |
|
82 | template = '"""\n%s\n"""' | |
85 | # Store the current value of multi_line_specials and turn it off before |
|
83 | # Store the current value of multi_line_specials and turn it off before | |
86 | # running test, since it could be true (case in which the test doesn't make |
|
84 | # running test, since it could be true (case in which the test doesn't make | |
87 | # sense, as multiline string literals *will* expand as magic in that case). |
|
85 | # sense, as multiline string literals *will* expand as magic in that case). | |
88 | msp = ip.prefilter_manager.multi_line_specials |
|
86 | msp = ip.prefilter_manager.multi_line_specials | |
89 | ip.prefilter_manager.multi_line_specials = False |
|
87 | ip.prefilter_manager.multi_line_specials = False | |
90 | try: |
|
88 | try: | |
91 | for mgk in ip.magics_manager.lsmagic()['line']: |
|
89 | for mgk in ip.magics_manager.lsmagic()['line']: | |
92 | raw = template % mgk |
|
90 | raw = template % mgk | |
93 | nt.assert_equal(ip.prefilter(raw), raw) |
|
91 | nt.assert_equal(ip.prefilter(raw), raw) | |
94 | finally: |
|
92 | finally: | |
95 | ip.prefilter_manager.multi_line_specials = msp |
|
93 | ip.prefilter_manager.multi_line_specials = msp | |
96 |
|
94 | |||
97 |
|
95 | |||
98 | def test_prefilter_attribute_errors(): |
|
96 | def test_prefilter_attribute_errors(): | |
99 | """Capture exceptions thrown by user objects on attribute access. |
|
97 | """Capture exceptions thrown by user objects on attribute access. | |
100 |
|
98 | |||
101 | See http://github.com/ipython/ipython/issues/988.""" |
|
99 | See http://github.com/ipython/ipython/issues/988.""" | |
102 |
|
100 | |||
103 | class X(object): |
|
101 | class X(object): | |
104 | def __getattr__(self, k): |
|
102 | def __getattr__(self, k): | |
105 | raise ValueError('broken object') |
|
103 | raise ValueError('broken object') | |
106 | def __call__(self, x): |
|
104 | def __call__(self, x): | |
107 | return x |
|
105 | return x | |
108 |
|
106 | |||
109 | # Create a callable broken object |
|
107 | # Create a callable broken object | |
110 | ip.user_ns['x'] = X() |
|
108 | ip.user_ns['x'] = X() | |
111 | ip.magic('autocall 2') |
|
109 | ip.magic('autocall 2') | |
112 | try: |
|
110 | try: | |
113 | # Even if x throws an attribute error when looking at its rewrite |
|
111 | # Even if x throws an attribute error when looking at its rewrite | |
114 | # attribute, we should not crash. So the test here is simply making |
|
112 | # attribute, we should not crash. So the test here is simply making | |
115 | # the prefilter call and not having an exception. |
|
113 | # the prefilter call and not having an exception. | |
116 | ip.prefilter('x 1') |
|
114 | ip.prefilter('x 1') | |
117 | finally: |
|
115 | finally: | |
118 | del ip.user_ns['x'] |
|
116 | del ip.user_ns['x'] | |
119 | ip.magic('autocall 0') |
|
117 | ip.magic('autocall 0') |
@@ -1,34 +1,30 b'' | |||||
1 | # -*- coding: utf-8 |
|
1 | # -*- coding: utf-8 | |
2 | """Tests for prompt generation.""" |
|
2 | """Tests for prompt generation.""" | |
3 |
|
3 | |||
4 | import unittest |
|
4 | import unittest | |
5 |
|
5 | |||
6 | from IPython.core.prompts import LazyEvaluate |
|
6 | from IPython.core.prompts import LazyEvaluate | |
7 | from IPython.testing.globalipapp import get_ipython |
|
|||
8 |
|
||||
9 | ip = get_ipython() |
|
|||
10 |
|
||||
11 |
|
7 | |||
12 | class PromptTests(unittest.TestCase): |
|
8 | class PromptTests(unittest.TestCase): | |
13 | def test_lazy_eval_unicode(self): |
|
9 | def test_lazy_eval_unicode(self): | |
14 | u = u'ünicødé' |
|
10 | u = u'ünicødé' | |
15 | lz = LazyEvaluate(lambda : u) |
|
11 | lz = LazyEvaluate(lambda : u) | |
16 | self.assertEqual(str(lz), u) |
|
12 | self.assertEqual(str(lz), u) | |
17 | self.assertEqual(format(lz), u) |
|
13 | self.assertEqual(format(lz), u) | |
18 |
|
14 | |||
19 | def test_lazy_eval_nonascii_bytes(self): |
|
15 | def test_lazy_eval_nonascii_bytes(self): | |
20 | u = u'ünicødé' |
|
16 | u = u'ünicødé' | |
21 | b = u.encode('utf8') |
|
17 | b = u.encode('utf8') | |
22 | lz = LazyEvaluate(lambda : b) |
|
18 | lz = LazyEvaluate(lambda : b) | |
23 | # unicode(lz) would fail |
|
19 | # unicode(lz) would fail | |
24 | self.assertEqual(str(lz), str(b)) |
|
20 | self.assertEqual(str(lz), str(b)) | |
25 | self.assertEqual(format(lz), str(b)) |
|
21 | self.assertEqual(format(lz), str(b)) | |
26 |
|
22 | |||
27 | def test_lazy_eval_float(self): |
|
23 | def test_lazy_eval_float(self): | |
28 | f = 0.503 |
|
24 | f = 0.503 | |
29 | lz = LazyEvaluate(lambda : f) |
|
25 | lz = LazyEvaluate(lambda : f) | |
30 |
|
26 | |||
31 | self.assertEqual(str(lz), str(f)) |
|
27 | self.assertEqual(str(lz), str(f)) | |
32 | self.assertEqual(format(lz), str(f)) |
|
28 | self.assertEqual(format(lz), str(f)) | |
33 | self.assertEqual(format(lz, '.1'), '0.5') |
|
29 | self.assertEqual(format(lz, '.1'), '0.5') | |
34 |
|
30 |
General Comments 0
You need to be logged in to leave comments.
Login now