blob: 9b41df1ad864b731a2b514bc2cab3cac4a193c30 [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 1, grammar.
2# This just tests whether the parser accepts them all.
3
Zachary Ware38c707e2015-04-13 15:00:43 -05004from test.support import check_syntax_error
Yury Selivanov75445082015-05-11 22:57:16 -04005import inspect
Thomas Wouters89f507f2006-12-13 04:49:30 +00006import unittest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +00007import sys
Thomas Wouters89f507f2006-12-13 04:49:30 +00008# testing import *
9from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000010
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000011
Thomas Wouters89f507f2006-12-13 04:49:30 +000012class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +000013
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050014 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000015 # Backslash means line continuation:
16 x = 1 \
17 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000018 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +000019
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 # Backslash does not means continuation in comments :\
21 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000022 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +000023
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050024 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000025 self.assertEqual(type(000), type(0))
26 self.assertEqual(0xff, 255)
27 self.assertEqual(0o377, 255)
28 self.assertEqual(2147483647, 0o17777777777)
29 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +000030 # "0x" is not a valid literal
31 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +000032 from sys import maxsize
33 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000034 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +000035 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000036 self.assertTrue(0o37777777777 > 0)
37 self.assertTrue(0xffffffff > 0)
38 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000039 for s in ('2147483648', '0o40000000000', '0x100000000',
40 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +000041 try:
42 x = eval(s)
43 except OverflowError:
44 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +000045 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000046 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000047 self.assertTrue(0o1777777777777777777777 > 0)
48 self.assertTrue(0xffffffffffffffff > 0)
49 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000050 for s in '9223372036854775808', '0o2000000000000000000000', \
51 '0x10000000000000000', \
52 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +000053 try:
54 x = eval(s)
55 except OverflowError:
56 self.fail("OverflowError on huge integer literal %r" % s)
57 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +000058 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +000059
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050060 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +000061 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +000062 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +000063 x = 0Xffffffffffffffff
64 x = 0o77777777777777777
65 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +000066 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +000067 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
68 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +000069
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050070 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000071 x = 3.14
72 x = 314.
73 x = 0.314
74 # XXX x = 000.314
75 x = .314
76 x = 3e14
77 x = 3E14
78 x = 3e-14
79 x = 3e+14
80 x = 3.e14
81 x = .3e14
82 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000083
Benjamin Petersonc4161622014-06-07 12:36:39 -070084 def test_float_exponent_tokenization(self):
85 # See issue 21642.
86 self.assertEqual(1 if 1else 0, 1)
87 self.assertEqual(1 if 0else 0, 0)
88 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
89
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050090 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000091 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
92 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
93 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +000094 x = "doesn't \"shrink\" does it"
95 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000096 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +000097 x = "does \"shrink\" doesn't it"
98 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000099 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000100 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000101The "quick"
102brown fox
103jumps over
104the 'lazy' dog.
105"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000106 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000107 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000108 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000109The "quick"
110brown fox
111jumps over
112the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000113'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000114 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000115 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000116The \"quick\"\n\
117brown fox\n\
118jumps over\n\
119the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000120"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000121 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000122 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000123The \"quick\"\n\
124brown fox\n\
125jumps over\n\
126the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000127'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000128 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000129
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500130 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000131 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000132 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000133 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134
Benjamin Peterson758888d2011-05-30 11:12:38 -0500135 def test_eof_error(self):
136 samples = ("def foo(", "\ndef foo(", "def foo(\n")
137 for s in samples:
138 with self.assertRaises(SyntaxError) as cm:
139 compile(s, "<test>", "exec")
140 self.assertIn("unexpected EOF", str(cm.exception))
141
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142class GrammarTests(unittest.TestCase):
143
144 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
145 # XXX can't test in a script -- this rule is only used when interactive
146
147 # file_input: (NEWLINE | stmt)* ENDMARKER
148 # Being tested as this very moment this very module
149
150 # expr_input: testlist NEWLINE
151 # XXX Hard to test -- used only in calls to input()
152
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500153 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000154 # testlist ENDMARKER
155 x = eval('1, 0 or 1')
156
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500157 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000158 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
159 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
160 ### decorators: decorator+
161 ### parameters: '(' [typedargslist] ')'
162 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000163 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000164 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000165 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000166 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000167 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000168 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000169 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000170 def f1(): pass
171 f1()
172 f1(*())
173 f1(*(), **{})
174 def f2(one_argument): pass
175 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000176 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
177 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000178 def a1(one_arg,): pass
179 def a2(two, args,): pass
180 def v0(*rest): pass
181 def v1(a, *rest): pass
182 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000183
184 f1()
185 f2(1)
186 f2(1,)
187 f3(1, 2)
188 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189 v0()
190 v0(1)
191 v0(1,)
192 v0(1,2)
193 v0(1,2,3,4,5,6,7,8,9,0)
194 v1(1)
195 v1(1,)
196 v1(1,2)
197 v1(1,2,3)
198 v1(1,2,3,4,5,6,7,8,9,0)
199 v2(1,2)
200 v2(1,2,3)
201 v2(1,2,3,4)
202 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000203
Thomas Wouters89f507f2006-12-13 04:49:30 +0000204 def d01(a=1): pass
205 d01()
206 d01(1)
207 d01(*(1,))
208 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400209 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000210 def d11(a, b=1): pass
211 d11(1)
212 d11(1, 2)
213 d11(1, **{'b':2})
214 def d21(a, b, c=1): pass
215 d21(1, 2)
216 d21(1, 2, 3)
217 d21(*(1, 2, 3))
218 d21(1, *(2, 3))
219 d21(1, 2, *(3,))
220 d21(1, 2, **{'c':3})
221 def d02(a=1, b=2): pass
222 d02()
223 d02(1)
224 d02(1, 2)
225 d02(*(1, 2))
226 d02(1, *(2,))
227 d02(1, **{'b':2})
228 d02(**{'a': 1, 'b': 2})
229 def d12(a, b=1, c=2): pass
230 d12(1)
231 d12(1, 2)
232 d12(1, 2, 3)
233 def d22(a, b, c=1, d=2): pass
234 d22(1, 2)
235 d22(1, 2, 3)
236 d22(1, 2, 3, 4)
237 def d01v(a=1, *rest): pass
238 d01v()
239 d01v(1)
240 d01v(1, 2)
241 d01v(*(1, 2, 3, 4))
242 d01v(*(1,))
243 d01v(**{'a':2})
244 def d11v(a, b=1, *rest): pass
245 d11v(1)
246 d11v(1, 2)
247 d11v(1, 2, 3)
248 def d21v(a, b, c=1, *rest): pass
249 d21v(1, 2)
250 d21v(1, 2, 3)
251 d21v(1, 2, 3, 4)
252 d21v(*(1, 2, 3, 4))
253 d21v(1, 2, **{'c': 3})
254 def d02v(a=1, b=2, *rest): pass
255 d02v()
256 d02v(1)
257 d02v(1, 2)
258 d02v(1, 2, 3)
259 d02v(1, *(2, 3, 4))
260 d02v(**{'a': 1, 'b': 2})
261 def d12v(a, b=1, c=2, *rest): pass
262 d12v(1)
263 d12v(1, 2)
264 d12v(1, 2, 3)
265 d12v(1, 2, 3, 4)
266 d12v(*(1, 2, 3, 4))
267 d12v(1, 2, *(3, 4, 5))
268 d12v(1, *(2,), **{'c': 3})
269 def d22v(a, b, c=1, d=2, *rest): pass
270 d22v(1, 2)
271 d22v(1, 2, 3)
272 d22v(1, 2, 3, 4)
273 d22v(1, 2, 3, 4, 5)
274 d22v(*(1, 2, 3, 4))
275 d22v(1, 2, *(3, 4, 5))
276 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000277
278 # keyword argument type tests
279 try:
280 str('x', **{b'foo':1 })
281 except TypeError:
282 pass
283 else:
284 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000285 # keyword only argument tests
286 def pos0key1(*, key): return key
287 pos0key1(key=100)
288 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
289 pos2key2(1, 2, k1=100)
290 pos2key2(1, 2, k1=100, k2=200)
291 pos2key2(1, 2, k2=100, k1=200)
292 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
293 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
294 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
295
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000296 # keyword arguments after *arglist
297 def f(*args, **kwargs):
298 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000299 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000300 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400301 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000302 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400303 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
304 ((), {'eggs':'scrambled', 'spam':'fried'}))
305 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
306 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000307
Neal Norwitzc1505362006-12-28 06:47:50 +0000308 # argument annotation tests
309 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000310 self.assertEqual(f.__annotations__, {'return': list})
Neal Norwitzc1505362006-12-28 06:47:50 +0000311 def f(x:int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000312 self.assertEqual(f.__annotations__, {'x': int})
Neal Norwitzc1505362006-12-28 06:47:50 +0000313 def f(*x:str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000314 self.assertEqual(f.__annotations__, {'x': str})
Neal Norwitzc1505362006-12-28 06:47:50 +0000315 def f(**x:float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000316 self.assertEqual(f.__annotations__, {'x': float})
Neal Norwitzc1505362006-12-28 06:47:50 +0000317 def f(x, y:1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000318 self.assertEqual(f.__annotations__, {'y': 3})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000319 def f(a, b:1, c:2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000320 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000321 def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000322 self.assertEqual(f.__annotations__,
Neal Norwitzc1505362006-12-28 06:47:50 +0000323 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000324 def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
Neal Norwitzc1505362006-12-28 06:47:50 +0000325 **k:11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000326 self.assertEqual(f.__annotations__,
Neal Norwitzc1505362006-12-28 06:47:50 +0000327 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
328 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500329 # Check for issue #20625 -- annotations mangling
330 class Spam:
331 def f(self, *, __kw:1):
332 pass
333 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500334 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
335 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000336 # Check for SF Bug #1697248 - mixing decorators and a return annotation
337 def null(x): return x
338 @null
339 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000340 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000341
Guido van Rossum0240b922007-02-26 21:23:50 +0000342 # test MAKE_CLOSURE with a variety of oparg's
343 closure = 1
344 def f(): return closure
345 def f(x=1): return closure
346 def f(*, k=1): return closure
347 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000348
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000349 # Check ast errors in *args and *kwargs
350 check_syntax_error(self, "f(*g(1=2))")
351 check_syntax_error(self, "f(**g(1=2))")
352
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500353 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000354 ### lambdef: 'lambda' [varargslist] ':' test
355 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000356 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000357 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000358 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000359 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000360 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000361 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000362 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000363 self.assertEqual(l5(1, 2), 5)
364 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000365 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000366 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000367 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000368 self.assertEqual(l6(1,2), 1+2+20)
369 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000370
371
Thomas Wouters89f507f2006-12-13 04:49:30 +0000372 ### stmt: simple_stmt | compound_stmt
373 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000374
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500375 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000376 ### simple_stmt: small_stmt (';' small_stmt)* [';']
377 x = 1; pass; del x
378 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200379 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380 x = 1; pass; del x;
381 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000382
Guido van Rossumd8faa362007-04-27 19:54:29 +0000383 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000384 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000385
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500386 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000387 # (exprlist '=')* exprlist
388 1
389 1, 2, 3
390 x = 1
391 x = 1, 2, 3
392 x = y = z = 1, 2, 3
393 x, y, z = 1, 2, 3
394 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000395
Thomas Wouters89f507f2006-12-13 04:49:30 +0000396 check_syntax_error(self, "x + 1 = 1")
397 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000398
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000399 # Check the heuristic for print & exec covers significant cases
400 # As well as placing some limits on false positives
401 def test_former_statements_refer_to_builtins(self):
402 keywords = "print", "exec"
403 # Cases where we want the custom error
404 cases = [
405 "{} foo",
406 "{} {{1:foo}}",
407 "if 1: {} foo",
408 "if 1: {} {{1:foo}}",
409 "if 1:\n {} foo",
410 "if 1:\n {} {{1:foo}}",
411 ]
412 for keyword in keywords:
413 custom_msg = "call to '{}'".format(keyword)
414 for case in cases:
415 source = case.format(keyword)
416 with self.subTest(source=source):
417 with self.assertRaisesRegex(SyntaxError, custom_msg):
418 exec(source)
419 source = source.replace("foo", "(foo.)")
420 with self.subTest(source=source):
421 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
422 exec(source)
423
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500424 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000425 # 'del' exprlist
426 abc = [1,2,3]
427 x, y, z = abc
428 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000429
Thomas Wouters89f507f2006-12-13 04:49:30 +0000430 del abc
431 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000432
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500433 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000434 # 'pass'
435 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000436
Thomas Wouters89f507f2006-12-13 04:49:30 +0000437 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
438 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000439
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500440 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000441 # 'break'
442 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000443
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500444 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000445 # 'continue'
446 i = 1
447 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000448
Thomas Wouters89f507f2006-12-13 04:49:30 +0000449 msg = ""
450 while not msg:
451 msg = "ok"
452 try:
453 continue
454 msg = "continue failed to continue inside try"
455 except:
456 msg = "continue inside try called except block"
457 if msg != "ok":
458 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000459
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 msg = ""
461 while not msg:
462 msg = "finally block not called"
463 try:
464 continue
465 finally:
466 msg = "ok"
467 if msg != "ok":
468 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000469
Thomas Wouters89f507f2006-12-13 04:49:30 +0000470 def test_break_continue_loop(self):
471 # This test warrants an explanation. It is a test specifically for SF bugs
472 # #463359 and #462937. The bug is that a 'break' statement executed or
473 # exception raised inside a try/except inside a loop, *after* a continue
474 # statement has been executed in that loop, will cause the wrong number of
475 # arguments to be popped off the stack and the instruction pointer reset to
476 # a very small number (usually 0.) Because of this, the following test
477 # *must* written as a function, and the tracking vars *must* be function
478 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000479
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480 def test_inner(extra_burning_oil = 1, count=0):
481 big_hippo = 2
482 while big_hippo:
483 count += 1
484 try:
485 if extra_burning_oil and big_hippo == 1:
486 extra_burning_oil -= 1
487 break
488 big_hippo -= 1
489 continue
490 except:
491 raise
492 if count > 2 or big_hippo != 1:
493 self.fail("continue then break in try/except in loop broken!")
494 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000495
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500496 def test_return(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000497 # 'return' [testlist]
498 def g1(): return
499 def g2(): return 1
500 g1()
501 x = g2()
502 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000503
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500504 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000505 # Allowed as standalone statement
506 def g(): yield 1
507 def g(): yield from ()
508 # Allowed as RHS of assignment
509 def g(): x = yield 1
510 def g(): x = yield from ()
511 # Ordinary yield accepts implicit tuples
512 def g(): yield 1, 1
513 def g(): x = yield 1, 1
514 # 'yield from' does not
515 check_syntax_error(self, "def g(): yield from (), 1")
516 check_syntax_error(self, "def g(): x = yield from (), 1")
517 # Requires parentheses as subexpression
518 def g(): 1, (yield 1)
519 def g(): 1, (yield from ())
520 check_syntax_error(self, "def g(): 1, yield 1")
521 check_syntax_error(self, "def g(): 1, yield from ()")
522 # Requires parentheses as call argument
523 def g(): f((yield 1))
524 def g(): f((yield 1), 1)
525 def g(): f((yield from ()))
526 def g(): f((yield from ()), 1)
527 check_syntax_error(self, "def g(): f(yield 1)")
528 check_syntax_error(self, "def g(): f(yield 1, 1)")
529 check_syntax_error(self, "def g(): f(yield from ())")
530 check_syntax_error(self, "def g(): f(yield from (), 1)")
531 # Not allowed at top level
532 check_syntax_error(self, "yield")
533 check_syntax_error(self, "yield from")
534 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +0000535 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000536 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +0300537 # Check annotation refleak on SyntaxError
538 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +0000539
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500540 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000541 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000542 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000543 except RuntimeError: pass
544 try: raise KeyboardInterrupt
545 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000546
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500547 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000548 # 'import' dotted_as_names
549 import sys
550 import time, sys
551 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
552 from time import time
553 from time import (time)
554 # not testable inside a function, but already done at top of the module
555 # from sys import *
556 from sys import path, argv
557 from sys import (path, argv)
558 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000559
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500560 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000561 # 'global' NAME (',' NAME)*
562 global a
563 global a, b
564 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000565
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500566 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +0000567 # 'nonlocal' NAME (',' NAME)*
568 x = 0
569 y = 0
570 def f():
571 nonlocal x
572 nonlocal x, y
573
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500574 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000575 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000576 assert 1
577 assert 1, 1
578 assert lambda x:x
579 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200580
581 try:
582 assert True
583 except AssertionError as e:
584 self.fail("'assert True' should not have raised an AssertionError")
585
586 try:
587 assert True, 'this should always pass'
588 except AssertionError as e:
589 self.fail("'assert True, msg' should not have "
590 "raised an AssertionError")
591
592 # these tests fail if python is run with -O, so check __debug__
593 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
594 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +0000595 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000596 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000597 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000598 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000599 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200600 self.fail("AssertionError not raised by assert 0")
601
602 try:
603 assert False
604 except AssertionError as e:
605 self.assertEqual(len(e.args), 0)
606 else:
607 self.fail("AssertionError not raised by 'assert False'")
608
Thomas Wouters80d373c2001-09-26 12:43:39 +0000609
Thomas Wouters89f507f2006-12-13 04:49:30 +0000610 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
611 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500613 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000614 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
615 if 1: pass
616 if 1: pass
617 else: pass
618 if 0: pass
619 elif 0: pass
620 if 0: pass
621 elif 0: pass
622 elif 0: pass
623 elif 0: pass
624 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000625
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500626 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000627 # 'while' test ':' suite ['else' ':' suite]
628 while 0: pass
629 while 0: pass
630 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000631
Christian Heimes969fe572008-01-25 11:23:10 +0000632 # Issue1920: "while 0" is optimized away,
633 # ensure that the "else" clause is still present.
634 x = 0
635 while 0:
636 x = 1
637 else:
638 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000639 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +0000640
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500641 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000642 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
643 for i in 1, 2, 3: pass
644 for i, j, k in (): pass
645 else: pass
646 class Squares:
647 def __init__(self, max):
648 self.max = max
649 self.sofar = []
650 def __len__(self): return len(self.sofar)
651 def __getitem__(self, i):
652 if not 0 <= i < self.max: raise IndexError
653 n = len(self.sofar)
654 while n <= i:
655 self.sofar.append(n*n)
656 n = n+1
657 return self.sofar[i]
658 n = 0
659 for x in Squares(10): n = n+x
660 if n != 285:
661 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000662
Thomas Wouters89f507f2006-12-13 04:49:30 +0000663 result = []
664 for x, in [(1,), (2,), (3,)]:
665 result.append(x)
666 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000667
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500668 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000669 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
670 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000671 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000672 try:
673 1/0
674 except ZeroDivisionError:
675 pass
676 else:
677 pass
678 try: 1/0
679 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000680 except TypeError as msg: pass
681 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000682 except: pass
683 else: pass
684 try: 1/0
685 except (EOFError, TypeError, ZeroDivisionError): pass
686 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000687 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 try: pass
689 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000690
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500691 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000692 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
693 if 1: pass
694 if 1:
695 pass
696 if 1:
697 #
698 #
699 #
700 pass
701 pass
702 #
703 pass
704 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000705
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500706 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000707 ### and_test ('or' and_test)*
708 ### and_test: not_test ('and' not_test)*
709 ### not_test: 'not' not_test | comparison
710 if not 1: pass
711 if 1 and 1: pass
712 if 1 or 1: pass
713 if not not not 1: pass
714 if not 1 and 1 and 1: pass
715 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000716
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500717 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000718 ### comparison: expr (comp_op expr)*
719 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
720 if 1: pass
721 x = (1 == 1)
722 if 1 == 1: pass
723 if 1 != 1: pass
724 if 1 < 1: pass
725 if 1 > 1: pass
726 if 1 <= 1: pass
727 if 1 >= 1: pass
728 if 1 is 1: pass
729 if 1 is not 1: pass
730 if 1 in (): pass
731 if 1 not in (): pass
732 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000733
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500734 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000735 x = 1 & 1
736 x = 1 ^ 1
737 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000738
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500739 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000740 x = 1 << 1
741 x = 1 >> 1
742 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000743
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500744 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000745 x = 1
746 x = 1 + 1
747 x = 1 - 1 - 1
748 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000749
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500750 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000751 x = 1 * 1
752 x = 1 / 1
753 x = 1 % 1
754 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000755
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500756 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000757 x = +1
758 x = -1
759 x = ~1
760 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
761 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000762
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500763 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000764 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
765 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000766
Thomas Wouters89f507f2006-12-13 04:49:30 +0000767 import sys, time
768 c = sys.path[0]
769 x = time.time()
770 x = sys.modules['time'].time()
771 a = '01234'
772 c = a[0]
773 c = a[-1]
774 s = a[0:5]
775 s = a[:5]
776 s = a[0:]
777 s = a[:]
778 s = a[-5:]
779 s = a[:-1]
780 s = a[-4:-3]
781 # A rough test of SF bug 1333982. http://python.org/sf/1333982
782 # The testing here is fairly incomplete.
783 # Test cases should include: commas with 1 and 2 colons
784 d = {}
785 d[1] = 1
786 d[1,] = 2
787 d[1,2] = 3
788 d[1,2,3] = 4
789 L = list(d)
790 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000791 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000792
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500793 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000794 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
795 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000796
Thomas Wouters89f507f2006-12-13 04:49:30 +0000797 x = (1)
798 x = (1 or 2 or 3)
799 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000800
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801 x = []
802 x = [1]
803 x = [1 or 2 or 3]
804 x = [1 or 2 or 3, 2, 3]
805 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000806
Thomas Wouters89f507f2006-12-13 04:49:30 +0000807 x = {}
808 x = {'one': 1}
809 x = {'one': 1,}
810 x = {'one' or 'two': 1 or 2}
811 x = {'one': 1, 'two': 2}
812 x = {'one': 1, 'two': 2,}
813 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000814
Thomas Wouters89f507f2006-12-13 04:49:30 +0000815 x = {'one'}
816 x = {'one', 1,}
817 x = {'one', 'two', 'three'}
818 x = {2, 3, 4,}
819
820 x = x
821 x = 'x'
822 x = 123
823
824 ### exprlist: expr (',' expr)* [',']
825 ### testlist: test (',' test)* [',']
826 # These have been exercised enough above
827
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500828 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000829 # 'class' NAME ['(' [testlist] ')'] ':' suite
830 class B: pass
831 class B2(): pass
832 class C1(B): pass
833 class C2(B): pass
834 class D(C1, C2, B): pass
835 class C:
836 def meth1(self): pass
837 def meth2(self, arg): pass
838 def meth3(self, a1, a2): pass
839
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000840 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
841 # decorators: decorator+
842 # decorated: decorators (classdef | funcdef)
843 def class_decorator(x): return x
844 @class_decorator
845 class G: pass
846
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500847 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000848 # dictorsetmaker: ( (test ':' test (comp_for |
849 # (',' test ':' test)* [','])) |
850 # (test (comp_for | (',' test)* [','])) )
851 nums = [1, 2, 3]
852 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
853
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500854 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000855 # list comprehension tests
856 nums = [1, 2, 3, 4, 5]
857 strs = ["Apple", "Banana", "Coconut"]
858 spcs = [" Apple", " Banana ", "Coco nut "]
859
860 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
861 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
862 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
863 self.assertEqual([(i, s) for i in nums for s in strs],
864 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
865 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
866 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
867 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
868 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
869 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
870 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
871 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
872 (5, 'Banana'), (5, 'Coconut')])
873 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
874 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
875
876 def test_in_func(l):
877 return [0 < x < 3 for x in l if x > 2]
878
879 self.assertEqual(test_in_func(nums), [False, False, False])
880
881 def test_nested_front():
882 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
883 [[1, 2], [3, 4], [5, 6]])
884
885 test_nested_front()
886
887 check_syntax_error(self, "[i, s for i in nums for s in strs]")
888 check_syntax_error(self, "[x if y]")
889
890 suppliers = [
891 (1, "Boeing"),
892 (2, "Ford"),
893 (3, "Macdonalds")
894 ]
895
896 parts = [
897 (10, "Airliner"),
898 (20, "Engine"),
899 (30, "Cheeseburger")
900 ]
901
902 suppart = [
903 (1, 10), (1, 20), (2, 20), (3, 30)
904 ]
905
906 x = [
907 (sname, pname)
908 for (sno, sname) in suppliers
909 for (pno, pname) in parts
910 for (sp_sno, sp_pno) in suppart
911 if sno == sp_sno and pno == sp_pno
912 ]
913
914 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
915 ('Macdonalds', 'Cheeseburger')])
916
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500917 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000918 # generator expression tests
919 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000920 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000921 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000922 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000923 self.fail('should produce StopIteration exception')
924 except StopIteration:
925 pass
926
927 a = 1
928 try:
929 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +0000930 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000931 self.fail('should produce TypeError')
932 except TypeError:
933 pass
934
935 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
936 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
937
938 a = [x for x in range(10)]
939 b = (x for x in (y for y in a))
940 self.assertEqual(sum(b), sum([x for x in range(10)]))
941
942 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
943 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
944 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
945 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
946 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
947 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)]))
948 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
949 check_syntax_error(self, "foo(x for x in range(10), 100)")
950 check_syntax_error(self, "foo(100, x for x in range(10))")
951
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500952 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000953 # test for outmost iterable precomputation
954 x = 10; g = (i for i in range(x)); x = 5
955 self.assertEqual(len(list(g)), 10)
956
957 # This should hold, since we're only precomputing outmost iterable.
958 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
959 x = 5; t = True;
960 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
961
962 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
963 # even though it's silly. Make sure it works (ifelse broke this.)
964 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
965 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
966
967 # verify unpacking single element tuples in listcomp/genexp.
968 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
969 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
970
Benjamin Petersonf17ab892009-05-29 21:55:57 +0000971 def test_with_statement(self):
972 class manager(object):
973 def __enter__(self):
974 return (1, 2)
975 def __exit__(self, *args):
976 pass
977
978 with manager():
979 pass
980 with manager() as x:
981 pass
982 with manager() as (x, y):
983 pass
984 with manager(), manager():
985 pass
986 with manager() as x, manager() as y:
987 pass
988 with manager() as x, manager():
989 pass
990
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500991 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000992 # Test ifelse expressions in various cases
993 def _checkeval(msg, ret):
994 "helper to check that evaluation of expressions is done correctly"
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000995 print(x)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000996 return ret
997
Nick Coghlan650f0d02007-04-15 12:05:43 +0000998 # the next line is not allowed anymore
999 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001000 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1001 self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
1002 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1003 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1004 self.assertEqual((5 and 6 if 0 else 1), 1)
1005 self.assertEqual(((5 and 6) if 0 else 1), 1)
1006 self.assertEqual((5 and (6 if 1 else 1)), 6)
1007 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1008 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1009 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1010 self.assertEqual((not 5 if 1 else 1), False)
1011 self.assertEqual((not 5 if 0 else 1), 1)
1012 self.assertEqual((6 + 1 if 1 else 2), 7)
1013 self.assertEqual((6 - 1 if 1 else 2), 5)
1014 self.assertEqual((6 * 2 if 1 else 4), 12)
1015 self.assertEqual((6 / 2 if 1 else 3), 3)
1016 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001017
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001018 def test_paren_evaluation(self):
1019 self.assertEqual(16 // (4 // 2), 8)
1020 self.assertEqual((16 // 4) // 2, 2)
1021 self.assertEqual(16 // 4 // 2, 2)
1022 self.assertTrue(False is (2 is 3))
1023 self.assertFalse((False is 2) is 3)
1024 self.assertFalse(False is 2 is 3)
1025
Benjamin Petersond51374e2014-04-09 23:55:56 -04001026 def test_matrix_mul(self):
1027 # This is not intended to be a comprehensive test, rather just to be few
1028 # samples of the @ operator in test_grammar.py.
1029 class M:
1030 def __matmul__(self, o):
1031 return 4
1032 def __imatmul__(self, o):
1033 self.other = o
1034 return self
1035 m = M()
1036 self.assertEqual(m @ m, 4)
1037 m @= 42
1038 self.assertEqual(m.other, 42)
1039
Yury Selivanov75445082015-05-11 22:57:16 -04001040 def test_async_await(self):
1041 async = 1
1042 await = 2
1043 self.assertEqual(async, 1)
1044
1045 def async():
1046 nonlocal await
1047 await = 10
1048 async()
1049 self.assertEqual(await, 10)
1050
1051 self.assertFalse(bool(async.__code__.co_flags & inspect.CO_COROUTINE))
1052
1053 async def test():
1054 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001055 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001056 if 1:
1057 await someobj()
1058
1059 self.assertEqual(test.__name__, 'test')
1060 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1061
1062 def decorator(func):
1063 setattr(func, '_marked', True)
1064 return func
1065
1066 @decorator
1067 async def test2():
1068 return 22
1069 self.assertTrue(test2._marked)
1070 self.assertEqual(test2.__name__, 'test2')
1071 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1072
1073 def test_async_for(self):
1074 class Done(Exception): pass
1075
1076 class AIter:
1077 async def __aiter__(self):
1078 return self
1079 async def __anext__(self):
1080 raise StopAsyncIteration
1081
1082 async def foo():
1083 async for i in AIter():
1084 pass
1085 async for i, j in AIter():
1086 pass
1087 async for i in AIter():
1088 pass
1089 else:
1090 pass
1091 raise Done
1092
1093 with self.assertRaises(Done):
1094 foo().send(None)
1095
1096 def test_async_with(self):
1097 class Done(Exception): pass
1098
1099 class manager:
1100 async def __aenter__(self):
1101 return (1, 2)
1102 async def __aexit__(self, *exc):
1103 return False
1104
1105 async def foo():
1106 async with manager():
1107 pass
1108 async with manager() as x:
1109 pass
1110 async with manager() as (x, y):
1111 pass
1112 async with manager(), manager():
1113 pass
1114 async with manager() as x, manager() as y:
1115 pass
1116 async with manager() as x, manager():
1117 pass
1118 raise Done
1119
1120 with self.assertRaises(Done):
1121 foo().send(None)
1122
Guido van Rossum3bead091992-01-27 17:00:37 +00001123
Thomas Wouters89f507f2006-12-13 04:49:30 +00001124if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001125 unittest.main()