1 # Copyright 2017 The TensorFlow Authors. All Rights Reserved. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 # ============================================================================== 15 """Tests for ast_util module.""" 16 17 from __future__ import absolute_import 18 from __future__ import division 19 from __future__ import print_function 20 21 import ast 22 23 from tensorflow.contrib.py2tf.pyct import ast_util 24 from tensorflow.contrib.py2tf.pyct import qual_names 25 from tensorflow.python.platform import test 26 27 28 class AstUtilTest(test.TestCase): 29 30 def test_rename_symbols(self): 31 node = ast.Tuple([ 32 ast.Name('a', ast.Load()), 33 ast.Name('b', ast.Load()), 34 ast.Attribute(ast.Name('b', None), 'c', ast.Store()), 35 ast.Attribute( 36 ast.Attribute(ast.Name('b', None), 'c', ast.Load()), 'd', 37 None) 38 ], None) 39 node = qual_names.resolve(node) 40 node = ast_util.rename_symbols( 41 node, 42 { 43 qual_names.QN('a'): qual_names.QN('renamed_a'), 44 qual_names.QN('b.c'): qual_names.QN('renamed_b_c'), 45 }) 46 47 self.assertEqual(node.elts[0].id, 'renamed_a') 48 self.assertTrue(isinstance(node.elts[0].ctx, ast.Load)) 49 self.assertEqual(node.elts[1].id, 'b') 50 self.assertEqual(node.elts[2].id, 'renamed_b_c') 51 self.assertTrue(isinstance(node.elts[2].ctx, ast.Store)) 52 self.assertEqual(node.elts[3].value.id, 'renamed_b_c') 53 self.assertTrue(isinstance(node.elts[3].value.ctx, ast.Load)) 54 55 def test_copy_clean(self): 56 ret = ast.Return( 57 ast.BinOp( 58 op=ast.Add(), 59 left=ast.Name(id='a', ctx=ast.Load()), 60 right=ast.Num(1))) 61 setattr(ret, '__foo', 'bar') 62 node = ast.FunctionDef( 63 name='f', 64 args=ast.arguments( 65 args=[ast.Name(id='a', ctx=ast.Param())], 66 vararg=None, 67 kwarg=None, 68 defaults=[]), 69 body=[ret], 70 decorator_list=[], 71 returns=None) 72 new_node = ast_util.copy_clean(node) 73 self.assertFalse(node is new_node) 74 self.assertFalse(ret is new_node.body[0]) 75 self.assertFalse(hasattr(new_node.body[0], '__foo')) 76 77 78 if __name__ == '__main__': 79 test.main() 80