blob: ca6b5d0c385f5095ad0e2ce299693358dae99567 [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 ()")
537
Guido van Rossum3bead091992-01-27 17:00:37 +0000538
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500539 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000540 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000541 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000542 except RuntimeError: pass
543 try: raise KeyboardInterrupt
544 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000545
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500546 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000547 # 'import' dotted_as_names
548 import sys
549 import time, sys
550 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
551 from time import time
552 from time import (time)
553 # not testable inside a function, but already done at top of the module
554 # from sys import *
555 from sys import path, argv
556 from sys import (path, argv)
557 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000558
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500559 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000560 # 'global' NAME (',' NAME)*
561 global a
562 global a, b
563 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000564
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500565 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +0000566 # 'nonlocal' NAME (',' NAME)*
567 x = 0
568 y = 0
569 def f():
570 nonlocal x
571 nonlocal x, y
572
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500573 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000574 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000575 assert 1
576 assert 1, 1
577 assert lambda x:x
578 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200579
580 try:
581 assert True
582 except AssertionError as e:
583 self.fail("'assert True' should not have raised an AssertionError")
584
585 try:
586 assert True, 'this should always pass'
587 except AssertionError as e:
588 self.fail("'assert True, msg' should not have "
589 "raised an AssertionError")
590
591 # these tests fail if python is run with -O, so check __debug__
592 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
593 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +0000594 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000595 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000596 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000597 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200599 self.fail("AssertionError not raised by assert 0")
600
601 try:
602 assert False
603 except AssertionError as e:
604 self.assertEqual(len(e.args), 0)
605 else:
606 self.fail("AssertionError not raised by 'assert False'")
607
Thomas Wouters80d373c2001-09-26 12:43:39 +0000608
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
610 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500612 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000613 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
614 if 1: pass
615 if 1: pass
616 else: pass
617 if 0: pass
618 elif 0: pass
619 if 0: pass
620 elif 0: pass
621 elif 0: pass
622 elif 0: pass
623 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000624
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500625 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000626 # 'while' test ':' suite ['else' ':' suite]
627 while 0: pass
628 while 0: pass
629 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000630
Christian Heimes969fe572008-01-25 11:23:10 +0000631 # Issue1920: "while 0" is optimized away,
632 # ensure that the "else" clause is still present.
633 x = 0
634 while 0:
635 x = 1
636 else:
637 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000638 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +0000639
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500640 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000641 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
642 for i in 1, 2, 3: pass
643 for i, j, k in (): pass
644 else: pass
645 class Squares:
646 def __init__(self, max):
647 self.max = max
648 self.sofar = []
649 def __len__(self): return len(self.sofar)
650 def __getitem__(self, i):
651 if not 0 <= i < self.max: raise IndexError
652 n = len(self.sofar)
653 while n <= i:
654 self.sofar.append(n*n)
655 n = n+1
656 return self.sofar[i]
657 n = 0
658 for x in Squares(10): n = n+x
659 if n != 285:
660 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000661
Thomas Wouters89f507f2006-12-13 04:49:30 +0000662 result = []
663 for x, in [(1,), (2,), (3,)]:
664 result.append(x)
665 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000666
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500667 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000668 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
669 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000670 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671 try:
672 1/0
673 except ZeroDivisionError:
674 pass
675 else:
676 pass
677 try: 1/0
678 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000679 except TypeError as msg: pass
680 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000681 except: pass
682 else: pass
683 try: 1/0
684 except (EOFError, TypeError, ZeroDivisionError): pass
685 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000686 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000687 try: pass
688 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000689
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500690 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000691 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
692 if 1: pass
693 if 1:
694 pass
695 if 1:
696 #
697 #
698 #
699 pass
700 pass
701 #
702 pass
703 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000704
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500705 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000706 ### and_test ('or' and_test)*
707 ### and_test: not_test ('and' not_test)*
708 ### not_test: 'not' not_test | comparison
709 if not 1: pass
710 if 1 and 1: pass
711 if 1 or 1: pass
712 if not not not 1: pass
713 if not 1 and 1 and 1: pass
714 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000715
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500716 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000717 ### comparison: expr (comp_op expr)*
718 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
719 if 1: pass
720 x = (1 == 1)
721 if 1 == 1: pass
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 is 1: pass
728 if 1 is not 1: pass
729 if 1 in (): pass
730 if 1 not in (): pass
731 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 +0000732
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500733 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000734 x = 1 & 1
735 x = 1 ^ 1
736 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000737
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500738 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000739 x = 1 << 1
740 x = 1 >> 1
741 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000742
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500743 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000744 x = 1
745 x = 1 + 1
746 x = 1 - 1 - 1
747 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000748
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500749 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000750 x = 1 * 1
751 x = 1 / 1
752 x = 1 % 1
753 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000754
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500755 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756 x = +1
757 x = -1
758 x = ~1
759 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
760 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000761
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500762 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000763 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
764 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000765
Thomas Wouters89f507f2006-12-13 04:49:30 +0000766 import sys, time
767 c = sys.path[0]
768 x = time.time()
769 x = sys.modules['time'].time()
770 a = '01234'
771 c = a[0]
772 c = a[-1]
773 s = a[0:5]
774 s = a[:5]
775 s = a[0:]
776 s = a[:]
777 s = a[-5:]
778 s = a[:-1]
779 s = a[-4:-3]
780 # A rough test of SF bug 1333982. http://python.org/sf/1333982
781 # The testing here is fairly incomplete.
782 # Test cases should include: commas with 1 and 2 colons
783 d = {}
784 d[1] = 1
785 d[1,] = 2
786 d[1,2] = 3
787 d[1,2,3] = 4
788 L = list(d)
789 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000790 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000791
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500792 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000793 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
794 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000795
Thomas Wouters89f507f2006-12-13 04:49:30 +0000796 x = (1)
797 x = (1 or 2 or 3)
798 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000799
Thomas Wouters89f507f2006-12-13 04:49:30 +0000800 x = []
801 x = [1]
802 x = [1 or 2 or 3]
803 x = [1 or 2 or 3, 2, 3]
804 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000805
Thomas Wouters89f507f2006-12-13 04:49:30 +0000806 x = {}
807 x = {'one': 1}
808 x = {'one': 1,}
809 x = {'one' or 'two': 1 or 2}
810 x = {'one': 1, 'two': 2}
811 x = {'one': 1, 'two': 2,}
812 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000813
Thomas Wouters89f507f2006-12-13 04:49:30 +0000814 x = {'one'}
815 x = {'one', 1,}
816 x = {'one', 'two', 'three'}
817 x = {2, 3, 4,}
818
819 x = x
820 x = 'x'
821 x = 123
822
823 ### exprlist: expr (',' expr)* [',']
824 ### testlist: test (',' test)* [',']
825 # These have been exercised enough above
826
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500827 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000828 # 'class' NAME ['(' [testlist] ')'] ':' suite
829 class B: pass
830 class B2(): pass
831 class C1(B): pass
832 class C2(B): pass
833 class D(C1, C2, B): pass
834 class C:
835 def meth1(self): pass
836 def meth2(self, arg): pass
837 def meth3(self, a1, a2): pass
838
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000839 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
840 # decorators: decorator+
841 # decorated: decorators (classdef | funcdef)
842 def class_decorator(x): return x
843 @class_decorator
844 class G: pass
845
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500846 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000847 # dictorsetmaker: ( (test ':' test (comp_for |
848 # (',' test ':' test)* [','])) |
849 # (test (comp_for | (',' test)* [','])) )
850 nums = [1, 2, 3]
851 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
852
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500853 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000854 # list comprehension tests
855 nums = [1, 2, 3, 4, 5]
856 strs = ["Apple", "Banana", "Coconut"]
857 spcs = [" Apple", " Banana ", "Coco nut "]
858
859 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
860 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
861 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
862 self.assertEqual([(i, s) for i in nums for s in strs],
863 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
864 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
865 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
866 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
867 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
868 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
869 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
870 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
871 (5, 'Banana'), (5, 'Coconut')])
872 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
873 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
874
875 def test_in_func(l):
876 return [0 < x < 3 for x in l if x > 2]
877
878 self.assertEqual(test_in_func(nums), [False, False, False])
879
880 def test_nested_front():
881 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
882 [[1, 2], [3, 4], [5, 6]])
883
884 test_nested_front()
885
886 check_syntax_error(self, "[i, s for i in nums for s in strs]")
887 check_syntax_error(self, "[x if y]")
888
889 suppliers = [
890 (1, "Boeing"),
891 (2, "Ford"),
892 (3, "Macdonalds")
893 ]
894
895 parts = [
896 (10, "Airliner"),
897 (20, "Engine"),
898 (30, "Cheeseburger")
899 ]
900
901 suppart = [
902 (1, 10), (1, 20), (2, 20), (3, 30)
903 ]
904
905 x = [
906 (sname, pname)
907 for (sno, sname) in suppliers
908 for (pno, pname) in parts
909 for (sp_sno, sp_pno) in suppart
910 if sno == sp_sno and pno == sp_pno
911 ]
912
913 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
914 ('Macdonalds', 'Cheeseburger')])
915
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500916 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000917 # generator expression tests
918 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000919 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000920 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000921 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000922 self.fail('should produce StopIteration exception')
923 except StopIteration:
924 pass
925
926 a = 1
927 try:
928 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +0000929 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000930 self.fail('should produce TypeError')
931 except TypeError:
932 pass
933
934 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
935 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
936
937 a = [x for x in range(10)]
938 b = (x for x in (y for y in a))
939 self.assertEqual(sum(b), sum([x for x in range(10)]))
940
941 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
942 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
943 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
944 self.assertEqual(sum(x for x in (y for y in (z for z 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) if True)) if True), 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 False) if True), 0)
948 check_syntax_error(self, "foo(x for x in range(10), 100)")
949 check_syntax_error(self, "foo(100, x for x in range(10))")
950
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500951 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000952 # test for outmost iterable precomputation
953 x = 10; g = (i for i in range(x)); x = 5
954 self.assertEqual(len(list(g)), 10)
955
956 # This should hold, since we're only precomputing outmost iterable.
957 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
958 x = 5; t = True;
959 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
960
961 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
962 # even though it's silly. Make sure it works (ifelse broke this.)
963 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
964 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
965
966 # verify unpacking single element tuples in listcomp/genexp.
967 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
968 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
969
Benjamin Petersonf17ab892009-05-29 21:55:57 +0000970 def test_with_statement(self):
971 class manager(object):
972 def __enter__(self):
973 return (1, 2)
974 def __exit__(self, *args):
975 pass
976
977 with manager():
978 pass
979 with manager() as x:
980 pass
981 with manager() as (x, y):
982 pass
983 with manager(), manager():
984 pass
985 with manager() as x, manager() as y:
986 pass
987 with manager() as x, manager():
988 pass
989
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500990 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000991 # Test ifelse expressions in various cases
992 def _checkeval(msg, ret):
993 "helper to check that evaluation of expressions is done correctly"
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000994 print(x)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000995 return ret
996
Nick Coghlan650f0d02007-04-15 12:05:43 +0000997 # the next line is not allowed anymore
998 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000999 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1000 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])
1001 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1002 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1003 self.assertEqual((5 and 6 if 0 else 1), 1)
1004 self.assertEqual(((5 and 6) if 0 else 1), 1)
1005 self.assertEqual((5 and (6 if 1 else 1)), 6)
1006 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1007 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1008 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1009 self.assertEqual((not 5 if 1 else 1), False)
1010 self.assertEqual((not 5 if 0 else 1), 1)
1011 self.assertEqual((6 + 1 if 1 else 2), 7)
1012 self.assertEqual((6 - 1 if 1 else 2), 5)
1013 self.assertEqual((6 * 2 if 1 else 4), 12)
1014 self.assertEqual((6 / 2 if 1 else 3), 3)
1015 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001016
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001017 def test_paren_evaluation(self):
1018 self.assertEqual(16 // (4 // 2), 8)
1019 self.assertEqual((16 // 4) // 2, 2)
1020 self.assertEqual(16 // 4 // 2, 2)
1021 self.assertTrue(False is (2 is 3))
1022 self.assertFalse((False is 2) is 3)
1023 self.assertFalse(False is 2 is 3)
1024
Benjamin Petersond51374e2014-04-09 23:55:56 -04001025 def test_matrix_mul(self):
1026 # This is not intended to be a comprehensive test, rather just to be few
1027 # samples of the @ operator in test_grammar.py.
1028 class M:
1029 def __matmul__(self, o):
1030 return 4
1031 def __imatmul__(self, o):
1032 self.other = o
1033 return self
1034 m = M()
1035 self.assertEqual(m @ m, 4)
1036 m @= 42
1037 self.assertEqual(m.other, 42)
1038
Yury Selivanov75445082015-05-11 22:57:16 -04001039 def test_async_await(self):
1040 async = 1
1041 await = 2
1042 self.assertEqual(async, 1)
1043
1044 def async():
1045 nonlocal await
1046 await = 10
1047 async()
1048 self.assertEqual(await, 10)
1049
1050 self.assertFalse(bool(async.__code__.co_flags & inspect.CO_COROUTINE))
1051
1052 async def test():
1053 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001054 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001055 if 1:
1056 await someobj()
1057
1058 self.assertEqual(test.__name__, 'test')
1059 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1060
1061 def decorator(func):
1062 setattr(func, '_marked', True)
1063 return func
1064
1065 @decorator
1066 async def test2():
1067 return 22
1068 self.assertTrue(test2._marked)
1069 self.assertEqual(test2.__name__, 'test2')
1070 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1071
1072 def test_async_for(self):
1073 class Done(Exception): pass
1074
1075 class AIter:
1076 async def __aiter__(self):
1077 return self
1078 async def __anext__(self):
1079 raise StopAsyncIteration
1080
1081 async def foo():
1082 async for i in AIter():
1083 pass
1084 async for i, j in AIter():
1085 pass
1086 async for i in AIter():
1087 pass
1088 else:
1089 pass
1090 raise Done
1091
1092 with self.assertRaises(Done):
1093 foo().send(None)
1094
1095 def test_async_with(self):
1096 class Done(Exception): pass
1097
1098 class manager:
1099 async def __aenter__(self):
1100 return (1, 2)
1101 async def __aexit__(self, *exc):
1102 return False
1103
1104 async def foo():
1105 async with manager():
1106 pass
1107 async with manager() as x:
1108 pass
1109 async with manager() as (x, y):
1110 pass
1111 async with manager(), manager():
1112 pass
1113 async with manager() as x, manager() as y:
1114 pass
1115 async with manager() as x, manager():
1116 pass
1117 raise Done
1118
1119 with self.assertRaises(Done):
1120 foo().send(None)
1121
Guido van Rossum3bead091992-01-27 17:00:37 +00001122
Thomas Wouters89f507f2006-12-13 04:49:30 +00001123if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001124 unittest.main()