You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

240 lines
6.2 KiB

  1. import unittest
  2. import test.support
  3. import io
  4. import os
  5. import tokenize
  6. import ast
  7. import unparse
  8. def read_pyfile(filename):
  9. """Read and return the contents of a Python source file (as a
  10. string), taking into account the file encoding."""
  11. with open(filename, "rb") as pyfile:
  12. encoding = tokenize.detect_encoding(pyfile.readline)[0]
  13. with open(filename, "r", encoding=encoding) as pyfile:
  14. source = pyfile.read()
  15. return source
  16. for_else = """\
  17. def f():
  18. for x in range(10):
  19. break
  20. else:
  21. y = 2
  22. z = 3
  23. """
  24. while_else = """\
  25. def g():
  26. while True:
  27. break
  28. else:
  29. y = 2
  30. z = 3
  31. """
  32. relative_import = """\
  33. from . import fred
  34. from .. import barney
  35. from .australia import shrimp as prawns
  36. """
  37. nonlocal_ex = """\
  38. def f():
  39. x = 1
  40. def g():
  41. nonlocal x
  42. x = 2
  43. y = 7
  44. def h():
  45. nonlocal x, y
  46. """
  47. # also acts as test for 'except ... as ...'
  48. raise_from = """\
  49. try:
  50. 1 / 0
  51. except ZeroDivisionError as e:
  52. raise ArithmeticError from e
  53. """
  54. class_decorator = """\
  55. @f1(arg)
  56. @f2
  57. class Foo: pass
  58. """
  59. elif1 = """\
  60. if cond1:
  61. suite1
  62. elif cond2:
  63. suite2
  64. else:
  65. suite3
  66. """
  67. elif2 = """\
  68. if cond1:
  69. suite1
  70. elif cond2:
  71. suite2
  72. """
  73. try_except_finally = """\
  74. try:
  75. suite1
  76. except ex1:
  77. suite2
  78. except ex2:
  79. suite3
  80. else:
  81. suite4
  82. finally:
  83. suite5
  84. """
  85. class ASTTestCase(unittest.TestCase):
  86. def assertASTEqual(self, ast1, ast2):
  87. self.assertEqual(ast.dump(ast1), ast.dump(ast2))
  88. def check_roundtrip(self, code1, filename="internal"):
  89. ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST)
  90. unparse_buffer = io.StringIO()
  91. unparse.Unparser(ast1, unparse_buffer)
  92. code2 = unparse_buffer.getvalue()
  93. ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST)
  94. self.assertASTEqual(ast1, ast2)
  95. class UnparseTestCase(ASTTestCase):
  96. # Tests for specific bugs found in earlier versions of unparse
  97. def test_del_statement(self):
  98. self.check_roundtrip("del x, y, z")
  99. def test_shifts(self):
  100. self.check_roundtrip("45 << 2")
  101. self.check_roundtrip("13 >> 7")
  102. def test_for_else(self):
  103. self.check_roundtrip(for_else)
  104. def test_while_else(self):
  105. self.check_roundtrip(while_else)
  106. def test_unary_parens(self):
  107. self.check_roundtrip("(-1)**7")
  108. self.check_roundtrip("(-1.)**8")
  109. self.check_roundtrip("(-1j)**6")
  110. self.check_roundtrip("not True or False")
  111. self.check_roundtrip("True or not False")
  112. def test_integer_parens(self):
  113. self.check_roundtrip("3 .__abs__()")
  114. def test_huge_float(self):
  115. self.check_roundtrip("1e1000")
  116. self.check_roundtrip("-1e1000")
  117. self.check_roundtrip("1e1000j")
  118. self.check_roundtrip("-1e1000j")
  119. def test_min_int(self):
  120. self.check_roundtrip(str(-2**31))
  121. self.check_roundtrip(str(-2**63))
  122. def test_imaginary_literals(self):
  123. self.check_roundtrip("7j")
  124. self.check_roundtrip("-7j")
  125. self.check_roundtrip("0j")
  126. self.check_roundtrip("-0j")
  127. def test_lambda_parentheses(self):
  128. self.check_roundtrip("(lambda: int)()")
  129. def test_chained_comparisons(self):
  130. self.check_roundtrip("1 < 4 <= 5")
  131. self.check_roundtrip("a is b is c is not d")
  132. def test_function_arguments(self):
  133. self.check_roundtrip("def f(): pass")
  134. self.check_roundtrip("def f(a): pass")
  135. self.check_roundtrip("def f(b = 2): pass")
  136. self.check_roundtrip("def f(a, b): pass")
  137. self.check_roundtrip("def f(a, b = 2): pass")
  138. self.check_roundtrip("def f(a = 5, b = 2): pass")
  139. self.check_roundtrip("def f(*, a = 1, b = 2): pass")
  140. self.check_roundtrip("def f(*, a = 1, b): pass")
  141. self.check_roundtrip("def f(*, a, b = 2): pass")
  142. self.check_roundtrip("def f(a, b = None, *, c, **kwds): pass")
  143. self.check_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass")
  144. self.check_roundtrip("def f(*args, **kwargs): pass")
  145. def test_relative_import(self):
  146. self.check_roundtrip(relative_import)
  147. def test_nonlocal(self):
  148. self.check_roundtrip(nonlocal_ex)
  149. def test_raise_from(self):
  150. self.check_roundtrip(raise_from)
  151. def test_bytes(self):
  152. self.check_roundtrip("b'123'")
  153. def test_annotations(self):
  154. self.check_roundtrip("def f(a : int): pass")
  155. self.check_roundtrip("def f(a: int = 5): pass")
  156. self.check_roundtrip("def f(*args: [int]): pass")
  157. self.check_roundtrip("def f(**kwargs: dict): pass")
  158. self.check_roundtrip("def f() -> None: pass")
  159. def test_set_literal(self):
  160. self.check_roundtrip("{'a', 'b', 'c'}")
  161. def test_set_comprehension(self):
  162. self.check_roundtrip("{x for x in range(5)}")
  163. def test_dict_comprehension(self):
  164. self.check_roundtrip("{x: x*x for x in range(10)}")
  165. def test_class_decorators(self):
  166. self.check_roundtrip(class_decorator)
  167. def test_class_definition(self):
  168. self.check_roundtrip("class A(metaclass=type, *[], **{}): pass")
  169. def test_elifs(self):
  170. self.check_roundtrip(elif1)
  171. self.check_roundtrip(elif2)
  172. def test_try_except_finally(self):
  173. self.check_roundtrip(try_except_finally)
  174. class DirectoryTestCase(ASTTestCase):
  175. """Test roundtrip behaviour on all files in Lib and Lib/test."""
  176. # test directories, relative to the root of the distribution
  177. test_directories = 'Lib', os.path.join('Lib', 'test')
  178. def test_files(self):
  179. # get names of files to test
  180. dist_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
  181. names = []
  182. for d in self.test_directories:
  183. test_dir = os.path.join(dist_dir, d)
  184. for n in os.listdir(test_dir):
  185. if n.endswith('.py') and not n.startswith('bad'):
  186. names.append(os.path.join(test_dir, n))
  187. for filename in names:
  188. if test.support.verbose:
  189. print('Testing %s' % filename)
  190. source = read_pyfile(filename)
  191. self.check_roundtrip(source)
  192. def test_main():
  193. test.support.run_unittest(UnparseTestCase, DirectoryTestCase)
  194. if __name__ == '__main__':
  195. test_main()