blob: 6c060f3d2555b7aa919a1452f204a211c560ae48 [file] [log] [blame]
Mark Dickinsonae100052010-06-28 19:44:20 +00001import unittest
2import test.support
Mark Dickinsonae100052010-06-28 19:44:20 +00003import io
Mark Dickinsond751c2e2010-06-29 14:08:23 +00004import os
5import tokenize
Mark Dickinsonae100052010-06-28 19:44:20 +00006import ast
Mark Dickinsonae100052010-06-28 19:44:20 +00007import unparse
8
Mark Dickinsond751c2e2010-06-29 14:08:23 +00009def read_pyfile(filename):
10 """Read and return the contents of a Python source file (as a
11 string), taking into account the file encoding."""
12 with open(filename, "rb") as pyfile:
13 encoding = tokenize.detect_encoding(pyfile.readline)[0]
14 with open(filename, "r", encoding=encoding) as pyfile:
15 source = pyfile.read()
16 return source
17
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +000018for_else = """\
Mark Dickinsonae100052010-06-28 19:44:20 +000019def f():
20 for x in range(10):
21 break
22 else:
23 y = 2
24 z = 3
25"""
26
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +000027while_else = """\
Mark Dickinsonae100052010-06-28 19:44:20 +000028def g():
29 while True:
30 break
31 else:
32 y = 2
33 z = 3
34"""
35
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +000036relative_import = """\
37from . import fred
38from .. import barney
39from .australia import shrimp as prawns
40"""
41
42nonlocal_ex = """\
43def f():
44 x = 1
45 def g():
46 nonlocal x
47 x = 2
48 y = 7
49 def h():
50 nonlocal x, y
51"""
52
53# also acts as test for 'except ... as ...'
54raise_from = """\
55try:
56 1 / 0
57except ZeroDivisionError as e:
58 raise ArithmeticError from e
59"""
60
61class_decorator = """\
62@f1(arg)
63@f2
64class Foo: pass
65"""
66
Mark Dickinsond751c2e2010-06-29 14:08:23 +000067class ASTTestCase(unittest.TestCase):
68 def assertASTEqual(self, ast1, ast2):
69 self.assertEqual(ast.dump(ast1), ast.dump(ast2))
Mark Dickinsonae100052010-06-28 19:44:20 +000070
71 def check_roundtrip(self, code1, filename="internal"):
Mark Dickinsond751c2e2010-06-29 14:08:23 +000072 ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST)
Mark Dickinsonae100052010-06-28 19:44:20 +000073 unparse_buffer = io.StringIO()
74 unparse.Unparser(ast1, unparse_buffer)
75 code2 = unparse_buffer.getvalue()
Mark Dickinsond751c2e2010-06-29 14:08:23 +000076 ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST)
77 self.assertASTEqual(ast1, ast2)
78
79class UnparseTestCase(ASTTestCase):
80 # Tests for specific bugs found in earlier versions of unparse
Mark Dickinsonae100052010-06-28 19:44:20 +000081
82 def test_del_statement(self):
83 self.check_roundtrip("del x, y, z")
84
85 def test_shifts(self):
86 self.check_roundtrip("45 << 2")
87 self.check_roundtrip("13 >> 7")
88
89 def test_for_else(self):
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +000090 self.check_roundtrip(for_else)
Mark Dickinsonae100052010-06-28 19:44:20 +000091
92 def test_while_else(self):
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +000093 self.check_roundtrip(while_else)
Mark Dickinsonae100052010-06-28 19:44:20 +000094
95 def test_unary_parens(self):
96 self.check_roundtrip("(-1)**7")
97 self.check_roundtrip("not True or False")
98 self.check_roundtrip("True or not False")
99
Mark Dickinson3eb02902010-06-29 08:52:36 +0000100 def test_integer_parens(self):
101 self.check_roundtrip("3 .__abs__()")
102
Mark Dickinson8042e282010-06-29 10:01:48 +0000103 def test_huge_float(self):
104 self.check_roundtrip("1e1000")
105 self.check_roundtrip("-1e1000")
106
107 def test_lambda_parentheses(self):
108 self.check_roundtrip("(lambda: int)()")
109
Mark Dickinsonf5451e52010-06-28 20:09:18 +0000110 def test_chained_comparisons(self):
111 self.check_roundtrip("1 < 4 <= 5")
112 self.check_roundtrip("a is b is c is not d")
113
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000114 def test_function_arguments(self):
115 self.check_roundtrip("def f(): pass")
116 self.check_roundtrip("def f(a): pass")
117 self.check_roundtrip("def f(b = 2): pass")
118 self.check_roundtrip("def f(a, b): pass")
119 self.check_roundtrip("def f(a, b = 2): pass")
120 self.check_roundtrip("def f(a = 5, b = 2): pass")
121 self.check_roundtrip("def f(*, a = 1, b = 2): pass")
122 self.check_roundtrip("def f(*, a = 1, b): pass")
123 self.check_roundtrip("def f(*, a, b = 2): pass")
124 self.check_roundtrip("def f(a, b = None, *, c, **kwds): pass")
125 self.check_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass")
126 self.check_roundtrip("def f(*args, **kwargs): pass")
127
128 def test_relative_import(self):
129 self.check_roundtrip(relative_import)
130
131 def test_nonlocal(self):
132 self.check_roundtrip(nonlocal_ex)
133
134 def test_raise_from(self):
135 self.check_roundtrip(raise_from)
136
137 def test_bytes(self):
138 self.check_roundtrip("b'123'")
139
140 def test_annotations(self):
141 self.check_roundtrip("def f(a : int): pass")
142 self.check_roundtrip("def f(a: int = 5): pass")
143 self.check_roundtrip("def f(*args: [int]): pass")
144 self.check_roundtrip("def f(**kwargs: dict): pass")
145 self.check_roundtrip("def f() -> None: pass")
146
147 def test_set_literal(self):
148 self.check_roundtrip("{'a', 'b', 'c'}")
149
150 def test_set_comprehension(self):
151 self.check_roundtrip("{x for x in range(5)}")
152
153 def test_dict_comprehension(self):
154 self.check_roundtrip("{x: x*x for x in range(10)}")
155
156 def test_class_decorators(self):
157 self.check_roundtrip(class_decorator)
Mark Dickinsonae100052010-06-28 19:44:20 +0000158
Mark Dickinsond751c2e2010-06-29 14:08:23 +0000159
160class DirectoryTestCase(ASTTestCase):
161 """Test roundtrip behaviour on all files in Lib and Lib/test."""
162
163 # test directories, relative to the root of the distribution
164 test_directories = 'Lib', os.path.join('Lib', 'test')
165
166 def test_files(self):
167 # get names of files to test
168 dist_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
169
170 names = []
171 for d in self.test_directories:
172 test_dir = os.path.join(dist_dir, d)
173 for n in os.listdir(test_dir):
174 if n.endswith('.py') and not n.startswith('bad'):
175 names.append(os.path.join(test_dir, n))
176
177 for filename in names:
178 if test.support.verbose:
179 print('Testing %s' % filename)
180 source = read_pyfile(filename)
181 self.check_roundtrip(source)
182
183
Mark Dickinsonae100052010-06-28 19:44:20 +0000184def test_main():
Mark Dickinsond751c2e2010-06-29 14:08:23 +0000185 test.support.run_unittest(UnparseTestCase, DirectoryTestCase)
Mark Dickinsonae100052010-06-28 19:44:20 +0000186
187if __name__ == '__main__':
188 test_main()