blob: 3027de10cd8383cb393660a6b406f31ba9fa4e72 [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
Jeremy Hylton4336eda2004-08-07 19:25:33 +000010class CompilerTest(unittest.TestCase):
11
12 def testCompileLibrary(self):
13 # A simple but large test. Compile all the code in the
14 # standard library and its test suite. This doesn't verify
15 # that any of the code is correct, merely the compiler is able
16 # to generate some kind of code for it.
Tim Peters2841af42006-01-07 23:20:46 +000017
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018 next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
Jeremy Hylton4336eda2004-08-07 19:25:33 +000019 libdir = os.path.dirname(unittest.__file__)
20 testdir = os.path.dirname(test.test_support.__file__)
21
Guido van Rossum4f72a782006-10-27 23:31:49 +000022## for dir in [libdir, testdir]:
23## for basename in os.listdir(dir):
24## # Print still working message since this test can be really slow
25## if next_time <= time.time():
26## next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
27## print >>sys.__stdout__, \
28## ' testCompileLibrary still working, be patient...'
29## sys.__stdout__.flush()
30##
31## if not basename.endswith(".py"):
32## continue
33## if not TEST_ALL and random() < 0.98:
34## continue
35## path = os.path.join(dir, basename)
36## if test.test_support.verbose:
37## print "compiling", path
38## f = open(path, "U")
39## buf = f.read()
40## f.close()
41## if "badsyntax" in basename or "bad_coding" in basename:
42## self.assertRaises(SyntaxError, compiler.compile,
43## buf, basename, "exec")
44## else:
45## try:
46## compiler.compile(buf, basename, "exec")
47## except Exception, e:
48## args = list(e.args)
49## args[0] += "[in file %s]" % basename
50## e.args = tuple(args)
51## raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052
Guido van Rossum4f72a782006-10-27 23:31:49 +000053 path = "/home/jiwon/p3yk/Lib/test/test_keywordonlyarg.py"
54 if test.test_support.verbose:
55 print "compiling", path
56 f = open(path, "U")
57 buf = f.read()
58 f.close()
59 #try:
60 compiler.compile(buf, "test_keywordonlyarg.py", "exec")
61 #except Exception, e:
62 # args = list(e.args)
63 # args[0] += "[in file %s]" % path
64 # e.args = tuple(args)
65 # raise
66
Jeremy Hylton4336eda2004-08-07 19:25:33 +000067
Brett Cannonf4189912005-04-09 02:30:16 +000068 def testNewClassSyntax(self):
69 compiler.compile("class foo():pass\n\n","<string>","exec")
Tim Peterse8906822005-04-20 17:45:13 +000070
Guido van Rossum5bde08d2006-03-02 04:24:01 +000071 def testYieldExpr(self):
72 compiler.compile("def g(): yield\n\n", "<string>", "exec")
73
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 def testTryExceptFinally(self):
75 # Test that except and finally clauses in one try stmt are recognized
76 c = compiler.compile("try:\n 1/0\nexcept:\n e = 1\nfinally:\n f = 1",
77 "<string>", "exec")
78 dct = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +000079 exec(c, dct)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080 self.assertEquals(dct.get('e'), 1)
81 self.assertEquals(dct.get('f'), 1)
82
Thomas Wouters477c8d52006-05-27 19:21:47 +000083 def testDefaultArgs(self):
84 self.assertRaises(SyntaxError, compiler.parse, "def foo(a=1, b): pass")
85
Thomas Wouters0e3f5912006-08-11 14:57:12 +000086 def testDocstrings(self):
87 c = compiler.compile('"doc"', '<string>', 'exec')
88 self.assert_('__doc__' in c.co_names)
89 c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
90 g = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +000091 exec(c, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092 self.assertEquals(g['f'].__doc__, "doc")
93
Jeremy Hylton566d9342004-09-07 15:28:01 +000094 def testLineNo(self):
95 # Test that all nodes except Module have a correct lineno attribute.
96 filename = __file__
Thomas Wouters0e3f5912006-08-11 14:57:12 +000097 if filename.endswith((".pyc", ".pyo")):
Jeremy Hylton566d9342004-09-07 15:28:01 +000098 filename = filename[:-1]
99 tree = compiler.parseFile(filename)
100 self.check_lineno(tree)
101
102 def check_lineno(self, node):
103 try:
104 self._check_lineno(node)
105 except AssertionError:
106 print node.__class__, node.lineno
107 raise
108
109 def _check_lineno(self, node):
110 if not node.__class__ in NOLINENO:
Tim Peters0e9980f2004-09-12 03:49:31 +0000111 self.assert_(isinstance(node.lineno, int),
Jeremy Hylton566d9342004-09-07 15:28:01 +0000112 "lineno=%s on %s" % (node.lineno, node.__class__))
Tim Peters0e9980f2004-09-12 03:49:31 +0000113 self.assert_(node.lineno > 0,
Jeremy Hylton566d9342004-09-07 15:28:01 +0000114 "lineno=%s on %s" % (node.lineno, node.__class__))
115 for child in node.getChildNodes():
116 self.check_lineno(child)
117
Neil Schemenauerf3694702005-06-02 05:55:20 +0000118 def testFlatten(self):
119 self.assertEquals(flatten([1, [2]]), [1, 2])
120 self.assertEquals(flatten((1, (2,))), [1, 2])
121
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000122 def testNestedScope(self):
123 c = compiler.compile('def g():\n'
124 ' a = 1\n'
125 ' def f(): return a + 2\n'
126 ' return f()\n'
127 'result = g()',
128 '<string>',
129 'exec')
130 dct = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000131 exec(c, dct)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000132 self.assertEquals(dct.get('result'), 3)
133
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000134 def testGenExp(self):
135 c = compiler.compile('list((i,j) for i in range(3) if i < 3'
136 ' for j in range(4) if j > 2)',
137 '<string>',
138 'eval')
139 self.assertEquals(eval(c), [(0, 3), (1, 3), (2, 3)])
140
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141
Jeremy Hylton566d9342004-09-07 15:28:01 +0000142NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard)
143
144###############################################################################
145# code below is just used to trigger some possible errors, for the benefit of
146# testLineNo
147###############################################################################
148
149class Toto:
150 """docstring"""
151 pass
152
153a, b = 2, 3
154[c, d] = 5, 6
155l = [(x, y) for x, y in zip(range(5), range(5,10))]
156l[0]
157l[3:4]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000158d = {'a': 2}
159d = {}
160t = ()
161t = (1, 2)
162l = []
163l = [1, 2]
Jeremy Hylton566d9342004-09-07 15:28:01 +0000164if l:
165 pass
166else:
167 a, b = b, a
168
169try:
170 print yo
171except:
172 yo = 3
173else:
174 yo += 3
Tim Peters0e9980f2004-09-12 03:49:31 +0000175
Jeremy Hylton566d9342004-09-07 15:28:01 +0000176try:
177 a += b
178finally:
179 b = 0
Tim Peters0e9980f2004-09-12 03:49:31 +0000180
Michael W. Hudsone0b855f2004-11-08 16:46:02 +0000181from math import *
182
Jeremy Hylton566d9342004-09-07 15:28:01 +0000183###############################################################################
184
Jeremy Hylton4336eda2004-08-07 19:25:33 +0000185def test_main():
Raymond Hettingered20ad82004-09-04 20:09:13 +0000186 global TEST_ALL
187 TEST_ALL = test.test_support.is_resource_enabled("compiler")
Jeremy Hylton4336eda2004-08-07 19:25:33 +0000188 test.test_support.run_unittest(CompilerTest)
189
190if __name__ == "__main__":
191 test_main()