TestTreeFragment.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from Cython.TestUtils import CythonTest
  2. from Cython.Compiler.TreeFragment import *
  3. from Cython.Compiler.Nodes import *
  4. from Cython.Compiler.UtilNodes import *
  5. import Cython.Compiler.Naming as Naming
  6. class TestTreeFragments(CythonTest):
  7. def test_basic(self):
  8. F = self.fragment(u"x = 4")
  9. T = F.copy()
  10. self.assertCode(u"x = 4", T)
  11. def test_copy_is_taken(self):
  12. F = self.fragment(u"if True: x = 4")
  13. T1 = F.root
  14. T2 = F.copy()
  15. self.assertEqual("x", T2.stats[0].if_clauses[0].body.lhs.name)
  16. T2.stats[0].if_clauses[0].body.lhs.name = "other"
  17. self.assertEqual("x", T1.stats[0].if_clauses[0].body.lhs.name)
  18. def test_substitutions_are_copied(self):
  19. T = self.fragment(u"y + y").substitute({"y": NameNode(pos=None, name="x")})
  20. self.assertEqual("x", T.stats[0].expr.operand1.name)
  21. self.assertEqual("x", T.stats[0].expr.operand2.name)
  22. self.assert_(T.stats[0].expr.operand1 is not T.stats[0].expr.operand2)
  23. def test_substitution(self):
  24. F = self.fragment(u"x = 4")
  25. y = NameNode(pos=None, name=u"y")
  26. T = F.substitute({"x" : y})
  27. self.assertCode(u"y = 4", T)
  28. def test_exprstat(self):
  29. F = self.fragment(u"PASS")
  30. pass_stat = PassStatNode(pos=None)
  31. T = F.substitute({"PASS" : pass_stat})
  32. self.assert_(isinstance(T.stats[0], PassStatNode), T)
  33. def test_pos_is_transferred(self):
  34. F = self.fragment(u"""
  35. x = y
  36. x = u * v ** w
  37. """)
  38. T = F.substitute({"v" : NameNode(pos=None, name="a")})
  39. v = F.root.stats[1].rhs.operand2.operand1
  40. a = T.stats[1].rhs.operand2.operand1
  41. self.assertEqual(v.pos, a.pos)
  42. def test_temps(self):
  43. TemplateTransform.temp_name_counter = 0
  44. F = self.fragment(u"""
  45. TMP
  46. x = TMP
  47. """)
  48. T = F.substitute(temps=[u"TMP"])
  49. s = T.body.stats
  50. self.assert_(isinstance(s[0].expr, TempRefNode))
  51. self.assert_(isinstance(s[1].rhs, TempRefNode))
  52. self.assert_(s[0].expr.handle is s[1].rhs.handle)
  53. if __name__ == "__main__":
  54. import unittest
  55. unittest.main()