Debian Codegraph @

Lib/test/test_tokenize.py

raw
1 import os
2 import re
3 import token
4 import tokenize
5 import unittest
6 from io import BytesIO, StringIO
7 from textwrap import dedent
8 from unittest import TestCase, mock
9 from test import support
10 from test.support import os_helper
11 from test.support.script_helper import run_test_script, make_script, run_python_until_end
12 from test.support.numbers import (
13 VALID_UNDERSCORE_LITERALS,
14 INVALID_UNDERSCORE_LITERALS,
15 )
16
17
18 # Converts a source string into a list of textual representation
19 # of the tokens such as:
20 # ` NAME 'if' (1, 0) (1, 2)`
21 # to make writing tests easier.
22 def stringify_tokens_from_source(token_generator, source_string):
23 result = []
24 num_lines = len(source_string.splitlines())
25 missing_trailing_nl = source_string[-1] not in '\r\n'
26
27 for type, token, start, end, line in token_generator:
28 if type == tokenize.ENDMARKER:
29 break
30 # Ignore the new line on the last line if the input lacks one
31 if missing_trailing_nl and type == tokenize.NEWLINE and end[0] == num_lines:
32 continue
33 type = tokenize.tok_name[type]
34 result.append(f" {type:10} {token!r:13} {start} {end}")
35
36 return result
37
38 class TokenizeTest(TestCase):
39 # Tests for the tokenize module.
40
41 # The tests can be really simple. Given a small fragment of source
42 # code, print out a table with tokens. The ENDMARKER, ENCODING and
43 # final NEWLINE are omitted for brevity.
44
45 def check_tokenize(self, s, expected):
46 # Format the tokens in s in a table format.
47 # The ENDMARKER and final NEWLINE are omitted.
48 f = BytesIO(s.encode('utf-8'))
49 result = stringify_tokens_from_source(tokenize.tokenize(f.readline), s)
50 self.assertEqual(result,
51 [" ENCODING 'utf-8' (0, 0) (0, 0)"] +
52 expected.rstrip().splitlines())
53
54 def test_invalid_readline(self):
55 def gen():
56 yield "sdfosdg"
57 yield "sdfosdg"
58 with self.assertRaises(TypeError):
59 list(tokenize.tokenize(gen().__next__))
60
61 def gen():
62 yield b"sdfosdg"
63 yield b"sdfosdg"
64 with self.assertRaises(TypeError):
65 list(tokenize.generate_tokens(gen().__next__))
66
67 def gen():
68 yield "sdfosdg"
69 1/0
70 with self.assertRaises(ZeroDivisionError):
71 list(tokenize.generate_tokens(gen().__next__))
72
73 def test_implicit_newline(self):
74 # Make sure that the tokenizer puts in an implicit NEWLINE
75 # when the input lacks a trailing new line.
76 f = BytesIO("x".encode('utf-8'))
77 tokens = list(tokenize.tokenize(f.readline))
78 self.assertEqual(tokens[-2].type, tokenize.NEWLINE)
79 self.assertEqual(tokens[-1].type, tokenize.ENDMARKER)
80
81 def test_basic(self):
82 self.check_tokenize("1 + 1", """\
83 NUMBER '1' (1, 0) (1, 1)
84 OP '+' (1, 2) (1, 3)
85 NUMBER '1' (1, 4) (1, 5)
86 """)
87 self.check_tokenize("if False:\n"
88 " # NL\n"
89 " \n"
90 " True = False # NEWLINE\n", """\
91 NAME 'if' (1, 0) (1, 2)
92 NAME 'False' (1, 3) (1, 8)
93 OP ':' (1, 8) (1, 9)
94 NEWLINE '\\n' (1, 9) (1, 10)
95 COMMENT '# NL' (2, 4) (2, 8)
96 NL '\\n' (2, 8) (2, 9)
97 NL '\\n' (3, 4) (3, 5)
98 INDENT ' ' (4, 0) (4, 4)
99 NAME 'True' (4, 4) (4, 8)
100 OP '=' (4, 9) (4, 10)
101 NAME 'False' (4, 11) (4, 16)
102 COMMENT '# NEWLINE' (4, 17) (4, 26)
103 NEWLINE '\\n' (4, 26) (4, 27)
104 DEDENT '' (5, 0) (5, 0)
105 """)
106
107 self.check_tokenize("if True:\r\n # NL\r\n foo='bar'\r\n\r\n", """\
108 NAME 'if' (1, 0) (1, 2)
109 NAME 'True' (1, 3) (1, 7)
110 OP ':' (1, 7) (1, 8)
111 NEWLINE '\\r\\n' (1, 8) (1, 10)
112 COMMENT '# NL' (2, 4) (2, 8)
113 NL '\\r\\n' (2, 8) (2, 10)
114 INDENT ' ' (3, 0) (3, 4)
115 NAME 'foo' (3, 4) (3, 7)
116 OP '=' (3, 7) (3, 8)
117 STRING "\'bar\'" (3, 8) (3, 13)
118 NEWLINE '\\r\\n' (3, 13) (3, 15)
119 NL '\\r\\n' (4, 0) (4, 2)
120 DEDENT '' (5, 0) (5, 0)
121 """)
122
123 self.check_tokenize("x = 1 + \\\r\n1\r\n", """\
124 NAME 'x' (1, 0) (1, 1)
125 OP '=' (1, 2) (1, 3)
126 NUMBER '1' (1, 4) (1, 5)
127 OP '+' (1, 6) (1, 7)
128 NUMBER '1' (2, 0) (2, 1)
129 NEWLINE '\\r\\n' (2, 1) (2, 3)
130 """)
131
132 indent_error_file = b"""\
133 def k(x):
134 x += 2
135 x += 5
136 """
137 readline = BytesIO(indent_error_file).readline
138 with self.assertRaisesRegex(IndentationError,
139 "unindent does not match any "
140 "outer indentation level") as e:
141 for tok in tokenize.tokenize(readline):
142 pass
143 self.assertEqual(e.exception.lineno, 3)
144 self.assertEqual(e.exception.filename, '<string>')
145 self.assertEqual(e.exception.end_lineno, None)
146 self.assertEqual(e.exception.end_offset, None)
147 self.assertEqual(
148 e.exception.msg,
149 'unindent does not match any outer indentation level')
150 self.assertEqual(e.exception.offset, 9)
151 self.assertEqual(e.exception.text, ' x += 5')
152
153 def test_int(self):
154 # Ordinary integers and binary operators
155 self.check_tokenize("0xff <= 255", """\
156 NUMBER '0xff' (1, 0) (1, 4)
157 OP '<=' (1, 5) (1, 7)
158 NUMBER '255' (1, 8) (1, 11)
159 """)
160 self.check_tokenize("0b10 <= 255", """\
161 NUMBER '0b10' (1, 0) (1, 4)
162 OP '<=' (1, 5) (1, 7)
163 NUMBER '255' (1, 8) (1, 11)
164 """)
165 self.check_tokenize("0o123 <= 0O123", """\
166 NUMBER '0o123' (1, 0) (1, 5)
167 OP '<=' (1, 6) (1, 8)
168 NUMBER '0O123' (1, 9) (1, 14)
169 """)
170 self.check_tokenize("1234567 > ~0x15", """\
171 NUMBER '1234567' (1, 0) (1, 7)
172 OP '>' (1, 8) (1, 9)
173 OP '~' (1, 10) (1, 11)
174 NUMBER '0x15' (1, 11) (1, 15)
175 """)
176 self.check_tokenize("2134568 != 1231515", """\
177 NUMBER '2134568' (1, 0) (1, 7)
178 OP '!=' (1, 8) (1, 10)
179 NUMBER '1231515' (1, 11) (1, 18)
180 """)
181 self.check_tokenize("(-124561-1) & 200000000", """\
182 OP '(' (1, 0) (1, 1)
183 OP '-' (1, 1) (1, 2)
184 NUMBER '124561' (1, 2) (1, 8)
185 OP '-' (1, 8) (1, 9)
186 NUMBER '1' (1, 9) (1, 10)
187 OP ')' (1, 10) (1, 11)
188 OP '&' (1, 12) (1, 13)
189 NUMBER '200000000' (1, 14) (1, 23)
190 """)
191 self.check_tokenize("0xdeadbeef != -1", """\
192 NUMBER '0xdeadbeef' (1, 0) (1, 10)
193 OP '!=' (1, 11) (1, 13)
194 OP '-' (1, 14) (1, 15)
195 NUMBER '1' (1, 15) (1, 16)
196 """)
197 self.check_tokenize("0xdeadc0de & 12345", """\
198 NUMBER '0xdeadc0de' (1, 0) (1, 10)
199 OP '&' (1, 11) (1, 12)
200 NUMBER '12345' (1, 13) (1, 18)
201 """)
202 self.check_tokenize("0xFF & 0x15 | 1234", """\
203 NUMBER '0xFF' (1, 0) (1, 4)
204 OP '&' (1, 5) (1, 6)
205 NUMBER '0x15' (1, 7) (1, 11)
206 OP '|' (1, 12) (1, 13)
207 NUMBER '1234' (1, 14) (1, 18)
208 """)
209
210 def test_long(self):
211 # Long integers
212 self.check_tokenize("x = 0", """\
213 NAME 'x' (1, 0) (1, 1)
214 OP '=' (1, 2) (1, 3)
215 NUMBER '0' (1, 4) (1, 5)
216 """)
217 self.check_tokenize("x = 0xfffffffffff", """\
218 NAME 'x' (1, 0) (1, 1)
219 OP '=' (1, 2) (1, 3)
220 NUMBER '0xfffffffffff' (1, 4) (1, 17)
221 """)
222 self.check_tokenize("x = 123141242151251616110", """\
223 NAME 'x' (1, 0) (1, 1)
224 OP '=' (1, 2) (1, 3)
225 NUMBER '123141242151251616110' (1, 4) (1, 25)
226 """)
227 self.check_tokenize("x = -15921590215012591", """\
228 NAME 'x' (1, 0) (1, 1)
229 OP '=' (1, 2) (1, 3)
230 OP '-' (1, 4) (1, 5)
231 NUMBER '15921590215012591' (1, 5) (1, 22)
232 """)
233
234 def test_float(self):
235 # Floating-point numbers
236 self.check_tokenize("x = 3.14159", """\
237 NAME 'x' (1, 0) (1, 1)
238 OP '=' (1, 2) (1, 3)
239 NUMBER '3.14159' (1, 4) (1, 11)
240 """)
241 self.check_tokenize("x = 314159.", """\
242 NAME 'x' (1, 0) (1, 1)
243 OP '=' (1, 2) (1, 3)
244 NUMBER '314159.' (1, 4) (1, 11)
245 """)
246 self.check_tokenize("x = .314159", """\
247 NAME 'x' (1, 0) (1, 1)
248 OP '=' (1, 2) (1, 3)
249 NUMBER '.314159' (1, 4) (1, 11)
250 """)
251 self.check_tokenize("x = 3e14159", """\
252 NAME 'x' (1, 0) (1, 1)
253 OP '=' (1, 2) (1, 3)
254 NUMBER '3e14159' (1, 4) (1, 11)
255 """)
256 self.check_tokenize("x = 3E123", """\
257 NAME 'x' (1, 0) (1, 1)
258 OP '=' (1, 2) (1, 3)
259 NUMBER '3E123' (1, 4) (1, 9)
260 """)
261 self.check_tokenize("x+y = 3e-1230", """\
262 NAME 'x' (1, 0) (1, 1)
263 OP '+' (1, 1) (1, 2)
264 NAME 'y' (1, 2) (1, 3)
265 OP '=' (1, 4) (1, 5)
266 NUMBER '3e-1230' (1, 6) (1, 13)
267 """)
268 self.check_tokenize("x = 3.14e159", """\
269 NAME 'x' (1, 0) (1, 1)
270 OP '=' (1, 2) (1, 3)
271 NUMBER '3.14e159' (1, 4) (1, 12)
272 """)
273
274 def test_underscore_literals(self):
275 def number_token(s):
276 f = BytesIO(s.encode('utf-8'))
277 for toktype, token, start, end, line in tokenize.tokenize(f.readline):
278 if toktype == tokenize.NUMBER:
279 return token
280 return 'invalid token'
281 for lit in VALID_UNDERSCORE_LITERALS:
282 if '(' in lit:
283 # this won't work with compound complex inputs
284 continue
285 self.assertEqual(number_token(lit), lit)
286 # Valid cases with extra underscores in the tokenize module
287 # See gh-105549 for context
288 extra_valid_cases = {"0_7", "09_99"}
289 for lit in INVALID_UNDERSCORE_LITERALS:
290 if lit in extra_valid_cases:
291 continue
292 try:
293 number_token(lit)
294 except tokenize.TokenError:
295 continue
296 self.assertNotEqual(number_token(lit), lit)
297
298 def test_string(self):
299 # String literals
300 self.check_tokenize("x = ''; y = \"\"", """\
301 NAME 'x' (1, 0) (1, 1)
302 OP '=' (1, 2) (1, 3)
303 STRING "''" (1, 4) (1, 6)
304 OP ';' (1, 6) (1, 7)
305 NAME 'y' (1, 8) (1, 9)
306 OP '=' (1, 10) (1, 11)
307 STRING '""' (1, 12) (1, 14)
308 """)
309 self.check_tokenize("x = '\"'; y = \"'\"", """\
310 NAME 'x' (1, 0) (1, 1)
311 OP '=' (1, 2) (1, 3)
312 STRING '\\'"\\'' (1, 4) (1, 7)
313 OP ';' (1, 7) (1, 8)
314 NAME 'y' (1, 9) (1, 10)
315 OP '=' (1, 11) (1, 12)
316 STRING '"\\'"' (1, 13) (1, 16)
317 """)
318 self.check_tokenize("x = \"doesn't \"shrink\", does it\"", """\
319 NAME 'x' (1, 0) (1, 1)
320 OP '=' (1, 2) (1, 3)
321 STRING '"doesn\\'t "' (1, 4) (1, 14)
322 NAME 'shrink' (1, 14) (1, 20)
323 STRING '", does it"' (1, 20) (1, 31)
324 """)
325 self.check_tokenize("x = 'abc' + 'ABC'", """\
326 NAME 'x' (1, 0) (1, 1)
327 OP '=' (1, 2) (1, 3)
328 STRING "'abc'" (1, 4) (1, 9)
329 OP '+' (1, 10) (1, 11)
330 STRING "'ABC'" (1, 12) (1, 17)
331 """)
332 self.check_tokenize('y = "ABC" + "ABC"', """\
333 NAME 'y' (1, 0) (1, 1)
334 OP '=' (1, 2) (1, 3)
335 STRING '"ABC"' (1, 4) (1, 9)
336 OP '+' (1, 10) (1, 11)
337 STRING '"ABC"' (1, 12) (1, 17)
338 """)
339 self.check_tokenize("x = r'abc' + r'ABC' + R'ABC' + R'ABC'", """\
340 NAME 'x' (1, 0) (1, 1)
341 OP '=' (1, 2) (1, 3)
342 STRING "r'abc'" (1, 4) (1, 10)
343 OP '+' (1, 11) (1, 12)
344 STRING "r'ABC'" (1, 13) (1, 19)
345 OP '+' (1, 20) (1, 21)
346 STRING "R'ABC'" (1, 22) (1, 28)
347 OP '+' (1, 29) (1, 30)
348 STRING "R'ABC'" (1, 31) (1, 37)
349 """)
350 self.check_tokenize('y = r"abc" + r"ABC" + R"ABC" + R"ABC"', """\
351 NAME 'y' (1, 0) (1, 1)
352 OP '=' (1, 2) (1, 3)
353 STRING 'r"abc"' (1, 4) (1, 10)
354 OP '+' (1, 11) (1, 12)
355 STRING 'r"ABC"' (1, 13) (1, 19)
356 OP '+' (1, 20) (1, 21)
357 STRING 'R"ABC"' (1, 22) (1, 28)
358 OP '+' (1, 29) (1, 30)
359 STRING 'R"ABC"' (1, 31) (1, 37)
360 """)
361
362 self.check_tokenize("u'abc' + U'abc'", """\
363 STRING "u'abc'" (1, 0) (1, 6)
364 OP '+' (1, 7) (1, 8)
365 STRING "U'abc'" (1, 9) (1, 15)
366 """)
367 self.check_tokenize('u"abc" + U"abc"', """\
368 STRING 'u"abc"' (1, 0) (1, 6)
369 OP '+' (1, 7) (1, 8)
370 STRING 'U"abc"' (1, 9) (1, 15)
371 """)
372
373 self.check_tokenize("b'abc' + B'abc'", """\
374 STRING "b'abc'" (1, 0) (1, 6)
375 OP '+' (1, 7) (1, 8)
376 STRING "B'abc'" (1, 9) (1, 15)
377 """)
378 self.check_tokenize('b"abc" + B"abc"', """\
379 STRING 'b"abc"' (1, 0) (1, 6)
380 OP '+' (1, 7) (1, 8)
381 STRING 'B"abc"' (1, 9) (1, 15)
382 """)
383 self.check_tokenize("br'abc' + bR'abc' + Br'abc' + BR'abc'", """\
384 STRING "br'abc'" (1, 0) (1, 7)
385 OP '+' (1, 8) (1, 9)
386 STRING "bR'abc'" (1, 10) (1, 17)
387 OP '+' (1, 18) (1, 19)
388 STRING "Br'abc'" (1, 20) (1, 27)
389 OP '+' (1, 28) (1, 29)
390 STRING "BR'abc'" (1, 30) (1, 37)
391 """)
392 self.check_tokenize('br"abc" + bR"abc" + Br"abc" + BR"abc"', """\
393 STRING 'br"abc"' (1, 0) (1, 7)
394 OP '+' (1, 8) (1, 9)
395 STRING 'bR"abc"' (1, 10) (1, 17)
396 OP '+' (1, 18) (1, 19)
397 STRING 'Br"abc"' (1, 20) (1, 27)
398 OP '+' (1, 28) (1, 29)
399 STRING 'BR"abc"' (1, 30) (1, 37)
400 """)
401 self.check_tokenize("rb'abc' + rB'abc' + Rb'abc' + RB'abc'", """\
402 STRING "rb'abc'" (1, 0) (1, 7)
403 OP '+' (1, 8) (1, 9)
404 STRING "rB'abc'" (1, 10) (1, 17)
405 OP '+' (1, 18) (1, 19)
406 STRING "Rb'abc'" (1, 20) (1, 27)
407 OP '+' (1, 28) (1, 29)
408 STRING "RB'abc'" (1, 30) (1, 37)
409 """)
410 self.check_tokenize('rb"abc" + rB"abc" + Rb"abc" + RB"abc"', """\
411 STRING 'rb"abc"' (1, 0) (1, 7)
412 OP '+' (1, 8) (1, 9)
413 STRING 'rB"abc"' (1, 10) (1, 17)
414 OP '+' (1, 18) (1, 19)
415 STRING 'Rb"abc"' (1, 20) (1, 27)
416 OP '+' (1, 28) (1, 29)
417 STRING 'RB"abc"' (1, 30) (1, 37)
418 """)
419 # Check 0, 1, and 2 character string prefixes.
420 self.check_tokenize(r'"a\
421 de\
422 fg"', """\
423 STRING '"a\\\\\\nde\\\\\\nfg"\' (1, 0) (3, 3)
424 """)
425 self.check_tokenize(r'u"a\
426 de"', """\
427 STRING 'u"a\\\\\\nde"\' (1, 0) (2, 3)
428 """)
429 self.check_tokenize(r'rb"a\
430 d"', """\
431 STRING 'rb"a\\\\\\nd"\' (1, 0) (2, 2)
432 """)
433 self.check_tokenize(r'"""a\
434 b"""', """\
435 STRING '\"\""a\\\\\\nb\"\""' (1, 0) (2, 4)
436 """)
437 self.check_tokenize(r'u"""a\
438 b"""', """\
439 STRING 'u\"\""a\\\\\\nb\"\""' (1, 0) (2, 4)
440 """)
441 self.check_tokenize(r'rb"""a\
442 b\
443 c"""', """\
444 STRING 'rb"\""a\\\\\\nb\\\\\\nc"\""' (1, 0) (3, 4)
445 """)
446 self.check_tokenize('f"abc"', """\
447 FSTRING_START 'f"' (1, 0) (1, 2)
448 FSTRING_MIDDLE 'abc' (1, 2) (1, 5)
449 FSTRING_END '"' (1, 5) (1, 6)
450 """)
451 self.check_tokenize('fR"a{b}c"', """\
452 FSTRING_START 'fR"' (1, 0) (1, 3)
453 FSTRING_MIDDLE 'a' (1, 3) (1, 4)
454 OP '{' (1, 4) (1, 5)
455 NAME 'b' (1, 5) (1, 6)
456 OP '}' (1, 6) (1, 7)
457 FSTRING_MIDDLE 'c' (1, 7) (1, 8)
458 FSTRING_END '"' (1, 8) (1, 9)
459 """)
460 self.check_tokenize('fR"a{{{b!r}}}c"', """\
461 FSTRING_START 'fR"' (1, 0) (1, 3)
462 FSTRING_MIDDLE 'a{' (1, 3) (1, 5)
463 OP '{' (1, 6) (1, 7)
464 NAME 'b' (1, 7) (1, 8)
465 OP '!' (1, 8) (1, 9)
466 NAME 'r' (1, 9) (1, 10)
467 OP '}' (1, 10) (1, 11)
468 FSTRING_MIDDLE '}' (1, 11) (1, 12)
469 FSTRING_MIDDLE 'c' (1, 13) (1, 14)
470 FSTRING_END '"' (1, 14) (1, 15)
471 """)
472 self.check_tokenize('f"{{{1+1}}}"', """\
473 FSTRING_START 'f"' (1, 0) (1, 2)
474 FSTRING_MIDDLE '{' (1, 2) (1, 3)
475 OP '{' (1, 4) (1, 5)
476 NUMBER '1' (1, 5) (1, 6)
477 OP '+' (1, 6) (1, 7)
478 NUMBER '1' (1, 7) (1, 8)
479 OP '}' (1, 8) (1, 9)
480 FSTRING_MIDDLE '}' (1, 9) (1, 10)
481 FSTRING_END '"' (1, 11) (1, 12)
482 """)
483 self.check_tokenize('f"""{f\'\'\'{f\'{f"{1+1}"}\'}\'\'\'}"""', """\
484 FSTRING_START 'f\"""' (1, 0) (1, 4)
485 OP '{' (1, 4) (1, 5)
486 FSTRING_START "f'''" (1, 5) (1, 9)
487 OP '{' (1, 9) (1, 10)
488 FSTRING_START "f'" (1, 10) (1, 12)
489 OP '{' (1, 12) (1, 13)
490 FSTRING_START 'f"' (1, 13) (1, 15)
491 OP '{' (1, 15) (1, 16)
492 NUMBER '1' (1, 16) (1, 17)
493 OP '+' (1, 17) (1, 18)
494 NUMBER '1' (1, 18) (1, 19)
495 OP '}' (1, 19) (1, 20)
496 FSTRING_END '"' (1, 20) (1, 21)
497 OP '}' (1, 21) (1, 22)
498 FSTRING_END "'" (1, 22) (1, 23)
499 OP '}' (1, 23) (1, 24)
500 FSTRING_END "'''" (1, 24) (1, 27)
501 OP '}' (1, 27) (1, 28)
502 FSTRING_END '\"""' (1, 28) (1, 31)
503 """)
504 self.check_tokenize('f""" x\nstr(data, encoding={invalid!r})\n"""', """\
505 FSTRING_START 'f\"""' (1, 0) (1, 4)
506 FSTRING_MIDDLE ' x\\nstr(data, encoding=' (1, 4) (2, 19)
507 OP '{' (2, 19) (2, 20)
508 NAME 'invalid' (2, 20) (2, 27)
509 OP '!' (2, 27) (2, 28)
510 NAME 'r' (2, 28) (2, 29)
511 OP '}' (2, 29) (2, 30)
512 FSTRING_MIDDLE ')\\n' (2, 30) (3, 0)
513 FSTRING_END '\"""' (3, 0) (3, 3)
514 """)
515 self.check_tokenize('f"""123456789\nsomething{None}bad"""', """\
516 FSTRING_START 'f\"""' (1, 0) (1, 4)
517 FSTRING_MIDDLE '123456789\\nsomething' (1, 4) (2, 9)
518 OP '{' (2, 9) (2, 10)
519 NAME 'None' (2, 10) (2, 14)
520 OP '}' (2, 14) (2, 15)
521 FSTRING_MIDDLE 'bad' (2, 15) (2, 18)
522 FSTRING_END '\"""' (2, 18) (2, 21)
523 """)
524 self.check_tokenize('f"""abc"""', """\
525 FSTRING_START 'f\"""' (1, 0) (1, 4)
526 FSTRING_MIDDLE 'abc' (1, 4) (1, 7)
527 FSTRING_END '\"""' (1, 7) (1, 10)
528 """)
529 self.check_tokenize(r'f"abc\
530 def"', """\
531 FSTRING_START 'f"' (1, 0) (1, 2)
532 FSTRING_MIDDLE 'abc\\\\\\ndef' (1, 2) (2, 3)
533 FSTRING_END '"' (2, 3) (2, 4)
534 """)
535 self.check_tokenize(r'Rf"abc\
536 def"', """\
537 FSTRING_START 'Rf"' (1, 0) (1, 3)
538 FSTRING_MIDDLE 'abc\\\\\\ndef' (1, 3) (2, 3)
539 FSTRING_END '"' (2, 3) (2, 4)
540 """)
541 self.check_tokenize("f'some words {a+b:.3f} more words {c+d=} final words'", """\
542 FSTRING_START "f'" (1, 0) (1, 2)
543 FSTRING_MIDDLE 'some words ' (1, 2) (1, 13)
544 OP '{' (1, 13) (1, 14)
545 NAME 'a' (1, 14) (1, 15)
546 OP '+' (1, 15) (1, 16)
547 NAME 'b' (1, 16) (1, 17)
548 OP ':' (1, 17) (1, 18)
549 FSTRING_MIDDLE '.3f' (1, 18) (1, 21)
550 OP '}' (1, 21) (1, 22)
551 FSTRING_MIDDLE ' more words ' (1, 22) (1, 34)
552 OP '{' (1, 34) (1, 35)
553 NAME 'c' (1, 35) (1, 36)
554 OP '+' (1, 36) (1, 37)
555 NAME 'd' (1, 37) (1, 38)
556 OP '=' (1, 38) (1, 39)
557 OP '}' (1, 39) (1, 40)
558 FSTRING_MIDDLE ' final words' (1, 40) (1, 52)
559 FSTRING_END "'" (1, 52) (1, 53)
560 """)
561 self.check_tokenize("""\
562 f'''{
563 3
564 =}'''""", """\
565 FSTRING_START "f'''" (1, 0) (1, 4)
566 OP '{' (1, 4) (1, 5)
567 NL '\\n' (1, 5) (1, 6)
568 NUMBER '3' (2, 0) (2, 1)
569 NL '\\n' (2, 1) (2, 2)
570 OP '=' (3, 0) (3, 1)
571 OP '}' (3, 1) (3, 2)
572 FSTRING_END "'''" (3, 2) (3, 5)
573 """)
574 self.check_tokenize("""\
575 f'''__{
576 x:a
577 }__'''""", """\
578 FSTRING_START "f'''" (1, 0) (1, 4)
579 FSTRING_MIDDLE '__' (1, 4) (1, 6)
580 OP '{' (1, 6) (1, 7)
581 NL '\\n' (1, 7) (1, 8)
582 NAME 'x' (2, 4) (2, 5)
583 OP ':' (2, 5) (2, 6)
584 FSTRING_MIDDLE 'a\\n' (2, 6) (3, 0)
585 OP '}' (3, 0) (3, 1)
586 FSTRING_MIDDLE '__' (3, 1) (3, 3)
587 FSTRING_END "'''" (3, 3) (3, 6)
588 """)
589 self.check_tokenize("""\
590 f'''__{
591 x:a
592 b
593 c
594 d
595 }__'''""", """\
596 FSTRING_START "f'''" (1, 0) (1, 4)
597 FSTRING_MIDDLE '__' (1, 4) (1, 6)
598 OP '{' (1, 6) (1, 7)
599 NL '\\n' (1, 7) (1, 8)
600 NAME 'x' (2, 4) (2, 5)
601 OP ':' (2, 5) (2, 6)
602 FSTRING_MIDDLE 'a\\n b\\n c\\n d\\n' (2, 6) (6, 0)
603 OP '}' (6, 0) (6, 1)
604 FSTRING_MIDDLE '__' (6, 1) (6, 3)
605 FSTRING_END "'''" (6, 3) (6, 6)
606 """)
607
608 self.check_tokenize("""\
609 '''Autorzy, którzy tą jednostkę mają wpisani jako AKTUALNA -- czyli
610 aktualni pracownicy, obecni pracownicy'''
611 """, """\
612 INDENT ' ' (1, 0) (1, 4)
613 STRING "'''Autorzy, którzy tą jednostkę mają wpisani jako AKTUALNA -- czyli\\n aktualni pracownicy, obecni pracownicy'''" (1, 4) (2, 45)
614 NEWLINE '\\n' (2, 45) (2, 46)
615 DEDENT '' (3, 0) (3, 0)
616 """)
617
618 def test_function(self):
619 self.check_tokenize("def d22(a, b, c=2, d=2, *k): pass", """\
620 NAME 'def' (1, 0) (1, 3)
621 NAME 'd22' (1, 4) (1, 7)
622 OP '(' (1, 7) (1, 8)
623 NAME 'a' (1, 8) (1, 9)
624 OP ',' (1, 9) (1, 10)
625 NAME 'b' (1, 11) (1, 12)
626 OP ',' (1, 12) (1, 13)
627 NAME 'c' (1, 14) (1, 15)
628 OP '=' (1, 15) (1, 16)
629 NUMBER '2' (1, 16) (1, 17)
630 OP ',' (1, 17) (1, 18)
631 NAME 'd' (1, 19) (1, 20)
632 OP '=' (1, 20) (1, 21)
633 NUMBER '2' (1, 21) (1, 22)
634 OP ',' (1, 22) (1, 23)
635 OP '*' (1, 24) (1, 25)
636 NAME 'k' (1, 25) (1, 26)
637 OP ')' (1, 26) (1, 27)
638 OP ':' (1, 27) (1, 28)
639 NAME 'pass' (1, 29) (1, 33)
640 """)
641 self.check_tokenize("def d01v_(a=1, *k, **w): pass", """\
642 NAME 'def' (1, 0) (1, 3)
643 NAME 'd01v_' (1, 4) (1, 9)
644 OP '(' (1, 9) (1, 10)
645 NAME 'a' (1, 10) (1, 11)
646 OP '=' (1, 11) (1, 12)
647 NUMBER '1' (1, 12) (1, 13)
648 OP ',' (1, 13) (1, 14)
649 OP '*' (1, 15) (1, 16)
650 NAME 'k' (1, 16) (1, 17)
651 OP ',' (1, 17) (1, 18)
652 OP '**' (1, 19) (1, 21)
653 NAME 'w' (1, 21) (1, 22)
654 OP ')' (1, 22) (1, 23)
655 OP ':' (1, 23) (1, 24)
656 NAME 'pass' (1, 25) (1, 29)
657 """)
658 self.check_tokenize("def d23(a: str, b: int=3) -> int: pass", """\
659 NAME 'def' (1, 0) (1, 3)
660 NAME 'd23' (1, 4) (1, 7)
661 OP '(' (1, 7) (1, 8)
662 NAME 'a' (1, 8) (1, 9)
663 OP ':' (1, 9) (1, 10)
664 NAME 'str' (1, 11) (1, 14)
665 OP ',' (1, 14) (1, 15)
666 NAME 'b' (1, 16) (1, 17)
667 OP ':' (1, 17) (1, 18)
668 NAME 'int' (1, 19) (1, 22)
669 OP '=' (1, 22) (1, 23)
670 NUMBER '3' (1, 23) (1, 24)
671 OP ')' (1, 24) (1, 25)
672 OP '->' (1, 26) (1, 28)
673 NAME 'int' (1, 29) (1, 32)
674 OP ':' (1, 32) (1, 33)
675 NAME 'pass' (1, 34) (1, 38)
676 """)
677
678 def test_comparison(self):
679 # Comparison
680 self.check_tokenize("if 1 < 1 > 1 == 1 >= 5 <= 0x15 <= 0x12 != "
681 "1 and 5 in 1 not in 1 is 1 or 5 is not 1: pass", """\
682 NAME 'if' (1, 0) (1, 2)
683 NUMBER '1' (1, 3) (1, 4)
684 OP '<' (1, 5) (1, 6)
685 NUMBER '1' (1, 7) (1, 8)
686 OP '>' (1, 9) (1, 10)
687 NUMBER '1' (1, 11) (1, 12)
688 OP '==' (1, 13) (1, 15)
689 NUMBER '1' (1, 16) (1, 17)
690 OP '>=' (1, 18) (1, 20)
691 NUMBER '5' (1, 21) (1, 22)
692 OP '<=' (1, 23) (1, 25)
693 NUMBER '0x15' (1, 26) (1, 30)
694 OP '<=' (1, 31) (1, 33)
695 NUMBER '0x12' (1, 34) (1, 38)
696 OP '!=' (1, 39) (1, 41)
697 NUMBER '1' (1, 42) (1, 43)
698 NAME 'and' (1, 44) (1, 47)
699 NUMBER '5' (1, 48) (1, 49)
700 NAME 'in' (1, 50) (1, 52)
701 NUMBER '1' (1, 53) (1, 54)
702 NAME 'not' (1, 55) (1, 58)
703 NAME 'in' (1, 59) (1, 61)
704 NUMBER '1' (1, 62) (1, 63)
705 NAME 'is' (1, 64) (1, 66)
706 NUMBER '1' (1, 67) (1, 68)
707 NAME 'or' (1, 69) (1, 71)
708 NUMBER '5' (1, 72) (1, 73)
709 NAME 'is' (1, 74) (1, 76)
710 NAME 'not' (1, 77) (1, 80)
711 NUMBER '1' (1, 81) (1, 82)
712 OP ':' (1, 82) (1, 83)
713 NAME 'pass' (1, 84) (1, 88)
714 """)
715
716 def test_shift(self):
717 # Shift
718 self.check_tokenize("x = 1 << 1 >> 5", """\
719 NAME 'x' (1, 0) (1, 1)
720 OP '=' (1, 2) (1, 3)
721 NUMBER '1' (1, 4) (1, 5)
722 OP '<<' (1, 6) (1, 8)
723 NUMBER '1' (1, 9) (1, 10)
724 OP '>>' (1, 11) (1, 13)
725 NUMBER '5' (1, 14) (1, 15)
726 """)
727
728 def test_additive(self):
729 # Additive
730 self.check_tokenize("x = 1 - y + 15 - 1 + 0x124 + z + a[5]", """\
731 NAME 'x' (1, 0) (1, 1)
732 OP '=' (1, 2) (1, 3)
733 NUMBER '1' (1, 4) (1, 5)
734 OP '-' (1, 6) (1, 7)
735 NAME 'y' (1, 8) (1, 9)
736 OP '+' (1, 10) (1, 11)
737 NUMBER '15' (1, 12) (1, 14)
738 OP '-' (1, 15) (1, 16)
739 NUMBER '1' (1, 17) (1, 18)
740 OP '+' (1, 19) (1, 20)
741 NUMBER '0x124' (1, 21) (1, 26)
742 OP '+' (1, 27) (1, 28)
743 NAME 'z' (1, 29) (1, 30)
744 OP '+' (1, 31) (1, 32)
745 NAME 'a' (1, 33) (1, 34)
746 OP '[' (1, 34) (1, 35)
747 NUMBER '5' (1, 35) (1, 36)
748 OP ']' (1, 36) (1, 37)
749 """)
750
751 def test_multiplicative(self):
752 # Multiplicative
753 self.check_tokenize("x = 1//1*1/5*12%0x12@42", """\
754 NAME 'x' (1, 0) (1, 1)
755 OP '=' (1, 2) (1, 3)
756 NUMBER '1' (1, 4) (1, 5)
757 OP '//' (1, 5) (1, 7)
758 NUMBER '1' (1, 7) (1, 8)
759 OP '*' (1, 8) (1, 9)
760 NUMBER '1' (1, 9) (1, 10)
761 OP '/' (1, 10) (1, 11)
762 NUMBER '5' (1, 11) (1, 12)
763 OP '*' (1, 12) (1, 13)
764 NUMBER '12' (1, 13) (1, 15)
765 OP '%' (1, 15) (1, 16)
766 NUMBER '0x12' (1, 16) (1, 20)
767 OP '@' (1, 20) (1, 21)
768 NUMBER '42' (1, 21) (1, 23)
769 """)
770
771 def test_unary(self):
772 # Unary
773 self.check_tokenize("~1 ^ 1 & 1 |1 ^ -1", """\
774 OP '~' (1, 0) (1, 1)
775 NUMBER '1' (1, 1) (1, 2)
776 OP '^' (1, 3) (1, 4)
777 NUMBER '1' (1, 5) (1, 6)
778 OP '&' (1, 7) (1, 8)
779 NUMBER '1' (1, 9) (1, 10)
780 OP '|' (1, 11) (1, 12)
781 NUMBER '1' (1, 12) (1, 13)
782 OP '^' (1, 14) (1, 15)
783 OP '-' (1, 16) (1, 17)
784 NUMBER '1' (1, 17) (1, 18)
785 """)
786 self.check_tokenize("-1*1/1+1*1//1 - ---1**1", """\
787 OP '-' (1, 0) (1, 1)
788 NUMBER '1' (1, 1) (1, 2)
789 OP '*' (1, 2) (1, 3)
790 NUMBER '1' (1, 3) (1, 4)
791 OP '/' (1, 4) (1, 5)
792 NUMBER '1' (1, 5) (1, 6)
793 OP '+' (1, 6) (1, 7)
794 NUMBER '1' (1, 7) (1, 8)
795 OP '*' (1, 8) (1, 9)
796 NUMBER '1' (1, 9) (1, 10)
797 OP '//' (1, 10) (1, 12)
798 NUMBER '1' (1, 12) (1, 13)
799 OP '-' (1, 14) (1, 15)
800 OP '-' (1, 16) (1, 17)
801 OP '-' (1, 17) (1, 18)
802 OP '-' (1, 18) (1, 19)
803 NUMBER '1' (1, 19) (1, 20)
804 OP '**' (1, 20) (1, 22)
805 NUMBER '1' (1, 22) (1, 23)
806 """)
807
808 def test_selector(self):
809 # Selector
810 self.check_tokenize("import sys, time\nx = sys.modules['time'].time()", """\
811 NAME 'import' (1, 0) (1, 6)
812 NAME 'sys' (1, 7) (1, 10)
813 OP ',' (1, 10) (1, 11)
814 NAME 'time' (1, 12) (1, 16)
815 NEWLINE '\\n' (1, 16) (1, 17)
816 NAME 'x' (2, 0) (2, 1)
817 OP '=' (2, 2) (2, 3)
818 NAME 'sys' (2, 4) (2, 7)
819 OP '.' (2, 7) (2, 8)
820 NAME 'modules' (2, 8) (2, 15)
821 OP '[' (2, 15) (2, 16)
822 STRING "'time'" (2, 16) (2, 22)
823 OP ']' (2, 22) (2, 23)
824 OP '.' (2, 23) (2, 24)
825 NAME 'time' (2, 24) (2, 28)
826 OP '(' (2, 28) (2, 29)
827 OP ')' (2, 29) (2, 30)
828 """)
829
830 def test_method(self):
831 # Methods
832 self.check_tokenize("@staticmethod\ndef foo(x,y): pass", """\
833 OP '@' (1, 0) (1, 1)
834 NAME 'staticmethod' (1, 1) (1, 13)
835 NEWLINE '\\n' (1, 13) (1, 14)
836 NAME 'def' (2, 0) (2, 3)
837 NAME 'foo' (2, 4) (2, 7)
838 OP '(' (2, 7) (2, 8)
839 NAME 'x' (2, 8) (2, 9)
840 OP ',' (2, 9) (2, 10)
841 NAME 'y' (2, 10) (2, 11)
842 OP ')' (2, 11) (2, 12)
843 OP ':' (2, 12) (2, 13)
844 NAME 'pass' (2, 14) (2, 18)
845 """)
846
847 def test_tabs(self):
848 # Evil tabs
849 self.check_tokenize("def f():\n"
850 "\tif x\n"
851 " \tpass", """\
852 NAME 'def' (1, 0) (1, 3)
853 NAME 'f' (1, 4) (1, 5)
854 OP '(' (1, 5) (1, 6)
855 OP ')' (1, 6) (1, 7)
856 OP ':' (1, 7) (1, 8)
857 NEWLINE '\\n' (1, 8) (1, 9)
858 INDENT '\\t' (2, 0) (2, 1)
859 NAME 'if' (2, 1) (2, 3)
860 NAME 'x' (2, 4) (2, 5)
861 NEWLINE '\\n' (2, 5) (2, 6)
862 INDENT ' \\t' (3, 0) (3, 9)
863 NAME 'pass' (3, 9) (3, 13)
864 DEDENT '' (4, 0) (4, 0)
865 DEDENT '' (4, 0) (4, 0)
866 """)
867
868 def test_non_ascii_identifiers(self):
869 # Non-ascii identifiers
870 self.check_tokenize("Örter = 'places'\ngrün = 'green'", """\
871 NAME 'Örter' (1, 0) (1, 5)
872 OP '=' (1, 6) (1, 7)
873 STRING "'places'" (1, 8) (1, 16)
874 NEWLINE '\\n' (1, 16) (1, 17)
875 NAME 'grün' (2, 0) (2, 4)
876 OP '=' (2, 5) (2, 6)
877 STRING "'green'" (2, 7) (2, 14)
878 """)
879
880 def test_unicode(self):
881 # Legacy unicode literals:
882 self.check_tokenize("Örter = u'places'\ngrün = U'green'", """\
883 NAME 'Örter' (1, 0) (1, 5)
884 OP '=' (1, 6) (1, 7)
885 STRING "u'places'" (1, 8) (1, 17)
886 NEWLINE '\\n' (1, 17) (1, 18)
887 NAME 'grün' (2, 0) (2, 4)
888 OP '=' (2, 5) (2, 6)
889 STRING "U'green'" (2, 7) (2, 15)
890 """)
891
892 def test_async(self):
893 # Async/await extension:
894 self.check_tokenize("async = 1", """\
895 NAME 'async' (1, 0) (1, 5)
896 OP '=' (1, 6) (1, 7)
897 NUMBER '1' (1, 8) (1, 9)
898 """)
899
900 self.check_tokenize("a = (async = 1)", """\
901 NAME 'a' (1, 0) (1, 1)
902 OP '=' (1, 2) (1, 3)
903 OP '(' (1, 4) (1, 5)
904 NAME 'async' (1, 5) (1, 10)
905 OP '=' (1, 11) (1, 12)
906 NUMBER '1' (1, 13) (1, 14)
907 OP ')' (1, 14) (1, 15)
908 """)
909
910 self.check_tokenize("async()", """\
911 NAME 'async' (1, 0) (1, 5)
912 OP '(' (1, 5) (1, 6)
913 OP ')' (1, 6) (1, 7)
914 """)
915
916 self.check_tokenize("class async(Bar):pass", """\
917 NAME 'class' (1, 0) (1, 5)
918 NAME 'async' (1, 6) (1, 11)
919 OP '(' (1, 11) (1, 12)
920 NAME 'Bar' (1, 12) (1, 15)
921 OP ')' (1, 15) (1, 16)
922 OP ':' (1, 16) (1, 17)
923 NAME 'pass' (1, 17) (1, 21)
924 """)
925
926 self.check_tokenize("class async:pass", """\
927 NAME 'class' (1, 0) (1, 5)
928 NAME 'async' (1, 6) (1, 11)
929 OP ':' (1, 11) (1, 12)
930 NAME 'pass' (1, 12) (1, 16)
931 """)
932
933 self.check_tokenize("await = 1", """\
934 NAME 'await' (1, 0) (1, 5)
935 OP '=' (1, 6) (1, 7)
936 NUMBER '1' (1, 8) (1, 9)
937 """)
938
939 self.check_tokenize("foo.async", """\
940 NAME 'foo' (1, 0) (1, 3)
941 OP '.' (1, 3) (1, 4)
942 NAME 'async' (1, 4) (1, 9)
943 """)
944
945 self.check_tokenize("async for a in b: pass", """\
946 NAME 'async' (1, 0) (1, 5)
947 NAME 'for' (1, 6) (1, 9)
948 NAME 'a' (1, 10) (1, 11)
949 NAME 'in' (1, 12) (1, 14)
950 NAME 'b' (1, 15) (1, 16)
951 OP ':' (1, 16) (1, 17)
952 NAME 'pass' (1, 18) (1, 22)
953 """)
954
955 self.check_tokenize("async with a as b: pass", """\
956 NAME 'async' (1, 0) (1, 5)
957 NAME 'with' (1, 6) (1, 10)
958 NAME 'a' (1, 11) (1, 12)
959 NAME 'as' (1, 13) (1, 15)
960 NAME 'b' (1, 16) (1, 17)
961 OP ':' (1, 17) (1, 18)
962 NAME 'pass' (1, 19) (1, 23)
963 """)
964
965 self.check_tokenize("async.foo", """\
966 NAME 'async' (1, 0) (1, 5)
967 OP '.' (1, 5) (1, 6)
968 NAME 'foo' (1, 6) (1, 9)
969 """)
970
971 self.check_tokenize("async", """\
972 NAME 'async' (1, 0) (1, 5)
973 """)
974
975 self.check_tokenize("async\n#comment\nawait", """\
976 NAME 'async' (1, 0) (1, 5)
977 NEWLINE '\\n' (1, 5) (1, 6)
978 COMMENT '#comment' (2, 0) (2, 8)
979 NL '\\n' (2, 8) (2, 9)
980 NAME 'await' (3, 0) (3, 5)
981 """)
982
983 self.check_tokenize("async\n...\nawait", """\
984 NAME 'async' (1, 0) (1, 5)
985 NEWLINE '\\n' (1, 5) (1, 6)
986 OP '...' (2, 0) (2, 3)
987 NEWLINE '\\n' (2, 3) (2, 4)
988 NAME 'await' (3, 0) (3, 5)
989 """)
990
991 self.check_tokenize("async\nawait", """\
992 NAME 'async' (1, 0) (1, 5)
993 NEWLINE '\\n' (1, 5) (1, 6)
994 NAME 'await' (2, 0) (2, 5)
995 """)
996
997 self.check_tokenize("foo.async + 1", """\
998 NAME 'foo' (1, 0) (1, 3)
999 OP '.' (1, 3) (1, 4)
1000 NAME 'async' (1, 4) (1, 9)
1001 OP '+' (1, 10) (1, 11)
1002 NUMBER '1' (1, 12) (1, 13)
1003 """)
1004
1005 self.check_tokenize("async def foo(): pass", """\
1006 NAME 'async' (1, 0) (1, 5)
1007 NAME 'def' (1, 6) (1, 9)
1008 NAME 'foo' (1, 10) (1, 13)
1009 OP '(' (1, 13) (1, 14)
1010 OP ')' (1, 14) (1, 15)
1011 OP ':' (1, 15) (1, 16)
1012 NAME 'pass' (1, 17) (1, 21)
1013 """)
1014
1015 self.check_tokenize('''\
1016 async def foo():
1017 def foo(await):
1018 await = 1
1019 if 1:
1020 await
1021 async += 1
1022 ''', """\
1023 NAME 'async' (1, 0) (1, 5)
1024 NAME 'def' (1, 6) (1, 9)
1025 NAME 'foo' (1, 10) (1, 13)
1026 OP '(' (1, 13) (1, 14)
1027 OP ')' (1, 14) (1, 15)
1028 OP ':' (1, 15) (1, 16)
1029 NEWLINE '\\n' (1, 16) (1, 17)
1030 INDENT ' ' (2, 0) (2, 2)
1031 NAME 'def' (2, 2) (2, 5)
1032 NAME 'foo' (2, 6) (2, 9)
1033 OP '(' (2, 9) (2, 10)
1034 NAME 'await' (2, 10) (2, 15)
1035 OP ')' (2, 15) (2, 16)
1036 OP ':' (2, 16) (2, 17)
1037 NEWLINE '\\n' (2, 17) (2, 18)
1038 INDENT ' ' (3, 0) (3, 4)
1039 NAME 'await' (3, 4) (3, 9)
1040 OP '=' (3, 10) (3, 11)
1041 NUMBER '1' (3, 12) (3, 13)
1042 NEWLINE '\\n' (3, 13) (3, 14)
1043 DEDENT '' (4, 2) (4, 2)
1044 NAME 'if' (4, 2) (4, 4)
1045 NUMBER '1' (4, 5) (4, 6)
1046 OP ':' (4, 6) (4, 7)
1047 NEWLINE '\\n' (4, 7) (4, 8)
1048 INDENT ' ' (5, 0) (5, 4)
1049 NAME 'await' (5, 4) (5, 9)
1050 NEWLINE '\\n' (5, 9) (5, 10)
1051 DEDENT '' (6, 0) (6, 0)
1052 DEDENT '' (6, 0) (6, 0)
1053 NAME 'async' (6, 0) (6, 5)
1054 OP '+=' (6, 6) (6, 8)
1055 NUMBER '1' (6, 9) (6, 10)
1056 NEWLINE '\\n' (6, 10) (6, 11)
1057 """)
1058
1059 self.check_tokenize('''\
1060 async def foo():
1061 async for i in 1: pass''', """\
1062 NAME 'async' (1, 0) (1, 5)
1063 NAME 'def' (1, 6) (1, 9)
1064 NAME 'foo' (1, 10) (1, 13)
1065 OP '(' (1, 13) (1, 14)
1066 OP ')' (1, 14) (1, 15)
1067 OP ':' (1, 15) (1, 16)
1068 NEWLINE '\\n' (1, 16) (1, 17)
1069 INDENT ' ' (2, 0) (2, 2)
1070 NAME 'async' (2, 2) (2, 7)
1071 NAME 'for' (2, 8) (2, 11)
1072 NAME 'i' (2, 12) (2, 13)
1073 NAME 'in' (2, 14) (2, 16)
1074 NUMBER '1' (2, 17) (2, 18)
1075 OP ':' (2, 18) (2, 19)
1076 NAME 'pass' (2, 20) (2, 24)
1077 DEDENT '' (3, 0) (3, 0)
1078 """)
1079
1080 self.check_tokenize('''async def foo(async): await''', """\
1081 NAME 'async' (1, 0) (1, 5)
1082 NAME 'def' (1, 6) (1, 9)
1083 NAME 'foo' (1, 10) (1, 13)
1084 OP '(' (1, 13) (1, 14)
1085 NAME 'async' (1, 14) (1, 19)
1086 OP ')' (1, 19) (1, 20)
1087 OP ':' (1, 20) (1, 21)
1088 NAME 'await' (1, 22) (1, 27)
1089 """)
1090
1091 self.check_tokenize('''\
1092 def f():
1093
1094 def baz(): pass
1095 async def bar(): pass
1096
1097 await = 2''', """\
1098 NAME 'def' (1, 0) (1, 3)
1099 NAME 'f' (1, 4) (1, 5)
1100 OP '(' (1, 5) (1, 6)
1101 OP ')' (1, 6) (1, 7)
1102 OP ':' (1, 7) (1, 8)
1103 NEWLINE '\\n' (1, 8) (1, 9)
1104 NL '\\n' (2, 0) (2, 1)
1105 INDENT ' ' (3, 0) (3, 2)
1106 NAME 'def' (3, 2) (3, 5)
1107 NAME 'baz' (3, 6) (3, 9)
1108 OP '(' (3, 9) (3, 10)
1109 OP ')' (3, 10) (3, 11)
1110 OP ':' (3, 11) (3, 12)
1111 NAME 'pass' (3, 13) (3, 17)
1112 NEWLINE '\\n' (3, 17) (3, 18)
1113 NAME 'async' (4, 2) (4, 7)
1114 NAME 'def' (4, 8) (4, 11)
1115 NAME 'bar' (4, 12) (4, 15)
1116 OP '(' (4, 15) (4, 16)
1117 OP ')' (4, 16) (4, 17)
1118 OP ':' (4, 17) (4, 18)
1119 NAME 'pass' (4, 19) (4, 23)
1120 NEWLINE '\\n' (4, 23) (4, 24)
1121 NL '\\n' (5, 0) (5, 1)
1122 NAME 'await' (6, 2) (6, 7)
1123 OP '=' (6, 8) (6, 9)
1124 NUMBER '2' (6, 10) (6, 11)
1125 DEDENT '' (7, 0) (7, 0)
1126 """)
1127
1128 self.check_tokenize('''\
1129 async def f():
1130
1131 def baz(): pass
1132 async def bar(): pass
1133
1134 await = 2''', """\
1135 NAME 'async' (1, 0) (1, 5)
1136 NAME 'def' (1, 6) (1, 9)
1137 NAME 'f' (1, 10) (1, 11)
1138 OP '(' (1, 11) (1, 12)
1139 OP ')' (1, 12) (1, 13)
1140 OP ':' (1, 13) (1, 14)
1141 NEWLINE '\\n' (1, 14) (1, 15)
1142 NL '\\n' (2, 0) (2, 1)
1143 INDENT ' ' (3, 0) (3, 2)
1144 NAME 'def' (3, 2) (3, 5)
1145 NAME 'baz' (3, 6) (3, 9)
1146 OP '(' (3, 9) (3, 10)
1147 OP ')' (3, 10) (3, 11)
1148 OP ':' (3, 11) (3, 12)
1149 NAME 'pass' (3, 13) (3, 17)
1150 NEWLINE '\\n' (3, 17) (3, 18)
1151 NAME 'async' (4, 2) (4, 7)
1152 NAME 'def' (4, 8) (4, 11)
1153 NAME 'bar' (4, 12) (4, 15)
1154 OP '(' (4, 15) (4, 16)
1155 OP ')' (4, 16) (4, 17)
1156 OP ':' (4, 17) (4, 18)
1157 NAME 'pass' (4, 19) (4, 23)
1158 NEWLINE '\\n' (4, 23) (4, 24)
1159 NL '\\n' (5, 0) (5, 1)
1160 NAME 'await' (6, 2) (6, 7)
1161 OP '=' (6, 8) (6, 9)
1162 NUMBER '2' (6, 10) (6, 11)
1163 DEDENT '' (7, 0) (7, 0)
1164 """)
1165
1166 def test_newline_after_parenthesized_block_with_comment(self):
1167 self.check_tokenize('''\
1168 [
1169 # A comment here
1170 1
1171 ]
1172 ''', """\
1173 OP '[' (1, 0) (1, 1)
1174 NL '\\n' (1, 1) (1, 2)
1175 COMMENT '# A comment here' (2, 4) (2, 20)
1176 NL '\\n' (2, 20) (2, 21)
1177 NUMBER '1' (3, 4) (3, 5)
1178 NL '\\n' (3, 5) (3, 6)
1179 OP ']' (4, 0) (4, 1)
1180 NEWLINE '\\n' (4, 1) (4, 2)
1181 """)
1182
1183 def test_closing_parenthesis_from_different_line(self):
1184 self.check_tokenize("); x", """\
1185 OP ')' (1, 0) (1, 1)
1186 OP ';' (1, 1) (1, 2)
1187 NAME 'x' (1, 3) (1, 4)
1188 """)
1189
1190 def test_multiline_non_ascii_fstring(self):
1191 self.check_tokenize("""\
1192 a = f'''
1193 Autorzy, którzy tą jednostkę mają wpisani jako AKTUALNA -- czyli'''""", """\
1194 NAME 'a' (1, 0) (1, 1)
1195 OP '=' (1, 2) (1, 3)
1196 FSTRING_START "f\'\'\'" (1, 4) (1, 8)
1197 FSTRING_MIDDLE '\\n Autorzy, którzy tą jednostkę mają wpisani jako AKTUALNA -- czyli' (1, 8) (2, 68)
1198 FSTRING_END "\'\'\'" (2, 68) (2, 71)
1199 """)
1200
1201 def test_multiline_non_ascii_fstring_with_expr(self):
1202 self.check_tokenize("""\
1203 f'''
1204 🔗 This is a test {test_arg1}🔗
1205 🔗'''""", """\
1206 FSTRING_START "f\'\'\'" (1, 0) (1, 4)
1207 FSTRING_MIDDLE '\\n 🔗 This is a test ' (1, 4) (2, 21)
1208 OP '{' (2, 21) (2, 22)
1209 NAME 'test_arg1' (2, 22) (2, 31)
1210 OP '}' (2, 31) (2, 32)
1211 FSTRING_MIDDLE '🔗\\n🔗' (2, 32) (3, 1)
1212 FSTRING_END "\'\'\'" (3, 1) (3, 4)
1213 """)
1214
1215 # gh-139516, the '\n' is explicit to ensure no trailing whitespace which would invalidate the test
1216 self.check_tokenize('''f"{f(a=lambda: 'à'\n)}"''', """\
1217 FSTRING_START \'f"\' (1, 0) (1, 2)
1218 OP '{' (1, 2) (1, 3)
1219 NAME 'f' (1, 3) (1, 4)
1220 OP '(' (1, 4) (1, 5)
1221 NAME 'a' (1, 5) (1, 6)
1222 OP '=' (1, 6) (1, 7)
1223 NAME 'lambda' (1, 7) (1, 13)
1224 OP ':' (1, 13) (1, 14)
1225 STRING "\'à\'" (1, 15) (1, 18)
1226 NL '\\n' (1, 18) (1, 19)
1227 OP ')' (2, 0) (2, 1)
1228 OP '}' (2, 1) (2, 2)
1229 FSTRING_END \'"\' (2, 2) (2, 3)
1230 """)
1231
1232 class GenerateTokensTest(TokenizeTest):
1233 def check_tokenize(self, s, expected):
1234 # Format the tokens in s in a table format.
1235 # The ENDMARKER and final NEWLINE are omitted.
1236 f = StringIO(s)
1237 result = stringify_tokens_from_source(tokenize.generate_tokens(f.readline), s)
1238 self.assertEqual(result, expected.rstrip().splitlines())
1239
1240
1241 def decistmt(s):
1242 result = []
1243 g = tokenize.tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string
1244 for toknum, tokval, _, _, _ in g:
1245 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens
1246 result.extend([
1247 (tokenize.NAME, 'Decimal'),
1248 (tokenize.OP, '('),
1249 (tokenize.STRING, repr(tokval)),
1250 (tokenize.OP, ')')
1251 ])
1252 else:
1253 result.append((toknum, tokval))
1254 return tokenize.untokenize(result).decode('utf-8').strip()
1255
1256 class TestMisc(TestCase):
1257
1258 def test_decistmt(self):
1259 # Substitute Decimals for floats in a string of statements.
1260 # This is an example from the docs.
1261
1262 from decimal import Decimal
1263 s = '+21.3e-5*-.1234/81.7'
1264 self.assertEqual(decistmt(s),
1265 "+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')")
1266
1267 # The format of the exponent is inherited from the platform C library.
1268 # Known cases are "e-007" (Windows) and "e-07" (not Windows). Since
1269 # we're only showing 11 digits, and the 12th isn't close to 5, the
1270 # rest of the output should be platform-independent.
1271 self.assertRegex(repr(eval(s)), '-3.2171603427[0-9]*e-0+7')
1272
1273 # Output from calculations with Decimal should be identical across all
1274 # platforms.
1275 self.assertEqual(eval(decistmt(s)),
1276 Decimal('-3.217160342717258261933904529E-7'))
1277
1278 def test___all__(self):
1279 expected = token.__all__ + [
1280 "TokenInfo", "TokenError", "generate_tokens",
1281 "detect_encoding", "untokenize", "open", "tokenize",
1282 ]
1283 self.assertCountEqual(tokenize.__all__, expected)
1284
1285
1286 class TestTokenizerAdheresToPep0263(TestCase):
1287 """
1288 Test that tokenizer adheres to the coding behaviour stipulated in PEP 0263.
1289 """
1290
1291 def _testFile(self, filename):
1292 path = os.path.join(os.path.dirname(__file__), 'tokenizedata', filename)
1293 with open(path, 'rb') as f:
1294 TestRoundtrip.check_roundtrip(self, f)
1295
1296 def test_utf8_coding_cookie_and_no_utf8_bom(self):
1297 f = 'tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt'
1298 self._testFile(f)
1299
1300 def test_latin1_coding_cookie_and_utf8_bom(self):
1301 """
1302 As per PEP 0263, if a file starts with a utf-8 BOM signature, the only
1303 allowed encoding for the comment is 'utf-8'. The text file used in
1304 this test starts with a BOM signature, but specifies latin1 as the
1305 coding, so verify that a SyntaxError is raised, which matches the
1306 behaviour of the interpreter when it encounters a similar condition.
1307 """
1308 f = 'tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt'
1309 self.assertRaises(SyntaxError, self._testFile, f)
1310
1311 def test_no_coding_cookie_and_utf8_bom(self):
1312 f = 'tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt'
1313 self._testFile(f)
1314
1315 def test_utf8_coding_cookie_and_utf8_bom(self):
1316 f = 'tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt'
1317 self._testFile(f)
1318
1319 def test_bad_coding_cookie(self):
1320 self.assertRaises(SyntaxError, self._testFile, 'bad_coding.py')
1321 self.assertRaises(SyntaxError, self._testFile, 'bad_coding2.py')
1322
1323
1324 class Test_Tokenize(TestCase):
1325
1326 def test__tokenize_decodes_with_specified_encoding(self):
1327 literal = '"ЉЊЈЁЂ"'
1328 line = literal.encode('utf-8')
1329 first = False
1330 def readline():
1331 nonlocal first
1332 if not first:
1333 first = True
1334 yield line
1335 else:
1336 yield b''
1337
1338 # skip the initial encoding token and the end tokens
1339 tokens = list(tokenize._generate_tokens_from_c_tokenizer(readline().__next__,
1340 encoding='utf-8',
1341 extra_tokens=True))[:-2]
1342 expected_tokens = [tokenize.TokenInfo(3, '"ЉЊЈЁЂ"', (1, 0), (1, 7), '"ЉЊЈЁЂ"')]
1343 self.assertEqual(tokens, expected_tokens,
1344 "bytes not decoded with encoding")
1345
1346
1347 class TestDetectEncoding(TestCase):
1348
1349 def get_readline(self, lines):
1350 index = 0
1351 def readline():
1352 nonlocal index
1353 if index == len(lines):
1354 raise StopIteration
1355 line = lines[index]
1356 index += 1
1357 return line
1358 return readline
1359
1360 def test_no_bom_no_encoding_cookie(self):
1361 lines = (
1362 b'#!/home/\xc3\xa4/bin/python\n',
1363 b'# something \xe2\x82\xac\n',
1364 b'print(something)\n',
1365 b'do_something(else)\n'
1366 )
1367 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1368 self.assertEqual(encoding, 'utf-8')
1369 self.assertEqual(consumed_lines, list(lines[:2]))
1370
1371 def test_no_bom_no_encoding_cookie_first_line_error(self):
1372 lines = (
1373 b'#!/home/\xa4/bin/python\n\n',
1374 b'print(something)\n',
1375 b'do_something(else)\n'
1376 )
1377 with self.assertRaises(SyntaxError):
1378 tokenize.detect_encoding(self.get_readline(lines))
1379
1380 def test_no_bom_no_encoding_cookie_second_line_error(self):
1381 lines = (
1382 b'#!/usr/bin/python\n',
1383 b'# something \xe2\n',
1384 b'print(something)\n',
1385 b'do_something(else)\n'
1386 )
1387 with self.assertRaises(SyntaxError):
1388 tokenize.detect_encoding(self.get_readline(lines))
1389
1390 def test_bom_no_cookie(self):
1391 lines = (
1392 b'\xef\xbb\xbf#!/home/\xc3\xa4/bin/python\n',
1393 b'print(something)\n',
1394 b'do_something(else)\n'
1395 )
1396 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1397 self.assertEqual(encoding, 'utf-8-sig')
1398 self.assertEqual(consumed_lines,
1399 [b'#!/home/\xc3\xa4/bin/python\n', b'print(something)\n'])
1400
1401 def test_bom_no_cookie_first_line_error(self):
1402 lines = (
1403 b'\xef\xbb\xbf#!/home/\xa4/bin/python\n',
1404 b'print(something)\n',
1405 b'do_something(else)\n'
1406 )
1407 with self.assertRaises(SyntaxError):
1408 tokenize.detect_encoding(self.get_readline(lines))
1409
1410 def test_bom_no_cookie_second_line_error(self):
1411 lines = (
1412 b'\xef\xbb\xbf#!/usr/bin/python\n',
1413 b'# something \xe2\n',
1414 b'print(something)\n',
1415 b'do_something(else)\n'
1416 )
1417 with self.assertRaises(SyntaxError):
1418 tokenize.detect_encoding(self.get_readline(lines))
1419
1420 def test_cookie_first_line_no_bom(self):
1421 lines = (
1422 b'# -*- coding: latin-1 -*-\n',
1423 b'print(something)\n',
1424 b'do_something(else)\n'
1425 )
1426 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1427 self.assertEqual(encoding, 'iso-8859-1')
1428 self.assertEqual(consumed_lines, [b'# -*- coding: latin-1 -*-\n'])
1429
1430 def test_matched_bom_and_cookie_first_line(self):
1431 lines = (
1432 b'\xef\xbb\xbf# coding=utf-8\n',
1433 b'print(something)\n',
1434 b'do_something(else)\n'
1435 )
1436 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1437 self.assertEqual(encoding, 'utf-8-sig')
1438 self.assertEqual(consumed_lines, [b'# coding=utf-8\n'])
1439
1440 def test_mismatched_bom_and_cookie_first_line_raises_syntaxerror(self):
1441 lines = (
1442 b'\xef\xbb\xbf# vim: set fileencoding=ascii :\n',
1443 b'print(something)\n',
1444 b'do_something(else)\n'
1445 )
1446 readline = self.get_readline(lines)
1447 self.assertRaises(SyntaxError, tokenize.detect_encoding, readline)
1448
1449 def test_cookie_second_line_no_bom(self):
1450 lines = (
1451 b'#! something\n',
1452 b'# vim: set fileencoding=ascii :\n',
1453 b'print(something)\n',
1454 b'do_something(else)\n'
1455 )
1456 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1457 self.assertEqual(encoding, 'ascii')
1458 expected = [b'#! something\n', b'# vim: set fileencoding=ascii :\n']
1459 self.assertEqual(consumed_lines, expected)
1460
1461 def test_matched_bom_and_cookie_second_line(self):
1462 lines = (
1463 b'\xef\xbb\xbf#! something\n',
1464 b'f# coding=utf-8\n',
1465 b'print(something)\n',
1466 b'do_something(else)\n'
1467 )
1468 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1469 self.assertEqual(encoding, 'utf-8-sig')
1470 self.assertEqual(consumed_lines,
1471 [b'#! something\n', b'f# coding=utf-8\n'])
1472
1473 def test_mismatched_bom_and_cookie_second_line_raises_syntaxerror(self):
1474 lines = (
1475 b'\xef\xbb\xbf#! something\n',
1476 b'# vim: set fileencoding=ascii :\n',
1477 b'print(something)\n',
1478 b'do_something(else)\n'
1479 )
1480 readline = self.get_readline(lines)
1481 self.assertRaises(SyntaxError, tokenize.detect_encoding, readline)
1482
1483 def test_cookie_second_line_noncommented_first_line(self):
1484 lines = (
1485 b"print('\xc2\xa3')\n",
1486 b'# vim: set fileencoding=iso8859-15 :\n',
1487 b"print('\xe2\x82\xac')\n"
1488 )
1489 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1490 self.assertEqual(encoding, 'utf-8')
1491 expected = [b"print('\xc2\xa3')\n"]
1492 self.assertEqual(consumed_lines, expected)
1493
1494 def test_cookie_second_line_empty_first_line(self):
1495 lines = (
1496 b'\n',
1497 b'# vim: set fileencoding=iso8859-15 :\n',
1498 b"print('\xe2\x82\xac')\n"
1499 )
1500 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1501 self.assertEqual(encoding, 'iso8859-15')
1502 expected = [b'\n', b'# vim: set fileencoding=iso8859-15 :\n']
1503 self.assertEqual(consumed_lines, expected)
1504
1505 def test_cookie_third_line(self):
1506 lines = (
1507 b'#!/home/\xc3\xa4/bin/python\n',
1508 b'# something\n',
1509 b'# vim: set fileencoding=ascii :\n',
1510 b'print(something)\n',
1511 b'do_something(else)\n'
1512 )
1513 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1514 self.assertEqual(encoding, 'utf-8')
1515 self.assertEqual(consumed_lines, list(lines[:2]))
1516
1517 def test_double_coding_line(self):
1518 # If the first line matches the second line is ignored.
1519 lines = (
1520 b'#coding:iso8859-15\n',
1521 b'#coding:latin1\n',
1522 b'print(something)\n'
1523 )
1524 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1525 self.assertEqual(encoding, 'iso8859-15')
1526 self.assertEqual(consumed_lines, list(lines[:1]))
1527
1528 def test_double_coding_same_line(self):
1529 lines = (
1530 b'#coding:iso8859-15 coding:latin1\n',
1531 b'print(something)\n'
1532 )
1533 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1534 self.assertEqual(encoding, 'iso8859-15')
1535 self.assertEqual(consumed_lines, list(lines[:1]))
1536
1537 def test_double_coding_utf8(self):
1538 lines = (
1539 b'#coding:utf-8\n',
1540 b'#coding:latin1\n',
1541 b'print(something)\n'
1542 )
1543 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(lines))
1544 self.assertEqual(encoding, 'utf-8')
1545 self.assertEqual(consumed_lines, list(lines[:1]))
1546
1547 def test_latin1_normalization(self):
1548 # See get_normal_name() in Parser/tokenizer/helpers.c.
1549 encodings = ("latin-1", "iso-8859-1", "iso-latin-1", "latin-1-unix",
1550 "iso-8859-1-unix", "iso-latin-1-mac")
1551 for encoding in encodings:
1552 for rep in ("-", "_"):
1553 enc = encoding.replace("-", rep)
1554 lines = (b"#!/usr/bin/python\n",
1555 b"# coding: " + enc.encode("ascii") + b"\n",
1556 b"print(things)\n",
1557 b"do_something += 4\n")
1558 rl = self.get_readline(lines)
1559 found, consumed_lines = tokenize.detect_encoding(rl)
1560 self.assertEqual(found, "iso-8859-1")
1561
1562 def test_syntaxerror_latin1(self):
1563 # Issue 14629: need to raise TokenError if the first
1564 # line(s) have non-UTF-8 characters
1565 lines = (
1566 b'print("\xdf")', # Latin-1: LATIN SMALL LETTER SHARP S
1567 )
1568 readline = self.get_readline(lines)
1569 self.assertRaises(SyntaxError, tokenize.detect_encoding, readline)
1570
1571 def test_utf8_normalization(self):
1572 # See get_normal_name() in Parser/tokenizer/helpers.c.
1573 encodings = ("utf-8", "utf-8-mac", "utf-8-unix")
1574 for encoding in encodings:
1575 for rep in ("-", "_"):
1576 enc = encoding.replace("-", rep)
1577 lines = (b"#!/usr/bin/python\n",
1578 b"# coding: " + enc.encode("ascii") + b"\n",
1579 b"1 + 3\n")
1580 rl = self.get_readline(lines)
1581 found, consumed_lines = tokenize.detect_encoding(rl)
1582 self.assertEqual(found, "utf-8")
1583
1584 def test_short_files(self):
1585 readline = self.get_readline((b'print(something)\n',))
1586 encoding, consumed_lines = tokenize.detect_encoding(readline)
1587 self.assertEqual(encoding, 'utf-8')
1588 self.assertEqual(consumed_lines, [b'print(something)\n'])
1589
1590 encoding, consumed_lines = tokenize.detect_encoding(self.get_readline(()))
1591 self.assertEqual(encoding, 'utf-8')
1592 self.assertEqual(consumed_lines, [])
1593
1594 readline = self.get_readline((b'\xef\xbb\xbfprint(something)\n',))
1595 encoding, consumed_lines = tokenize.detect_encoding(readline)
1596 self.assertEqual(encoding, 'utf-8-sig')
1597 self.assertEqual(consumed_lines, [b'print(something)\n'])
1598
1599 readline = self.get_readline((b'\xef\xbb\xbf',))
1600 encoding, consumed_lines = tokenize.detect_encoding(readline)
1601 self.assertEqual(encoding, 'utf-8-sig')
1602 self.assertEqual(consumed_lines, [])
1603
1604 readline = self.get_readline((b'# coding: bad\n',))
1605 self.assertRaises(SyntaxError, tokenize.detect_encoding, readline)
1606
1607 def test_false_encoding(self):
1608 # Issue 18873: "Encoding" detected in non-comment lines
1609 readline = self.get_readline((b'print("#coding=fake")',))
1610 encoding, consumed_lines = tokenize.detect_encoding(readline)
1611 self.assertEqual(encoding, 'utf-8')
1612 self.assertEqual(consumed_lines, [b'print("#coding=fake")'])
1613
1614 def test_open(self):
1615 filename = os_helper.TESTFN + '.py'
1616 self.addCleanup(os_helper.unlink, filename)
1617
1618 # test coding cookie
1619 for encoding in ('iso-8859-15', 'utf-8'):
1620 with open(filename, 'w', encoding=encoding) as fp:
1621 print("# coding: %s" % encoding, file=fp)
1622 print("print('euro:\u20ac')", file=fp)
1623 with tokenize.open(filename) as fp:
1624 self.assertEqual(fp.encoding, encoding)
1625 self.assertEqual(fp.mode, 'r')
1626
1627 # test BOM (no coding cookie)
1628 with open(filename, 'w', encoding='utf-8-sig') as fp:
1629 print("print('euro:\u20ac')", file=fp)
1630 with tokenize.open(filename) as fp:
1631 self.assertEqual(fp.encoding, 'utf-8-sig')
1632 self.assertEqual(fp.mode, 'r')
1633
1634 def test_filename_in_exception(self):
1635 # When possible, include the file name in the exception.
1636 path = 'some_file_path'
1637 lines = (
1638 b'print("\xdf")', # Latin-1: LATIN SMALL LETTER SHARP S
1639 )
1640 class Bunk:
1641 def __init__(self, lines, path):
1642 self.name = path
1643 self._lines = lines
1644 self._index = 0
1645
1646 def readline(self):
1647 if self._index == len(lines):
1648 raise StopIteration
1649 line = lines[self._index]
1650 self._index += 1
1651 return line
1652
1653 with self.assertRaises(SyntaxError):
1654 ins = Bunk(lines, path)
1655 # Make sure lacking a name isn't an issue.
1656 del ins.name
1657 tokenize.detect_encoding(ins.readline)
1658 with self.assertRaisesRegex(SyntaxError, '.*{}'.format(path)):
1659 ins = Bunk(lines, path)
1660 tokenize.detect_encoding(ins.readline)
1661
1662 def test_open_error(self):
1663 # Issue #23840: open() must close the binary file on error
1664 m = BytesIO(b'#coding:xxx')
1665 with mock.patch('tokenize._builtin_open', return_value=m):
1666 self.assertRaises(SyntaxError, tokenize.open, 'foobar')
1667 self.assertTrue(m.closed)
1668
1669
1670 class TestTokenize(TestCase):
1671
1672 def test_tokenize(self):
1673 import tokenize as tokenize_module
1674 encoding = "utf-8"
1675 encoding_used = None
1676 def mock_detect_encoding(readline):
1677 return encoding, [b'first', b'second']
1678
1679 def mock__tokenize(readline, encoding, **kwargs):
1680 nonlocal encoding_used
1681 encoding_used = encoding
1682 out = []
1683 while True:
1684 try:
1685 next_line = readline()
1686 except StopIteration:
1687 return out
1688 if next_line:
1689 out.append(next_line)
1690 continue
1691 return out
1692
1693 counter = 0
1694 def mock_readline():
1695 nonlocal counter
1696 counter += 1
1697 if counter == 5:
1698 return b''
1699 return str(counter).encode()
1700
1701 orig_detect_encoding = tokenize_module.detect_encoding
1702 orig_c_token = tokenize_module._generate_tokens_from_c_tokenizer
1703 tokenize_module.detect_encoding = mock_detect_encoding
1704 tokenize_module._generate_tokens_from_c_tokenizer = mock__tokenize
1705 try:
1706 results = tokenize.tokenize(mock_readline)
1707 self.assertEqual(list(results)[1:],
1708 [b'first', b'second', b'1', b'2', b'3', b'4'])
1709 finally:
1710 tokenize_module.detect_encoding = orig_detect_encoding
1711 tokenize_module._generate_tokens_from_c_tokenizer = orig_c_token
1712
1713 self.assertEqual(encoding_used, encoding)
1714
1715 def test_oneline_defs(self):
1716 buf = []
1717 for i in range(500):
1718 buf.append('def i{i}(): return {i}'.format(i=i))
1719 buf.append('OK')
1720 buf = '\n'.join(buf)
1721
1722 # Test that 500 consequent, one-line defs is OK
1723 toks = list(tokenize.tokenize(BytesIO(buf.encode('utf-8')).readline))
1724 self.assertEqual(toks[-3].string, 'OK') # [-1] is always ENDMARKER
1725 # [-2] is always NEWLINE
1726
1727 def assertExactTypeEqual(self, opstr, *optypes):
1728 tokens = list(tokenize.tokenize(BytesIO(opstr.encode('utf-8')).readline))
1729 num_optypes = len(optypes)
1730 self.assertEqual(len(tokens), 3 + num_optypes)
1731 self.assertEqual(tokenize.tok_name[tokens[0].exact_type],
1732 tokenize.tok_name[tokenize.ENCODING])
1733 for i in range(num_optypes):
1734 self.assertEqual(tokenize.tok_name[tokens[i + 1].exact_type],
1735 tokenize.tok_name[optypes[i]])
1736 self.assertEqual(tokenize.tok_name[tokens[1 + num_optypes].exact_type],
1737 tokenize.tok_name[token.NEWLINE])
1738 self.assertEqual(tokenize.tok_name[tokens[2 + num_optypes].exact_type],
1739 tokenize.tok_name[token.ENDMARKER])
1740
1741 def test_exact_type(self):
1742 self.assertExactTypeEqual('()', token.LPAR, token.RPAR)
1743 self.assertExactTypeEqual('[]', token.LSQB, token.RSQB)
1744 self.assertExactTypeEqual(':', token.COLON)
1745 self.assertExactTypeEqual(',', token.COMMA)
1746 self.assertExactTypeEqual(';', token.SEMI)
1747 self.assertExactTypeEqual('+', token.PLUS)
1748 self.assertExactTypeEqual('-', token.MINUS)
1749 self.assertExactTypeEqual('*', token.STAR)
1750 self.assertExactTypeEqual('/', token.SLASH)
1751 self.assertExactTypeEqual('|', token.VBAR)
1752 self.assertExactTypeEqual('&', token.AMPER)
1753 self.assertExactTypeEqual('<', token.LESS)
1754 self.assertExactTypeEqual('>', token.GREATER)
1755 self.assertExactTypeEqual('=', token.EQUAL)
1756 self.assertExactTypeEqual('.', token.DOT)
1757 self.assertExactTypeEqual('%', token.PERCENT)
1758 self.assertExactTypeEqual('{}', token.LBRACE, token.RBRACE)
1759 self.assertExactTypeEqual('==', token.EQEQUAL)
1760 self.assertExactTypeEqual('!=', token.NOTEQUAL)
1761 self.assertExactTypeEqual('<=', token.LESSEQUAL)
1762 self.assertExactTypeEqual('>=', token.GREATEREQUAL)
1763 self.assertExactTypeEqual('~', token.TILDE)
1764 self.assertExactTypeEqual('^', token.CIRCUMFLEX)
1765 self.assertExactTypeEqual('<<', token.LEFTSHIFT)
1766 self.assertExactTypeEqual('>>', token.RIGHTSHIFT)
1767 self.assertExactTypeEqual('**', token.DOUBLESTAR)
1768 self.assertExactTypeEqual('+=', token.PLUSEQUAL)
1769 self.assertExactTypeEqual('-=', token.MINEQUAL)
1770 self.assertExactTypeEqual('*=', token.STAREQUAL)
1771 self.assertExactTypeEqual('/=', token.SLASHEQUAL)
1772 self.assertExactTypeEqual('%=', token.PERCENTEQUAL)
1773 self.assertExactTypeEqual('&=', token.AMPEREQUAL)
1774 self.assertExactTypeEqual('|=', token.VBAREQUAL)
1775 self.assertExactTypeEqual('^=', token.CIRCUMFLEXEQUAL)
1776 self.assertExactTypeEqual('^=', token.CIRCUMFLEXEQUAL)
1777 self.assertExactTypeEqual('<<=', token.LEFTSHIFTEQUAL)
1778 self.assertExactTypeEqual('>>=', token.RIGHTSHIFTEQUAL)
1779 self.assertExactTypeEqual('**=', token.DOUBLESTAREQUAL)
1780 self.assertExactTypeEqual('//', token.DOUBLESLASH)
1781 self.assertExactTypeEqual('//=', token.DOUBLESLASHEQUAL)
1782 self.assertExactTypeEqual(':=', token.COLONEQUAL)
1783 self.assertExactTypeEqual('...', token.ELLIPSIS)
1784 self.assertExactTypeEqual('->', token.RARROW)
1785 self.assertExactTypeEqual('@', token.AT)
1786 self.assertExactTypeEqual('@=', token.ATEQUAL)
1787
1788 self.assertExactTypeEqual('a**2+b**2==c**2',
1789 tokenize.NAME, token.DOUBLESTAR, tokenize.NUMBER,
1790 token.PLUS,
1791 tokenize.NAME, token.DOUBLESTAR, tokenize.NUMBER,
1792 token.EQEQUAL,
1793 tokenize.NAME, token.DOUBLESTAR, tokenize.NUMBER)
1794 self.assertExactTypeEqual('{1, 2, 3}',
1795 token.LBRACE,
1796 token.NUMBER, token.COMMA,
1797 token.NUMBER, token.COMMA,
1798 token.NUMBER,
1799 token.RBRACE)
1800 self.assertExactTypeEqual('^(x & 0x1)',
1801 token.CIRCUMFLEX,
1802 token.LPAR,
1803 token.NAME, token.AMPER, token.NUMBER,
1804 token.RPAR)
1805
1806 def test_pathological_trailing_whitespace(self):
1807 # See http://bugs.python.org/issue16152
1808 self.assertExactTypeEqual('@ ', token.AT)
1809
1810 def test_comment_at_the_end_of_the_source_without_newline(self):
1811 # See http://bugs.python.org/issue44667
1812 source = 'b = 1\n\n#test'
1813 expected_tokens = [
1814 tokenize.TokenInfo(type=token.ENCODING, string='utf-8', start=(0, 0), end=(0, 0), line=''),
1815 tokenize.TokenInfo(type=token.NAME, string='b', start=(1, 0), end=(1, 1), line='b = 1\n'),
1816 tokenize.TokenInfo(type=token.OP, string='=', start=(1, 2), end=(1, 3), line='b = 1\n'),
1817 tokenize.TokenInfo(type=token.NUMBER, string='1', start=(1, 4), end=(1, 5), line='b = 1\n'),
1818 tokenize.TokenInfo(type=token.NEWLINE, string='\n', start=(1, 5), end=(1, 6), line='b = 1\n'),
1819 tokenize.TokenInfo(type=token.NL, string='\n', start=(2, 0), end=(2, 1), line='\n'),
1820 tokenize.TokenInfo(type=token.COMMENT, string='#test', start=(3, 0), end=(3, 5), line='#test'),
1821 tokenize.TokenInfo(type=token.NL, string='', start=(3, 5), end=(3, 6), line='#test'),
1822 tokenize.TokenInfo(type=token.ENDMARKER, string='', start=(4, 0), end=(4, 0), line='')
1823 ]
1824
1825 tokens = list(tokenize.tokenize(BytesIO(source.encode('utf-8')).readline))
1826 self.assertEqual(tokens, expected_tokens)
1827
1828 def test_newline_and_space_at_the_end_of_the_source_without_newline(self):
1829 # See https://github.com/python/cpython/issues/105435
1830 source = 'a\n '
1831 expected_tokens = [
1832 tokenize.TokenInfo(token.ENCODING, string='utf-8', start=(0, 0), end=(0, 0), line=''),
1833 tokenize.TokenInfo(token.NAME, string='a', start=(1, 0), end=(1, 1), line='a\n'),
1834 tokenize.TokenInfo(token.NEWLINE, string='\n', start=(1, 1), end=(1, 2), line='a\n'),
1835 tokenize.TokenInfo(token.NL, string='', start=(2, 1), end=(2, 2), line=' '),
1836 tokenize.TokenInfo(token.ENDMARKER, string='', start=(3, 0), end=(3, 0), line='')
1837 ]
1838
1839 tokens = list(tokenize.tokenize(BytesIO(source.encode('utf-8')).readline))
1840 self.assertEqual(tokens, expected_tokens)
1841
1842 def test_invalid_character_in_fstring_middle(self):
1843 # See gh-103824
1844 script = b'''F"""
1845 \xe5"""'''
1846
1847 with os_helper.temp_dir() as temp_dir:
1848 filename = os.path.join(temp_dir, "script.py")
1849 with open(filename, 'wb') as file:
1850 file.write(script)
1851 rs, _ = run_python_until_end(filename)
1852 self.assertIn(b"SyntaxError", rs.err)
1853
1854
1855 class UntokenizeTest(TestCase):
1856
1857 def test_bad_input_order(self):
1858 # raise if previous row
1859 u = tokenize.Untokenizer()
1860 u.prev_row = 2
1861 u.prev_col = 2
1862 with self.assertRaises(ValueError) as cm:
1863 u.add_whitespace((1,3))
1864 self.assertEqual(cm.exception.args[0],
1865 'start (1,3) precedes previous end (2,2)')
1866 # raise if previous column in row
1867 self.assertRaises(ValueError, u.add_whitespace, (2,1))
1868
1869 def test_backslash_continuation(self):
1870 # The problem is that <whitespace>\<newline> leaves no token
1871 u = tokenize.Untokenizer()
1872 u.prev_row = 1
1873 u.prev_col = 1
1874 u.tokens = []
1875 u.add_whitespace((2, 0))
1876 self.assertEqual(u.tokens, ['\\\n'])
1877 u.prev_row = 2
1878 u.add_whitespace((4, 4))
1879 self.assertEqual(u.tokens, ['\\\n', '\\\n\\\n', ' '])
1880 TestRoundtrip.check_roundtrip(self, 'a\n b\n c\n \\\n c\n')
1881
1882 def test_iter_compat(self):
1883 u = tokenize.Untokenizer()
1884 token = (tokenize.NAME, 'Hello')
1885 tokens = [(tokenize.ENCODING, 'utf-8'), token]
1886 u.compat(token, iter([]))
1887 self.assertEqual(u.tokens, ["Hello "])
1888 u = tokenize.Untokenizer()
1889 self.assertEqual(u.untokenize(iter([token])), 'Hello ')
1890 u = tokenize.Untokenizer()
1891 self.assertEqual(u.untokenize(iter(tokens)), 'Hello ')
1892 self.assertEqual(u.encoding, 'utf-8')
1893 self.assertEqual(tokenize.untokenize(iter(tokens)), b'Hello ')
1894
1895
1896 def contains_ambiguous_backslash(source):
1897 """Return `True` if the source contains a backslash on a
1898 line by itself. For example:
1899
1900 a = (1
1901 \\
1902 )
1903
1904 Code like this cannot be untokenized exactly. This is because
1905 the tokenizer does not produce any tokens for the line containing
1906 the backslash and so there is no way to know its indent.
1907 """
1908 pattern = re.compile(br'\n\s*\\\r?\n')
1909 return pattern.search(source) is not None
1910
1911
1912 class TestRoundtrip(TestCase):
1913
1914 def check_roundtrip(self, f):
1915 """
1916 Test roundtrip for `untokenize`. `f` is an open file or a string.
1917 The source code in f is tokenized to both 5- and 2-tuples.
1918 Both sequences are converted back to source code via
1919 tokenize.untokenize(), and the latter tokenized again to 2-tuples.
1920 The test fails if the 3 pair tokenizations do not match.
1921
1922 If the source code can be untokenized unambiguously, the
1923 untokenized code must match the original code exactly.
1924
1925 When untokenize bugs are fixed, untokenize with 5-tuples should
1926 reproduce code that does not contain a backslash continuation
1927 following spaces. A proper test should test this.
1928 """
1929 # Get source code and original tokenizations
1930 if isinstance(f, str):
1931 code = f.encode('utf-8')
1932 else:
1933 code = f.read()
1934 readline = iter(code.splitlines(keepends=True)).__next__
1935 tokens5 = list(tokenize.tokenize(readline))
1936 tokens2 = [tok[:2] for tok in tokens5]
1937 # Reproduce tokens2 from pairs
1938 bytes_from2 = tokenize.untokenize(tokens2)
1939 readline2 = iter(bytes_from2.splitlines(keepends=True)).__next__
1940 tokens2_from2 = [tok[:2] for tok in tokenize.tokenize(readline2)]
1941 self.assertEqual(tokens2_from2, tokens2)
1942 # Reproduce tokens2 from 5-tuples
1943 bytes_from5 = tokenize.untokenize(tokens5)
1944 readline5 = iter(bytes_from5.splitlines(keepends=True)).__next__
1945 tokens2_from5 = [tok[:2] for tok in tokenize.tokenize(readline5)]
1946 self.assertEqual(tokens2_from5, tokens2)
1947
1948 if not contains_ambiguous_backslash(code):
1949 # The BOM does not produce a token so there is no way to preserve it.
1950 code_without_bom = code.removeprefix(b'\xef\xbb\xbf')
1951 readline = iter(code_without_bom.splitlines(keepends=True)).__next__
1952 untokenized_code = tokenize.untokenize(tokenize.tokenize(readline))
1953 self.assertEqual(code_without_bom, untokenized_code)
1954
1955 def check_line_extraction(self, f):
1956 if isinstance(f, str):
1957 code = f.encode('utf-8')
1958 else:
1959 code = f.read()
1960 readline = iter(code.splitlines(keepends=True)).__next__
1961 for tok in tokenize.tokenize(readline):
1962 if tok.type in {tokenize.ENCODING, tokenize.ENDMARKER}:
1963 continue
1964 self.assertEqual(tok.string, tok.line[tok.start[1]: tok.end[1]])
1965
1966 def test_roundtrip(self):
1967 # There are some standard formatting practices that are easy to get right.
1968
1969 self.check_roundtrip("if x == 1:\n"
1970 " print(x)\n")
1971 self.check_roundtrip("# This is a comment\n"
1972 "# This also\n")
1973
1974 # Some people use different formatting conventions, which makes
1975 # untokenize a little trickier. Note that this test involves trailing
1976 # whitespace after the colon. Note that we use hex escapes to make the
1977 # two trailing blanks apparent in the expected output.
1978
1979 self.check_roundtrip("if x == 1 : \n"
1980 " print(x)\n")
1981 fn = support.findfile("tokenize_tests.txt", subdir="tokenizedata")
1982 with open(fn, 'rb') as f:
1983 self.check_roundtrip(f)
1984 self.check_roundtrip("if x == 1:\n"
1985 " # A comment by itself.\n"
1986 " print(x) # Comment here, too.\n"
1987 " # Another comment.\n"
1988 "after_if = True\n")
1989 self.check_roundtrip("if (x # The comments need to go in the right place\n"
1990 " == 1):\n"
1991 " print('x==1')\n")
1992 self.check_roundtrip("class Test: # A comment here\n"
1993 " # A comment with weird indent\n"
1994 " after_com = 5\n"
1995 " def x(m): return m*5 # a one liner\n"
1996 " def y(m): # A whitespace after the colon\n"
1997 " return y*4 # 3-space indent\n")
1998
1999 # Some error-handling code
2000 self.check_roundtrip("try: import somemodule\n"
2001 "except ImportError: # comment\n"
2002 " print('Can not import' # comment2\n)"
2003 "else: print('Loaded')\n")
2004
2005 self.check_roundtrip("f'\\N{EXCLAMATION MARK}'")
2006 self.check_roundtrip(r"f'\\N{SNAKE}'")
2007 self.check_roundtrip(r"f'\\N{{SNAKE}}'")
2008 self.check_roundtrip(r"f'\N{SNAKE}'")
2009 self.check_roundtrip(r"f'\\\N{SNAKE}'")
2010 self.check_roundtrip(r"f'\\\\\N{SNAKE}'")
2011 self.check_roundtrip(r"f'\\\\\\\N{SNAKE}'")
2012
2013 self.check_roundtrip(r"f'\\N{1}'")
2014 self.check_roundtrip(r"f'\\\\N{2}'")
2015 self.check_roundtrip(r"f'\\\\\\N{3}'")
2016 self.check_roundtrip(r"f'\\\\\\\\N{4}'")
2017
2018 self.check_roundtrip(r"f'\\N{{'")
2019 self.check_roundtrip(r"f'\\\\N{{'")
2020 self.check_roundtrip(r"f'\\\\\\N{{'")
2021 self.check_roundtrip(r"f'\\\\\\\\N{{'")
2022
2023 self.check_roundtrip(r"f'\n{{foo}}'")
2024 self.check_roundtrip(r"f'\\n{{foo}}'")
2025 self.check_roundtrip(r"f'\\\n{{foo}}'")
2026 self.check_roundtrip(r"f'\\\\n{{foo}}'")
2027
2028 self.check_roundtrip(r"f'\t{{foo}}'")
2029 self.check_roundtrip(r"f'\\t{{foo}}'")
2030 self.check_roundtrip(r"f'\\\t{{foo}}'")
2031 self.check_roundtrip(r"f'\\\\t{{foo}}'")
2032
2033 self.check_roundtrip(r"rf'\t{{foo}}'")
2034 self.check_roundtrip(r"rf'\\t{{foo}}'")
2035 self.check_roundtrip(r"rf'\\\t{{foo}}'")
2036 self.check_roundtrip(r"rf'\\\\t{{foo}}'")
2037
2038 self.check_roundtrip(r"rf'\{{foo}}'")
2039 self.check_roundtrip(r"f'\\{{foo}}'")
2040 self.check_roundtrip(r"rf'\\\{{foo}}'")
2041 self.check_roundtrip(r"f'\\\\{{foo}}'")
2042 cases = [
2043 """
2044 if 1:
2045 "foo"
2046 "bar"
2047 """,
2048 """
2049 if 1:
2050 ("foo"
2051 "bar")
2052 """,
2053 """
2054 if 1:
2055 "foo"
2056 "bar"
2057 """ ]
2058 for case in cases:
2059 self.check_roundtrip(case)
2060
2061
2062 def test_continuation(self):
2063 # Balancing continuation
2064 self.check_roundtrip("a = (3,4, \n"
2065 "5,6)\n"
2066 "y = [3, 4,\n"
2067 "5]\n"
2068 "z = {'a': 5,\n"
2069 "'b':15, 'c':True}\n"
2070 "x = len(y) + 5 - a[\n"
2071 "3] - a[2]\n"
2072 "+ len(z) - z[\n"
2073 "'b']\n")
2074
2075 def test_backslash_continuation(self):
2076 # Backslash means line continuation, except for comments
2077 self.check_roundtrip("x=1+\\\n"
2078 "1\n"
2079 "# This is a comment\\\n"
2080 "# This also\n")
2081 self.check_roundtrip("# Comment \\\n"
2082 "x = 0")
2083
2084 def test_string_concatenation(self):
2085 # Two string literals on the same line
2086 self.check_roundtrip("'' ''")
2087
2088 def test_random_files(self):
2089 # Test roundtrip on random python modules.
2090 # pass the '-ucpu' option to process the full directory.
2091
2092 import glob, random
2093 tempdir = os.path.dirname(__file__) or os.curdir
2094 testfiles = glob.glob(os.path.join(glob.escape(tempdir), "test*.py"))
2095
2096 if not support.is_resource_enabled("cpu"):
2097 testfiles = random.sample(testfiles, 10)
2098
2099 for testfile in testfiles:
2100 if support.verbose >= 2:
2101 print('tokenize', testfile)
2102 with open(testfile, 'rb') as f:
2103 with self.subTest(file=testfile):
2104 self.check_roundtrip(f)
2105 self.check_line_extraction(f)
2106
2107
2108 def roundtrip(self, code):
2109 if isinstance(code, str):
2110 code = code.encode('utf-8')
2111 return tokenize.untokenize(tokenize.tokenize(BytesIO(code).readline)).decode('utf-8')
2112
2113 def test_indentation_semantics_retained(self):
2114 """
2115 Ensure that although whitespace might be mutated in a roundtrip,
2116 the semantic meaning of the indentation remains consistent.
2117 """
2118 code = "if False:\n\tx=3\n\tx=3\n"
2119 codelines = self.roundtrip(code).split('\n')
2120 self.assertEqual(codelines[1], codelines[2])
2121 self.check_roundtrip(code)
2122
2123
2124 class InvalidPythonTests(TestCase):
2125 def test_number_followed_by_name(self):
2126 # See issue #gh-105549
2127 source = "2sin(x)"
2128 expected_tokens = [
2129 tokenize.TokenInfo(type=token.NUMBER, string='2', start=(1, 0), end=(1, 1), line='2sin(x)'),
2130 tokenize.TokenInfo(type=token.NAME, string='sin', start=(1, 1), end=(1, 4), line='2sin(x)'),
2131 tokenize.TokenInfo(type=token.OP, string='(', start=(1, 4), end=(1, 5), line='2sin(x)'),
2132 tokenize.TokenInfo(type=token.NAME, string='x', start=(1, 5), end=(1, 6), line='2sin(x)'),
2133 tokenize.TokenInfo(type=token.OP, string=')', start=(1, 6), end=(1, 7), line='2sin(x)'),
2134 tokenize.TokenInfo(type=token.NEWLINE, string='', start=(1, 7), end=(1, 8), line='2sin(x)'),
2135 tokenize.TokenInfo(type=token.ENDMARKER, string='', start=(2, 0), end=(2, 0), line='')
2136 ]
2137
2138 tokens = list(tokenize.generate_tokens(StringIO(source).readline))
2139 self.assertEqual(tokens, expected_tokens)
2140
2141 def test_number_starting_with_zero(self):
2142 source = "01234"
2143 expected_tokens = [
2144 tokenize.TokenInfo(type=token.NUMBER, string='01234', start=(1, 0), end=(1, 5), line='01234'),
2145 tokenize.TokenInfo(type=token.NEWLINE, string='', start=(1, 5), end=(1, 6), line='01234'),
2146 tokenize.TokenInfo(type=token.ENDMARKER, string='', start=(2, 0), end=(2, 0), line='')
2147 ]
2148
2149 tokens = list(tokenize.generate_tokens(StringIO(source).readline))
2150 self.assertEqual(tokens, expected_tokens)
2151
2152 class CTokenizeTest(TestCase):
2153 def check_tokenize(self, s, expected):
2154 # Format the tokens in s in a table format.
2155 # The ENDMARKER and final NEWLINE are omitted.
2156 f = StringIO(s)
2157 with self.subTest(source=s):
2158 result = stringify_tokens_from_source(
2159 tokenize._generate_tokens_from_c_tokenizer(f.readline), s
2160 )
2161 self.assertEqual(result, expected.rstrip().splitlines())
2162
2163 def test_encoding(self):
2164 def readline(encoding):
2165 yield "1+1".encode(encoding)
2166
2167 expected = [
2168 tokenize.TokenInfo(type=tokenize.NUMBER, string='1', start=(1, 0), end=(1, 1), line='1+1'),
2169 tokenize.TokenInfo(type=tokenize.OP, string='+', start=(1, 1), end=(1, 2), line='1+1'),
2170 tokenize.TokenInfo(type=tokenize.NUMBER, string='1', start=(1, 2), end=(1, 3), line='1+1'),
2171 tokenize.TokenInfo(type=tokenize.NEWLINE, string='', start=(1, 3), end=(1, 4), line='1+1'),
2172 tokenize.TokenInfo(type=tokenize.ENDMARKER, string='', start=(2, 0), end=(2, 0), line='')
2173 ]
2174 for encoding in ["utf-8", "latin-1", "utf-16"]:
2175 with self.subTest(encoding=encoding):
2176 tokens = list(tokenize._generate_tokens_from_c_tokenizer(
2177 readline(encoding).__next__,
2178 extra_tokens=True,
2179 encoding=encoding,
2180 ))
2181 self.assertEqual(tokens, expected)
2182
2183 def test_int(self):
2184
2185 self.check_tokenize('0xff <= 255', """\
2186 NUMBER '0xff' (1, 0) (1, 4)
2187 LESSEQUAL '<=' (1, 5) (1, 7)
2188 NUMBER '255' (1, 8) (1, 11)
2189 """)
2190
2191 self.check_tokenize('0b10 <= 255', """\
2192 NUMBER '0b10' (1, 0) (1, 4)
2193 LESSEQUAL '<=' (1, 5) (1, 7)
2194 NUMBER '255' (1, 8) (1, 11)
2195 """)
2196
2197 self.check_tokenize('0o123 <= 0O123', """\
2198 NUMBER '0o123' (1, 0) (1, 5)
2199 LESSEQUAL '<=' (1, 6) (1, 8)
2200 NUMBER '0O123' (1, 9) (1, 14)
2201 """)
2202
2203 self.check_tokenize('1234567 > ~0x15', """\
2204 NUMBER '1234567' (1, 0) (1, 7)
2205 GREATER '>' (1, 8) (1, 9)
2206 TILDE '~' (1, 10) (1, 11)
2207 NUMBER '0x15' (1, 11) (1, 15)
2208 """)
2209
2210 self.check_tokenize('2134568 != 1231515', """\
2211 NUMBER '2134568' (1, 0) (1, 7)
2212 NOTEQUAL '!=' (1, 8) (1, 10)
2213 NUMBER '1231515' (1, 11) (1, 18)
2214 """)
2215
2216 self.check_tokenize('(-124561-1) & 200000000', """\
2217 LPAR '(' (1, 0) (1, 1)
2218 MINUS '-' (1, 1) (1, 2)
2219 NUMBER '124561' (1, 2) (1, 8)
2220 MINUS '-' (1, 8) (1, 9)
2221 NUMBER '1' (1, 9) (1, 10)
2222 RPAR ')' (1, 10) (1, 11)
2223 AMPER '&' (1, 12) (1, 13)
2224 NUMBER '200000000' (1, 14) (1, 23)
2225 """)
2226
2227 self.check_tokenize('0xdeadbeef != -1', """\
2228 NUMBER '0xdeadbeef' (1, 0) (1, 10)
2229 NOTEQUAL '!=' (1, 11) (1, 13)
2230 MINUS '-' (1, 14) (1, 15)
2231 NUMBER '1' (1, 15) (1, 16)
2232 """)
2233
2234 self.check_tokenize('0xdeadc0de & 12345', """\
2235 NUMBER '0xdeadc0de' (1, 0) (1, 10)
2236 AMPER '&' (1, 11) (1, 12)
2237 NUMBER '12345' (1, 13) (1, 18)
2238 """)
2239
2240 self.check_tokenize('0xFF & 0x15 | 1234', """\
2241 NUMBER '0xFF' (1, 0) (1, 4)
2242 AMPER '&' (1, 5) (1, 6)
2243 NUMBER '0x15' (1, 7) (1, 11)
2244 VBAR '|' (1, 12) (1, 13)
2245 NUMBER '1234' (1, 14) (1, 18)
2246 """)
2247
2248 def test_float(self):
2249
2250 self.check_tokenize('x = 3.14159', """\
2251 NAME 'x' (1, 0) (1, 1)
2252 EQUAL '=' (1, 2) (1, 3)
2253 NUMBER '3.14159' (1, 4) (1, 11)
2254 """)
2255
2256 self.check_tokenize('x = 314159.', """\
2257 NAME 'x' (1, 0) (1, 1)
2258 EQUAL '=' (1, 2) (1, 3)
2259 NUMBER '314159.' (1, 4) (1, 11)
2260 """)
2261
2262 self.check_tokenize('x = .314159', """\
2263 NAME 'x' (1, 0) (1, 1)
2264 EQUAL '=' (1, 2) (1, 3)
2265 NUMBER '.314159' (1, 4) (1, 11)
2266 """)
2267
2268 self.check_tokenize('x = 3e14159', """\
2269 NAME 'x' (1, 0) (1, 1)
2270 EQUAL '=' (1, 2) (1, 3)
2271 NUMBER '3e14159' (1, 4) (1, 11)
2272 """)
2273
2274 self.check_tokenize('x = 3E123', """\
2275 NAME 'x' (1, 0) (1, 1)
2276 EQUAL '=' (1, 2) (1, 3)
2277 NUMBER '3E123' (1, 4) (1, 9)
2278 """)
2279
2280 self.check_tokenize('x+y = 3e-1230', """\
2281 NAME 'x' (1, 0) (1, 1)
2282 PLUS '+' (1, 1) (1, 2)
2283 NAME 'y' (1, 2) (1, 3)
2284 EQUAL '=' (1, 4) (1, 5)
2285 NUMBER '3e-1230' (1, 6) (1, 13)
2286 """)
2287
2288 self.check_tokenize('x = 3.14e159', """\
2289 NAME 'x' (1, 0) (1, 1)
2290 EQUAL '=' (1, 2) (1, 3)
2291 NUMBER '3.14e159' (1, 4) (1, 12)
2292 """)
2293
2294 def test_string(self):
2295
2296 self.check_tokenize('x = \'\'; y = ""', """\
2297 NAME 'x' (1, 0) (1, 1)
2298 EQUAL '=' (1, 2) (1, 3)
2299 STRING "''" (1, 4) (1, 6)
2300 SEMI ';' (1, 6) (1, 7)
2301 NAME 'y' (1, 8) (1, 9)
2302 EQUAL '=' (1, 10) (1, 11)
2303 STRING '""' (1, 12) (1, 14)
2304 """)
2305
2306 self.check_tokenize('x = \'"\'; y = "\'"', """\
2307 NAME 'x' (1, 0) (1, 1)
2308 EQUAL '=' (1, 2) (1, 3)
2309 STRING '\\'"\\'' (1, 4) (1, 7)
2310 SEMI ';' (1, 7) (1, 8)
2311 NAME 'y' (1, 9) (1, 10)
2312 EQUAL '=' (1, 11) (1, 12)
2313 STRING '"\\'"' (1, 13) (1, 16)
2314 """)
2315
2316 self.check_tokenize('x = "doesn\'t "shrink", does it"', """\
2317 NAME 'x' (1, 0) (1, 1)
2318 EQUAL '=' (1, 2) (1, 3)
2319 STRING '"doesn\\'t "' (1, 4) (1, 14)
2320 NAME 'shrink' (1, 14) (1, 20)
2321 STRING '", does it"' (1, 20) (1, 31)
2322 """)
2323
2324 self.check_tokenize("x = 'abc' + 'ABC'", """\
2325 NAME 'x' (1, 0) (1, 1)
2326 EQUAL '=' (1, 2) (1, 3)
2327 STRING "'abc'" (1, 4) (1, 9)
2328 PLUS '+' (1, 10) (1, 11)
2329 STRING "'ABC'" (1, 12) (1, 17)
2330 """)
2331
2332 self.check_tokenize('y = "ABC" + "ABC"', """\
2333 NAME 'y' (1, 0) (1, 1)
2334 EQUAL '=' (1, 2) (1, 3)
2335 STRING '"ABC"' (1, 4) (1, 9)
2336 PLUS '+' (1, 10) (1, 11)
2337 STRING '"ABC"' (1, 12) (1, 17)
2338 """)
2339
2340 self.check_tokenize("x = r'abc' + r'ABC' + R'ABC' + R'ABC'", """\
2341 NAME 'x' (1, 0) (1, 1)
2342 EQUAL '=' (1, 2) (1, 3)
2343 STRING "r'abc'" (1, 4) (1, 10)
2344 PLUS '+' (1, 11) (1, 12)
2345 STRING "r'ABC'" (1, 13) (1, 19)
2346 PLUS '+' (1, 20) (1, 21)
2347 STRING "R'ABC'" (1, 22) (1, 28)
2348 PLUS '+' (1, 29) (1, 30)
2349 STRING "R'ABC'" (1, 31) (1, 37)
2350 """)
2351
2352 self.check_tokenize('y = r"abc" + r"ABC" + R"ABC" + R"ABC"', """\
2353 NAME 'y' (1, 0) (1, 1)
2354 EQUAL '=' (1, 2) (1, 3)
2355 STRING 'r"abc"' (1, 4) (1, 10)
2356 PLUS '+' (1, 11) (1, 12)
2357 STRING 'r"ABC"' (1, 13) (1, 19)
2358 PLUS '+' (1, 20) (1, 21)
2359 STRING 'R"ABC"' (1, 22) (1, 28)
2360 PLUS '+' (1, 29) (1, 30)
2361 STRING 'R"ABC"' (1, 31) (1, 37)
2362 """)
2363
2364 self.check_tokenize("u'abc' + U'abc'", """\
2365 STRING "u'abc'" (1, 0) (1, 6)
2366 PLUS '+' (1, 7) (1, 8)
2367 STRING "U'abc'" (1, 9) (1, 15)
2368 """)
2369
2370 self.check_tokenize('u"abc" + U"abc"', """\
2371 STRING 'u"abc"' (1, 0) (1, 6)
2372 PLUS '+' (1, 7) (1, 8)
2373 STRING 'U"abc"' (1, 9) (1, 15)
2374 """)
2375
2376 self.check_tokenize("b'abc' + B'abc'", """\
2377 STRING "b'abc'" (1, 0) (1, 6)
2378 PLUS '+' (1, 7) (1, 8)
2379 STRING "B'abc'" (1, 9) (1, 15)
2380 """)
2381
2382 self.check_tokenize('b"abc" + B"abc"', """\
2383 STRING 'b"abc"' (1, 0) (1, 6)
2384 PLUS '+' (1, 7) (1, 8)
2385 STRING 'B"abc"' (1, 9) (1, 15)
2386 """)
2387
2388 self.check_tokenize("br'abc' + bR'abc' + Br'abc' + BR'abc'", """\
2389 STRING "br'abc'" (1, 0) (1, 7)
2390 PLUS '+' (1, 8) (1, 9)
2391 STRING "bR'abc'" (1, 10) (1, 17)
2392 PLUS '+' (1, 18) (1, 19)
2393 STRING "Br'abc'" (1, 20) (1, 27)
2394 PLUS '+' (1, 28) (1, 29)
2395 STRING "BR'abc'" (1, 30) (1, 37)
2396 """)
2397
2398 self.check_tokenize('br"abc" + bR"abc" + Br"abc" + BR"abc"', """\
2399 STRING 'br"abc"' (1, 0) (1, 7)
2400 PLUS '+' (1, 8) (1, 9)
2401 STRING 'bR"abc"' (1, 10) (1, 17)
2402 PLUS '+' (1, 18) (1, 19)
2403 STRING 'Br"abc"' (1, 20) (1, 27)
2404 PLUS '+' (1, 28) (1, 29)
2405 STRING 'BR"abc"' (1, 30) (1, 37)
2406 """)
2407
2408 self.check_tokenize("rb'abc' + rB'abc' + Rb'abc' + RB'abc'", """\
2409 STRING "rb'abc'" (1, 0) (1, 7)
2410 PLUS '+' (1, 8) (1, 9)
2411 STRING "rB'abc'" (1, 10) (1, 17)
2412 PLUS '+' (1, 18) (1, 19)
2413 STRING "Rb'abc'" (1, 20) (1, 27)
2414 PLUS '+' (1, 28) (1, 29)
2415 STRING "RB'abc'" (1, 30) (1, 37)
2416 """)
2417
2418 self.check_tokenize('rb"abc" + rB"abc" + Rb"abc" + RB"abc"', """\
2419 STRING 'rb"abc"' (1, 0) (1, 7)
2420 PLUS '+' (1, 8) (1, 9)
2421 STRING 'rB"abc"' (1, 10) (1, 17)
2422 PLUS '+' (1, 18) (1, 19)
2423 STRING 'Rb"abc"' (1, 20) (1, 27)
2424 PLUS '+' (1, 28) (1, 29)
2425 STRING 'RB"abc"' (1, 30) (1, 37)
2426 """)
2427
2428 self.check_tokenize('"a\\\nde\\\nfg"', """\
2429 STRING '"a\\\\\\nde\\\\\\nfg"\' (1, 0) (3, 3)
2430 """)
2431
2432 self.check_tokenize('u"a\\\nde"', """\
2433 STRING 'u"a\\\\\\nde"\' (1, 0) (2, 3)
2434 """)
2435
2436 self.check_tokenize('rb"a\\\nd"', """\
2437 STRING 'rb"a\\\\\\nd"\' (1, 0) (2, 2)
2438 """)
2439
2440 self.check_tokenize(r'"""a\
2441 b"""', """\
2442 STRING '\"\""a\\\\\\nb\"\""' (1, 0) (2, 4)
2443 """)
2444 self.check_tokenize(r'u"""a\
2445 b"""', """\
2446 STRING 'u\"\""a\\\\\\nb\"\""' (1, 0) (2, 4)
2447 """)
2448 self.check_tokenize(r'rb"""a\
2449 b\
2450 c"""', """\
2451 STRING 'rb"\""a\\\\\\nb\\\\\\nc"\""' (1, 0) (3, 4)
2452 """)
2453
2454 self.check_tokenize(r'"hola\\\r\ndfgf"', """\
2455 STRING \'"hola\\\\\\\\\\\\r\\\\ndfgf"\' (1, 0) (1, 16)
2456 """)
2457
2458 self.check_tokenize('f"abc"', """\
2459 FSTRING_START 'f"' (1, 0) (1, 2)
2460 FSTRING_MIDDLE 'abc' (1, 2) (1, 5)
2461 FSTRING_END '"' (1, 5) (1, 6)
2462 """)
2463
2464 self.check_tokenize('fR"a{b}c"', """\
2465 FSTRING_START 'fR"' (1, 0) (1, 3)
2466 FSTRING_MIDDLE 'a' (1, 3) (1, 4)
2467 LBRACE '{' (1, 4) (1, 5)
2468 NAME 'b' (1, 5) (1, 6)
2469 RBRACE '}' (1, 6) (1, 7)
2470 FSTRING_MIDDLE 'c' (1, 7) (1, 8)
2471 FSTRING_END '"' (1, 8) (1, 9)
2472 """)
2473
2474 self.check_tokenize('f"""abc"""', """\
2475 FSTRING_START 'f\"""' (1, 0) (1, 4)
2476 FSTRING_MIDDLE 'abc' (1, 4) (1, 7)
2477 FSTRING_END '\"""' (1, 7) (1, 10)
2478 """)
2479
2480 self.check_tokenize(r'f"abc\
2481 def"', """\
2482 FSTRING_START \'f"\' (1, 0) (1, 2)
2483 FSTRING_MIDDLE 'abc\\\\\\ndef' (1, 2) (2, 3)
2484 FSTRING_END '"' (2, 3) (2, 4)
2485 """)
2486
2487 self.check_tokenize('''\
2488 f"{
2489 a}"''', """\
2490 FSTRING_START 'f"' (1, 0) (1, 2)
2491 LBRACE '{' (1, 2) (1, 3)
2492 NAME 'a' (2, 0) (2, 1)
2493 RBRACE '}' (2, 1) (2, 2)
2494 FSTRING_END '"' (2, 2) (2, 3)
2495 """)
2496
2497 self.check_tokenize(r'Rf"abc\
2498 def"', """\
2499 FSTRING_START 'Rf"' (1, 0) (1, 3)
2500 FSTRING_MIDDLE 'abc\\\\\\ndef' (1, 3) (2, 3)
2501 FSTRING_END '"' (2, 3) (2, 4)
2502 """)
2503
2504 self.check_tokenize(r'f"hola\\\r\ndfgf"', """\
2505 FSTRING_START \'f"\' (1, 0) (1, 2)
2506 FSTRING_MIDDLE 'hola\\\\\\\\\\\\r\\\\ndfgf' (1, 2) (1, 16)
2507 FSTRING_END \'"\' (1, 16) (1, 17)
2508 """)
2509
2510 self.check_tokenize("""\
2511 f'''__{
2512 x:a
2513 }__'''""", """\
2514 FSTRING_START "f'''" (1, 0) (1, 4)
2515 FSTRING_MIDDLE '__' (1, 4) (1, 6)
2516 LBRACE '{' (1, 6) (1, 7)
2517 NAME 'x' (2, 4) (2, 5)
2518 COLON ':' (2, 5) (2, 6)
2519 FSTRING_MIDDLE 'a\\n' (2, 6) (3, 0)
2520 RBRACE '}' (3, 0) (3, 1)
2521 FSTRING_MIDDLE '__' (3, 1) (3, 3)
2522 FSTRING_END "'''" (3, 3) (3, 6)
2523 """)
2524
2525 self.check_tokenize("""\
2526 f'''__{
2527 x:a
2528 b
2529 c
2530 d
2531 }__'''""", """\
2532 FSTRING_START "f'''" (1, 0) (1, 4)
2533 FSTRING_MIDDLE '__' (1, 4) (1, 6)
2534 LBRACE '{' (1, 6) (1, 7)
2535 NAME 'x' (2, 4) (2, 5)
2536 COLON ':' (2, 5) (2, 6)
2537 FSTRING_MIDDLE 'a\\n b\\n c\\n d\\n' (2, 6) (6, 0)
2538 RBRACE '}' (6, 0) (6, 1)
2539 FSTRING_MIDDLE '__' (6, 1) (6, 3)
2540 FSTRING_END "'''" (6, 3) (6, 6)
2541 """)
2542
2543 def test_function(self):
2544
2545 self.check_tokenize('def d22(a, b, c=2, d=2, *k): pass', """\
2546 NAME 'def' (1, 0) (1, 3)
2547 NAME 'd22' (1, 4) (1, 7)
2548 LPAR '(' (1, 7) (1, 8)
2549 NAME 'a' (1, 8) (1, 9)
2550 COMMA ',' (1, 9) (1, 10)
2551 NAME 'b' (1, 11) (1, 12)
2552 COMMA ',' (1, 12) (1, 13)
2553 NAME 'c' (1, 14) (1, 15)
2554 EQUAL '=' (1, 15) (1, 16)
2555 NUMBER '2' (1, 16) (1, 17)
2556 COMMA ',' (1, 17) (1, 18)
2557 NAME 'd' (1, 19) (1, 20)
2558 EQUAL '=' (1, 20) (1, 21)
2559 NUMBER '2' (1, 21) (1, 22)
2560 COMMA ',' (1, 22) (1, 23)
2561 STAR '*' (1, 24) (1, 25)
2562 NAME 'k' (1, 25) (1, 26)
2563 RPAR ')' (1, 26) (1, 27)
2564 COLON ':' (1, 27) (1, 28)
2565 NAME 'pass' (1, 29) (1, 33)
2566 """)
2567
2568 self.check_tokenize('def d01v_(a=1, *k, **w): pass', """\
2569 NAME 'def' (1, 0) (1, 3)
2570 NAME 'd01v_' (1, 4) (1, 9)
2571 LPAR '(' (1, 9) (1, 10)
2572 NAME 'a' (1, 10) (1, 11)
2573 EQUAL '=' (1, 11) (1, 12)
2574 NUMBER '1' (1, 12) (1, 13)
2575 COMMA ',' (1, 13) (1, 14)
2576 STAR '*' (1, 15) (1, 16)
2577 NAME 'k' (1, 16) (1, 17)
2578 COMMA ',' (1, 17) (1, 18)
2579 DOUBLESTAR '**' (1, 19) (1, 21)
2580 NAME 'w' (1, 21) (1, 22)
2581 RPAR ')' (1, 22) (1, 23)
2582 COLON ':' (1, 23) (1, 24)
2583 NAME 'pass' (1, 25) (1, 29)
2584 """)
2585
2586 self.check_tokenize('def d23(a: str, b: int=3) -> int: pass', """\
2587 NAME 'def' (1, 0) (1, 3)
2588 NAME 'd23' (1, 4) (1, 7)
2589 LPAR '(' (1, 7) (1, 8)
2590 NAME 'a' (1, 8) (1, 9)
2591 COLON ':' (1, 9) (1, 10)
2592 NAME 'str' (1, 11) (1, 14)
2593 COMMA ',' (1, 14) (1, 15)
2594 NAME 'b' (1, 16) (1, 17)
2595 COLON ':' (1, 17) (1, 18)
2596 NAME 'int' (1, 19) (1, 22)
2597 EQUAL '=' (1, 22) (1, 23)
2598 NUMBER '3' (1, 23) (1, 24)
2599 RPAR ')' (1, 24) (1, 25)
2600 RARROW '->' (1, 26) (1, 28)
2601 NAME 'int' (1, 29) (1, 32)
2602 COLON ':' (1, 32) (1, 33)
2603 NAME 'pass' (1, 34) (1, 38)
2604 """)
2605
2606 def test_comparison(self):
2607
2608 self.check_tokenize("if 1 < 1 > 1 == 1 >= 5 <= 0x15 <= 0x12 != "
2609 "1 and 5 in 1 not in 1 is 1 or 5 is not 1: pass", """\
2610 NAME 'if' (1, 0) (1, 2)
2611 NUMBER '1' (1, 3) (1, 4)
2612 LESS '<' (1, 5) (1, 6)
2613 NUMBER '1' (1, 7) (1, 8)
2614 GREATER '>' (1, 9) (1, 10)
2615 NUMBER '1' (1, 11) (1, 12)
2616 EQEQUAL '==' (1, 13) (1, 15)
2617 NUMBER '1' (1, 16) (1, 17)
2618 GREATEREQUAL '>=' (1, 18) (1, 20)
2619 NUMBER '5' (1, 21) (1, 22)
2620 LESSEQUAL '<=' (1, 23) (1, 25)
2621 NUMBER '0x15' (1, 26) (1, 30)
2622 LESSEQUAL '<=' (1, 31) (1, 33)
2623 NUMBER '0x12' (1, 34) (1, 38)
2624 NOTEQUAL '!=' (1, 39) (1, 41)
2625 NUMBER '1' (1, 42) (1, 43)
2626 NAME 'and' (1, 44) (1, 47)
2627 NUMBER '5' (1, 48) (1, 49)
2628 NAME 'in' (1, 50) (1, 52)
2629 NUMBER '1' (1, 53) (1, 54)
2630 NAME 'not' (1, 55) (1, 58)
2631 NAME 'in' (1, 59) (1, 61)
2632 NUMBER '1' (1, 62) (1, 63)
2633 NAME 'is' (1, 64) (1, 66)
2634 NUMBER '1' (1, 67) (1, 68)
2635 NAME 'or' (1, 69) (1, 71)
2636 NUMBER '5' (1, 72) (1, 73)
2637 NAME 'is' (1, 74) (1, 76)
2638 NAME 'not' (1, 77) (1, 80)
2639 NUMBER '1' (1, 81) (1, 82)
2640 COLON ':' (1, 82) (1, 83)
2641 NAME 'pass' (1, 84) (1, 88)
2642 """)
2643
2644 def test_additive(self):
2645
2646 self.check_tokenize('x = 1 - y + 15 - 1 + 0x124 + z + a[5]', """\
2647 NAME 'x' (1, 0) (1, 1)
2648 EQUAL '=' (1, 2) (1, 3)
2649 NUMBER '1' (1, 4) (1, 5)
2650 MINUS '-' (1, 6) (1, 7)
2651 NAME 'y' (1, 8) (1, 9)
2652 PLUS '+' (1, 10) (1, 11)
2653 NUMBER '15' (1, 12) (1, 14)
2654 MINUS '-' (1, 15) (1, 16)
2655 NUMBER '1' (1, 17) (1, 18)
2656 PLUS '+' (1, 19) (1, 20)
2657 NUMBER '0x124' (1, 21) (1, 26)
2658 PLUS '+' (1, 27) (1, 28)
2659 NAME 'z' (1, 29) (1, 30)
2660 PLUS '+' (1, 31) (1, 32)
2661 NAME 'a' (1, 33) (1, 34)
2662 LSQB '[' (1, 34) (1, 35)
2663 NUMBER '5' (1, 35) (1, 36)
2664 RSQB ']' (1, 36) (1, 37)
2665 """)
2666
2667 def test_multiplicative(self):
2668
2669 self.check_tokenize('x = 1//1*1/5*12%0x12@42', """\
2670 NAME 'x' (1, 0) (1, 1)
2671 EQUAL '=' (1, 2) (1, 3)
2672 NUMBER '1' (1, 4) (1, 5)
2673 DOUBLESLASH '//' (1, 5) (1, 7)
2674 NUMBER '1' (1, 7) (1, 8)
2675 STAR '*' (1, 8) (1, 9)
2676 NUMBER '1' (1, 9) (1, 10)
2677 SLASH '/' (1, 10) (1, 11)
2678 NUMBER '5' (1, 11) (1, 12)
2679 STAR '*' (1, 12) (1, 13)
2680 NUMBER '12' (1, 13) (1, 15)
2681 PERCENT '%' (1, 15) (1, 16)
2682 NUMBER '0x12' (1, 16) (1, 20)
2683 AT '@' (1, 20) (1, 21)
2684 NUMBER '42' (1, 21) (1, 23)
2685 """)
2686
2687 def test_unary(self):
2688
2689 self.check_tokenize('~1 ^ 1 & 1 |1 ^ -1', """\
2690 TILDE '~' (1, 0) (1, 1)
2691 NUMBER '1' (1, 1) (1, 2)
2692 CIRCUMFLEX '^' (1, 3) (1, 4)
2693 NUMBER '1' (1, 5) (1, 6)
2694 AMPER '&' (1, 7) (1, 8)
2695 NUMBER '1' (1, 9) (1, 10)
2696 VBAR '|' (1, 11) (1, 12)
2697 NUMBER '1' (1, 12) (1, 13)
2698 CIRCUMFLEX '^' (1, 14) (1, 15)
2699 MINUS '-' (1, 16) (1, 17)
2700 NUMBER '1' (1, 17) (1, 18)
2701 """)
2702
2703 self.check_tokenize('-1*1/1+1*1//1 - ---1**1', """\
2704 MINUS '-' (1, 0) (1, 1)
2705 NUMBER '1' (1, 1) (1, 2)
2706 STAR '*' (1, 2) (1, 3)
2707 NUMBER '1' (1, 3) (1, 4)
2708 SLASH '/' (1, 4) (1, 5)
2709 NUMBER '1' (1, 5) (1, 6)
2710 PLUS '+' (1, 6) (1, 7)
2711 NUMBER '1' (1, 7) (1, 8)
2712 STAR '*' (1, 8) (1, 9)
2713 NUMBER '1' (1, 9) (1, 10)
2714 DOUBLESLASH '//' (1, 10) (1, 12)
2715 NUMBER '1' (1, 12) (1, 13)
2716 MINUS '-' (1, 14) (1, 15)
2717 MINUS '-' (1, 16) (1, 17)
2718 MINUS '-' (1, 17) (1, 18)
2719 MINUS '-' (1, 18) (1, 19)
2720 NUMBER '1' (1, 19) (1, 20)
2721 DOUBLESTAR '**' (1, 20) (1, 22)
2722 NUMBER '1' (1, 22) (1, 23)
2723 """)
2724
2725 def test_selector(self):
2726
2727 self.check_tokenize("import sys, time\nx = sys.modules['time'].time()", """\
2728 NAME 'import' (1, 0) (1, 6)
2729 NAME 'sys' (1, 7) (1, 10)
2730 COMMA ',' (1, 10) (1, 11)
2731 NAME 'time' (1, 12) (1, 16)
2732 NEWLINE '' (1, 16) (1, 16)
2733 NAME 'x' (2, 0) (2, 1)
2734 EQUAL '=' (2, 2) (2, 3)
2735 NAME 'sys' (2, 4) (2, 7)
2736 DOT '.' (2, 7) (2, 8)
2737 NAME 'modules' (2, 8) (2, 15)
2738 LSQB '[' (2, 15) (2, 16)
2739 STRING "'time'" (2, 16) (2, 22)
2740 RSQB ']' (2, 22) (2, 23)
2741 DOT '.' (2, 23) (2, 24)
2742 NAME 'time' (2, 24) (2, 28)
2743 LPAR '(' (2, 28) (2, 29)
2744 RPAR ')' (2, 29) (2, 30)
2745 """)
2746
2747 def test_method(self):
2748
2749 self.check_tokenize('@staticmethod\ndef foo(x,y): pass', """\
2750 AT '@' (1, 0) (1, 1)
2751 NAME 'staticmethod' (1, 1) (1, 13)
2752 NEWLINE '' (1, 13) (1, 13)
2753 NAME 'def' (2, 0) (2, 3)
2754 NAME 'foo' (2, 4) (2, 7)
2755 LPAR '(' (2, 7) (2, 8)
2756 NAME 'x' (2, 8) (2, 9)
2757 COMMA ',' (2, 9) (2, 10)
2758 NAME 'y' (2, 10) (2, 11)
2759 RPAR ')' (2, 11) (2, 12)
2760 COLON ':' (2, 12) (2, 13)
2761 NAME 'pass' (2, 14) (2, 18)
2762 """)
2763
2764 def test_tabs(self):
2765
2766 self.check_tokenize('@staticmethod\ndef foo(x,y): pass', """\
2767 AT '@' (1, 0) (1, 1)
2768 NAME 'staticmethod' (1, 1) (1, 13)
2769 NEWLINE '' (1, 13) (1, 13)
2770 NAME 'def' (2, 0) (2, 3)
2771 NAME 'foo' (2, 4) (2, 7)
2772 LPAR '(' (2, 7) (2, 8)
2773 NAME 'x' (2, 8) (2, 9)
2774 COMMA ',' (2, 9) (2, 10)
2775 NAME 'y' (2, 10) (2, 11)
2776 RPAR ')' (2, 11) (2, 12)
2777 COLON ':' (2, 12) (2, 13)
2778 NAME 'pass' (2, 14) (2, 18)
2779 """)
2780
2781 def test_async(self):
2782
2783 self.check_tokenize('async = 1', """\
2784 NAME 'async' (1, 0) (1, 5)
2785 EQUAL '=' (1, 6) (1, 7)
2786 NUMBER '1' (1, 8) (1, 9)
2787 """)
2788
2789 self.check_tokenize('a = (async = 1)', """\
2790 NAME 'a' (1, 0) (1, 1)
2791 EQUAL '=' (1, 2) (1, 3)
2792 LPAR '(' (1, 4) (1, 5)
2793 NAME 'async' (1, 5) (1, 10)
2794 EQUAL '=' (1, 11) (1, 12)
2795 NUMBER '1' (1, 13) (1, 14)
2796 RPAR ')' (1, 14) (1, 15)
2797 """)
2798
2799 self.check_tokenize('async()', """\
2800 NAME 'async' (1, 0) (1, 5)
2801 LPAR '(' (1, 5) (1, 6)
2802 RPAR ')' (1, 6) (1, 7)
2803 """)
2804
2805 self.check_tokenize('class async(Bar):pass', """\
2806 NAME 'class' (1, 0) (1, 5)
2807 NAME 'async' (1, 6) (1, 11)
2808 LPAR '(' (1, 11) (1, 12)
2809 NAME 'Bar' (1, 12) (1, 15)
2810 RPAR ')' (1, 15) (1, 16)
2811 COLON ':' (1, 16) (1, 17)
2812 NAME 'pass' (1, 17) (1, 21)
2813 """)
2814
2815 self.check_tokenize('class async:pass', """\
2816 NAME 'class' (1, 0) (1, 5)
2817 NAME 'async' (1, 6) (1, 11)
2818 COLON ':' (1, 11) (1, 12)
2819 NAME 'pass' (1, 12) (1, 16)
2820 """)
2821
2822 self.check_tokenize('await = 1', """\
2823 NAME 'await' (1, 0) (1, 5)
2824 EQUAL '=' (1, 6) (1, 7)
2825 NUMBER '1' (1, 8) (1, 9)
2826 """)
2827
2828 self.check_tokenize('foo.async', """\
2829 NAME 'foo' (1, 0) (1, 3)
2830 DOT '.' (1, 3) (1, 4)
2831 NAME 'async' (1, 4) (1, 9)
2832 """)
2833
2834 self.check_tokenize('async for a in b: pass', """\
2835 NAME 'async' (1, 0) (1, 5)
2836 NAME 'for' (1, 6) (1, 9)
2837 NAME 'a' (1, 10) (1, 11)
2838 NAME 'in' (1, 12) (1, 14)
2839 NAME 'b' (1, 15) (1, 16)
2840 COLON ':' (1, 16) (1, 17)
2841 NAME 'pass' (1, 18) (1, 22)
2842 """)
2843
2844 self.check_tokenize('async with a as b: pass', """\
2845 NAME 'async' (1, 0) (1, 5)
2846 NAME 'with' (1, 6) (1, 10)
2847 NAME 'a' (1, 11) (1, 12)
2848 NAME 'as' (1, 13) (1, 15)
2849 NAME 'b' (1, 16) (1, 17)
2850 COLON ':' (1, 17) (1, 18)
2851 NAME 'pass' (1, 19) (1, 23)
2852 """)
2853
2854 self.check_tokenize('async.foo', """\
2855 NAME 'async' (1, 0) (1, 5)
2856 DOT '.' (1, 5) (1, 6)
2857 NAME 'foo' (1, 6) (1, 9)
2858 """)
2859
2860 self.check_tokenize('async', """\
2861 NAME 'async' (1, 0) (1, 5)
2862 """)
2863
2864 self.check_tokenize('async\n#comment\nawait', """\
2865 NAME 'async' (1, 0) (1, 5)
2866 NEWLINE '' (1, 5) (1, 5)
2867 NAME 'await' (3, 0) (3, 5)
2868 """)
2869
2870 self.check_tokenize('async\n...\nawait', """\
2871 NAME 'async' (1, 0) (1, 5)
2872 NEWLINE '' (1, 5) (1, 5)
2873 ELLIPSIS '...' (2, 0) (2, 3)
2874 NEWLINE '' (2, 3) (2, 3)
2875 NAME 'await' (3, 0) (3, 5)
2876 """)
2877
2878 self.check_tokenize('async\nawait', """\
2879 NAME 'async' (1, 0) (1, 5)
2880 NEWLINE '' (1, 5) (1, 5)
2881 NAME 'await' (2, 0) (2, 5)
2882 """)
2883
2884 self.check_tokenize('foo.async + 1', """\
2885 NAME 'foo' (1, 0) (1, 3)
2886 DOT '.' (1, 3) (1, 4)
2887 NAME 'async' (1, 4) (1, 9)
2888 PLUS '+' (1, 10) (1, 11)
2889 NUMBER '1' (1, 12) (1, 13)
2890 """)
2891
2892 self.check_tokenize('async def foo(): pass', """\
2893 NAME 'async' (1, 0) (1, 5)
2894 NAME 'def' (1, 6) (1, 9)
2895 NAME 'foo' (1, 10) (1, 13)
2896 LPAR '(' (1, 13) (1, 14)
2897 RPAR ')' (1, 14) (1, 15)
2898 COLON ':' (1, 15) (1, 16)
2899 NAME 'pass' (1, 17) (1, 21)
2900 """)
2901
2902 self.check_tokenize('''\
2903 async def foo():
2904 def foo(await):
2905 await = 1
2906 if 1:
2907 await
2908 async += 1
2909 ''', """\
2910 NAME 'async' (1, 0) (1, 5)
2911 NAME 'def' (1, 6) (1, 9)
2912 NAME 'foo' (1, 10) (1, 13)
2913 LPAR '(' (1, 13) (1, 14)
2914 RPAR ')' (1, 14) (1, 15)
2915 COLON ':' (1, 15) (1, 16)
2916 NEWLINE '' (1, 16) (1, 16)
2917 INDENT '' (2, -1) (2, -1)
2918 NAME 'def' (2, 2) (2, 5)
2919 NAME 'foo' (2, 6) (2, 9)
2920 LPAR '(' (2, 9) (2, 10)
2921 NAME 'await' (2, 10) (2, 15)
2922 RPAR ')' (2, 15) (2, 16)
2923 COLON ':' (2, 16) (2, 17)
2924 NEWLINE '' (2, 17) (2, 17)
2925 INDENT '' (3, -1) (3, -1)
2926 NAME 'await' (3, 4) (3, 9)
2927 EQUAL '=' (3, 10) (3, 11)
2928 NUMBER '1' (3, 12) (3, 13)
2929 NEWLINE '' (3, 13) (3, 13)
2930 DEDENT '' (4, -1) (4, -1)
2931 NAME 'if' (4, 2) (4, 4)
2932 NUMBER '1' (4, 5) (4, 6)
2933 COLON ':' (4, 6) (4, 7)
2934 NEWLINE '' (4, 7) (4, 7)
2935 INDENT '' (5, -1) (5, -1)
2936 NAME 'await' (5, 4) (5, 9)
2937 NEWLINE '' (5, 9) (5, 9)
2938 DEDENT '' (6, -1) (6, -1)
2939 DEDENT '' (6, -1) (6, -1)
2940 NAME 'async' (6, 0) (6, 5)
2941 PLUSEQUAL '+=' (6, 6) (6, 8)
2942 NUMBER '1' (6, 9) (6, 10)
2943 NEWLINE '' (6, 10) (6, 10)
2944 """)
2945
2946 self.check_tokenize('async def foo():\n async for i in 1: pass', """\
2947 NAME 'async' (1, 0) (1, 5)
2948 NAME 'def' (1, 6) (1, 9)
2949 NAME 'foo' (1, 10) (1, 13)
2950 LPAR '(' (1, 13) (1, 14)
2951 RPAR ')' (1, 14) (1, 15)
2952 COLON ':' (1, 15) (1, 16)
2953 NEWLINE '' (1, 16) (1, 16)
2954 INDENT '' (2, -1) (2, -1)
2955 NAME 'async' (2, 2) (2, 7)
2956 NAME 'for' (2, 8) (2, 11)
2957 NAME 'i' (2, 12) (2, 13)
2958 NAME 'in' (2, 14) (2, 16)
2959 NUMBER '1' (2, 17) (2, 18)
2960 COLON ':' (2, 18) (2, 19)
2961 NAME 'pass' (2, 20) (2, 24)
2962 DEDENT '' (2, -1) (2, -1)
2963 """)
2964
2965 self.check_tokenize('async def foo(async): await', """\
2966 NAME 'async' (1, 0) (1, 5)
2967 NAME 'def' (1, 6) (1, 9)
2968 NAME 'foo' (1, 10) (1, 13)
2969 LPAR '(' (1, 13) (1, 14)
2970 NAME 'async' (1, 14) (1, 19)
2971 RPAR ')' (1, 19) (1, 20)
2972 COLON ':' (1, 20) (1, 21)
2973 NAME 'await' (1, 22) (1, 27)
2974 """)
2975
2976 self.check_tokenize('''\
2977 def f():
2978
2979 def baz(): pass
2980 async def bar(): pass
2981
2982 await = 2''', """\
2983 NAME 'def' (1, 0) (1, 3)
2984 NAME 'f' (1, 4) (1, 5)
2985 LPAR '(' (1, 5) (1, 6)
2986 RPAR ')' (1, 6) (1, 7)
2987 COLON ':' (1, 7) (1, 8)
2988 NEWLINE '' (1, 8) (1, 8)
2989 INDENT '' (3, -1) (3, -1)
2990 NAME 'def' (3, 2) (3, 5)
2991 NAME 'baz' (3, 6) (3, 9)
2992 LPAR '(' (3, 9) (3, 10)
2993 RPAR ')' (3, 10) (3, 11)
2994 COLON ':' (3, 11) (3, 12)
2995 NAME 'pass' (3, 13) (3, 17)
2996 NEWLINE '' (3, 17) (3, 17)
2997 NAME 'async' (4, 2) (4, 7)
2998 NAME 'def' (4, 8) (4, 11)
2999 NAME 'bar' (4, 12) (4, 15)
3000 LPAR '(' (4, 15) (4, 16)
3001 RPAR ')' (4, 16) (4, 17)
3002 COLON ':' (4, 17) (4, 18)
3003 NAME 'pass' (4, 19) (4, 23)
3004 NEWLINE '' (4, 23) (4, 23)
3005 NAME 'await' (6, 2) (6, 7)
3006 EQUAL '=' (6, 8) (6, 9)
3007 NUMBER '2' (6, 10) (6, 11)
3008 DEDENT '' (6, -1) (6, -1)
3009 """)
3010
3011 self.check_tokenize('''\
3012 async def f():
3013
3014 def baz(): pass
3015 async def bar(): pass
3016
3017 await = 2''', """\
3018 NAME 'async' (1, 0) (1, 5)
3019 NAME 'def' (1, 6) (1, 9)
3020 NAME 'f' (1, 10) (1, 11)
3021 LPAR '(' (1, 11) (1, 12)
3022 RPAR ')' (1, 12) (1, 13)
3023 COLON ':' (1, 13) (1, 14)
3024 NEWLINE '' (1, 14) (1, 14)
3025 INDENT '' (3, -1) (3, -1)
3026 NAME 'def' (3, 2) (3, 5)
3027 NAME 'baz' (3, 6) (3, 9)
3028 LPAR '(' (3, 9) (3, 10)
3029 RPAR ')' (3, 10) (3, 11)
3030 COLON ':' (3, 11) (3, 12)
3031 NAME 'pass' (3, 13) (3, 17)
3032 NEWLINE '' (3, 17) (3, 17)
3033 NAME 'async' (4, 2) (4, 7)
3034 NAME 'def' (4, 8) (4, 11)
3035 NAME 'bar' (4, 12) (4, 15)
3036 LPAR '(' (4, 15) (4, 16)
3037 RPAR ')' (4, 16) (4, 17)
3038 COLON ':' (4, 17) (4, 18)
3039 NAME 'pass' (4, 19) (4, 23)
3040 NEWLINE '' (4, 23) (4, 23)
3041 NAME 'await' (6, 2) (6, 7)
3042 EQUAL '=' (6, 8) (6, 9)
3043 NUMBER '2' (6, 10) (6, 11)
3044 DEDENT '' (6, -1) (6, -1)
3045 """)
3046
3047 def test_unicode(self):
3048
3049 self.check_tokenize("Örter = u'places'\ngrün = U'green'", """\
3050 NAME 'Örter' (1, 0) (1, 5)
3051 EQUAL '=' (1, 6) (1, 7)
3052 STRING "u'places'" (1, 8) (1, 17)
3053 NEWLINE '' (1, 17) (1, 17)
3054 NAME 'grün' (2, 0) (2, 4)
3055 EQUAL '=' (2, 5) (2, 6)
3056 STRING "U'green'" (2, 7) (2, 15)
3057 """)
3058
3059 def test_invalid_syntax(self):
3060 def get_tokens(string):
3061 the_string = StringIO(string)
3062 return list(tokenize._generate_tokens_from_c_tokenizer(the_string.readline))
3063
3064 for case in [
3065 "(1+2]",
3066 "(1+2}",
3067 "{1+2]",
3068 "1_",
3069 "1.2_",
3070 "1e2_",
3071 "1e+",
3072
3073 "\xa0",
3074 "€",
3075 "0b12",
3076 "0b1_2",
3077 "0b2",
3078 "0b1_",
3079 "0b",
3080 "0o18",
3081 "0o1_8",
3082 "0o8",
3083 "0o1_",
3084 "0o",
3085 "0x1_",
3086 "0x",
3087 "1_",
3088 "012",
3089 "1.2_",
3090 "1e2_",
3091 "1e+",
3092 "'sdfsdf",
3093 "'''sdfsdf''",
3094 "("*1000+"a"+")"*1000,
3095 "]",
3096 """\
3097 f'__{
3098 x:d
3099 }__'""",
3100 " a\n\x00",
3101 ]:
3102 with self.subTest(case=case):
3103 self.assertRaises(tokenize.TokenError, get_tokens, case)
3104
3105 def test_max_indent(self):
3106 MAXINDENT = 100
3107
3108 def generate_source(indents):
3109 source = ''.join((' ' * x) + 'if True:\n' for x in range(indents))
3110 source += ' ' * indents + 'pass\n'
3111 return source
3112
3113 valid = generate_source(MAXINDENT - 1)
3114 the_input = StringIO(valid)
3115 tokens = list(tokenize._generate_tokens_from_c_tokenizer(the_input.readline))
3116 self.assertEqual(tokens[-2].type, tokenize.DEDENT)
3117 self.assertEqual(tokens[-1].type, tokenize.ENDMARKER)
3118 compile(valid, "<string>", "exec")
3119
3120 invalid = generate_source(MAXINDENT)
3121 the_input = StringIO(invalid)
3122 self.assertRaises(IndentationError, lambda: list(tokenize._generate_tokens_from_c_tokenizer(the_input.readline)))
3123 self.assertRaises(
3124 IndentationError, compile, invalid, "<string>", "exec"
3125 )
3126
3127 def test_continuation_lines_indentation(self):
3128 def get_tokens(string):
3129 the_string = StringIO(string)
3130 return [(kind, string) for (kind, string, *_)
3131 in tokenize._generate_tokens_from_c_tokenizer(the_string.readline)]
3132
3133 code = dedent("""
3134 def fib(n):
3135 \\
3136 '''Print a Fibonacci series up to n.'''
3137 \\
3138 a, b = 0, 1
3139 """)
3140
3141 self.check_tokenize(code, """\
3142 NAME 'def' (2, 0) (2, 3)
3143 NAME 'fib' (2, 4) (2, 7)
3144 LPAR '(' (2, 7) (2, 8)
3145 NAME 'n' (2, 8) (2, 9)
3146 RPAR ')' (2, 9) (2, 10)
3147 COLON ':' (2, 10) (2, 11)
3148 NEWLINE '' (2, 11) (2, 11)
3149 INDENT '' (4, -1) (4, -1)
3150 STRING "'''Print a Fibonacci series up to n.'''" (4, 0) (4, 39)
3151 NEWLINE '' (4, 39) (4, 39)
3152 NAME 'a' (6, 0) (6, 1)
3153 COMMA ',' (6, 1) (6, 2)
3154 NAME 'b' (6, 3) (6, 4)
3155 EQUAL '=' (6, 5) (6, 6)
3156 NUMBER '0' (6, 7) (6, 8)
3157 COMMA ',' (6, 8) (6, 9)
3158 NUMBER '1' (6, 10) (6, 11)
3159 NEWLINE '' (6, 11) (6, 11)
3160 DEDENT '' (6, -1) (6, -1)
3161 """)
3162
3163 code_no_cont = dedent("""
3164 def fib(n):
3165 '''Print a Fibonacci series up to n.'''
3166 a, b = 0, 1
3167 """)
3168
3169 self.assertEqual(get_tokens(code), get_tokens(code_no_cont))
3170
3171 code = dedent("""
3172 pass
3173 \\
3174
3175 pass
3176 """)
3177
3178 self.check_tokenize(code, """\
3179 NAME 'pass' (2, 0) (2, 4)
3180 NEWLINE '' (2, 4) (2, 4)
3181 NAME 'pass' (5, 0) (5, 4)
3182 NEWLINE '' (5, 4) (5, 4)
3183 """)
3184
3185 code_no_cont = dedent("""
3186 pass
3187 pass
3188 """)
3189
3190 self.assertEqual(get_tokens(code), get_tokens(code_no_cont))
3191
3192 code = dedent("""
3193 if x:
3194 y = 1
3195 \\
3196 \\
3197 \\
3198 \\
3199 foo = 1
3200 """)
3201
3202 self.check_tokenize(code, """\
3203 NAME 'if' (2, 0) (2, 2)
3204 NAME 'x' (2, 3) (2, 4)
3205 COLON ':' (2, 4) (2, 5)
3206 NEWLINE '' (2, 5) (2, 5)
3207 INDENT '' (3, -1) (3, -1)
3208 NAME 'y' (3, 4) (3, 5)
3209 EQUAL '=' (3, 6) (3, 7)
3210 NUMBER '1' (3, 8) (3, 9)
3211 NEWLINE '' (3, 9) (3, 9)
3212 NAME 'foo' (8, 4) (8, 7)
3213 EQUAL '=' (8, 8) (8, 9)
3214 NUMBER '1' (8, 10) (8, 11)
3215 NEWLINE '' (8, 11) (8, 11)
3216 DEDENT '' (8, -1) (8, -1)
3217 """)
3218
3219 code_no_cont = dedent("""
3220 if x:
3221 y = 1
3222 foo = 1
3223 """)
3224
3225 self.assertEqual(get_tokens(code), get_tokens(code_no_cont))
3226
3227
3228 class CTokenizerBufferTests(unittest.TestCase):
3229 def test_newline_at_the_end_of_buffer(self):
3230 # See issue 99581: Make sure that if we need to add a new line at the
3231 # end of the buffer, we have enough space in the buffer, specially when
3232 # the current line is as long as the buffer space available.
3233 test_script = f"""\
3234 #coding: latin-1
3235 #{"a"*10000}
3236 #{"a"*10002}"""
3237 with os_helper.temp_dir() as temp_dir:
3238 file_name = make_script(temp_dir, 'foo', test_script)
3239 run_test_script(file_name)
3240
3241
3242 if __name__ == "__main__":
3243 unittest.main()