Debian Codegraph @

tests/test_async_helpers.py

raw
1 """
2 Test for async helpers.
3
4 Should only trigger on python 3.5+ or will have syntax errors.
5 """
6
7 import sys
8 from itertools import chain, repeat
9 from textwrap import dedent, indent
10 from typing import TYPE_CHECKING
11 from unittest import TestCase
12
13 import pytest
14
15 from IPython.core.async_helpers import _should_be_async
16 from IPython.testing.decorators import skip_without
17
18 if TYPE_CHECKING:
19 from IPython import get_ipython
20
21 ip = get_ipython()
22
23
24 def iprc(x):
25 return ip.run_cell(dedent(x)).raise_error()
26
27
28 def iprc_nr(x):
29 return ip.run_cell(dedent(x))
30
31
32 class AsyncTest(TestCase):
33 def test_should_be_async(self):
34 self.assertFalse(_should_be_async("False"))
35 self.assertTrue(_should_be_async("await bar()"))
36 self.assertTrue(_should_be_async("x = await bar()"))
37 self.assertFalse(
38 _should_be_async(
39 dedent(
40 """
41 async def awaitable():
42 pass
43 """
44 )
45 )
46 )
47
48 self.assertFalse(_should_be_async("return await foo()"))
49 self.assertFalse(_should_be_async("return bar()"))
50 self.assertFalse(_should_be_async("some invalid Python code"))
51
52 self.assertFalse(_should_be_async("'\\ud800'"))
53
54 if sys.version_info >= (3, 13):
55 # Note: the next assert assumes the tests run without the `-OO` flag
56 self.assertFalse(_should_be_async("'\\ud800'\nawait foo"))
57
58 def _get_top_level_cases(self):
59 # These are test cases that should be valid in a function
60 # but invalid outside of a function.
61 test_cases = []
62 test_cases.append(("basic", "{val}"))
63
64 # Note, in all conditional cases, I use True instead of
65 # False so that the peephole optimizer won't optimize away
66 # the return, so CPython will see this as a syntax error:
67 #
68 # while True:
69 # break
70 # return
71 #
72 # But not this:
73 #
74 # while False:
75 # return
76 #
77 # See https://bugs.python.org/issue1875
78
79 test_cases.append(
80 (
81 "if",
82 dedent(
83 """
84 if True:
85 {val}
86 """
87 ),
88 )
89 )
90
91 test_cases.append(
92 (
93 "while",
94 dedent(
95 """
96 while True:
97 {val}
98 break
99 """
100 ),
101 )
102 )
103
104 test_cases.append(
105 (
106 "try",
107 dedent(
108 """
109 try:
110 {val}
111 except:
112 pass
113 """
114 ),
115 )
116 )
117
118 test_cases.append(
119 (
120 "except",
121 dedent(
122 """
123 try:
124 pass
125 except:
126 {val}
127 """
128 ),
129 )
130 )
131
132 test_cases.append(
133 (
134 "finally",
135 dedent(
136 """
137 try:
138 pass
139 except:
140 pass
141 finally:
142 {val}
143 """
144 ),
145 )
146 )
147
148 test_cases.append(
149 (
150 "for",
151 dedent(
152 """
153 for _ in range(4):
154 {val}
155 """
156 ),
157 )
158 )
159
160 test_cases.append(
161 (
162 "nested",
163 dedent(
164 """
165 if True:
166 while True:
167 {val}
168 break
169 """
170 ),
171 )
172 )
173
174 test_cases.append(
175 (
176 "deep-nested",
177 dedent(
178 """
179 if True:
180 while True:
181 break
182 for x in range(3):
183 if True:
184 while True:
185 for x in range(3):
186 {val}
187 """
188 ),
189 )
190 )
191
192 return test_cases
193
194 def _get_ry_syntax_errors(self):
195 # This is a mix of tests that should be a syntax error if
196 # return or yield whether or not they are in a function
197
198 test_cases = []
199
200 test_cases.append(
201 (
202 "class",
203 dedent(
204 """
205 class V:
206 {val}
207 """
208 ),
209 )
210 )
211
212 test_cases.append(
213 (
214 "nested-class",
215 dedent(
216 """
217 class V:
218 class C:
219 {val}
220 """
221 ),
222 )
223 )
224
225 return test_cases
226
227 def test_top_level_return_error(self):
228 tl_err_test_cases = self._get_top_level_cases()
229 tl_err_test_cases.extend(self._get_ry_syntax_errors())
230
231 vals = (
232 "return",
233 "yield",
234 "yield from (_ for _ in range(3))",
235 dedent(
236 """
237 def f():
238 pass
239 return
240 """
241 ),
242 )
243
244 for test_name, test_case in tl_err_test_cases:
245 # This example should work if 'pass' is used as the value
246 with self.subTest((test_name, "pass")):
247 iprc(test_case.format(val="pass"))
248
249 # It should fail with all the values
250 for val in vals:
251 with self.subTest((test_name, val)):
252 msg = "Syntax error not raised for %s, %s" % (test_name, val)
253 with self.assertRaises(SyntaxError, msg=msg):
254 iprc(test_case.format(val=val))
255
256 def test_in_func_no_error(self):
257 # Test that the implementation of top-level return/yield
258 # detection isn't *too* aggressive, and works inside a function
259 func_contexts = []
260
261 func_contexts.append(
262 (
263 "func",
264 False,
265 dedent(
266 """
267 def f():"""
268 ),
269 )
270 )
271
272 func_contexts.append(
273 (
274 "method",
275 False,
276 dedent(
277 """
278 class MyClass:
279 def __init__(self):
280 """
281 ),
282 )
283 )
284
285 func_contexts.append(
286 (
287 "async-func",
288 True,
289 dedent(
290 """
291 async def f():"""
292 ),
293 )
294 )
295
296 func_contexts.append(
297 (
298 "async-method",
299 True,
300 dedent(
301 """
302 class MyClass:
303 async def f(self):"""
304 ),
305 )
306 )
307
308 func_contexts.append(
309 (
310 "closure",
311 False,
312 dedent(
313 """
314 def f():
315 def g():
316 """
317 ),
318 )
319 )
320
321 def nest_case(context, case):
322 # Detect indentation
323 lines = context.strip().splitlines()
324 prefix_len = 0
325 for c in lines[-1]:
326 if c != " ":
327 break
328 prefix_len += 1
329
330 indented_case = indent(case, " " * (prefix_len + 4))
331 return context + "\n" + indented_case
332
333 # Gather and run the tests
334
335 # yield is allowed in async functions, starting in Python 3.6,
336 # and yield from is not allowed in any version
337 vals = ("return", "yield", "yield from (_ for _ in range(3))")
338
339 success_tests = zip(self._get_top_level_cases(), repeat(False))
340 failure_tests = zip(self._get_ry_syntax_errors(), repeat(True))
341
342 tests = chain(success_tests, failure_tests)
343
344 for context_name, async_func, context in func_contexts:
345 for (test_name, test_case), should_fail in tests:
346 nested_case = nest_case(context, test_case)
347
348 for val in vals:
349 test_id = (context_name, test_name, val)
350 cell = nested_case.format(val=val)
351
352 with self.subTest(test_id):
353 if should_fail:
354 msg = "SyntaxError not raised for %s" % str(test_id)
355 with self.assertRaises(SyntaxError, msg=msg):
356 iprc(cell)
357
358 print(cell)
359 else:
360 iprc(cell)
361
362 def test_nonlocal(self):
363 # fails if outer scope is not a function scope or if var not defined
364 with self.assertRaises(SyntaxError):
365 iprc("nonlocal x")
366 iprc(
367 """
368 x = 1
369 def f():
370 nonlocal x
371 x = 10000
372 yield x
373 """
374 )
375 iprc(
376 """
377 def f():
378 def g():
379 nonlocal x
380 x = 10000
381 yield x
382 """
383 )
384
385 # works if outer scope is a function scope and var exists
386 iprc(
387 """
388 def f():
389 x = 20
390 def g():
391 nonlocal x
392 x = 10000
393 yield x
394 """
395 )
396
397 def test_execute(self):
398 iprc(
399 """
400 import asyncio
401 await asyncio.sleep(0.001)
402 """
403 )
404
405 def test_autoawait(self):
406 iprc("%autoawait False")
407 iprc("%autoawait True")
408 iprc(
409 """
410 from asyncio import sleep
411 await sleep(0.1)
412 """
413 )
414
415 def test_memory_error(self):
416 """
417 The pgen parser in 3.8 or before use to raise MemoryError on too many
418 nested parens anymore"""
419
420 iprc("(" * 200 + ")" * 200)
421
422 @pytest.mark.xfail(reason="fail on curio 1.6 and before on Python 3.12")
423 @pytest.mark.skip(
424 reason="skip_without(curio) fails on 3.12 for now even with other skip so must uncond skip"
425 )
426 # @skip_without("curio")
427 def test_autoawait_curio(self):
428 iprc("%autoawait curio")
429
430 @skip_without("trio")
431 def test_autoawait_trio(self):
432 iprc("%autoawait trio")
433
434 @skip_without("trio")
435 def test_autoawait_trio_wrong_sleep(self):
436 iprc("%autoawait trio")
437 res = iprc_nr(
438 """
439 import asyncio
440 await asyncio.sleep(0)
441 """
442 )
443 with self.assertRaises(TypeError):
444 res.raise_error()
445
446 @skip_without("trio")
447 def test_autoawait_asyncio_wrong_sleep(self):
448 iprc("%autoawait asyncio")
449 res = iprc_nr(
450 """
451 import trio
452 await trio.sleep(0)
453 """
454 )
455 with self.assertRaises(RuntimeError):
456 res.raise_error()
457
458 def tearDown(self):
459 ip.loop_runner = "asyncio"