blob: d3c1cc498d2633db8e99e5207d5d17ab2461bed8 [file] [log] [blame]
Raymond Hettingerda99d1c2005-06-21 07:43:58 +00001from test.test_support import verbose, findfile, is_resource_enabled, TestFailed
Raymond Hettinger68c04532005-06-10 11:05:19 +00002import os, glob, random
3from tokenize import (tokenize, generate_tokens, untokenize,
4 NUMBER, NAME, OP, STRING)
Guido van Rossum0874f7f1997-10-27 22:15:06 +00005
Guido van Rossum0874f7f1997-10-27 22:15:06 +00006if verbose:
7 print 'starting...'
Tim Peters11cb8132003-05-12 19:29:36 +00008
Tim Peters0ff2ee02003-05-12 19:42:04 +00009f = file(findfile('tokenize_tests' + os.extsep + 'txt'))
Raymond Hettinger68c04532005-06-10 11:05:19 +000010tokenize(f.readline)
Tim Peters11cb8132003-05-12 19:29:36 +000011f.close()
12
Raymond Hettinger68c04532005-06-10 11:05:19 +000013
14
15###### Test roundtrip for untokenize ##########################
16
17def test_roundtrip(f):
18 ## print 'Testing:', f
19 f = file(f)
20 try:
21 fulltok = list(generate_tokens(f.readline))
22 finally:
23 f.close()
24
25 t1 = [tok[:2] for tok in fulltok]
26 newtext = untokenize(t1)
27 readline = iter(newtext.splitlines(1)).next
28 t2 = [tok[:2] for tok in generate_tokens(readline)]
29 assert t1 == t2
30
31
32f = findfile('tokenize_tests' + os.extsep + 'txt')
33test_roundtrip(f)
34
35testdir = os.path.dirname(f) or os.curdir
36testfiles = glob.glob(testdir + os.sep + 'test*.py')
37if not is_resource_enabled('compiler'):
38 testfiles = random.sample(testfiles, 10)
39
40for f in testfiles:
41 test_roundtrip(f)
42
43
Raymond Hettingerda99d1c2005-06-21 07:43:58 +000044###### Test detecton of IndentationError ######################
45
46from cStringIO import StringIO
47
48sampleBadText = """
49def foo():
50 bar
51 baz
52"""
53
54try:
55 for tok in generate_tokens(StringIO(sampleBadText).readline):
56 pass
57except IndentationError:
58 pass
59else:
60 raise TestFailed("Did not detect IndentationError:")
61
Raymond Hettinger68c04532005-06-10 11:05:19 +000062
63###### Test example in the docs ###############################
64
65from decimal import Decimal
66from cStringIO import StringIO
67
68def decistmt(s):
69 """Substitute Decimals for floats in a string of statements.
70
71 >>> from decimal import Decimal
72 >>> s = 'print +21.3e-5*-.1234/81.7'
73 >>> decistmt(s)
74 "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')"
75
76 >>> exec(s)
77 -3.21716034272e-007
78 >>> exec(decistmt(s))
79 -3.217160342717258261933904529E-7
80
81 """
82 result = []
83 g = generate_tokens(StringIO(s).readline) # tokenize the string
84 for toknum, tokval, _, _, _ in g:
85 if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens
86 result.extend([
87 (NAME, 'Decimal'),
88 (OP, '('),
89 (STRING, repr(tokval)),
90 (OP, ')')
91 ])
92 else:
93 result.append((toknum, tokval))
94 return untokenize(result)
95
96import doctest
97doctest.testmod()
98
Guido van Rossum0874f7f1997-10-27 22:15:06 +000099if verbose:
100 print 'finished'