Mark Dickinson | 623b979 | 2010-06-28 19:31:41 +0000 | [diff] [blame^] | 1 | import unittest |
| 2 | from test import test_support |
| 3 | |
| 4 | import cStringIO |
| 5 | import ast |
| 6 | import _ast |
| 7 | import unparse |
| 8 | |
| 9 | forelse = """\ |
| 10 | def f(): |
| 11 | for x in range(10): |
| 12 | break |
| 13 | else: |
| 14 | y = 2 |
| 15 | z = 3 |
| 16 | """ |
| 17 | |
| 18 | whileelse = """\ |
| 19 | def g(): |
| 20 | while True: |
| 21 | break |
| 22 | else: |
| 23 | y = 2 |
| 24 | z = 3 |
| 25 | """ |
| 26 | |
| 27 | class UnparseTestCase(unittest.TestCase): |
| 28 | # Tests for specific bugs found in earlier versions of unparse |
| 29 | |
| 30 | def check_roundtrip(self, code1, filename="internal"): |
| 31 | ast1 = compile(code1, filename, "exec", _ast.PyCF_ONLY_AST) |
| 32 | unparse_buffer = cStringIO.StringIO() |
| 33 | unparse.Unparser(ast1, unparse_buffer) |
| 34 | code2 = unparse_buffer.getvalue() |
| 35 | ast2 = compile(code2, filename, "exec", _ast.PyCF_ONLY_AST) |
| 36 | self.assertEqual(ast.dump(ast1), ast.dump(ast2)) |
| 37 | |
| 38 | def test_del_statement(self): |
| 39 | self.check_roundtrip("del x, y, z") |
| 40 | |
| 41 | def test_shifts(self): |
| 42 | self.check_roundtrip("45 << 2") |
| 43 | self.check_roundtrip("13 >> 7") |
| 44 | |
| 45 | def test_for_else(self): |
| 46 | self.check_roundtrip(forelse) |
| 47 | |
| 48 | def test_while_else(self): |
| 49 | self.check_roundtrip(forelse) |
| 50 | |
| 51 | def test_unary_parens(self): |
| 52 | self.check_roundtrip("(-1)**7") |
| 53 | self.check_roundtrip("not True or False") |
| 54 | self.check_roundtrip("True or not False") |
| 55 | |
| 56 | |
| 57 | def test_main(): |
| 58 | test_support.run_unittest(UnparseTestCase) |
| 59 | |
| 60 | if __name__ == '__main__': |
| 61 | test_main() |