blob: 732036888dc5820f83dd510a78160fc63a4984d7 [file] [log] [blame]
Jeremy Hylton4336eda2004-08-07 19:25:33 +00001import compiler
Neil Schemenauerf3694702005-06-02 05:55:20 +00002from compiler.ast import flatten
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003import os, sys, time, unittest
Jeremy Hylton4336eda2004-08-07 19:25:33 +00004import test.test_support
Raymond Hettingered20ad82004-09-04 20:09:13 +00005from random import random
Jeremy Hylton4336eda2004-08-07 19:25:33 +00006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007# How much time in seconds can pass before we print a 'Still working' message.
8_PRINT_WORKING_MSG_INTERVAL = 5 * 60
9
Thomas Wouters9fe394c2007-02-05 01:24:16 +000010class TrivialContext(object):
11 def __enter__(self):
12 return self
13 def __exit__(self, *exc_info):
14 pass
15
Jeremy Hylton4336eda2004-08-07 19:25:33 +000016class CompilerTest(unittest.TestCase):
17
18 def testCompileLibrary(self):
19 # A simple but large test. Compile all the code in the
20 # standard library and its test suite. This doesn't verify
21 # that any of the code is correct, merely the compiler is able
22 # to generate some kind of code for it.
Tim Peters2841af42006-01-07 23:20:46 +000023
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024 next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
Jeremy Hylton4336eda2004-08-07 19:25:33 +000025 libdir = os.path.dirname(unittest.__file__)
26 testdir = os.path.dirname(test.test_support.__file__)
27
Guido van Rossumf59677a2006-11-22 04:55:53 +000028 for dir in [libdir, testdir]:
29 for basename in os.listdir(dir):
30 # Print still working message since this test can be really slow
31 if next_time <= time.time():
32 next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
33 print >>sys.__stdout__, \
34 ' testCompileLibrary still working, be patient...'
35 sys.__stdout__.flush()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000036
Guido van Rossumf59677a2006-11-22 04:55:53 +000037 if not basename.endswith(".py"):
38 continue
39 if not TEST_ALL and random() < 0.98:
40 continue
41 path = os.path.join(dir, basename)
42 if test.test_support.verbose:
43 print "compiling", path
44 f = open(path, "U")
45 buf = f.read()
46 f.close()
47 if "badsyntax" in basename or "bad_coding" in basename:
48 self.assertRaises(SyntaxError, compiler.compile,
49 buf, basename, "exec")
50 else:
51 try:
52 compiler.compile(buf, basename, "exec")
Guido van Rossumb940e112007-01-10 16:19:56 +000053 except Exception as e:
Guido van Rossumf59677a2006-11-22 04:55:53 +000054 args = list(e.args)
55 args[0] += "[in file %s]" % basename
56 e.args = tuple(args)
57 raise
Jeremy Hylton4336eda2004-08-07 19:25:33 +000058
Brett Cannonf4189912005-04-09 02:30:16 +000059 def testNewClassSyntax(self):
60 compiler.compile("class foo():pass\n\n","<string>","exec")
Tim Peterse8906822005-04-20 17:45:13 +000061
Guido van Rossum5bde08d2006-03-02 04:24:01 +000062 def testYieldExpr(self):
63 compiler.compile("def g(): yield\n\n", "<string>", "exec")
64
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065 def testTryExceptFinally(self):
66 # Test that except and finally clauses in one try stmt are recognized
67 c = compiler.compile("try:\n 1/0\nexcept:\n e = 1\nfinally:\n f = 1",
68 "<string>", "exec")
69 dct = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +000070 exec(c, dct)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071 self.assertEquals(dct.get('e'), 1)
72 self.assertEquals(dct.get('f'), 1)
73
Thomas Wouters477c8d52006-05-27 19:21:47 +000074 def testDefaultArgs(self):
75 self.assertRaises(SyntaxError, compiler.parse, "def foo(a=1, b): pass")
76
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077 def testDocstrings(self):
78 c = compiler.compile('"doc"', '<string>', 'exec')
79 self.assert_('__doc__' in c.co_names)
80 c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
81 g = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +000082 exec(c, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083 self.assertEquals(g['f'].__doc__, "doc")
84
Jeremy Hylton566d9342004-09-07 15:28:01 +000085 def testLineNo(self):
86 # Test that all nodes except Module have a correct lineno attribute.
87 filename = __file__
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088 if filename.endswith((".pyc", ".pyo")):
Jeremy Hylton566d9342004-09-07 15:28:01 +000089 filename = filename[:-1]
90 tree = compiler.parseFile(filename)
91 self.check_lineno(tree)
92
93 def check_lineno(self, node):
94 try:
95 self._check_lineno(node)
96 except AssertionError:
97 print node.__class__, node.lineno
98 raise
99
100 def _check_lineno(self, node):
101 if not node.__class__ in NOLINENO:
Tim Peters0e9980f2004-09-12 03:49:31 +0000102 self.assert_(isinstance(node.lineno, int),
Jeremy Hylton566d9342004-09-07 15:28:01 +0000103 "lineno=%s on %s" % (node.lineno, node.__class__))
Tim Peters0e9980f2004-09-12 03:49:31 +0000104 self.assert_(node.lineno > 0,
Jeremy Hylton566d9342004-09-07 15:28:01 +0000105 "lineno=%s on %s" % (node.lineno, node.__class__))
106 for child in node.getChildNodes():
107 self.check_lineno(child)
108
Neil Schemenauerf3694702005-06-02 05:55:20 +0000109 def testFlatten(self):
110 self.assertEquals(flatten([1, [2]]), [1, 2])
111 self.assertEquals(flatten((1, (2,))), [1, 2])
112
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000113 def testNestedScope(self):
114 c = compiler.compile('def g():\n'
115 ' a = 1\n'
116 ' def f(): return a + 2\n'
117 ' return f()\n'
118 'result = g()',
119 '<string>',
120 'exec')
121 dct = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000122 exec(c, dct)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123 self.assertEquals(dct.get('result'), 3)
Neal Norwitzc1505362006-12-28 06:47:50 +0000124 c = compiler.compile('def g(a):\n'
125 ' def f(): return a + 2\n'
126 ' return f()\n'
127 'result = g(1)',
128 '<string>',
129 'exec')
130 dct = {}
131 exec(c, dct)
132 self.assertEquals(dct.get('result'), 3)
133 c = compiler.compile('def g((a, b)):\n'
134 ' def f(): return a + b\n'
135 ' return f()\n'
136 'result = g((1, 2))',
137 '<string>',
138 'exec')
139 dct = {}
140 exec(c, dct)
141 self.assertEquals(dct.get('result'), 3)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000143 def testGenExp(self):
144 c = compiler.compile('list((i,j) for i in range(3) if i < 3'
145 ' for j in range(4) if j > 2)',
146 '<string>',
147 'eval')
148 self.assertEquals(eval(c), [(0, 3), (1, 3), (2, 3)])
149
Neal Norwitzc1505362006-12-28 06:47:50 +0000150 def testFuncAnnotations(self):
151 testdata = [
152 ('def f(a: 1): pass', {'a': 1}),
153 ('''def f(a, (b:1, c:2, d), e:3=4, f=5,
154 *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass
155 ''', {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
156 'k': 11, 'return': 12}),
157 ]
158 for sourcecode, expected in testdata:
159 # avoid IndentationError: unexpected indent from trailing lines
160 sourcecode = sourcecode.rstrip()+'\n'
161 c = compiler.compile(sourcecode, '<string>', 'exec')
162 dct = {}
163 exec(c, dct)
164 self.assertEquals(dct['f'].func_annotations, expected)
165
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000166 def testWith(self):
167 # SF bug 1638243
168 c = compiler.compile('from __future__ import with_statement\n'
169 'def f():\n'
170 ' with TrivialContext():\n'
171 ' return 1\n'
172 'result = f()',
173 '<string>',
174 'exec' )
175 dct = {'TrivialContext': TrivialContext}
176 exec(c, dct)
177 self.assertEquals(dct.get('result'), 1)
178
179 def testWithAss(self):
180 c = compiler.compile('from __future__ import with_statement\n'
181 'def f():\n'
182 ' with TrivialContext() as tc:\n'
183 ' return 1\n'
184 'result = f()',
185 '<string>',
186 'exec' )
187 dct = {'TrivialContext': TrivialContext}
188 exec(c, dct)
189 self.assertEquals(dct.get('result'), 1)
190
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191
Jeremy Hylton566d9342004-09-07 15:28:01 +0000192NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard)
193
194###############################################################################
195# code below is just used to trigger some possible errors, for the benefit of
196# testLineNo
197###############################################################################
198
199class Toto:
200 """docstring"""
201 pass
202
203a, b = 2, 3
204[c, d] = 5, 6
205l = [(x, y) for x, y in zip(range(5), range(5,10))]
206l[0]
207l[3:4]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000208d = {'a': 2}
209d = {}
210t = ()
211t = (1, 2)
212l = []
213l = [1, 2]
Jeremy Hylton566d9342004-09-07 15:28:01 +0000214if l:
215 pass
216else:
217 a, b = b, a
218
219try:
220 print yo
221except:
222 yo = 3
223else:
224 yo += 3
Tim Peters0e9980f2004-09-12 03:49:31 +0000225
Jeremy Hylton566d9342004-09-07 15:28:01 +0000226try:
227 a += b
228finally:
229 b = 0
Tim Peters0e9980f2004-09-12 03:49:31 +0000230
Michael W. Hudsone0b855f2004-11-08 16:46:02 +0000231from math import *
232
Jeremy Hylton566d9342004-09-07 15:28:01 +0000233###############################################################################
234
Neal Norwitzc1505362006-12-28 06:47:50 +0000235def test_main(all=False):
Raymond Hettingered20ad82004-09-04 20:09:13 +0000236 global TEST_ALL
Neal Norwitzc1505362006-12-28 06:47:50 +0000237 TEST_ALL = all or test.test_support.is_resource_enabled("compiler")
Jeremy Hylton4336eda2004-08-07 19:25:33 +0000238 test.test_support.run_unittest(CompilerTest)
239
240if __name__ == "__main__":
Neal Norwitzc1505362006-12-28 06:47:50 +0000241 import sys
242 test_main('all' in sys.argv)