polymorphism2.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # Copyright David Abrahams 2004. Distributed under the Boost
  2. # Software License, Version 1.0. (See accompanying
  3. # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. import unittest
  5. import sys
  6. class PolymorphTest(unittest.TestCase):
  7. def testReturnCpp(self):
  8. # Python Created Object With Same Id As
  9. # Cpp Created B Object
  10. # b = B(872)
  11. # Get Reference To Cpp Created B Object
  12. a = getBCppObj()
  13. # Python Created B Object and Cpp B Object
  14. # Should have same result by calling f()
  15. self.assertEqual ('B::f()', a.f())
  16. self.assertEqual ('B::f()', call_f(a))
  17. self.assertEqual ('A::f()', call_f(A()))
  18. def test_references(self):
  19. # B is not exposed to Python
  20. a = getBCppObj()
  21. self.assertEqual(type(a), A)
  22. # C is exposed to Python
  23. c = getCCppObj()
  24. self.assertEqual(type(c), C)
  25. def test_factory(self):
  26. self.assertEqual(type(factory(0)), A)
  27. self.assertEqual(type(factory(1)), A)
  28. self.assertEqual(type(factory(2)), C)
  29. def test_return_py(self):
  30. class X(A):
  31. def f(self):
  32. return 'X.f'
  33. x = X()
  34. self.assertEqual ('X.f', x.f())
  35. self.assertEqual ('X.f', call_f(x))
  36. def test_self_default(self):
  37. class X(A):
  38. def f(self):
  39. return 'X.f() -> ' + A.f(self)
  40. x = X()
  41. self.assertEqual ('X.f() -> A::f()', x.f())
  42. # This one properly raises the "dangling reference" exception
  43. # self.failUnlessEqual ('X.f() -> A::f()', call_f(x))
  44. def test_wrapper_downcast(self):
  45. a = pass_a(D())
  46. self.assertEqual('D::g()', a.g())
  47. def test_pure_virtual(self):
  48. p = P()
  49. self.assertRaises(RuntimeError, p.f)
  50. q = Q()
  51. self.assertEqual ('Q::f()', q.f())
  52. class R(P):
  53. def f(self):
  54. return 'R.f'
  55. r = R()
  56. self.assertEqual ('R.f', r.f())
  57. def test():
  58. # remove the option that upsets unittest
  59. import sys
  60. sys.argv = [ x for x in sys.argv if x != '--broken-auto-ptr' ]
  61. unittest.main()
  62. # This nasty hack basically says that if we're loaded by another module, we'll
  63. # be testing polymorphism2_auto_ptr_ext instead of polymorphism2_ext.
  64. if __name__ == "__main__":
  65. from polymorphism2_ext import *
  66. test()
  67. else:
  68. from polymorphism2_auto_ptr_ext import *