blob: c55dc0ebed6432f92df84074ef09e35ea487b7b7 [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
Guido van Rossumbe19ed72007-02-09 05:37:30 +000033 print(' testCompileLibrary still working, be patient...', file=sys.__stdout__)
Guido van Rossumf59677a2006-11-22 04:55:53 +000034 sys.__stdout__.flush()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000035
Guido van Rossumf59677a2006-11-22 04:55:53 +000036 if not basename.endswith(".py"):
37 continue
38 if not TEST_ALL and random() < 0.98:
39 continue
40 path = os.path.join(dir, basename)
41 if test.test_support.verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000042 print("compiling", path)
Guido van Rossumf59677a2006-11-22 04:55:53 +000043 f = open(path, "U")
44 buf = f.read()
45 f.close()
46 if "badsyntax" in basename or "bad_coding" in basename:
47 self.assertRaises(SyntaxError, compiler.compile,
48 buf, basename, "exec")
49 else:
50 try:
51 compiler.compile(buf, basename, "exec")
Guido van Rossumb940e112007-01-10 16:19:56 +000052 except Exception as e:
Guido van Rossumd16e81a2007-03-19 17:56:01 +000053 args = list(e.args) or [""]
54 args[0] = "%s [in file %s]" % (args[0], basename)
Guido van Rossumf59677a2006-11-22 04:55:53 +000055 e.args = tuple(args)
56 raise
Jeremy Hylton4336eda2004-08-07 19:25:33 +000057
Brett Cannonf4189912005-04-09 02:30:16 +000058 def testNewClassSyntax(self):
59 compiler.compile("class foo():pass\n\n","<string>","exec")
Tim Peterse8906822005-04-20 17:45:13 +000060
Guido van Rossum5bde08d2006-03-02 04:24:01 +000061 def testYieldExpr(self):
62 compiler.compile("def g(): yield\n\n", "<string>", "exec")
63
Thomas Wouters0e3f5912006-08-11 14:57:12 +000064 def testTryExceptFinally(self):
65 # Test that except and finally clauses in one try stmt are recognized
66 c = compiler.compile("try:\n 1/0\nexcept:\n e = 1\nfinally:\n f = 1",
67 "<string>", "exec")
68 dct = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +000069 exec(c, dct)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070 self.assertEquals(dct.get('e'), 1)
71 self.assertEquals(dct.get('f'), 1)
72
Thomas Wouters477c8d52006-05-27 19:21:47 +000073 def testDefaultArgs(self):
74 self.assertRaises(SyntaxError, compiler.parse, "def foo(a=1, b): pass")
75
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076 def testDocstrings(self):
77 c = compiler.compile('"doc"', '<string>', 'exec')
78 self.assert_('__doc__' in c.co_names)
79 c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
80 g = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +000081 exec(c, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082 self.assertEquals(g['f'].__doc__, "doc")
83
Jeremy Hylton566d9342004-09-07 15:28:01 +000084 def testLineNo(self):
85 # Test that all nodes except Module have a correct lineno attribute.
86 filename = __file__
Thomas Wouters0e3f5912006-08-11 14:57:12 +000087 if filename.endswith((".pyc", ".pyo")):
Jeremy Hylton566d9342004-09-07 15:28:01 +000088 filename = filename[:-1]
89 tree = compiler.parseFile(filename)
90 self.check_lineno(tree)
91
92 def check_lineno(self, node):
93 try:
94 self._check_lineno(node)
95 except AssertionError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000096 print(node.__class__, node.lineno)
Jeremy Hylton566d9342004-09-07 15:28:01 +000097 raise
98
99 def _check_lineno(self, node):
100 if not node.__class__ in NOLINENO:
Tim Peters0e9980f2004-09-12 03:49:31 +0000101 self.assert_(isinstance(node.lineno, int),
Jeremy Hylton566d9342004-09-07 15:28:01 +0000102 "lineno=%s on %s" % (node.lineno, node.__class__))
Tim Peters0e9980f2004-09-12 03:49:31 +0000103 self.assert_(node.lineno > 0,
Jeremy Hylton566d9342004-09-07 15:28:01 +0000104 "lineno=%s on %s" % (node.lineno, node.__class__))
105 for child in node.getChildNodes():
106 self.check_lineno(child)
107
Neil Schemenauerf3694702005-06-02 05:55:20 +0000108 def testFlatten(self):
109 self.assertEquals(flatten([1, [2]]), [1, 2])
110 self.assertEquals(flatten((1, (2,))), [1, 2])
111
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112 def testNestedScope(self):
113 c = compiler.compile('def g():\n'
114 ' a = 1\n'
115 ' def f(): return a + 2\n'
116 ' return f()\n'
117 'result = g()',
118 '<string>',
119 'exec')
120 dct = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000121 exec(c, dct)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000122 self.assertEquals(dct.get('result'), 3)
Neal Norwitzc1505362006-12-28 06:47:50 +0000123 c = compiler.compile('def g(a):\n'
124 ' def f(): return a + 2\n'
125 ' return f()\n'
126 'result = g(1)',
127 '<string>',
128 'exec')
129 dct = {}
130 exec(c, dct)
131 self.assertEquals(dct.get('result'), 3)
132 c = compiler.compile('def g((a, b)):\n'
133 ' def f(): return a + b\n'
134 ' return f()\n'
135 'result = g((1, 2))',
136 '<string>',
137 'exec')
138 dct = {}
139 exec(c, dct)
140 self.assertEquals(dct.get('result'), 3)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000142 def testGenExp(self):
143 c = compiler.compile('list((i,j) for i in range(3) if i < 3'
144 ' for j in range(4) if j > 2)',
145 '<string>',
146 'eval')
147 self.assertEquals(eval(c), [(0, 3), (1, 3), (2, 3)])
148
Neal Norwitzc1505362006-12-28 06:47:50 +0000149 def testFuncAnnotations(self):
150 testdata = [
151 ('def f(a: 1): pass', {'a': 1}),
152 ('''def f(a, (b:1, c:2, d), e:3=4, f=5,
153 *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass
154 ''', {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
155 'k': 11, 'return': 12}),
156 ]
157 for sourcecode, expected in testdata:
158 # avoid IndentationError: unexpected indent from trailing lines
159 sourcecode = sourcecode.rstrip()+'\n'
160 c = compiler.compile(sourcecode, '<string>', 'exec')
161 dct = {}
162 exec(c, dct)
Neal Norwitz221085d2007-02-25 20:55:47 +0000163 self.assertEquals(dct['f'].__annotations__, expected)
Neal Norwitzc1505362006-12-28 06:47:50 +0000164
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000165 def testWith(self):
166 # SF bug 1638243
167 c = compiler.compile('from __future__ import with_statement\n'
168 'def f():\n'
169 ' with TrivialContext():\n'
170 ' return 1\n'
171 'result = f()',
172 '<string>',
173 'exec' )
174 dct = {'TrivialContext': TrivialContext}
175 exec(c, dct)
176 self.assertEquals(dct.get('result'), 1)
177
178 def testWithAss(self):
179 c = compiler.compile('from __future__ import with_statement\n'
180 'def f():\n'
181 ' with TrivialContext() as tc:\n'
182 ' return 1\n'
183 'result = f()',
184 '<string>',
185 'exec' )
186 dct = {'TrivialContext': TrivialContext}
187 exec(c, dct)
188 self.assertEquals(dct.get('result'), 1)
189
Thomas Wouters00e41de2007-02-23 19:56:57 +0000190 def testBytesLiteral(self):
191 c = compiler.compile("b'foo'", '<string>', 'eval')
192 b = eval(c)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000193
Thomas Wouters00e41de2007-02-23 19:56:57 +0000194 c = compiler.compile('def f(b=b"foo"):\n'
195 ' b[0] += 1\n'
196 ' return b\n'
197 'f(); f(); result = f()\n',
198 '<string>',
199 'exec')
200 dct = {}
201 exec(c, dct)
202 self.assertEquals(dct.get('result'), b"ioo")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203
Thomas Wouters00e41de2007-02-23 19:56:57 +0000204 c = compiler.compile('def f():\n'
205 ' b = b"foo"\n'
206 ' b[0] += 1\n'
207 ' return b\n'
208 'f(); f(); result = f()\n',
209 '<string>',
210 'exec')
211 dct = {}
212 exec(c, dct)
213 self.assertEquals(dct.get('result'), b"goo")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000214
Jeremy Hylton566d9342004-09-07 15:28:01 +0000215NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard)
216
217###############################################################################
218# code below is just used to trigger some possible errors, for the benefit of
219# testLineNo
220###############################################################################
221
222class Toto:
223 """docstring"""
224 pass
225
226a, b = 2, 3
227[c, d] = 5, 6
228l = [(x, y) for x, y in zip(range(5), range(5,10))]
229l[0]
230l[3:4]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000231d = {'a': 2}
232d = {}
233t = ()
234t = (1, 2)
235l = []
236l = [1, 2]
Jeremy Hylton566d9342004-09-07 15:28:01 +0000237if l:
238 pass
239else:
240 a, b = b, a
241
242try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000243 print(yo)
Jeremy Hylton566d9342004-09-07 15:28:01 +0000244except:
245 yo = 3
246else:
247 yo += 3
Tim Peters0e9980f2004-09-12 03:49:31 +0000248
Jeremy Hylton566d9342004-09-07 15:28:01 +0000249try:
250 a += b
251finally:
252 b = 0
Tim Peters0e9980f2004-09-12 03:49:31 +0000253
Michael W. Hudsone0b855f2004-11-08 16:46:02 +0000254from math import *
255
Jeremy Hylton566d9342004-09-07 15:28:01 +0000256###############################################################################
257
Neal Norwitzc1505362006-12-28 06:47:50 +0000258def test_main(all=False):
Raymond Hettingered20ad82004-09-04 20:09:13 +0000259 global TEST_ALL
Neal Norwitzc1505362006-12-28 06:47:50 +0000260 TEST_ALL = all or test.test_support.is_resource_enabled("compiler")
Jeremy Hylton4336eda2004-08-07 19:25:33 +0000261 test.test_support.run_unittest(CompilerTest)
262
263if __name__ == "__main__":
Neal Norwitzc1505362006-12-28 06:47:50 +0000264 import sys
265 test_main('all' in sys.argv)