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.

276 lines
7.0 KiB

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