TestVisitor.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from Cython.Compiler.ModuleNode import ModuleNode
  2. from Cython.Compiler.Symtab import ModuleScope
  3. from Cython.TestUtils import TransformTest
  4. from Cython.Compiler.Visitor import MethodDispatcherTransform
  5. from Cython.Compiler.ParseTreeTransforms import (
  6. NormalizeTree, AnalyseDeclarationsTransform,
  7. AnalyseExpressionsTransform, InterpretCompilerDirectives)
  8. class TestMethodDispatcherTransform(TransformTest):
  9. _tree = None
  10. def _build_tree(self):
  11. if self._tree is None:
  12. context = None
  13. def fake_module(node):
  14. scope = ModuleScope('test', None, None)
  15. return ModuleNode(node.pos, doc=None, body=node,
  16. scope=scope, full_module_name='test',
  17. directive_comments={})
  18. pipeline = [
  19. fake_module,
  20. NormalizeTree(context),
  21. InterpretCompilerDirectives(context, {}),
  22. AnalyseDeclarationsTransform(context),
  23. AnalyseExpressionsTransform(context),
  24. ]
  25. self._tree = self.run_pipeline(pipeline, u"""
  26. cdef bytes s = b'asdfg'
  27. cdef dict d = {1:2}
  28. x = s * 3
  29. d.get('test')
  30. """)
  31. return self._tree
  32. def test_builtin_method(self):
  33. calls = [0]
  34. class Test(MethodDispatcherTransform):
  35. def _handle_simple_method_dict_get(self, node, func, args, unbound):
  36. calls[0] += 1
  37. return node
  38. tree = self._build_tree()
  39. Test(None)(tree)
  40. self.assertEqual(1, calls[0])
  41. def test_binop_method(self):
  42. calls = {'bytes': 0, 'object': 0}
  43. class Test(MethodDispatcherTransform):
  44. def _handle_simple_method_bytes___mul__(self, node, func, args, unbound):
  45. calls['bytes'] += 1
  46. return node
  47. def _handle_simple_method_object___mul__(self, node, func, args, unbound):
  48. calls['object'] += 1
  49. return node
  50. tree = self._build_tree()
  51. Test(None)(tree)
  52. self.assertEqual(1, calls['bytes'])
  53. self.assertEqual(0, calls['object'])