Debian Codegraph @

pypy/interpreter/test/test_syntax.py

raw symbols SCIP
1 from __future__ import with_statement
2 import py
3 import commands
4 import pypy.conftest
5
6 def splitcases(s):
7 lines = [line.rstrip() for line in s.split('\n')]
8 s = '\n'.join(lines)
9 result = []
10 for case in s.split('\n\n'):
11 if case.strip():
12 result.append(str(py.code.Source(case))+'\n')
13 return result
14
15
16 VALID = splitcases("""
17
18 def f():
19 def g():
20 global x
21 exec("hi")
22 x
23
24 def f(x):
25 def g():
26 global x
27 exec("hi")
28 x
29
30 def f():
31 def g():
32 exec("hi")
33
34 def f():
35 exec("hi")
36
37 def f():
38 exec("hi")
39 def g():
40 global x
41 x
42
43 def f():
44 exec("hi")
45 def g(x):
46 x
47
48 def f():
49 exec("hi")
50 lambda x: x
51
52 def f():
53 exec("hi")
54 x
55
56 def f():
57 exec("hi")
58 (i for i in x)
59
60 def f():
61 class g:
62 exec("hi")
63 x
64
65 """)
66
67 ## --- the following one is valid in CPython, but not sensibly so:
68 ## --- if x is rebound, then it is even rebound in the parent scope!
69 ## def f(x):
70 ## class g:
71 ## exec "x=41"
72 ## x
73
74 INVALID = splitcases("""
75
76 def f():
77 from x import *
78
79 def f():
80 (i for i in x) = 10
81
82 async def foo(a=await something()):
83 pass
84
85 async def foo():
86 await
87
88 def foo():
89 await something()
90
91 async def foo():
92 yield from []
93
94 async def foo():
95 await await fut
96
97 async def foo():
98 yield
99 return 42
100
101 async def foo():
102 return (yield 1)
103
104 async def foo():
105 if a:
106 return 42
107 yield
108
109 """)
110
111
112 for i in range(len(VALID)):
113 exec """def test_valid_%d(space, tmpdir):
114 checkvalid_cpython(tmpdir, %d, %r)
115 checkvalid(space, %r)
116 """ % (i, i, VALID[i], VALID[i])
117
118 for i in range(len(INVALID)):
119 exec """def test_invalid_%d(space, tmpdir):
120 checkinvalid_cpython(tmpdir, %d, %r)
121 checkinvalid(space, %r)
122 """ % (i, i, INVALID[i], INVALID[i])
123
124
125 def checksyntax_cpython(tmpdir, i, s):
126 python3 = pypy.conftest.option.python
127 if python3 is None:
128 print 'Warning: cannot run python3 to check syntax'
129 return
130
131 src = '''
132 try:
133 exec("""%s
134 """)
135 except SyntaxError as e:
136 print(e)
137 raise SystemExit(1)
138 else:
139 print('OK')
140 ''' % s
141 pyfile = tmpdir.join('checkvalid_%d.py' % i)
142 pyfile.write(src)
143 res = commands.getoutput('"%s" "%s"' % (python3, pyfile))
144 return res
145
146 def checkvalid_cpython(tmpdir, i, s):
147 res = checksyntax_cpython(tmpdir, i, s)
148 if res is not None and res != 'OK':
149 print s
150 print
151 print res
152 assert False, 'checkvalid_cpython failed'
153
154 def checkinvalid_cpython(tmpdir, i, s):
155 res = checksyntax_cpython(tmpdir, i, s)
156 if res is not None and res == 'OK':
157 print s
158 print
159 print res
160 assert False, 'checkinvalid_cpython failed, did not raise SyntaxError'
161
162
163 def checkvalid(space, s):
164 try:
165 space.call_function(space.builtin.get('compile'),
166 space.wrap(s),
167 space.wrap('?'),
168 space.wrap('exec'))
169 except:
170 print '\n' + s
171 raise
172
173 def checkinvalid(space, s):
174 from pypy.interpreter.error import OperationError
175 try:
176 try:
177 space.call_function(space.builtin.get('compile'),
178 space.wrap(s),
179 space.wrap('?'),
180 space.wrap('exec'))
181 except OperationError as e:
182 if not e.match(space, space.w_SyntaxError):
183 raise
184 else:
185 raise Exception("Should have raised SyntaxError")
186 except:
187 print '\n' + s
188 raise
189
190
191 class AppTestCondExpr:
192 def test_condexpr(self):
193 for s, expected in [("x = 1 if True else 2", 1),
194 ("x = 1 if False else 2", 2)]:
195 ns = {}
196 exec(s, ns)
197 assert ns['x'] == expected
198
199 class AppTestYield:
200 def test_bare_yield(self):
201 s = "def f():\n yield"
202
203 exec(s)
204
205
206 class AppTestDecorators:
207
208 def test_function_decorators(self):
209 '''
210 def other():
211 return 4
212 def dec(f):
213 return other
214 ns = {}
215 ns["dec"] = dec
216 exec("""if 1:
217 @dec
218 def g():
219 pass
220 """, ns)
221 assert ns["g"] is other
222 assert ns["g"]() == 4
223 '''
224
225 def test_application_order(self):
226 '''
227 def dec1(f):
228 record.append(1)
229 return f
230 def dec2(f):
231 record.append(2)
232 return f
233 record = []
234 ns = {"dec1" : dec1, "dec2" : dec2}
235 exec("""if 1:
236 @dec1
237 @dec2
238 def g():
239 pass
240 """, ns)
241 assert record == [2, 1]
242 del record[:]
243 exec("""if 1:
244 @dec1
245 @dec2
246 class x:
247 pass
248 """, ns)
249 assert record == [2, 1]
250 '''
251
252 def test_class_decorators(self):
253 s = """@func
254 class x: pass"""
255 ns = {"func" : lambda cls: 4}
256 exec(s, ns)
257 assert ns["x"] == 4
258
259
260 class AppTestPrintFunction:
261
262 def test_simple_print(self):
263 """
264 import builtins
265 s = "x = print"
266 ns = {}
267 exec(s, ns)
268 assert ns["x"] is builtins.print
269 """
270
271 def test_print(self):
272 s = """
273 from io import StringIO
274 s = StringIO()
275 print("Hello,", "person", file=s)
276 """
277 ns = {}
278 exec(s, ns)
279 assert ns["s"].getvalue() == "Hello, person\n"
280
281
282 class AppTestUnicodeLiterals:
283
284 def test_simple(self):
285 s = """
286 x = 'u'
287 y = r'u'
288 b = b'u'
289 c = br'u'
290 d = rb'u'
291 """
292 ns = {}
293 exec(s, ns)
294 assert isinstance(ns["x"], str)
295 assert isinstance(ns["y"], str)
296 assert isinstance(ns["b"], bytes)
297 assert isinstance(ns["c"], bytes)
298 assert isinstance(ns["d"], bytes)
299
300 def test_triple_quotes(self):
301 s = '''
302 x = """u"""
303 y = r"""u"""
304 b = b"""u"""
305 c = br"""u"""
306 d = rb"""u"""
307 '''
308
309 ns = {}
310 exec(s, ns)
311 assert isinstance(ns["x"], str)
312 assert isinstance(ns["y"], str)
313 assert isinstance(ns["b"], bytes)
314 assert isinstance(ns["c"], bytes)
315 assert isinstance(ns["d"], bytes)
316
317 def test_both_futures_with_semicolon(self):
318 # Issue #2526: a corner case which crashes only if the file
319 # contains *nothing more* than two __future__ imports separated
320 # by a semicolon.
321 s = """
322 from __future__ import unicode_literals; from __future__ import print_function
323 """
324 exec(s, {})
325
326
327 class AppTestComprehensions:
328
329 def test_dictcomps(self):
330 d = eval("{x : x for x in range(10)}")
331 assert isinstance(d, dict)
332 assert d == dict(zip(range(10), range(10)))
333 d = eval("{x : x for x in range(10) if x % 2}")
334 l = [x for x in range(10) if x % 2]
335 assert d == dict(zip(l, l))
336
337 def test_setcomps(self):
338 s = eval("{x for x in range(10)}")
339 assert isinstance(s, set)
340 assert s == set(range(10))
341 s = eval("{x for x in range(10) if x % 2}")
342 assert s == set(x for x in range(10) if x % 2)
343
344 def test_set_literal(self):
345 s = eval("{1}")
346 assert isinstance(s, set)
347 assert s == set((1,))
348 s = eval("{0, 1, 2, 3}")
349 assert isinstance(s, set)
350 assert s == set(range(4))
351
352
353 class AppTestWith:
354 def test_with_simple(self):
355 class Context:
356 def __init__(self):
357 self.calls = list()
358
359 def __enter__(self):
360 self.calls.append('__enter__')
361
362 def __exit__(self, exc_type, exc_value, exc_tb):
363 self.calls.append('__exit__')
364
365 acontext = Context()
366 with acontext:
367 pass
368 assert acontext.calls == '__enter__ __exit__'.split()
369
370 def test_compound_with(self):
371 class Context:
372 def __init__(self, var):
373 self.record = []
374 self.var = var
375 def __enter__(self):
376 self.record.append(("__enter__", self.var))
377 return self.var
378 def __exit__(self, tp, value, tb):
379 self.record.append(("__exit__", self.var))
380 c1 = Context("blah")
381 c2 = Context("bling")
382 with c1 as v1, c2 as v2:
383 pass
384 assert v1 == "blah"
385 assert v2 == "bling"
386 assert c1.record == [("__enter__", "blah"), ("__exit__", "blah")]
387 assert c2.record == [("__enter__", "bling"), ("__exit__", "bling")]
388
389 def test_with_as_var(self):
390 class Context:
391 def __init__(self):
392 self.calls = list()
393
394 def __enter__(self):
395 self.calls.append('__enter__')
396 return self.calls
397
398 def __exit__(self, exc_type, exc_value, exc_tb):
399 self.calls.append('__exit__')
400 self.exit_params = (exc_type, exc_value, exc_tb)
401
402 acontextfact = Context()
403 with acontextfact as avar:
404 avar.append('__body__')
405 pass
406 assert acontextfact.exit_params == (None, None, None)
407 assert acontextfact.calls == '__enter__ __body__ __exit__'.split()
408
409 def test_with_raise_exception(self):
410 class Context:
411 def __init__(self):
412 self.calls = list()
413
414 def __enter__(self):
415 self.calls.append('__enter__')
416 return self.calls
417
418 def __exit__(self, exc_type, exc_value, exc_tb):
419 self.calls.append('__exit__')
420 self.exit_params = (exc_type, exc_value, exc_tb)
421
422 acontextfact = Context()
423 error = RuntimeError('With Test')
424 try:
425 with acontextfact as avar:
426 avar.append('__body__')
427 raise error
428 avar.append('__after_raise__')
429 except RuntimeError:
430 pass
431 else:
432 raise AssertionError('With did not raise RuntimeError')
433 assert acontextfact.calls == '__enter__ __body__ __exit__'.split()
434 assert acontextfact.exit_params[0:2] == (RuntimeError, error)
435 import types
436 assert isinstance(acontextfact.exit_params[2], types.TracebackType)
437
438 def test_with_swallow_exception(self):
439 class Context:
440 def __init__(self):
441 self.calls = list()
442
443 def __enter__(self):
444 self.calls.append('__enter__')
445 return self.calls
446
447 def __exit__(self, exc_type, exc_value, exc_tb):
448 self.calls.append('__exit__')
449 self.exit_params = (exc_type, exc_value, exc_tb)
450 return True
451
452 acontextfact = Context()
453 error = RuntimeError('With Test')
454 with acontextfact as avar:
455 avar.append('__body__')
456 raise error
457 avar.append('__after_raise__')
458 assert acontextfact.calls == '__enter__ __body__ __exit__'.split()
459 assert acontextfact.exit_params[0:2] == (RuntimeError, error)
460 import types
461 assert isinstance(acontextfact.exit_params[2], types.TracebackType)
462
463 def test_with_reraise_exception(self):
464 class Context:
465 def __enter__(self):
466 self.calls = []
467 def __exit__(self, exc_type, exc_value, exc_tb):
468 self.calls.append('exit')
469 raise
470
471 c = Context()
472 try:
473 with c:
474 1 / 0
475 except ZeroDivisionError:
476 pass
477 else:
478 raise AssertionError('Should have reraised initial exception')
479 assert c.calls == ['exit']
480
481 def test_with_break(self):
482 class Context:
483 def __init__(self):
484 self.calls = list()
485
486 def __enter__(self):
487 self.calls.append('__enter__')
488 return self.calls
489
490 def __exit__(self, exc_type, exc_value, exc_tb):
491 self.calls.append('__exit__')
492 self.exit_params = (exc_type, exc_value, exc_tb)
493
494 acontextfact = Context()
495 error = RuntimeError('With Test')
496 for x in 1,:
497 with acontextfact as avar:
498 avar.append('__body__')
499 break
500 avar.append('__after_break__')
501 else:
502 raise AssertionError('Break failed with With, reached else clause')
503 assert acontextfact.calls == '__enter__ __body__ __exit__'.split()
504 assert acontextfact.exit_params == (None, None, None)
505
506 def test_with_continue(self):
507 class Context:
508 def __init__(self):
509 self.calls = list()
510
511 def __enter__(self):
512 self.calls.append('__enter__')
513 return self.calls
514
515 def __exit__(self, exc_type, exc_value, exc_tb):
516 self.calls.append('__exit__')
517 self.exit_params = (exc_type, exc_value, exc_tb)
518
519 acontextfact = Context()
520 error = RuntimeError('With Test')
521 for x in 1,:
522 with acontextfact as avar:
523 avar.append('__body__')
524 continue
525 avar.append('__after_continue__')
526 else:
527 avar.append('__continue__')
528 assert acontextfact.calls == '__enter__ __body__ __exit__ __continue__'.split()
529 assert acontextfact.exit_params == (None, None, None)
530
531 def test_with_return(self):
532 class Context:
533 def __init__(self):
534 self.calls = list()
535
536 def __enter__(self):
537 self.calls.append('__enter__')
538 return self.calls
539
540 def __exit__(self, exc_type, exc_value, exc_tb):
541 self.calls.append('__exit__')
542 self.exit_params = (exc_type, exc_value, exc_tb)
543
544 acontextfact = Context()
545 error = RuntimeError('With Test')
546 def g(acontextfact):
547 with acontextfact as avar:
548 avar.append('__body__')
549 return '__return__'
550 avar.append('__after_return__')
551 acontextfact.calls.append(g(acontextfact))
552 assert acontextfact.calls == '__enter__ __body__ __exit__ __return__'.split()
553 assert acontextfact.exit_params == (None, None, None)
554
555 def test_with_as_keyword(self):
556 with raises(SyntaxError):
557 exec("with = 9")
558
559 def test_with_as_keyword_compound(self):
560 with raises(SyntaxError):
561 exec("from __future__ import generators, with_statement\nwith = 9")
562
563 def test_missing_as_SyntaxError(self):
564 snippets = [
565 "import os.path a bar ",
566 "from os import path a bar",
567 """
568 with foo a bar:
569 pass
570 """]
571 for snippet in snippets:
572 with raises(SyntaxError):
573 exec(snippet)
574
575
576
577 class AppTestFunctionAnnotations:
578
579 def test_simple(self):
580 """
581 def f(e:3=4): pass
582 assert f.__annotations__ == {"e" : 3}
583 def f(a : 1, b : 2, *var : 3, hi : 4, bye : 5=0, **kw : 6) -> 42: pass
584 assert f.__annotations__ == {"a" : 1, "b" : 2, "var" : 3, "hi" : 4,
585 "bye" : 5, "kw" : 6, "return" : 42}
586 """
587
588 def test_bug_annotations_lambda(self):
589 """
590 # those used to crash
591 def broken(*a: lambda x: None):
592 pass
593
594 def broken(**a: lambda x: None):
595 pass
596 """
597
598 def test_bug_annotation_inside_nested_function(self):
599 """
600 # this used to crash
601 def f1():
602 def f2(*args: int):
603 pass
604 f1()
605 """
606 class AppTestSyntaxError:
607
608 def test_tokenizer_error_location(self):
609 line4 = "if ?: pass\n"
610 try:
611 exec("print\nprint\nprint\n" + line4)
612 except SyntaxError as e:
613 assert e.lineno == 4
614 assert e.text == line4
615 assert e.offset == e.text.index('?') + 1
616 else:
617 raise Exception("no SyntaxError??")
618
619 def test_grammar_error_location(self):
620 try:
621 exec("""if 1:
622 class Foo:
623 bla
624 a as e
625 bar
626 """)
627 except SyntaxError as e:
628 assert e.lineno == 4
629 assert e.text.endswith('a as e\n')
630 print(e.offset, e.text.index('as'))
631 assert e.offset == e.text.index('as') + 1 # offset is 1-based
632 else:
633 raise Exception("no SyntaxError??")
634
635 def test_astbuilder_error_location(self):
636 program = "(1, 2) += (3, 4)\n"
637 try:
638 exec(program)
639 except SyntaxError as e:
640 assert e.lineno == 1
641 assert e.text == program
642 else:
643 raise Exception("no SyntaxError??")
644
645 def test_codegen_error_location(self):
646 try:
647 exec("if 1:\n break")
648 except SyntaxError as e:
649 assert e.lineno == 2
650 assert e.text == " break"
651 assert e.offset == 6
652
653 def test_bad_encoding(self):
654 '''
655 program = """
656 # -*- coding: uft-8 -*-
657 pass
658 """
659 with raises(SyntaxError):
660 exec(program)
661 '''
662
663 def test_exception_target_in_nested_scope(self):
664 # issue 4617: This used to raise a SyntaxError
665 # "can not delete variable 'e' referenced in nested scope"
666 def print_error():
667 e
668 try:
669 something
670 except Exception as e:
671 print_error()
672 # implicit "del e" here
673
674 def test_cpython_issue2382(self):
675 code = 'Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +'
676 exc = raises(SyntaxError, compile, code, 'foo', 'exec')
677 assert exc.value.offset in (19, 20) # pypy, cpython
678
679 def test_empty_tuple_target(self): """
680 def f(n):
681 () = ()
682 ((), ()) = [[], []]
683 del ()
684 del ((), ())
685 [] = {}
686 ([], ()) = [[], ()]
687 [[], ()] = ((), [])
688 del []
689 del [[], ()]
690 for () in [(), []]: pass
691 for [] in ([],): pass
692 class Zen:
693 def __enter__(self): return ()
694 def __exit__(self, *args): pass
695 with Zen() as (): pass
696 () = [2, 3] * n
697 f(0)
698 try:
699 f(5)
700 except ValueError:
701 pass
702 else:
703 raise AssertionError("should have raised")
704 """
705
706 def test_starunpacking_as_iterator(self):
707 """
708 l = []
709 a = [1, 2, 3, 4]
710 b = [6, 7]
711 c = ()
712 for x in *a, *b, *c:
713 l.append(x)
714 assert l == [1, 2, 3, 4, 6, 7]
715 """