Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1 | # Python test set -- part 1, grammar. |
| 2 | # This just tests whether the parser accepts them all. |
| 3 | |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 4 | from test.support import check_syntax_error |
| 5 | from test.support.warnings_helper import check_syntax_warning |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 6 | import inspect |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 7 | import unittest |
Jeremy Hylton | 7d3dff2 | 2001-10-10 01:45:02 +0000 | [diff] [blame] | 8 | import sys |
Serhiy Storchaka | d31e773 | 2018-10-21 10:09:39 +0300 | [diff] [blame] | 9 | import warnings |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 10 | # testing import * |
| 11 | from sys import * |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 12 | |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 13 | # different import patterns to check that __annotations__ does not interfere |
| 14 | # with import machinery |
| 15 | import test.ann_module as ann_module |
| 16 | import typing |
| 17 | from collections import ChainMap |
| 18 | from test import ann_module2 |
| 19 | import test |
| 20 | |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 21 | # These are shared with test_tokenize and other test modules. |
| 22 | # |
| 23 | # Note: since several test cases filter out floats by looking for "e" and ".", |
| 24 | # don't add hexadecimal literals that contain "e" or "E". |
| 25 | VALID_UNDERSCORE_LITERALS = [ |
| 26 | '0_0_0', |
| 27 | '4_2', |
| 28 | '1_0000_0000', |
| 29 | '0b1001_0100', |
| 30 | '0xffff_ffff', |
| 31 | '0o5_7_7', |
| 32 | '1_00_00.5', |
| 33 | '1_00_00.5e5', |
| 34 | '1_00_00e5_1', |
| 35 | '1e1_0', |
| 36 | '.1_4', |
| 37 | '.1_4e1', |
| 38 | '0b_0', |
| 39 | '0x_f', |
| 40 | '0o_5', |
| 41 | '1_00_00j', |
| 42 | '1_00_00.5j', |
| 43 | '1_00_00e5_1j', |
| 44 | '.1_4j', |
| 45 | '(1_2.5+3_3j)', |
| 46 | '(.5_6j)', |
| 47 | ] |
| 48 | INVALID_UNDERSCORE_LITERALS = [ |
| 49 | # Trailing underscores: |
| 50 | '0_', |
| 51 | '42_', |
| 52 | '1.4j_', |
| 53 | '0x_', |
| 54 | '0b1_', |
| 55 | '0xf_', |
| 56 | '0o5_', |
| 57 | '0 if 1_Else 1', |
| 58 | # Underscores in the base selector: |
| 59 | '0_b0', |
| 60 | '0_xf', |
| 61 | '0_o5', |
| 62 | # Old-style octal, still disallowed: |
| 63 | '0_7', |
| 64 | '09_99', |
| 65 | # Multiple consecutive underscores: |
| 66 | '4_______2', |
| 67 | '0.1__4', |
| 68 | '0.1__4j', |
| 69 | '0b1001__0100', |
| 70 | '0xffff__ffff', |
| 71 | '0x___', |
| 72 | '0o5__77', |
| 73 | '1e1__0', |
| 74 | '1e1__0j', |
| 75 | # Underscore right before a dot: |
| 76 | '1_.4', |
| 77 | '1_.4j', |
| 78 | # Underscore right after a dot: |
| 79 | '1._4', |
| 80 | '1._4j', |
| 81 | '._5', |
| 82 | '._5j', |
| 83 | # Underscore right after a sign: |
| 84 | '1.0e+_1', |
| 85 | '1.0e+_1j', |
| 86 | # Underscore right before j: |
| 87 | '1.4_j', |
| 88 | '1.4e5_j', |
| 89 | # Underscore right before e: |
| 90 | '1_e1', |
| 91 | '1.4_e1', |
| 92 | '1.4_e1j', |
| 93 | # Underscore right after e: |
| 94 | '1e_1', |
| 95 | '1.4e_1', |
| 96 | '1.4e_1j', |
| 97 | # Complex cases with parens: |
| 98 | '(1+1.5_j_)', |
| 99 | '(1+1.5_j)', |
| 100 | ] |
| 101 | |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 102 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 103 | class TokenTests(unittest.TestCase): |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 104 | |
Serhiy Storchaka | e7a4bb5 | 2019-02-19 08:30:15 +0200 | [diff] [blame] | 105 | from test.support import check_syntax_error |
Serhiy Storchaka | cf7303e | 2018-07-09 15:09:35 +0300 | [diff] [blame] | 106 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 107 | def test_backslash(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 108 | # Backslash means line continuation: |
| 109 | x = 1 \ |
| 110 | + 1 |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 111 | self.assertEqual(x, 2, 'backslash for line continuation') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 112 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 113 | # Backslash does not means continuation in comments :\ |
| 114 | x = 0 |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 115 | self.assertEqual(x, 0, 'backslash ending comment') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 116 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 117 | def test_plain_integers(self): |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 118 | self.assertEqual(type(000), type(0)) |
| 119 | self.assertEqual(0xff, 255) |
| 120 | self.assertEqual(0o377, 255) |
| 121 | self.assertEqual(2147483647, 0o17777777777) |
| 122 | self.assertEqual(0b1001, 9) |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 123 | # "0x" is not a valid literal |
| 124 | self.assertRaises(SyntaxError, eval, "0x") |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 125 | from sys import maxsize |
| 126 | if maxsize == 2147483647: |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 127 | self.assertEqual(-2147483647-1, -0o20000000000) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 128 | # XXX -2147483648 |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 129 | self.assertTrue(0o37777777777 > 0) |
| 130 | self.assertTrue(0xffffffff > 0) |
| 131 | self.assertTrue(0b1111111111111111111111111111111 > 0) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 132 | for s in ('2147483648', '0o40000000000', '0x100000000', |
| 133 | '0b10000000000000000000000000000000'): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 134 | try: |
| 135 | x = eval(s) |
| 136 | except OverflowError: |
| 137 | self.fail("OverflowError on huge integer literal %r" % s) |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 138 | elif maxsize == 9223372036854775807: |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 139 | self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 140 | self.assertTrue(0o1777777777777777777777 > 0) |
| 141 | self.assertTrue(0xffffffffffffffff > 0) |
| 142 | self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 143 | for s in '9223372036854775808', '0o2000000000000000000000', \ |
| 144 | '0x10000000000000000', \ |
| 145 | '0b100000000000000000000000000000000000000000000000000000000000000': |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 146 | try: |
| 147 | x = eval(s) |
| 148 | except OverflowError: |
| 149 | self.fail("OverflowError on huge integer literal %r" % s) |
| 150 | else: |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 151 | self.fail('Weird maxsize value %r' % maxsize) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 152 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 153 | def test_long_integers(self): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 154 | x = 0 |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 155 | x = 0xffffffffffffffff |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 156 | x = 0Xffffffffffffffff |
| 157 | x = 0o77777777777777777 |
| 158 | x = 0O77777777777777777 |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 159 | x = 123456789012345678901234567890 |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 160 | x = 0b100000000000000000000000000000000000000000000000000000000000000000000 |
| 161 | x = 0B111111111111111111111111111111111111111111111111111111111111111111111 |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 162 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 163 | def test_floats(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 164 | x = 3.14 |
| 165 | x = 314. |
| 166 | x = 0.314 |
| 167 | # XXX x = 000.314 |
| 168 | x = .314 |
| 169 | x = 3e14 |
| 170 | x = 3E14 |
| 171 | x = 3e-14 |
| 172 | x = 3e+14 |
| 173 | x = 3.e14 |
| 174 | x = .3e14 |
| 175 | x = 3.1e4 |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 176 | |
Benjamin Peterson | c416162 | 2014-06-07 12:36:39 -0700 | [diff] [blame] | 177 | def test_float_exponent_tokenization(self): |
| 178 | # See issue 21642. |
| 179 | self.assertEqual(1 if 1else 0, 1) |
| 180 | self.assertEqual(1 if 0else 0, 0) |
| 181 | self.assertRaises(SyntaxError, eval, "0 if 1Else 0") |
| 182 | |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 183 | def test_underscore_literals(self): |
| 184 | for lit in VALID_UNDERSCORE_LITERALS: |
| 185 | self.assertEqual(eval(lit), eval(lit.replace('_', ''))) |
| 186 | for lit in INVALID_UNDERSCORE_LITERALS: |
| 187 | self.assertRaises(SyntaxError, eval, lit) |
| 188 | # Sanity check: no literal begins with an underscore |
| 189 | self.assertRaises(NameError, eval, "_0") |
| 190 | |
Serhiy Storchaka | cf7303e | 2018-07-09 15:09:35 +0300 | [diff] [blame] | 191 | def test_bad_numerical_literals(self): |
| 192 | check = self.check_syntax_error |
| 193 | check("0b12", "invalid digit '2' in binary literal") |
| 194 | check("0b1_2", "invalid digit '2' in binary literal") |
| 195 | check("0b2", "invalid digit '2' in binary literal") |
| 196 | check("0b1_", "invalid binary literal") |
| 197 | check("0b", "invalid binary literal") |
| 198 | check("0o18", "invalid digit '8' in octal literal") |
| 199 | check("0o1_8", "invalid digit '8' in octal literal") |
| 200 | check("0o8", "invalid digit '8' in octal literal") |
| 201 | check("0o1_", "invalid octal literal") |
| 202 | check("0o", "invalid octal literal") |
| 203 | check("0x1_", "invalid hexadecimal literal") |
| 204 | check("0x", "invalid hexadecimal literal") |
| 205 | check("1_", "invalid decimal literal") |
| 206 | check("012", |
| 207 | "leading zeros in decimal integer literals are not permitted; " |
| 208 | "use an 0o prefix for octal integers") |
| 209 | check("1.2_", "invalid decimal literal") |
| 210 | check("1e2_", "invalid decimal literal") |
| 211 | check("1e+", "invalid decimal literal") |
| 212 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 213 | def test_string_literals(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 214 | x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y) |
| 215 | x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39) |
| 216 | x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 217 | x = "doesn't \"shrink\" does it" |
| 218 | y = 'doesn\'t "shrink" does it' |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 219 | self.assertTrue(len(x) == 24 and x == y) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 220 | x = "does \"shrink\" doesn't it" |
| 221 | y = 'does "shrink" doesn\'t it' |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 222 | self.assertTrue(len(x) == 24 and x == y) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 223 | x = """ |
Guido van Rossum | b6775db | 1994-08-01 11:34:53 +0000 | [diff] [blame] | 224 | The "quick" |
| 225 | brown fox |
| 226 | jumps over |
| 227 | the 'lazy' dog. |
| 228 | """ |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 229 | y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 230 | self.assertEqual(x, y) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 231 | y = ''' |
Guido van Rossum | b6775db | 1994-08-01 11:34:53 +0000 | [diff] [blame] | 232 | The "quick" |
| 233 | brown fox |
| 234 | jumps over |
| 235 | the 'lazy' dog. |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 236 | ''' |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 237 | self.assertEqual(x, y) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 238 | y = "\n\ |
Guido van Rossum | b6775db | 1994-08-01 11:34:53 +0000 | [diff] [blame] | 239 | The \"quick\"\n\ |
| 240 | brown fox\n\ |
| 241 | jumps over\n\ |
| 242 | the 'lazy' dog.\n\ |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 243 | " |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 244 | self.assertEqual(x, y) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 245 | y = '\n\ |
Guido van Rossum | b6775db | 1994-08-01 11:34:53 +0000 | [diff] [blame] | 246 | The \"quick\"\n\ |
| 247 | brown fox\n\ |
| 248 | jumps over\n\ |
| 249 | the \'lazy\' dog.\n\ |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 250 | ' |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 251 | self.assertEqual(x, y) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 252 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 253 | def test_ellipsis(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 254 | x = ... |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 255 | self.assertTrue(x is Ellipsis) |
Georg Brandl | dde0028 | 2007-03-18 19:01:53 +0000 | [diff] [blame] | 256 | self.assertRaises(SyntaxError, eval, ".. .") |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 257 | |
Benjamin Peterson | 758888d | 2011-05-30 11:12:38 -0500 | [diff] [blame] | 258 | def test_eof_error(self): |
| 259 | samples = ("def foo(", "\ndef foo(", "def foo(\n") |
| 260 | for s in samples: |
| 261 | with self.assertRaises(SyntaxError) as cm: |
| 262 | compile(s, "<test>", "exec") |
Pablo Galindo | d6d6371 | 2021-01-19 23:59:33 +0000 | [diff] [blame] | 263 | self.assertIn("was never closed", str(cm.exception)) |
Benjamin Peterson | 758888d | 2011-05-30 11:12:38 -0500 | [diff] [blame] | 264 | |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 265 | var_annot_global: int # a global annotated is necessary for test_var_annot |
| 266 | |
| 267 | # custom namespace for testing __annotations__ |
| 268 | |
| 269 | class CNS: |
| 270 | def __init__(self): |
| 271 | self._dct = {} |
| 272 | def __setitem__(self, item, value): |
| 273 | self._dct[item.lower()] = value |
| 274 | def __getitem__(self, item): |
| 275 | return self._dct[item] |
| 276 | |
| 277 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 278 | class GrammarTests(unittest.TestCase): |
| 279 | |
Hai Shi | 0c4f0f3 | 2020-06-30 21:46:31 +0800 | [diff] [blame] | 280 | from test.support import check_syntax_error |
| 281 | from test.support.warnings_helper import check_syntax_warning |
Serhiy Storchaka | 07ca9af | 2018-02-04 10:53:48 +0200 | [diff] [blame] | 282 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 283 | # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE |
| 284 | # XXX can't test in a script -- this rule is only used when interactive |
| 285 | |
| 286 | # file_input: (NEWLINE | stmt)* ENDMARKER |
| 287 | # Being tested as this very moment this very module |
| 288 | |
| 289 | # expr_input: testlist NEWLINE |
| 290 | # XXX Hard to test -- used only in calls to input() |
| 291 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 292 | def test_eval_input(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 293 | # testlist ENDMARKER |
| 294 | x = eval('1, 0 or 1') |
| 295 | |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 296 | def test_var_annot_basics(self): |
| 297 | # all these should be allowed |
| 298 | var1: int = 5 |
| 299 | var2: [int, str] |
| 300 | my_lst = [42] |
| 301 | def one(): |
| 302 | return 1 |
| 303 | int.new_attr: int |
| 304 | [list][0]: type |
| 305 | my_lst[one()-1]: int = 5 |
| 306 | self.assertEqual(my_lst, [5]) |
| 307 | |
| 308 | def test_var_annot_syntax_errors(self): |
| 309 | # parser pass |
| 310 | check_syntax_error(self, "def f: int") |
| 311 | check_syntax_error(self, "x: int: str") |
| 312 | check_syntax_error(self, "def f():\n" |
| 313 | " nonlocal x: int\n") |
| 314 | # AST pass |
| 315 | check_syntax_error(self, "[x, 0]: int\n") |
| 316 | check_syntax_error(self, "f(): int\n") |
| 317 | check_syntax_error(self, "(x,): int") |
| 318 | check_syntax_error(self, "def f():\n" |
| 319 | " (x, y): int = (1, 2)\n") |
| 320 | # symtable pass |
| 321 | check_syntax_error(self, "def f():\n" |
| 322 | " x: int\n" |
| 323 | " global x\n") |
| 324 | check_syntax_error(self, "def f():\n" |
| 325 | " global x\n" |
| 326 | " x: int\n") |
| 327 | |
| 328 | def test_var_annot_basic_semantics(self): |
| 329 | # execution order |
| 330 | with self.assertRaises(ZeroDivisionError): |
| 331 | no_name[does_not_exist]: no_name_again = 1/0 |
| 332 | with self.assertRaises(NameError): |
| 333 | no_name[does_not_exist]: 1/0 = 0 |
| 334 | global var_annot_global |
| 335 | |
| 336 | # function semantics |
| 337 | def f(): |
| 338 | st: str = "Hello" |
| 339 | a.b: int = (1, 2) |
| 340 | return st |
| 341 | self.assertEqual(f.__annotations__, {}) |
| 342 | def f_OK(): |
| 343 | x: 1/0 |
| 344 | f_OK() |
| 345 | def fbad(): |
| 346 | x: int |
| 347 | print(x) |
| 348 | with self.assertRaises(UnboundLocalError): |
| 349 | fbad() |
| 350 | def f2bad(): |
| 351 | (no_such_global): int |
| 352 | print(no_such_global) |
| 353 | try: |
| 354 | f2bad() |
| 355 | except Exception as e: |
| 356 | self.assertIs(type(e), NameError) |
| 357 | |
| 358 | # class semantics |
| 359 | class C: |
Guido van Rossum | 015d874 | 2016-09-11 09:45:24 -0700 | [diff] [blame] | 360 | __foo: int |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 361 | s: str = "attr" |
| 362 | z = 2 |
| 363 | def __init__(self, x): |
| 364 | self.x: int = x |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 365 | self.assertEqual(C.__annotations__, {'_C__foo': 'int', 's': 'str'}) |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 366 | with self.assertRaises(NameError): |
| 367 | class CBad: |
| 368 | no_such_name_defined.attr: int = 0 |
| 369 | with self.assertRaises(NameError): |
| 370 | class Cbad2(C): |
| 371 | x: int |
| 372 | x.y: list = [] |
| 373 | |
| 374 | def test_var_annot_metaclass_semantics(self): |
| 375 | class CMeta(type): |
| 376 | @classmethod |
| 377 | def __prepare__(metacls, name, bases, **kwds): |
| 378 | return {'__annotations__': CNS()} |
| 379 | class CC(metaclass=CMeta): |
| 380 | XX: 'ANNOT' |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 381 | self.assertEqual(CC.__annotations__['xx'], repr('ANNOT')) |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 382 | |
| 383 | def test_var_annot_module_semantics(self): |
| 384 | with self.assertRaises(AttributeError): |
| 385 | print(test.__annotations__) |
| 386 | self.assertEqual(ann_module.__annotations__, |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 387 | {1: 2, 'x': 'int', 'y': 'str', 'f': 'Tuple[int, int]'}) |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 388 | self.assertEqual(ann_module.M.__annotations__, |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 389 | {'123': 123, 'o': 'type'}) |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 390 | self.assertEqual(ann_module2.__annotations__, {}) |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 391 | |
| 392 | def test_var_annot_in_module(self): |
| 393 | # check that functions fail the same way when executed |
| 394 | # outside of module where they were defined |
| 395 | from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann |
| 396 | with self.assertRaises(NameError): |
| 397 | f_bad_ann() |
| 398 | with self.assertRaises(NameError): |
| 399 | g_bad_ann() |
| 400 | with self.assertRaises(NameError): |
| 401 | D_bad_ann(5) |
| 402 | |
| 403 | def test_var_annot_simple_exec(self): |
| 404 | gns = {}; lns= {} |
| 405 | exec("'docstring'\n" |
| 406 | "__annotations__[1] = 2\n" |
| 407 | "x: int = 5\n", gns, lns) |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 408 | self.assertEqual(lns["__annotations__"], {1: 2, 'x': 'int'}) |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 409 | with self.assertRaises(KeyError): |
| 410 | gns['__annotations__'] |
| 411 | |
| 412 | def test_var_annot_custom_maps(self): |
| 413 | # tests with custom locals() and __annotations__ |
| 414 | ns = {'__annotations__': CNS()} |
| 415 | exec('X: int; Z: str = "Z"; (w): complex = 1j', ns) |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 416 | self.assertEqual(ns['__annotations__']['x'], 'int') |
| 417 | self.assertEqual(ns['__annotations__']['z'], 'str') |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 418 | with self.assertRaises(KeyError): |
| 419 | ns['__annotations__']['w'] |
| 420 | nonloc_ns = {} |
| 421 | class CNS2: |
| 422 | def __init__(self): |
| 423 | self._dct = {} |
| 424 | def __setitem__(self, item, value): |
| 425 | nonlocal nonloc_ns |
| 426 | self._dct[item] = value |
| 427 | nonloc_ns[item] = value |
| 428 | def __getitem__(self, item): |
| 429 | return self._dct[item] |
| 430 | exec('x: int = 1', {}, CNS2()) |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 431 | self.assertEqual(nonloc_ns['__annotations__']['x'], 'int') |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 432 | |
| 433 | def test_var_annot_refleak(self): |
| 434 | # complex case: custom locals plus custom __annotations__ |
| 435 | # this was causing refleak |
| 436 | cns = CNS() |
| 437 | nonloc_ns = {'__annotations__': cns} |
| 438 | class CNS2: |
| 439 | def __init__(self): |
| 440 | self._dct = {'__annotations__': cns} |
| 441 | def __setitem__(self, item, value): |
| 442 | nonlocal nonloc_ns |
| 443 | self._dct[item] = value |
| 444 | nonloc_ns[item] = value |
| 445 | def __getitem__(self, item): |
| 446 | return self._dct[item] |
| 447 | exec('X: str', {}, CNS2()) |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 448 | self.assertEqual(nonloc_ns['__annotations__']['x'], 'str') |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 449 | |
Ivan Levkivskyi | 62c35a8 | 2019-01-25 01:39:19 +0000 | [diff] [blame] | 450 | def test_var_annot_rhs(self): |
| 451 | ns = {} |
| 452 | exec('x: tuple = 1, 2', ns) |
| 453 | self.assertEqual(ns['x'], (1, 2)) |
| 454 | stmt = ('def f():\n' |
| 455 | ' x: int = yield') |
| 456 | exec(stmt, ns) |
| 457 | self.assertEqual(list(ns['f']()), [None]) |
| 458 | |
Pablo Galindo | 8565f6b | 2019-06-03 08:34:20 +0100 | [diff] [blame] | 459 | ns = {"a": 1, 'b': (2, 3, 4), "c":5, "Tuple": typing.Tuple} |
| 460 | exec('x: Tuple[int, ...] = a,*b,c', ns) |
| 461 | self.assertEqual(ns['x'], (1, 2, 3, 4, 5)) |
| 462 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 463 | def test_funcdef(self): |
Neal Norwitz | c150536 | 2006-12-28 06:47:50 +0000 | [diff] [blame] | 464 | ### [decorators] 'def' NAME parameters ['->' test] ':' suite |
Brandt Bucher | be501ca | 2020-03-03 14:25:44 -0800 | [diff] [blame] | 465 | ### decorator: '@' namedexpr_test NEWLINE |
Neal Norwitz | c150536 | 2006-12-28 06:47:50 +0000 | [diff] [blame] | 466 | ### decorators: decorator+ |
| 467 | ### parameters: '(' [typedargslist] ')' |
| 468 | ### typedargslist: ((tfpdef ['=' test] ',')* |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 469 | ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) |
Neal Norwitz | c150536 | 2006-12-28 06:47:50 +0000 | [diff] [blame] | 470 | ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 471 | ### tfpdef: NAME [':' test] |
Neal Norwitz | c150536 | 2006-12-28 06:47:50 +0000 | [diff] [blame] | 472 | ### varargslist: ((vfpdef ['=' test] ',')* |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 473 | ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) |
Neal Norwitz | c150536 | 2006-12-28 06:47:50 +0000 | [diff] [blame] | 474 | ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 475 | ### vfpdef: NAME |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 476 | def f1(): pass |
| 477 | f1() |
| 478 | f1(*()) |
| 479 | f1(*(), **{}) |
| 480 | def f2(one_argument): pass |
| 481 | def f3(two, arguments): pass |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 482 | self.assertEqual(f2.__code__.co_varnames, ('one_argument',)) |
| 483 | self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments')) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 484 | def a1(one_arg,): pass |
| 485 | def a2(two, args,): pass |
| 486 | def v0(*rest): pass |
| 487 | def v1(a, *rest): pass |
| 488 | def v2(a, b, *rest): pass |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 489 | |
| 490 | f1() |
| 491 | f2(1) |
| 492 | f2(1,) |
| 493 | f3(1, 2) |
| 494 | f3(1, 2,) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 495 | v0() |
| 496 | v0(1) |
| 497 | v0(1,) |
| 498 | v0(1,2) |
| 499 | v0(1,2,3,4,5,6,7,8,9,0) |
| 500 | v1(1) |
| 501 | v1(1,) |
| 502 | v1(1,2) |
| 503 | v1(1,2,3) |
| 504 | v1(1,2,3,4,5,6,7,8,9,0) |
| 505 | v2(1,2) |
| 506 | v2(1,2,3) |
| 507 | v2(1,2,3,4) |
| 508 | v2(1,2,3,4,5,6,7,8,9,0) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 509 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 510 | def d01(a=1): pass |
| 511 | d01() |
| 512 | d01(1) |
| 513 | d01(*(1,)) |
Yury Selivanov | 14acf5f | 2015-08-05 17:54:10 -0400 | [diff] [blame] | 514 | d01(*[] or [2]) |
| 515 | d01(*() or (), *{} and (), **() or {}) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 516 | d01(**{'a':2}) |
Benjamin Peterson | de12b79 | 2015-05-16 09:44:45 -0400 | [diff] [blame] | 517 | d01(**{'a':2} or {}) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 518 | def d11(a, b=1): pass |
| 519 | d11(1) |
| 520 | d11(1, 2) |
| 521 | d11(1, **{'b':2}) |
| 522 | def d21(a, b, c=1): pass |
| 523 | d21(1, 2) |
| 524 | d21(1, 2, 3) |
| 525 | d21(*(1, 2, 3)) |
| 526 | d21(1, *(2, 3)) |
| 527 | d21(1, 2, *(3,)) |
| 528 | d21(1, 2, **{'c':3}) |
| 529 | def d02(a=1, b=2): pass |
| 530 | d02() |
| 531 | d02(1) |
| 532 | d02(1, 2) |
| 533 | d02(*(1, 2)) |
| 534 | d02(1, *(2,)) |
| 535 | d02(1, **{'b':2}) |
| 536 | d02(**{'a': 1, 'b': 2}) |
| 537 | def d12(a, b=1, c=2): pass |
| 538 | d12(1) |
| 539 | d12(1, 2) |
| 540 | d12(1, 2, 3) |
| 541 | def d22(a, b, c=1, d=2): pass |
| 542 | d22(1, 2) |
| 543 | d22(1, 2, 3) |
| 544 | d22(1, 2, 3, 4) |
| 545 | def d01v(a=1, *rest): pass |
| 546 | d01v() |
| 547 | d01v(1) |
| 548 | d01v(1, 2) |
| 549 | d01v(*(1, 2, 3, 4)) |
| 550 | d01v(*(1,)) |
| 551 | d01v(**{'a':2}) |
| 552 | def d11v(a, b=1, *rest): pass |
| 553 | d11v(1) |
| 554 | d11v(1, 2) |
| 555 | d11v(1, 2, 3) |
| 556 | def d21v(a, b, c=1, *rest): pass |
| 557 | d21v(1, 2) |
| 558 | d21v(1, 2, 3) |
| 559 | d21v(1, 2, 3, 4) |
| 560 | d21v(*(1, 2, 3, 4)) |
| 561 | d21v(1, 2, **{'c': 3}) |
| 562 | def d02v(a=1, b=2, *rest): pass |
| 563 | d02v() |
| 564 | d02v(1) |
| 565 | d02v(1, 2) |
| 566 | d02v(1, 2, 3) |
| 567 | d02v(1, *(2, 3, 4)) |
| 568 | d02v(**{'a': 1, 'b': 2}) |
| 569 | def d12v(a, b=1, c=2, *rest): pass |
| 570 | d12v(1) |
| 571 | d12v(1, 2) |
| 572 | d12v(1, 2, 3) |
| 573 | d12v(1, 2, 3, 4) |
| 574 | d12v(*(1, 2, 3, 4)) |
| 575 | d12v(1, 2, *(3, 4, 5)) |
| 576 | d12v(1, *(2,), **{'c': 3}) |
| 577 | def d22v(a, b, c=1, d=2, *rest): pass |
| 578 | d22v(1, 2) |
| 579 | d22v(1, 2, 3) |
| 580 | d22v(1, 2, 3, 4) |
| 581 | d22v(1, 2, 3, 4, 5) |
| 582 | d22v(*(1, 2, 3, 4)) |
| 583 | d22v(1, 2, *(3, 4, 5)) |
| 584 | d22v(1, *(2, 3), **{'d': 4}) |
Georg Brandl | d8b690f | 2008-05-16 17:28:50 +0000 | [diff] [blame] | 585 | |
| 586 | # keyword argument type tests |
Serhiy Storchaka | 12f4334 | 2020-07-20 15:53:55 +0300 | [diff] [blame] | 587 | with warnings.catch_warnings(): |
| 588 | warnings.simplefilter('ignore', BytesWarning) |
| 589 | try: |
| 590 | str('x', **{b'foo':1 }) |
| 591 | except TypeError: |
| 592 | pass |
| 593 | else: |
| 594 | self.fail('Bytes should not work as keyword argument names') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 595 | # keyword only argument tests |
| 596 | def pos0key1(*, key): return key |
| 597 | pos0key1(key=100) |
| 598 | def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2 |
| 599 | pos2key2(1, 2, k1=100) |
| 600 | pos2key2(1, 2, k1=100, k2=200) |
| 601 | pos2key2(1, 2, k2=100, k1=200) |
| 602 | def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg |
| 603 | pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200) |
| 604 | pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100) |
| 605 | |
Robert Collins | df39599 | 2015-08-12 08:00:06 +1200 | [diff] [blame] | 606 | self.assertRaises(SyntaxError, eval, "def f(*): pass") |
| 607 | self.assertRaises(SyntaxError, eval, "def f(*,): pass") |
| 608 | self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass") |
| 609 | |
Benjamin Peterson | 2d735bc | 2008-08-19 20:57:10 +0000 | [diff] [blame] | 610 | # keyword arguments after *arglist |
| 611 | def f(*args, **kwargs): |
| 612 | return args, kwargs |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 613 | self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), |
Benjamin Peterson | 2d735bc | 2008-08-19 20:57:10 +0000 | [diff] [blame] | 614 | {'x':2, 'y':5})) |
Benjamin Peterson | 025e9eb | 2015-05-05 20:16:41 -0400 | [diff] [blame] | 615 | self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {})) |
Benjamin Peterson | 2d735bc | 2008-08-19 20:57:10 +0000 | [diff] [blame] | 616 | self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") |
Benjamin Peterson | 025e9eb | 2015-05-05 20:16:41 -0400 | [diff] [blame] | 617 | self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}), |
| 618 | ((), {'eggs':'scrambled', 'spam':'fried'})) |
| 619 | self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}), |
| 620 | ((), {'eggs':'scrambled', 'spam':'fried'})) |
Benjamin Peterson | 2d735bc | 2008-08-19 20:57:10 +0000 | [diff] [blame] | 621 | |
Serhiy Storchaka | 0cc99c8 | 2018-01-04 10:36:35 +0200 | [diff] [blame] | 622 | # Check ast errors in *args and *kwargs |
| 623 | check_syntax_error(self, "f(*g(1=2))") |
| 624 | check_syntax_error(self, "f(**g(1=2))") |
| 625 | |
Neal Norwitz | c150536 | 2006-12-28 06:47:50 +0000 | [diff] [blame] | 626 | # argument annotation tests |
| 627 | def f(x) -> list: pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 628 | self.assertEqual(f.__annotations__, {'return': 'list'}) |
Zachary Ware | ce17f76 | 2015-08-01 21:55:36 -0500 | [diff] [blame] | 629 | def f(x: int): pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 630 | self.assertEqual(f.__annotations__, {'x': 'int'}) |
Pablo Galindo | a0c01bf | 2019-05-31 15:19:50 +0100 | [diff] [blame] | 631 | def f(x: int, /): pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 632 | self.assertEqual(f.__annotations__, {'x': 'int'}) |
Pablo Galindo | a0c01bf | 2019-05-31 15:19:50 +0100 | [diff] [blame] | 633 | def f(x: int = 34, /): pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 634 | self.assertEqual(f.__annotations__, {'x': 'int'}) |
Zachary Ware | ce17f76 | 2015-08-01 21:55:36 -0500 | [diff] [blame] | 635 | def f(*x: str): pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 636 | self.assertEqual(f.__annotations__, {'x': 'str'}) |
Zachary Ware | ce17f76 | 2015-08-01 21:55:36 -0500 | [diff] [blame] | 637 | def f(**x: float): pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 638 | self.assertEqual(f.__annotations__, {'x': 'float'}) |
Zachary Ware | ce17f76 | 2015-08-01 21:55:36 -0500 | [diff] [blame] | 639 | def f(a, b: 1, c: 2, d): pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 640 | self.assertEqual(f.__annotations__, {'b': '1', 'c': '2'}) |
Pablo Galindo | a0c01bf | 2019-05-31 15:19:50 +0100 | [diff] [blame] | 641 | def f(a, b: 1, /, c: 2, d): pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 642 | self.assertEqual(f.__annotations__, {'b': '1', 'c': '2'}) |
Zachary Ware | ce17f76 | 2015-08-01 21:55:36 -0500 | [diff] [blame] | 643 | def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 644 | self.assertEqual(f.__annotations__, |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 645 | {'b': '1', 'c': '2', 'e': '3', 'g': '6'}) |
Zachary Ware | ce17f76 | 2015-08-01 21:55:36 -0500 | [diff] [blame] | 646 | def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10, |
| 647 | **k: 11) -> 12: pass |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 648 | self.assertEqual(f.__annotations__, |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 649 | {'b': '1', 'c': '2', 'e': '3', 'g': '6', 'h': '7', 'j': '9', |
| 650 | 'k': '11', 'return': '12'}) |
Pablo Galindo | a0c01bf | 2019-05-31 15:19:50 +0100 | [diff] [blame] | 651 | def f(a, b: 1, c: 2, d, e: 3 = 4, f: int = 5, /, *g: 6, h: 7, i=8, j: 9 = 10, |
| 652 | **k: 11) -> 12: pass |
| 653 | self.assertEqual(f.__annotations__, |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 654 | {'b': '1', 'c': '2', 'e': '3', 'f': 'int', 'g': '6', 'h': '7', 'j': '9', |
| 655 | 'k': '11', 'return': '12'}) |
Yury Selivanov | 34ce99f | 2014-02-18 12:49:41 -0500 | [diff] [blame] | 656 | # Check for issue #20625 -- annotations mangling |
| 657 | class Spam: |
Zachary Ware | ce17f76 | 2015-08-01 21:55:36 -0500 | [diff] [blame] | 658 | def f(self, *, __kw: 1): |
Yury Selivanov | 34ce99f | 2014-02-18 12:49:41 -0500 | [diff] [blame] | 659 | pass |
| 660 | class Ham(Spam): pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 661 | self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': '1'}) |
| 662 | self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': '1'}) |
Nick Coghlan | 71011e2 | 2007-04-23 11:05:01 +0000 | [diff] [blame] | 663 | # Check for SF Bug #1697248 - mixing decorators and a return annotation |
| 664 | def null(x): return x |
| 665 | @null |
| 666 | def f(x) -> list: pass |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 667 | self.assertEqual(f.__annotations__, {'return': 'list'}) |
Nick Coghlan | 71011e2 | 2007-04-23 11:05:01 +0000 | [diff] [blame] | 668 | |
Brandt Bucher | be501ca | 2020-03-03 14:25:44 -0800 | [diff] [blame] | 669 | # Test expressions as decorators (PEP 614): |
| 670 | @False or null |
| 671 | def f(x): pass |
| 672 | @d := null |
| 673 | def f(x): pass |
| 674 | @lambda f: null(f) |
| 675 | def f(x): pass |
| 676 | @[..., null, ...][1] |
| 677 | def f(x): pass |
| 678 | @null(null)(null) |
| 679 | def f(x): pass |
| 680 | @[null][0].__call__.__call__ |
| 681 | def f(x): pass |
| 682 | |
Serhiy Storchaka | 64204de | 2016-06-12 17:36:24 +0300 | [diff] [blame] | 683 | # test closures with a variety of opargs |
Guido van Rossum | 0240b92 | 2007-02-26 21:23:50 +0000 | [diff] [blame] | 684 | closure = 1 |
| 685 | def f(): return closure |
| 686 | def f(x=1): return closure |
| 687 | def f(*, k=1): return closure |
| 688 | def f() -> int: return closure |
Neal Norwitz | c150536 | 2006-12-28 06:47:50 +0000 | [diff] [blame] | 689 | |
Robert Collins | df39599 | 2015-08-12 08:00:06 +1200 | [diff] [blame] | 690 | # Check trailing commas are permitted in funcdef argument list |
| 691 | def f(a,): pass |
| 692 | def f(*args,): pass |
| 693 | def f(**kwds,): pass |
| 694 | def f(a, *args,): pass |
| 695 | def f(a, **kwds,): pass |
| 696 | def f(*args, b,): pass |
| 697 | def f(*, b,): pass |
| 698 | def f(*args, **kwds,): pass |
| 699 | def f(a, *args, b,): pass |
| 700 | def f(a, *, b,): pass |
| 701 | def f(a, *args, **kwds,): pass |
| 702 | def f(*args, b, **kwds,): pass |
| 703 | def f(*, b, **kwds,): pass |
| 704 | def f(a, *args, b, **kwds,): pass |
| 705 | def f(a, *, b, **kwds,): pass |
| 706 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 707 | def test_lambdef(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 708 | ### lambdef: 'lambda' [varargslist] ':' test |
| 709 | l1 = lambda : 0 |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 710 | self.assertEqual(l1(), 0) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 711 | l2 = lambda : a[d] # XXX just testing the expression |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 712 | l3 = lambda : [2 < x for x in [-1, 3, 0]] |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 713 | self.assertEqual(l3(), [0, 1, 0]) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 714 | l4 = lambda x = lambda y = lambda z=1 : z : y() : x() |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 715 | self.assertEqual(l4(), 1) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 716 | l5 = lambda x, y, z=2: x + y + z |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 717 | self.assertEqual(l5(1, 2), 5) |
| 718 | self.assertEqual(l5(1, 2, 3), 6) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 719 | check_syntax_error(self, "lambda x: x = 2") |
Amaury Forgeot d'Arc | 35c8658 | 2008-06-17 21:11:29 +0000 | [diff] [blame] | 720 | check_syntax_error(self, "lambda (None,): None") |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 721 | l6 = lambda x, y, *, k=20: x+y+k |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 722 | self.assertEqual(l6(1,2), 1+2+20) |
| 723 | self.assertEqual(l6(1,2,k=10), 1+2+10) |
Guido van Rossum | b31c7f7 | 1993-11-11 10:31:23 +0000 | [diff] [blame] | 724 | |
Robert Collins | df39599 | 2015-08-12 08:00:06 +1200 | [diff] [blame] | 725 | # check that trailing commas are permitted |
| 726 | l10 = lambda a,: 0 |
| 727 | l11 = lambda *args,: 0 |
| 728 | l12 = lambda **kwds,: 0 |
| 729 | l13 = lambda a, *args,: 0 |
| 730 | l14 = lambda a, **kwds,: 0 |
| 731 | l15 = lambda *args, b,: 0 |
| 732 | l16 = lambda *, b,: 0 |
| 733 | l17 = lambda *args, **kwds,: 0 |
| 734 | l18 = lambda a, *args, b,: 0 |
| 735 | l19 = lambda a, *, b,: 0 |
| 736 | l20 = lambda a, *args, **kwds,: 0 |
| 737 | l21 = lambda *args, b, **kwds,: 0 |
| 738 | l22 = lambda *, b, **kwds,: 0 |
| 739 | l23 = lambda a, *args, b, **kwds,: 0 |
| 740 | l24 = lambda a, *, b, **kwds,: 0 |
| 741 | |
Guido van Rossum | b31c7f7 | 1993-11-11 10:31:23 +0000 | [diff] [blame] | 742 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 743 | ### stmt: simple_stmt | compound_stmt |
| 744 | # Tested below |
Georg Brandl | 52318d6 | 2006-09-06 07:06:08 +0000 | [diff] [blame] | 745 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 746 | def test_simple_stmt(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 747 | ### simple_stmt: small_stmt (';' small_stmt)* [';'] |
| 748 | x = 1; pass; del x |
| 749 | def foo(): |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 750 | # verify statements that end with semi-colons |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 751 | x = 1; pass; del x; |
| 752 | foo() |
Georg Brandl | 52318d6 | 2006-09-06 07:06:08 +0000 | [diff] [blame] | 753 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 754 | ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 755 | # Tested below |
Georg Brandl | 52318d6 | 2006-09-06 07:06:08 +0000 | [diff] [blame] | 756 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 757 | def test_expr_stmt(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 758 | # (exprlist '=')* exprlist |
Victor Stinner | 15a3095 | 2016-02-08 22:45:06 +0100 | [diff] [blame] | 759 | 1 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 760 | 1, 2, 3 |
| 761 | x = 1 |
| 762 | x = 1, 2, 3 |
| 763 | x = y = z = 1, 2, 3 |
| 764 | x, y, z = 1, 2, 3 |
| 765 | abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 766 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 767 | check_syntax_error(self, "x + 1 = 1") |
| 768 | check_syntax_error(self, "a + 1 = b + 2") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 769 | |
Nick Coghlan | 5b1fdc1 | 2014-06-16 19:48:02 +1000 | [diff] [blame] | 770 | # Check the heuristic for print & exec covers significant cases |
| 771 | # As well as placing some limits on false positives |
| 772 | def test_former_statements_refer_to_builtins(self): |
| 773 | keywords = "print", "exec" |
| 774 | # Cases where we want the custom error |
| 775 | cases = [ |
| 776 | "{} foo", |
| 777 | "{} {{1:foo}}", |
| 778 | "if 1: {} foo", |
| 779 | "if 1: {} {{1:foo}}", |
| 780 | "if 1:\n {} foo", |
| 781 | "if 1:\n {} {{1:foo}}", |
| 782 | ] |
| 783 | for keyword in keywords: |
| 784 | custom_msg = "call to '{}'".format(keyword) |
| 785 | for case in cases: |
| 786 | source = case.format(keyword) |
| 787 | with self.subTest(source=source): |
| 788 | with self.assertRaisesRegex(SyntaxError, custom_msg): |
| 789 | exec(source) |
| 790 | source = source.replace("foo", "(foo.)") |
| 791 | with self.subTest(source=source): |
| 792 | with self.assertRaisesRegex(SyntaxError, "invalid syntax"): |
| 793 | exec(source) |
| 794 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 795 | def test_del_stmt(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 796 | # 'del' exprlist |
| 797 | abc = [1,2,3] |
| 798 | x, y, z = abc |
| 799 | xyz = x, y, z |
Barry Warsaw | 7e3e1c1 | 2000-10-11 21:26:03 +0000 | [diff] [blame] | 800 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 801 | del abc |
| 802 | del x, y, (z, xyz) |
Barry Warsaw | 9182b45 | 2000-08-29 04:57:10 +0000 | [diff] [blame] | 803 | |
Shantanu | 27c0d9b | 2020-05-11 14:53:58 -0700 | [diff] [blame] | 804 | x, y, z = "xyz" |
| 805 | del x |
| 806 | del y, |
| 807 | del (z) |
| 808 | del () |
| 809 | |
| 810 | a, b, c, d, e, f, g = "abcdefg" |
| 811 | del a, (b, c), (d, (e, f)) |
| 812 | |
| 813 | a, b, c, d, e, f, g = "abcdefg" |
| 814 | del a, [b, c], (d, [e, f]) |
| 815 | |
| 816 | abcd = list("abcd") |
| 817 | del abcd[1:2] |
| 818 | |
| 819 | compile("del a, (b[0].c, (d.e, f.g[1:2])), [h.i.j], ()", "<testcase>", "exec") |
| 820 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 821 | def test_pass_stmt(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 822 | # 'pass' |
| 823 | pass |
Barry Warsaw | 9182b45 | 2000-08-29 04:57:10 +0000 | [diff] [blame] | 824 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 825 | # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt |
| 826 | # Tested below |
Barry Warsaw | 9182b45 | 2000-08-29 04:57:10 +0000 | [diff] [blame] | 827 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 828 | def test_break_stmt(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 829 | # 'break' |
| 830 | while 1: break |
Barry Warsaw | 9182b45 | 2000-08-29 04:57:10 +0000 | [diff] [blame] | 831 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 832 | def test_continue_stmt(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 833 | # 'continue' |
| 834 | i = 1 |
| 835 | while i: i = 0; continue |
Barry Warsaw | 9182b45 | 2000-08-29 04:57:10 +0000 | [diff] [blame] | 836 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 837 | msg = "" |
| 838 | while not msg: |
| 839 | msg = "ok" |
| 840 | try: |
| 841 | continue |
| 842 | msg = "continue failed to continue inside try" |
| 843 | except: |
| 844 | msg = "continue inside try called except block" |
| 845 | if msg != "ok": |
| 846 | self.fail(msg) |
Barry Warsaw | efc92ee | 2000-08-21 15:46:50 +0000 | [diff] [blame] | 847 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 848 | msg = "" |
| 849 | while not msg: |
| 850 | msg = "finally block not called" |
| 851 | try: |
| 852 | continue |
| 853 | finally: |
| 854 | msg = "ok" |
| 855 | if msg != "ok": |
| 856 | self.fail(msg) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 857 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 858 | def test_break_continue_loop(self): |
| 859 | # This test warrants an explanation. It is a test specifically for SF bugs |
| 860 | # #463359 and #462937. The bug is that a 'break' statement executed or |
| 861 | # exception raised inside a try/except inside a loop, *after* a continue |
| 862 | # statement has been executed in that loop, will cause the wrong number of |
| 863 | # arguments to be popped off the stack and the instruction pointer reset to |
| 864 | # a very small number (usually 0.) Because of this, the following test |
| 865 | # *must* written as a function, and the tracking vars *must* be function |
| 866 | # arguments with default values. Otherwise, the test will loop and loop. |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 867 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 868 | def test_inner(extra_burning_oil = 1, count=0): |
| 869 | big_hippo = 2 |
| 870 | while big_hippo: |
| 871 | count += 1 |
| 872 | try: |
| 873 | if extra_burning_oil and big_hippo == 1: |
| 874 | extra_burning_oil -= 1 |
| 875 | break |
| 876 | big_hippo -= 1 |
| 877 | continue |
| 878 | except: |
| 879 | raise |
| 880 | if count > 2 or big_hippo != 1: |
| 881 | self.fail("continue then break in try/except in loop broken!") |
| 882 | test_inner() |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 883 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 884 | def test_return(self): |
David Cuthbert | fd97d1f | 2018-09-21 18:31:15 -0700 | [diff] [blame] | 885 | # 'return' [testlist_star_expr] |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 886 | def g1(): return |
| 887 | def g2(): return 1 |
David Cuthbert | fd97d1f | 2018-09-21 18:31:15 -0700 | [diff] [blame] | 888 | def g3(): |
| 889 | z = [2, 3] |
| 890 | return 1, *z |
| 891 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 892 | g1() |
| 893 | x = g2() |
David Cuthbert | fd97d1f | 2018-09-21 18:31:15 -0700 | [diff] [blame] | 894 | y = g3() |
| 895 | self.assertEqual(y, (1, 2, 3), "unparenthesized star expr return") |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 896 | check_syntax_error(self, "class foo:return 1") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 897 | |
Serhiy Storchaka | 7cc42c3 | 2018-01-02 02:38:35 +0200 | [diff] [blame] | 898 | def test_break_in_finally(self): |
| 899 | count = 0 |
| 900 | while count < 2: |
| 901 | count += 1 |
| 902 | try: |
| 903 | pass |
| 904 | finally: |
| 905 | break |
| 906 | self.assertEqual(count, 1) |
| 907 | |
| 908 | count = 0 |
| 909 | while count < 2: |
| 910 | count += 1 |
| 911 | try: |
| 912 | continue |
| 913 | finally: |
| 914 | break |
| 915 | self.assertEqual(count, 1) |
| 916 | |
| 917 | count = 0 |
| 918 | while count < 2: |
| 919 | count += 1 |
| 920 | try: |
| 921 | 1/0 |
| 922 | finally: |
| 923 | break |
| 924 | self.assertEqual(count, 1) |
| 925 | |
| 926 | for count in [0, 1]: |
| 927 | self.assertEqual(count, 0) |
| 928 | try: |
| 929 | pass |
| 930 | finally: |
| 931 | break |
| 932 | self.assertEqual(count, 0) |
| 933 | |
| 934 | for count in [0, 1]: |
| 935 | self.assertEqual(count, 0) |
| 936 | try: |
| 937 | continue |
| 938 | finally: |
| 939 | break |
| 940 | self.assertEqual(count, 0) |
| 941 | |
| 942 | for count in [0, 1]: |
| 943 | self.assertEqual(count, 0) |
| 944 | try: |
| 945 | 1/0 |
| 946 | finally: |
| 947 | break |
| 948 | self.assertEqual(count, 0) |
| 949 | |
Serhiy Storchaka | fe2bbb1 | 2018-03-18 09:56:52 +0200 | [diff] [blame] | 950 | def test_continue_in_finally(self): |
| 951 | count = 0 |
| 952 | while count < 2: |
| 953 | count += 1 |
| 954 | try: |
| 955 | pass |
| 956 | finally: |
| 957 | continue |
| 958 | break |
| 959 | self.assertEqual(count, 2) |
| 960 | |
| 961 | count = 0 |
| 962 | while count < 2: |
| 963 | count += 1 |
| 964 | try: |
| 965 | break |
| 966 | finally: |
| 967 | continue |
| 968 | self.assertEqual(count, 2) |
| 969 | |
| 970 | count = 0 |
| 971 | while count < 2: |
| 972 | count += 1 |
| 973 | try: |
| 974 | 1/0 |
| 975 | finally: |
| 976 | continue |
| 977 | break |
| 978 | self.assertEqual(count, 2) |
| 979 | |
| 980 | for count in [0, 1]: |
| 981 | try: |
| 982 | pass |
| 983 | finally: |
| 984 | continue |
| 985 | break |
| 986 | self.assertEqual(count, 1) |
| 987 | |
| 988 | for count in [0, 1]: |
| 989 | try: |
| 990 | break |
| 991 | finally: |
| 992 | continue |
| 993 | self.assertEqual(count, 1) |
| 994 | |
| 995 | for count in [0, 1]: |
| 996 | try: |
| 997 | 1/0 |
| 998 | finally: |
| 999 | continue |
| 1000 | break |
| 1001 | self.assertEqual(count, 1) |
| 1002 | |
Serhiy Storchaka | 7cc42c3 | 2018-01-02 02:38:35 +0200 | [diff] [blame] | 1003 | def test_return_in_finally(self): |
| 1004 | def g1(): |
| 1005 | try: |
| 1006 | pass |
| 1007 | finally: |
| 1008 | return 1 |
| 1009 | self.assertEqual(g1(), 1) |
| 1010 | |
| 1011 | def g2(): |
| 1012 | try: |
| 1013 | return 2 |
| 1014 | finally: |
| 1015 | return 3 |
| 1016 | self.assertEqual(g2(), 3) |
| 1017 | |
| 1018 | def g3(): |
| 1019 | try: |
| 1020 | 1/0 |
| 1021 | finally: |
| 1022 | return 4 |
| 1023 | self.assertEqual(g3(), 4) |
| 1024 | |
Serhiy Storchaka | ef61c52 | 2019-08-24 13:11:52 +0300 | [diff] [blame] | 1025 | def test_break_in_finally_after_return(self): |
| 1026 | # See issue #37830 |
| 1027 | def g1(x): |
| 1028 | for count in [0, 1]: |
| 1029 | count2 = 0 |
| 1030 | while count2 < 20: |
| 1031 | count2 += 10 |
| 1032 | try: |
| 1033 | return count + count2 |
| 1034 | finally: |
| 1035 | if x: |
| 1036 | break |
| 1037 | return 'end', count, count2 |
| 1038 | self.assertEqual(g1(False), 10) |
| 1039 | self.assertEqual(g1(True), ('end', 1, 10)) |
| 1040 | |
| 1041 | def g2(x): |
| 1042 | for count in [0, 1]: |
| 1043 | for count2 in [10, 20]: |
| 1044 | try: |
| 1045 | return count + count2 |
| 1046 | finally: |
| 1047 | if x: |
| 1048 | break |
| 1049 | return 'end', count, count2 |
| 1050 | self.assertEqual(g2(False), 10) |
| 1051 | self.assertEqual(g2(True), ('end', 1, 10)) |
| 1052 | |
| 1053 | def test_continue_in_finally_after_return(self): |
| 1054 | # See issue #37830 |
| 1055 | def g1(x): |
| 1056 | count = 0 |
| 1057 | while count < 100: |
| 1058 | count += 1 |
| 1059 | try: |
| 1060 | return count |
| 1061 | finally: |
| 1062 | if x: |
| 1063 | continue |
| 1064 | return 'end', count |
| 1065 | self.assertEqual(g1(False), 1) |
| 1066 | self.assertEqual(g1(True), ('end', 100)) |
| 1067 | |
| 1068 | def g2(x): |
| 1069 | for count in [0, 1]: |
| 1070 | try: |
| 1071 | return count |
| 1072 | finally: |
| 1073 | if x: |
| 1074 | continue |
| 1075 | return 'end', count |
| 1076 | self.assertEqual(g2(False), 0) |
| 1077 | self.assertEqual(g2(True), ('end', 1)) |
| 1078 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1079 | def test_yield(self): |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 1080 | # Allowed as standalone statement |
| 1081 | def g(): yield 1 |
| 1082 | def g(): yield from () |
| 1083 | # Allowed as RHS of assignment |
| 1084 | def g(): x = yield 1 |
| 1085 | def g(): x = yield from () |
| 1086 | # Ordinary yield accepts implicit tuples |
| 1087 | def g(): yield 1, 1 |
| 1088 | def g(): x = yield 1, 1 |
| 1089 | # 'yield from' does not |
| 1090 | check_syntax_error(self, "def g(): yield from (), 1") |
| 1091 | check_syntax_error(self, "def g(): x = yield from (), 1") |
| 1092 | # Requires parentheses as subexpression |
| 1093 | def g(): 1, (yield 1) |
| 1094 | def g(): 1, (yield from ()) |
| 1095 | check_syntax_error(self, "def g(): 1, yield 1") |
| 1096 | check_syntax_error(self, "def g(): 1, yield from ()") |
| 1097 | # Requires parentheses as call argument |
| 1098 | def g(): f((yield 1)) |
| 1099 | def g(): f((yield 1), 1) |
| 1100 | def g(): f((yield from ())) |
| 1101 | def g(): f((yield from ()), 1) |
David Cuthbert | fd97d1f | 2018-09-21 18:31:15 -0700 | [diff] [blame] | 1102 | # Do not require parenthesis for tuple unpacking |
| 1103 | def g(): rest = 4, 5, 6; yield 1, 2, 3, *rest |
Serhiy Storchaka | 4642d5f | 2018-10-05 21:09:56 +0300 | [diff] [blame] | 1104 | self.assertEqual(list(g()), [(1, 2, 3, 4, 5, 6)]) |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 1105 | check_syntax_error(self, "def g(): f(yield 1)") |
| 1106 | check_syntax_error(self, "def g(): f(yield 1, 1)") |
| 1107 | check_syntax_error(self, "def g(): f(yield from ())") |
| 1108 | check_syntax_error(self, "def g(): f(yield from (), 1)") |
| 1109 | # Not allowed at top level |
| 1110 | check_syntax_error(self, "yield") |
| 1111 | check_syntax_error(self, "yield from") |
| 1112 | # Not allowed at class scope |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1113 | check_syntax_error(self, "class foo:yield 1") |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 1114 | check_syntax_error(self, "class foo:yield from ()") |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1115 | |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 1116 | def test_yield_in_comprehensions(self): |
| 1117 | # Check yield in comprehensions |
| 1118 | def g(): [x for x in [(yield 1)]] |
| 1119 | def g(): [x for x in [(yield from ())]] |
| 1120 | |
Serhiy Storchaka | 07ca9af | 2018-02-04 10:53:48 +0200 | [diff] [blame] | 1121 | check = self.check_syntax_error |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 1122 | check("def g(): [(yield x) for x in ()]", |
| 1123 | "'yield' inside list comprehension") |
| 1124 | check("def g(): [x for x in () if not (yield x)]", |
| 1125 | "'yield' inside list comprehension") |
| 1126 | check("def g(): [y for x in () for y in [(yield x)]]", |
| 1127 | "'yield' inside list comprehension") |
| 1128 | check("def g(): {(yield x) for x in ()}", |
| 1129 | "'yield' inside set comprehension") |
| 1130 | check("def g(): {(yield x): x for x in ()}", |
| 1131 | "'yield' inside dict comprehension") |
| 1132 | check("def g(): {x: (yield x) for x in ()}", |
| 1133 | "'yield' inside dict comprehension") |
| 1134 | check("def g(): ((yield x) for x in ())", |
| 1135 | "'yield' inside generator expression") |
| 1136 | check("def g(): [(yield from x) for x in ()]", |
| 1137 | "'yield' inside list comprehension") |
| 1138 | check("class C: [(yield x) for x in ()]", |
| 1139 | "'yield' inside list comprehension") |
| 1140 | check("[(yield x) for x in ()]", |
| 1141 | "'yield' inside list comprehension") |
| 1142 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1143 | def test_raise(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1144 | # 'raise' test [',' test] |
Collin Winter | 828f04a | 2007-08-31 00:04:24 +0000 | [diff] [blame] | 1145 | try: raise RuntimeError('just testing') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1146 | except RuntimeError: pass |
| 1147 | try: raise KeyboardInterrupt |
| 1148 | except KeyboardInterrupt: pass |
Jeremy Hylton | 3faa52e | 2001-02-01 22:48:12 +0000 | [diff] [blame] | 1149 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1150 | def test_import(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1151 | # 'import' dotted_as_names |
| 1152 | import sys |
| 1153 | import time, sys |
| 1154 | # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) |
| 1155 | from time import time |
| 1156 | from time import (time) |
| 1157 | # not testable inside a function, but already done at top of the module |
| 1158 | # from sys import * |
| 1159 | from sys import path, argv |
| 1160 | from sys import (path, argv) |
| 1161 | from sys import (path, argv,) |
Tim Peters | 10fb386 | 2001-02-09 20:17:14 +0000 | [diff] [blame] | 1162 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1163 | def test_global(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1164 | # 'global' NAME (',' NAME)* |
| 1165 | global a |
| 1166 | global a, b |
| 1167 | global one, two, three, four, five, six, seven, eight, nine, ten |
Thomas Wouters | 80d373c | 2001-09-26 12:43:39 +0000 | [diff] [blame] | 1168 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1169 | def test_nonlocal(self): |
Benjamin Peterson | a933e52 | 2008-10-24 22:16:39 +0000 | [diff] [blame] | 1170 | # 'nonlocal' NAME (',' NAME)* |
| 1171 | x = 0 |
| 1172 | y = 0 |
| 1173 | def f(): |
| 1174 | nonlocal x |
| 1175 | nonlocal x, y |
| 1176 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1177 | def test_assert(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1178 | # assertTruestmt: 'assert' test [',' test] |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1179 | assert 1 |
| 1180 | assert 1, 1 |
| 1181 | assert lambda x:x |
| 1182 | assert 1, lambda x:x+1 |
Ezio Melotti | 6cc5bf7 | 2011-12-02 18:22:52 +0200 | [diff] [blame] | 1183 | |
| 1184 | try: |
| 1185 | assert True |
| 1186 | except AssertionError as e: |
| 1187 | self.fail("'assert True' should not have raised an AssertionError") |
| 1188 | |
| 1189 | try: |
| 1190 | assert True, 'this should always pass' |
| 1191 | except AssertionError as e: |
| 1192 | self.fail("'assert True, msg' should not have " |
| 1193 | "raised an AssertionError") |
| 1194 | |
| 1195 | # these tests fail if python is run with -O, so check __debug__ |
| 1196 | @unittest.skipUnless(__debug__, "Won't work if __debug__ is False") |
| 1197 | def testAssert2(self): |
Thomas Wouters | 80d373c | 2001-09-26 12:43:39 +0000 | [diff] [blame] | 1198 | try: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1199 | assert 0, "msg" |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1200 | except AssertionError as e: |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 1201 | self.assertEqual(e.args[0], "msg") |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1202 | else: |
Ezio Melotti | 6cc5bf7 | 2011-12-02 18:22:52 +0200 | [diff] [blame] | 1203 | self.fail("AssertionError not raised by assert 0") |
| 1204 | |
| 1205 | try: |
| 1206 | assert False |
| 1207 | except AssertionError as e: |
| 1208 | self.assertEqual(len(e.args), 0) |
| 1209 | else: |
| 1210 | self.fail("AssertionError not raised by 'assert False'") |
| 1211 | |
Serhiy Storchaka | e7a4bb5 | 2019-02-19 08:30:15 +0200 | [diff] [blame] | 1212 | self.check_syntax_warning('assert(x, "msg")', |
| 1213 | 'assertion is always true') |
Serhiy Storchaka | d31e773 | 2018-10-21 10:09:39 +0300 | [diff] [blame] | 1214 | with warnings.catch_warnings(): |
Serhiy Storchaka | e7a4bb5 | 2019-02-19 08:30:15 +0200 | [diff] [blame] | 1215 | warnings.simplefilter('error', SyntaxWarning) |
Serhiy Storchaka | d31e773 | 2018-10-21 10:09:39 +0300 | [diff] [blame] | 1216 | compile('assert x, "msg"', '<testcase>', 'exec') |
| 1217 | |
Thomas Wouters | 80d373c | 2001-09-26 12:43:39 +0000 | [diff] [blame] | 1218 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1219 | ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef |
| 1220 | # Tested below |
Jeremy Hylton | 3e0055f | 2005-10-20 19:59:25 +0000 | [diff] [blame] | 1221 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1222 | def test_if(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1223 | # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] |
| 1224 | if 1: pass |
| 1225 | if 1: pass |
| 1226 | else: pass |
| 1227 | if 0: pass |
| 1228 | elif 0: pass |
| 1229 | if 0: pass |
| 1230 | elif 0: pass |
| 1231 | elif 0: pass |
| 1232 | elif 0: pass |
| 1233 | else: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1234 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1235 | def test_while(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1236 | # 'while' test ':' suite ['else' ':' suite] |
| 1237 | while 0: pass |
| 1238 | while 0: pass |
| 1239 | else: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1240 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 1241 | # Issue1920: "while 0" is optimized away, |
| 1242 | # ensure that the "else" clause is still present. |
| 1243 | x = 0 |
| 1244 | while 0: |
| 1245 | x = 1 |
| 1246 | else: |
| 1247 | x = 2 |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 1248 | self.assertEqual(x, 2) |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 1249 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1250 | def test_for(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1251 | # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] |
| 1252 | for i in 1, 2, 3: pass |
| 1253 | for i, j, k in (): pass |
| 1254 | else: pass |
| 1255 | class Squares: |
| 1256 | def __init__(self, max): |
| 1257 | self.max = max |
| 1258 | self.sofar = [] |
| 1259 | def __len__(self): return len(self.sofar) |
| 1260 | def __getitem__(self, i): |
| 1261 | if not 0 <= i < self.max: raise IndexError |
| 1262 | n = len(self.sofar) |
| 1263 | while n <= i: |
| 1264 | self.sofar.append(n*n) |
| 1265 | n = n+1 |
| 1266 | return self.sofar[i] |
| 1267 | n = 0 |
| 1268 | for x in Squares(10): n = n+x |
| 1269 | if n != 285: |
| 1270 | self.fail('for over growing sequence') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1271 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1272 | result = [] |
| 1273 | for x, in [(1,), (2,), (3,)]: |
| 1274 | result.append(x) |
| 1275 | self.assertEqual(result, [1, 2, 3]) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1276 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1277 | def test_try(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1278 | ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] |
| 1279 | ### | 'try' ':' suite 'finally' ':' suite |
Lysandros Nikolaou | ce21cfc | 2020-05-14 23:13:50 +0300 | [diff] [blame] | 1280 | ### except_clause: 'except' [expr ['as' NAME]] |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1281 | try: |
| 1282 | 1/0 |
| 1283 | except ZeroDivisionError: |
| 1284 | pass |
| 1285 | else: |
| 1286 | pass |
| 1287 | try: 1/0 |
| 1288 | except EOFError: pass |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1289 | except TypeError as msg: pass |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1290 | except: pass |
| 1291 | else: pass |
| 1292 | try: 1/0 |
| 1293 | except (EOFError, TypeError, ZeroDivisionError): pass |
| 1294 | try: 1/0 |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1295 | except (EOFError, TypeError, ZeroDivisionError) as msg: pass |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1296 | try: pass |
| 1297 | finally: pass |
Lysandros Nikolaou | ce21cfc | 2020-05-14 23:13:50 +0300 | [diff] [blame] | 1298 | with self.assertRaises(SyntaxError): |
| 1299 | compile("try:\n pass\nexcept Exception as a.b:\n pass", "?", "exec") |
| 1300 | compile("try:\n pass\nexcept Exception as a[b]:\n pass", "?", "exec") |
Jeremy Hylton | f828e2d | 2001-02-19 15:54:52 +0000 | [diff] [blame] | 1301 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1302 | def test_suite(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1303 | # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT |
| 1304 | if 1: pass |
| 1305 | if 1: |
| 1306 | pass |
| 1307 | if 1: |
| 1308 | # |
| 1309 | # |
| 1310 | # |
| 1311 | pass |
| 1312 | pass |
| 1313 | # |
| 1314 | pass |
| 1315 | # |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1316 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1317 | def test_test(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1318 | ### and_test ('or' and_test)* |
| 1319 | ### and_test: not_test ('and' not_test)* |
| 1320 | ### not_test: 'not' not_test | comparison |
| 1321 | if not 1: pass |
| 1322 | if 1 and 1: pass |
| 1323 | if 1 or 1: pass |
| 1324 | if not not not 1: pass |
| 1325 | if not 1 and 1 and 1: pass |
| 1326 | if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1327 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1328 | def test_comparison(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1329 | ### comparison: expr (comp_op expr)* |
| 1330 | ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not' |
| 1331 | if 1: pass |
| 1332 | x = (1 == 1) |
| 1333 | if 1 == 1: pass |
| 1334 | if 1 != 1: pass |
| 1335 | if 1 < 1: pass |
| 1336 | if 1 > 1: pass |
| 1337 | if 1 <= 1: pass |
| 1338 | if 1 >= 1: pass |
Serhiy Storchaka | 3bcbedc | 2019-01-18 07:47:48 +0200 | [diff] [blame] | 1339 | if x is x: pass |
| 1340 | if x is not x: pass |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1341 | if 1 in (): pass |
| 1342 | if 1 not in (): pass |
Serhiy Storchaka | 3bcbedc | 2019-01-18 07:47:48 +0200 | [diff] [blame] | 1343 | if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in x is x is not x: pass |
| 1344 | |
| 1345 | def test_comparison_is_literal(self): |
| 1346 | def check(test, msg='"is" with a literal'): |
Serhiy Storchaka | e7a4bb5 | 2019-02-19 08:30:15 +0200 | [diff] [blame] | 1347 | self.check_syntax_warning(test, msg) |
Serhiy Storchaka | 3bcbedc | 2019-01-18 07:47:48 +0200 | [diff] [blame] | 1348 | |
| 1349 | check('x is 1') |
| 1350 | check('x is "thing"') |
| 1351 | check('1 is x') |
| 1352 | check('x is y is 1') |
| 1353 | check('x is not 1', '"is not" with a literal') |
| 1354 | |
| 1355 | with warnings.catch_warnings(): |
Serhiy Storchaka | e7a4bb5 | 2019-02-19 08:30:15 +0200 | [diff] [blame] | 1356 | warnings.simplefilter('error', SyntaxWarning) |
Serhiy Storchaka | 3bcbedc | 2019-01-18 07:47:48 +0200 | [diff] [blame] | 1357 | compile('x is None', '<testcase>', 'exec') |
| 1358 | compile('x is False', '<testcase>', 'exec') |
| 1359 | compile('x is True', '<testcase>', 'exec') |
| 1360 | compile('x is ...', '<testcase>', 'exec') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1361 | |
Serhiy Storchaka | 62e4481 | 2019-02-16 08:12:19 +0200 | [diff] [blame] | 1362 | def test_warn_missed_comma(self): |
| 1363 | def check(test): |
Serhiy Storchaka | e7a4bb5 | 2019-02-19 08:30:15 +0200 | [diff] [blame] | 1364 | self.check_syntax_warning(test, msg) |
Serhiy Storchaka | 62e4481 | 2019-02-16 08:12:19 +0200 | [diff] [blame] | 1365 | |
| 1366 | msg=r'is not callable; perhaps you missed a comma\?' |
| 1367 | check('[(1, 2) (3, 4)]') |
| 1368 | check('[(x, y) (3, 4)]') |
| 1369 | check('[[1, 2] (3, 4)]') |
| 1370 | check('[{1, 2} (3, 4)]') |
| 1371 | check('[{1: 2} (3, 4)]') |
| 1372 | check('[[i for i in range(5)] (3, 4)]') |
| 1373 | check('[{i for i in range(5)} (3, 4)]') |
| 1374 | check('[(i for i in range(5)) (3, 4)]') |
| 1375 | check('[{i: i for i in range(5)} (3, 4)]') |
| 1376 | check('[f"{x}" (3, 4)]') |
| 1377 | check('[f"x={x}" (3, 4)]') |
| 1378 | check('["abc" (3, 4)]') |
| 1379 | check('[b"abc" (3, 4)]') |
| 1380 | check('[123 (3, 4)]') |
| 1381 | check('[12.3 (3, 4)]') |
| 1382 | check('[12.3j (3, 4)]') |
| 1383 | check('[None (3, 4)]') |
| 1384 | check('[True (3, 4)]') |
| 1385 | check('[... (3, 4)]') |
| 1386 | |
| 1387 | msg=r'is not subscriptable; perhaps you missed a comma\?' |
| 1388 | check('[{1, 2} [i, j]]') |
| 1389 | check('[{i for i in range(5)} [i, j]]') |
| 1390 | check('[(i for i in range(5)) [i, j]]') |
| 1391 | check('[(lambda x, y: x) [i, j]]') |
| 1392 | check('[123 [i, j]]') |
| 1393 | check('[12.3 [i, j]]') |
| 1394 | check('[12.3j [i, j]]') |
| 1395 | check('[None [i, j]]') |
| 1396 | check('[True [i, j]]') |
| 1397 | check('[... [i, j]]') |
| 1398 | |
| 1399 | msg=r'indices must be integers or slices, not tuple; perhaps you missed a comma\?' |
| 1400 | check('[(1, 2) [i, j]]') |
| 1401 | check('[(x, y) [i, j]]') |
| 1402 | check('[[1, 2] [i, j]]') |
| 1403 | check('[[i for i in range(5)] [i, j]]') |
| 1404 | check('[f"{x}" [i, j]]') |
| 1405 | check('[f"x={x}" [i, j]]') |
| 1406 | check('["abc" [i, j]]') |
| 1407 | check('[b"abc" [i, j]]') |
| 1408 | |
| 1409 | msg=r'indices must be integers or slices, not tuple;' |
| 1410 | check('[[1, 2] [3, 4]]') |
| 1411 | msg=r'indices must be integers or slices, not list;' |
| 1412 | check('[[1, 2] [[3, 4]]]') |
| 1413 | check('[[1, 2] [[i for i in range(5)]]]') |
| 1414 | msg=r'indices must be integers or slices, not set;' |
| 1415 | check('[[1, 2] [{3, 4}]]') |
| 1416 | check('[[1, 2] [{i for i in range(5)}]]') |
| 1417 | msg=r'indices must be integers or slices, not dict;' |
| 1418 | check('[[1, 2] [{3: 4}]]') |
| 1419 | check('[[1, 2] [{i: i for i in range(5)}]]') |
| 1420 | msg=r'indices must be integers or slices, not generator;' |
| 1421 | check('[[1, 2] [(i for i in range(5))]]') |
| 1422 | msg=r'indices must be integers or slices, not function;' |
| 1423 | check('[[1, 2] [(lambda x, y: x)]]') |
| 1424 | msg=r'indices must be integers or slices, not str;' |
| 1425 | check('[[1, 2] [f"{x}"]]') |
| 1426 | check('[[1, 2] [f"x={x}"]]') |
| 1427 | check('[[1, 2] ["abc"]]') |
| 1428 | msg=r'indices must be integers or slices, not' |
| 1429 | check('[[1, 2] [b"abc"]]') |
| 1430 | check('[[1, 2] [12.3]]') |
| 1431 | check('[[1, 2] [12.3j]]') |
| 1432 | check('[[1, 2] [None]]') |
| 1433 | check('[[1, 2] [...]]') |
| 1434 | |
| 1435 | with warnings.catch_warnings(): |
Serhiy Storchaka | e7a4bb5 | 2019-02-19 08:30:15 +0200 | [diff] [blame] | 1436 | warnings.simplefilter('error', SyntaxWarning) |
Serhiy Storchaka | 62e4481 | 2019-02-16 08:12:19 +0200 | [diff] [blame] | 1437 | compile('[(lambda x, y: x) (3, 4)]', '<testcase>', 'exec') |
| 1438 | compile('[[1, 2] [i]]', '<testcase>', 'exec') |
| 1439 | compile('[[1, 2] [0]]', '<testcase>', 'exec') |
| 1440 | compile('[[1, 2] [True]]', '<testcase>', 'exec') |
| 1441 | compile('[[1, 2] [1:2]]', '<testcase>', 'exec') |
| 1442 | compile('[{(1, 2): 3} [i, j]]', '<testcase>', 'exec') |
| 1443 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1444 | def test_binary_mask_ops(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1445 | x = 1 & 1 |
| 1446 | x = 1 ^ 1 |
| 1447 | x = 1 | 1 |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1448 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1449 | def test_shift_ops(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1450 | x = 1 << 1 |
| 1451 | x = 1 >> 1 |
| 1452 | x = 1 << 1 >> 1 |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1453 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1454 | def test_additive_ops(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1455 | x = 1 |
| 1456 | x = 1 + 1 |
| 1457 | x = 1 - 1 - 1 |
| 1458 | x = 1 - 1 + 1 - 1 + 1 |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1459 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1460 | def test_multiplicative_ops(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1461 | x = 1 * 1 |
| 1462 | x = 1 / 1 |
| 1463 | x = 1 % 1 |
| 1464 | x = 1 / 1 * 1 % 1 |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1465 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1466 | def test_unary_ops(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1467 | x = +1 |
| 1468 | x = -1 |
| 1469 | x = ~1 |
| 1470 | x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 |
| 1471 | x = -1*1/1 + 1*1 - ---1*1 |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1472 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1473 | def test_selectors(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1474 | ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME |
| 1475 | ### subscript: expr | [expr] ':' [expr] |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1476 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1477 | import sys, time |
| 1478 | c = sys.path[0] |
| 1479 | x = time.time() |
| 1480 | x = sys.modules['time'].time() |
| 1481 | a = '01234' |
| 1482 | c = a[0] |
| 1483 | c = a[-1] |
| 1484 | s = a[0:5] |
| 1485 | s = a[:5] |
| 1486 | s = a[0:] |
| 1487 | s = a[:] |
| 1488 | s = a[-5:] |
| 1489 | s = a[:-1] |
| 1490 | s = a[-4:-3] |
| 1491 | # A rough test of SF bug 1333982. http://python.org/sf/1333982 |
| 1492 | # The testing here is fairly incomplete. |
| 1493 | # Test cases should include: commas with 1 and 2 colons |
| 1494 | d = {} |
| 1495 | d[1] = 1 |
| 1496 | d[1,] = 2 |
| 1497 | d[1,2] = 3 |
| 1498 | d[1,2,3] = 4 |
| 1499 | L = list(d) |
Serhiy Storchaka | 0cc99c8 | 2018-01-04 10:36:35 +0200 | [diff] [blame] | 1500 | L.sort(key=lambda x: (type(x).__name__, x)) |
Florent Xicluna | 9b86b9a | 2010-03-19 19:00:44 +0000 | [diff] [blame] | 1501 | self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1502 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1503 | def test_atoms(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1504 | ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING |
| 1505 | ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1506 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1507 | x = (1) |
| 1508 | x = (1 or 2 or 3) |
| 1509 | x = (1 or 2 or 3, 2, 3) |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1510 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1511 | x = [] |
| 1512 | x = [1] |
| 1513 | x = [1 or 2 or 3] |
| 1514 | x = [1 or 2 or 3, 2, 3] |
| 1515 | x = [] |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1516 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1517 | x = {} |
| 1518 | x = {'one': 1} |
| 1519 | x = {'one': 1,} |
| 1520 | x = {'one' or 'two': 1 or 2} |
| 1521 | x = {'one': 1, 'two': 2} |
| 1522 | x = {'one': 1, 'two': 2,} |
| 1523 | x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1524 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1525 | x = {'one'} |
| 1526 | x = {'one', 1,} |
| 1527 | x = {'one', 'two', 'three'} |
| 1528 | x = {2, 3, 4,} |
| 1529 | |
| 1530 | x = x |
| 1531 | x = 'x' |
| 1532 | x = 123 |
| 1533 | |
| 1534 | ### exprlist: expr (',' expr)* [','] |
| 1535 | ### testlist: test (',' test)* [','] |
| 1536 | # These have been exercised enough above |
| 1537 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1538 | def test_classdef(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1539 | # 'class' NAME ['(' [testlist] ')'] ':' suite |
| 1540 | class B: pass |
| 1541 | class B2(): pass |
| 1542 | class C1(B): pass |
| 1543 | class C2(B): pass |
| 1544 | class D(C1, C2, B): pass |
| 1545 | class C: |
| 1546 | def meth1(self): pass |
| 1547 | def meth2(self, arg): pass |
| 1548 | def meth3(self, a1, a2): pass |
| 1549 | |
Brandt Bucher | be501ca | 2020-03-03 14:25:44 -0800 | [diff] [blame] | 1550 | # decorator: '@' namedexpr_test NEWLINE |
Guido van Rossum | b5a755e | 2007-07-18 18:15:48 +0000 | [diff] [blame] | 1551 | # decorators: decorator+ |
| 1552 | # decorated: decorators (classdef | funcdef) |
| 1553 | def class_decorator(x): return x |
| 1554 | @class_decorator |
| 1555 | class G: pass |
| 1556 | |
Brandt Bucher | be501ca | 2020-03-03 14:25:44 -0800 | [diff] [blame] | 1557 | # Test expressions as decorators (PEP 614): |
| 1558 | @False or class_decorator |
| 1559 | class H: pass |
| 1560 | @d := class_decorator |
| 1561 | class I: pass |
| 1562 | @lambda c: class_decorator(c) |
| 1563 | class J: pass |
| 1564 | @[..., class_decorator, ...][1] |
| 1565 | class K: pass |
| 1566 | @class_decorator(class_decorator)(class_decorator) |
| 1567 | class L: pass |
| 1568 | @[class_decorator][0].__call__.__call__ |
| 1569 | class M: pass |
| 1570 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1571 | def test_dictcomps(self): |
Guido van Rossum | b5a755e | 2007-07-18 18:15:48 +0000 | [diff] [blame] | 1572 | # dictorsetmaker: ( (test ':' test (comp_for | |
| 1573 | # (',' test ':' test)* [','])) | |
| 1574 | # (test (comp_for | (',' test)* [','])) ) |
| 1575 | nums = [1, 2, 3] |
| 1576 | self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4}) |
| 1577 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1578 | def test_listcomps(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1579 | # list comprehension tests |
| 1580 | nums = [1, 2, 3, 4, 5] |
| 1581 | strs = ["Apple", "Banana", "Coconut"] |
| 1582 | spcs = [" Apple", " Banana ", "Coco nut "] |
| 1583 | |
| 1584 | self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut']) |
| 1585 | self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15]) |
| 1586 | self.assertEqual([x for x in nums if x > 2], [3, 4, 5]) |
| 1587 | self.assertEqual([(i, s) for i in nums for s in strs], |
| 1588 | [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), |
| 1589 | (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), |
| 1590 | (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), |
| 1591 | (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), |
| 1592 | (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]) |
| 1593 | self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]], |
| 1594 | [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), |
| 1595 | (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), |
| 1596 | (5, 'Banana'), (5, 'Coconut')]) |
| 1597 | self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)], |
| 1598 | [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]) |
| 1599 | |
| 1600 | def test_in_func(l): |
| 1601 | return [0 < x < 3 for x in l if x > 2] |
| 1602 | |
| 1603 | self.assertEqual(test_in_func(nums), [False, False, False]) |
| 1604 | |
| 1605 | def test_nested_front(): |
| 1606 | self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]], |
| 1607 | [[1, 2], [3, 4], [5, 6]]) |
| 1608 | |
| 1609 | test_nested_front() |
| 1610 | |
| 1611 | check_syntax_error(self, "[i, s for i in nums for s in strs]") |
| 1612 | check_syntax_error(self, "[x if y]") |
| 1613 | |
| 1614 | suppliers = [ |
| 1615 | (1, "Boeing"), |
| 1616 | (2, "Ford"), |
| 1617 | (3, "Macdonalds") |
| 1618 | ] |
| 1619 | |
| 1620 | parts = [ |
| 1621 | (10, "Airliner"), |
| 1622 | (20, "Engine"), |
| 1623 | (30, "Cheeseburger") |
| 1624 | ] |
| 1625 | |
| 1626 | suppart = [ |
| 1627 | (1, 10), (1, 20), (2, 20), (3, 30) |
| 1628 | ] |
| 1629 | |
| 1630 | x = [ |
| 1631 | (sname, pname) |
| 1632 | for (sno, sname) in suppliers |
| 1633 | for (pno, pname) in parts |
| 1634 | for (sp_sno, sp_pno) in suppart |
| 1635 | if sno == sp_sno and pno == sp_pno |
| 1636 | ] |
| 1637 | |
| 1638 | self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), |
| 1639 | ('Macdonalds', 'Cheeseburger')]) |
| 1640 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1641 | def test_genexps(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1642 | # generator expression tests |
| 1643 | g = ([x for x in range(10)] for x in range(1)) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1644 | self.assertEqual(next(g), [x for x in range(10)]) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1645 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1646 | next(g) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1647 | self.fail('should produce StopIteration exception') |
| 1648 | except StopIteration: |
| 1649 | pass |
| 1650 | |
| 1651 | a = 1 |
| 1652 | try: |
| 1653 | g = (a for d in a) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1654 | next(g) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1655 | self.fail('should produce TypeError') |
| 1656 | except TypeError: |
| 1657 | pass |
| 1658 | |
| 1659 | self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd']) |
| 1660 | self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy']) |
| 1661 | |
| 1662 | a = [x for x in range(10)] |
| 1663 | b = (x for x in (y for y in a)) |
| 1664 | self.assertEqual(sum(b), sum([x for x in range(10)])) |
| 1665 | |
| 1666 | self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)])) |
| 1667 | self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2])) |
| 1668 | self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)])) |
| 1669 | self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)])) |
| 1670 | self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)])) |
| 1671 | 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)])) |
| 1672 | self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0) |
| 1673 | check_syntax_error(self, "foo(x for x in range(10), 100)") |
| 1674 | check_syntax_error(self, "foo(100, x for x in range(10))") |
| 1675 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1676 | def test_comprehension_specials(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1677 | # test for outmost iterable precomputation |
| 1678 | x = 10; g = (i for i in range(x)); x = 5 |
| 1679 | self.assertEqual(len(list(g)), 10) |
| 1680 | |
| 1681 | # This should hold, since we're only precomputing outmost iterable. |
| 1682 | x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) |
| 1683 | x = 5; t = True; |
| 1684 | self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g)) |
| 1685 | |
| 1686 | # Grammar allows multiple adjacent 'if's in listcomps and genexps, |
| 1687 | # even though it's silly. Make sure it works (ifelse broke this.) |
| 1688 | self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) |
| 1689 | self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) |
| 1690 | |
| 1691 | # verify unpacking single element tuples in listcomp/genexp. |
| 1692 | self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) |
| 1693 | self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) |
| 1694 | |
Benjamin Peterson | f17ab89 | 2009-05-29 21:55:57 +0000 | [diff] [blame] | 1695 | def test_with_statement(self): |
| 1696 | class manager(object): |
| 1697 | def __enter__(self): |
| 1698 | return (1, 2) |
| 1699 | def __exit__(self, *args): |
| 1700 | pass |
| 1701 | |
| 1702 | with manager(): |
| 1703 | pass |
| 1704 | with manager() as x: |
| 1705 | pass |
| 1706 | with manager() as (x, y): |
| 1707 | pass |
| 1708 | with manager(), manager(): |
| 1709 | pass |
| 1710 | with manager() as x, manager() as y: |
| 1711 | pass |
| 1712 | with manager() as x, manager(): |
| 1713 | pass |
| 1714 | |
Pablo Galindo | 1ed83ad | 2020-06-11 17:30:46 +0100 | [diff] [blame] | 1715 | with ( |
| 1716 | manager() |
| 1717 | ): |
| 1718 | pass |
Pablo Galindo | 99db2a1 | 2020-05-06 22:54:34 +0100 | [diff] [blame] | 1719 | |
Pablo Galindo | 1ed83ad | 2020-06-11 17:30:46 +0100 | [diff] [blame] | 1720 | with ( |
| 1721 | manager() as x |
| 1722 | ): |
| 1723 | pass |
| 1724 | |
| 1725 | with ( |
| 1726 | manager() as (x, y), |
| 1727 | manager() as z, |
| 1728 | ): |
| 1729 | pass |
| 1730 | |
| 1731 | with ( |
| 1732 | manager(), |
| 1733 | manager() |
| 1734 | ): |
| 1735 | pass |
| 1736 | |
| 1737 | with ( |
| 1738 | manager() as x, |
| 1739 | manager() as y |
| 1740 | ): |
| 1741 | pass |
| 1742 | |
| 1743 | with ( |
| 1744 | manager() as x, |
| 1745 | manager() |
| 1746 | ): |
| 1747 | pass |
| 1748 | |
| 1749 | with ( |
| 1750 | manager() as x, |
| 1751 | manager() as y, |
| 1752 | manager() as z, |
| 1753 | ): |
| 1754 | pass |
| 1755 | |
| 1756 | with ( |
| 1757 | manager() as x, |
| 1758 | manager() as y, |
| 1759 | manager(), |
| 1760 | ): |
| 1761 | pass |
Pablo Galindo | 99db2a1 | 2020-05-06 22:54:34 +0100 | [diff] [blame] | 1762 | |
Benjamin Peterson | c8507bf | 2011-05-30 10:52:48 -0500 | [diff] [blame] | 1763 | def test_if_else_expr(self): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1764 | # Test ifelse expressions in various cases |
| 1765 | def _checkeval(msg, ret): |
| 1766 | "helper to check that evaluation of expressions is done correctly" |
Victor Stinner | c6ec54d | 2016-04-12 18:33:41 +0200 | [diff] [blame] | 1767 | print(msg) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1768 | return ret |
| 1769 | |
Nick Coghlan | 650f0d0 | 2007-04-15 12:05:43 +0000 | [diff] [blame] | 1770 | # the next line is not allowed anymore |
| 1771 | #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1772 | self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True]) |
| 1773 | 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]) |
| 1774 | self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5) |
| 1775 | self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5) |
| 1776 | self.assertEqual((5 and 6 if 0 else 1), 1) |
| 1777 | self.assertEqual(((5 and 6) if 0 else 1), 1) |
| 1778 | self.assertEqual((5 and (6 if 1 else 1)), 6) |
| 1779 | self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3) |
| 1780 | self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1) |
| 1781 | self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5) |
| 1782 | self.assertEqual((not 5 if 1 else 1), False) |
| 1783 | self.assertEqual((not 5 if 0 else 1), 1) |
| 1784 | self.assertEqual((6 + 1 if 1 else 2), 7) |
| 1785 | self.assertEqual((6 - 1 if 1 else 2), 5) |
| 1786 | self.assertEqual((6 * 2 if 1 else 4), 12) |
| 1787 | self.assertEqual((6 / 2 if 1 else 3), 3) |
| 1788 | self.assertEqual((6 < 4 if 0 else 2), 2) |
Jeremy Hylton | 7b03bad | 2006-02-28 17:46:23 +0000 | [diff] [blame] | 1789 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame] | 1790 | def test_paren_evaluation(self): |
| 1791 | self.assertEqual(16 // (4 // 2), 8) |
| 1792 | self.assertEqual((16 // 4) // 2, 2) |
| 1793 | self.assertEqual(16 // 4 // 2, 2) |
Serhiy Storchaka | 3bcbedc | 2019-01-18 07:47:48 +0200 | [diff] [blame] | 1794 | x = 2 |
| 1795 | y = 3 |
| 1796 | self.assertTrue(False is (x is y)) |
| 1797 | self.assertFalse((False is x) is y) |
| 1798 | self.assertFalse(False is x is y) |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame] | 1799 | |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 1800 | def test_matrix_mul(self): |
| 1801 | # This is not intended to be a comprehensive test, rather just to be few |
| 1802 | # samples of the @ operator in test_grammar.py. |
| 1803 | class M: |
| 1804 | def __matmul__(self, o): |
| 1805 | return 4 |
| 1806 | def __imatmul__(self, o): |
| 1807 | self.other = o |
| 1808 | return self |
| 1809 | m = M() |
| 1810 | self.assertEqual(m @ m, 4) |
| 1811 | m @= 42 |
| 1812 | self.assertEqual(m.other, 42) |
| 1813 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 1814 | def test_async_await(self): |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 1815 | async def test(): |
| 1816 | def sum(): |
Yury Selivanov | 8fb307c | 2015-07-22 13:33:45 +0300 | [diff] [blame] | 1817 | pass |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 1818 | if 1: |
| 1819 | await someobj() |
| 1820 | |
| 1821 | self.assertEqual(test.__name__, 'test') |
| 1822 | self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE)) |
| 1823 | |
| 1824 | def decorator(func): |
| 1825 | setattr(func, '_marked', True) |
| 1826 | return func |
| 1827 | |
| 1828 | @decorator |
| 1829 | async def test2(): |
| 1830 | return 22 |
| 1831 | self.assertTrue(test2._marked) |
| 1832 | self.assertEqual(test2.__name__, 'test2') |
| 1833 | self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE)) |
| 1834 | |
| 1835 | def test_async_for(self): |
| 1836 | class Done(Exception): pass |
| 1837 | |
| 1838 | class AIter: |
Yury Selivanov | a6f6edb | 2016-06-09 15:08:31 -0400 | [diff] [blame] | 1839 | def __aiter__(self): |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame] | 1840 | return self |
| 1841 | async def __anext__(self): |
| 1842 | raise StopAsyncIteration |
| 1843 | |
| 1844 | async def foo(): |
| 1845 | async for i in AIter(): |
| 1846 | pass |
| 1847 | async for i, j in AIter(): |
| 1848 | pass |
| 1849 | async for i in AIter(): |
| 1850 | pass |
| 1851 | else: |
| 1852 | pass |
| 1853 | raise Done |
| 1854 | |
| 1855 | with self.assertRaises(Done): |
| 1856 | foo().send(None) |
| 1857 | |
| 1858 | def test_async_with(self): |
| 1859 | class Done(Exception): pass |
| 1860 | |
| 1861 | class manager: |
| 1862 | async def __aenter__(self): |
| 1863 | return (1, 2) |
| 1864 | async def __aexit__(self, *exc): |
| 1865 | return False |
| 1866 | |
| 1867 | async def foo(): |
| 1868 | async with manager(): |
| 1869 | pass |
| 1870 | async with manager() as x: |
| 1871 | pass |
| 1872 | async with manager() as (x, y): |
| 1873 | pass |
| 1874 | async with manager(), manager(): |
| 1875 | pass |
| 1876 | async with manager() as x, manager() as y: |
| 1877 | pass |
| 1878 | async with manager() as x, manager(): |
| 1879 | pass |
| 1880 | raise Done |
| 1881 | |
| 1882 | with self.assertRaises(Done): |
| 1883 | foo().send(None) |
| 1884 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 1885 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1886 | if __name__ == '__main__': |
Zachary Ware | 38c707e | 2015-04-13 15:00:43 -0500 | [diff] [blame] | 1887 | unittest.main() |