diff options
author | Irit Katriel <1055913+iritkatriel@users.noreply.github.com> | 2023-08-21 16:31:30 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-08-21 16:31:30 (GMT) |
commit | 10a91d7e98d847b05292eab828ff9ae51308d3ee (patch) | |
tree | a81f95a971c03710f13217cf89e0f12532341af8 /Lib/test/test_builtin.py | |
parent | 47022a079eb9d2a2af781abae3de4a71f80247c2 (diff) | |
download | cpython-10a91d7e98d847b05292eab828ff9ae51308d3ee.zip cpython-10a91d7e98d847b05292eab828ff9ae51308d3ee.tar.gz cpython-10a91d7e98d847b05292eab828ff9ae51308d3ee.tar.bz2 |
gh-108113: Make it possible to create an optimized AST (#108154)
Diffstat (limited to 'Lib/test/test_builtin.py')
-rw-r--r-- | Lib/test/test_builtin.py | 41 |
1 files changed, 32 insertions, 9 deletions
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index f5a5c03..ee3ba6a 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -369,16 +369,17 @@ class BuiltinTest(unittest.TestCase): (1, False, 'doc', False, False), (2, False, None, False, False)] for optval, *expected in values: + with self.subTest(optval=optval): # test both direct compilation and compilation via AST - codeobjs = [] - codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval)) - tree = ast.parse(codestr) - codeobjs.append(compile(tree, "<test>", "exec", optimize=optval)) - for code in codeobjs: - ns = {} - exec(code, ns) - rv = ns['f']() - self.assertEqual(rv, tuple(expected)) + codeobjs = [] + codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval)) + tree = ast.parse(codestr) + codeobjs.append(compile(tree, "<test>", "exec", optimize=optval)) + for code in codeobjs: + ns = {} + exec(code, ns) + rv = ns['f']() + self.assertEqual(rv, tuple(expected)) def test_compile_top_level_await_no_coro(self): """Make sure top level non-await codes get the correct coroutine flags""" @@ -517,6 +518,28 @@ class BuiltinTest(unittest.TestCase): exec(co, glob) self.assertEqual(type(glob['ticker']()), AsyncGeneratorType) + def test_compile_ast(self): + args = ("a*(1+2)", "f.py", "exec") + raw = compile(*args, flags = ast.PyCF_ONLY_AST).body[0] + opt = compile(*args, flags = ast.PyCF_OPTIMIZED_AST).body[0] + + for tree in (raw, opt): + self.assertIsInstance(tree.value, ast.BinOp) + self.assertIsInstance(tree.value.op, ast.Mult) + self.assertIsInstance(tree.value.left, ast.Name) + self.assertEqual(tree.value.left.id, 'a') + + raw_right = raw.value.right # expect BinOp(1, '+', 2) + self.assertIsInstance(raw_right, ast.BinOp) + self.assertIsInstance(raw_right.left, ast.Constant) + self.assertEqual(raw_right.left.value, 1) + self.assertIsInstance(raw_right.right, ast.Constant) + self.assertEqual(raw_right.right.value, 2) + + opt_right = opt.value.right # expect Constant(3) + self.assertIsInstance(opt_right, ast.Constant) + self.assertEqual(opt_right.value, 3) + def test_delattr(self): sys.spam = 1 delattr(sys, 'spam') |