test_virtual_functions.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import pytest
  2. from pybind11_tests import virtual_functions as m
  3. from pybind11_tests import ConstructorStats
  4. def test_override(capture, msg):
  5. class ExtendedExampleVirt(m.ExampleVirt):
  6. def __init__(self, state):
  7. super(ExtendedExampleVirt, self).__init__(state + 1)
  8. self.data = "Hello world"
  9. def run(self, value):
  10. print('ExtendedExampleVirt::run(%i), calling parent..' % value)
  11. return super(ExtendedExampleVirt, self).run(value + 1)
  12. def run_bool(self):
  13. print('ExtendedExampleVirt::run_bool()')
  14. return False
  15. def get_string1(self):
  16. return "override1"
  17. def pure_virtual(self):
  18. print('ExtendedExampleVirt::pure_virtual(): %s' % self.data)
  19. class ExtendedExampleVirt2(ExtendedExampleVirt):
  20. def __init__(self, state):
  21. super(ExtendedExampleVirt2, self).__init__(state + 1)
  22. def get_string2(self):
  23. return "override2"
  24. ex12 = m.ExampleVirt(10)
  25. with capture:
  26. assert m.runExampleVirt(ex12, 20) == 30
  27. assert capture == """
  28. Original implementation of ExampleVirt::run(state=10, value=20, str1=default1, str2=default2)
  29. """ # noqa: E501 line too long
  30. with pytest.raises(RuntimeError) as excinfo:
  31. m.runExampleVirtVirtual(ex12)
  32. assert msg(excinfo.value) == 'Tried to call pure virtual function "ExampleVirt::pure_virtual"'
  33. ex12p = ExtendedExampleVirt(10)
  34. with capture:
  35. assert m.runExampleVirt(ex12p, 20) == 32
  36. assert capture == """
  37. ExtendedExampleVirt::run(20), calling parent..
  38. Original implementation of ExampleVirt::run(state=11, value=21, str1=override1, str2=default2)
  39. """ # noqa: E501 line too long
  40. with capture:
  41. assert m.runExampleVirtBool(ex12p) is False
  42. assert capture == "ExtendedExampleVirt::run_bool()"
  43. with capture:
  44. m.runExampleVirtVirtual(ex12p)
  45. assert capture == "ExtendedExampleVirt::pure_virtual(): Hello world"
  46. ex12p2 = ExtendedExampleVirt2(15)
  47. with capture:
  48. assert m.runExampleVirt(ex12p2, 50) == 68
  49. assert capture == """
  50. ExtendedExampleVirt::run(50), calling parent..
  51. Original implementation of ExampleVirt::run(state=17, value=51, str1=override1, str2=override2)
  52. """ # noqa: E501 line too long
  53. cstats = ConstructorStats.get(m.ExampleVirt)
  54. assert cstats.alive() == 3
  55. del ex12, ex12p, ex12p2
  56. assert cstats.alive() == 0
  57. assert cstats.values() == ['10', '11', '17']
  58. assert cstats.copy_constructions == 0
  59. assert cstats.move_constructions >= 0
  60. def test_alias_delay_initialization1(capture):
  61. """`A` only initializes its trampoline class when we inherit from it
  62. If we just create and use an A instance directly, the trampoline initialization is
  63. bypassed and we only initialize an A() instead (for performance reasons).
  64. """
  65. class B(m.A):
  66. def __init__(self):
  67. super(B, self).__init__()
  68. def f(self):
  69. print("In python f()")
  70. # C++ version
  71. with capture:
  72. a = m.A()
  73. m.call_f(a)
  74. del a
  75. pytest.gc_collect()
  76. assert capture == "A.f()"
  77. # Python version
  78. with capture:
  79. b = B()
  80. m.call_f(b)
  81. del b
  82. pytest.gc_collect()
  83. assert capture == """
  84. PyA.PyA()
  85. PyA.f()
  86. In python f()
  87. PyA.~PyA()
  88. """
  89. def test_alias_delay_initialization2(capture):
  90. """`A2`, unlike the above, is configured to always initialize the alias
  91. While the extra initialization and extra class layer has small virtual dispatch
  92. performance penalty, it also allows us to do more things with the trampoline
  93. class such as defining local variables and performing construction/destruction.
  94. """
  95. class B2(m.A2):
  96. def __init__(self):
  97. super(B2, self).__init__()
  98. def f(self):
  99. print("In python B2.f()")
  100. # No python subclass version
  101. with capture:
  102. a2 = m.A2()
  103. m.call_f(a2)
  104. del a2
  105. pytest.gc_collect()
  106. a3 = m.A2(1)
  107. m.call_f(a3)
  108. del a3
  109. pytest.gc_collect()
  110. assert capture == """
  111. PyA2.PyA2()
  112. PyA2.f()
  113. A2.f()
  114. PyA2.~PyA2()
  115. PyA2.PyA2()
  116. PyA2.f()
  117. A2.f()
  118. PyA2.~PyA2()
  119. """
  120. # Python subclass version
  121. with capture:
  122. b2 = B2()
  123. m.call_f(b2)
  124. del b2
  125. pytest.gc_collect()
  126. assert capture == """
  127. PyA2.PyA2()
  128. PyA2.f()
  129. In python B2.f()
  130. PyA2.~PyA2()
  131. """
  132. # PyPy: Reference count > 1 causes call with noncopyable instance
  133. # to fail in ncv1.print_nc()
  134. @pytest.unsupported_on_pypy
  135. @pytest.mark.skipif(not hasattr(m, "NCVirt"), reason="NCVirt test broken on ICPC")
  136. def test_move_support():
  137. class NCVirtExt(m.NCVirt):
  138. def get_noncopyable(self, a, b):
  139. # Constructs and returns a new instance:
  140. nc = m.NonCopyable(a * a, b * b)
  141. return nc
  142. def get_movable(self, a, b):
  143. # Return a referenced copy
  144. self.movable = m.Movable(a, b)
  145. return self.movable
  146. class NCVirtExt2(m.NCVirt):
  147. def get_noncopyable(self, a, b):
  148. # Keep a reference: this is going to throw an exception
  149. self.nc = m.NonCopyable(a, b)
  150. return self.nc
  151. def get_movable(self, a, b):
  152. # Return a new instance without storing it
  153. return m.Movable(a, b)
  154. ncv1 = NCVirtExt()
  155. assert ncv1.print_nc(2, 3) == "36"
  156. assert ncv1.print_movable(4, 5) == "9"
  157. ncv2 = NCVirtExt2()
  158. assert ncv2.print_movable(7, 7) == "14"
  159. # Don't check the exception message here because it differs under debug/non-debug mode
  160. with pytest.raises(RuntimeError):
  161. ncv2.print_nc(9, 9)
  162. nc_stats = ConstructorStats.get(m.NonCopyable)
  163. mv_stats = ConstructorStats.get(m.Movable)
  164. assert nc_stats.alive() == 1
  165. assert mv_stats.alive() == 1
  166. del ncv1, ncv2
  167. assert nc_stats.alive() == 0
  168. assert mv_stats.alive() == 0
  169. assert nc_stats.values() == ['4', '9', '9', '9']
  170. assert mv_stats.values() == ['4', '5', '7', '7']
  171. assert nc_stats.copy_constructions == 0
  172. assert mv_stats.copy_constructions == 1
  173. assert nc_stats.move_constructions >= 0
  174. assert mv_stats.move_constructions >= 0
  175. def test_dispatch_issue(msg):
  176. """#159: virtual function dispatch has problems with similar-named functions"""
  177. class PyClass1(m.DispatchIssue):
  178. def dispatch(self):
  179. return "Yay.."
  180. class PyClass2(m.DispatchIssue):
  181. def dispatch(self):
  182. with pytest.raises(RuntimeError) as excinfo:
  183. super(PyClass2, self).dispatch()
  184. assert msg(excinfo.value) == 'Tried to call pure virtual function "Base::dispatch"'
  185. p = PyClass1()
  186. return m.dispatch_issue_go(p)
  187. b = PyClass2()
  188. assert m.dispatch_issue_go(b) == "Yay.."
  189. def test_override_ref():
  190. """#392/397: overriding reference-returning functions"""
  191. o = m.OverrideTest("asdf")
  192. # Not allowed (see associated .cpp comment)
  193. # i = o.str_ref()
  194. # assert o.str_ref() == "asdf"
  195. assert o.str_value() == "asdf"
  196. assert o.A_value().value == "hi"
  197. a = o.A_ref()
  198. assert a.value == "hi"
  199. a.value = "bye"
  200. assert a.value == "bye"
  201. def test_inherited_virtuals():
  202. class AR(m.A_Repeat):
  203. def unlucky_number(self):
  204. return 99
  205. class AT(m.A_Tpl):
  206. def unlucky_number(self):
  207. return 999
  208. obj = AR()
  209. assert obj.say_something(3) == "hihihi"
  210. assert obj.unlucky_number() == 99
  211. assert obj.say_everything() == "hi 99"
  212. obj = AT()
  213. assert obj.say_something(3) == "hihihi"
  214. assert obj.unlucky_number() == 999
  215. assert obj.say_everything() == "hi 999"
  216. for obj in [m.B_Repeat(), m.B_Tpl()]:
  217. assert obj.say_something(3) == "B says hi 3 times"
  218. assert obj.unlucky_number() == 13
  219. assert obj.lucky_number() == 7.0
  220. assert obj.say_everything() == "B says hi 1 times 13"
  221. for obj in [m.C_Repeat(), m.C_Tpl()]:
  222. assert obj.say_something(3) == "B says hi 3 times"
  223. assert obj.unlucky_number() == 4444
  224. assert obj.lucky_number() == 888.0
  225. assert obj.say_everything() == "B says hi 1 times 4444"
  226. class CR(m.C_Repeat):
  227. def lucky_number(self):
  228. return m.C_Repeat.lucky_number(self) + 1.25
  229. obj = CR()
  230. assert obj.say_something(3) == "B says hi 3 times"
  231. assert obj.unlucky_number() == 4444
  232. assert obj.lucky_number() == 889.25
  233. assert obj.say_everything() == "B says hi 1 times 4444"
  234. class CT(m.C_Tpl):
  235. pass
  236. obj = CT()
  237. assert obj.say_something(3) == "B says hi 3 times"
  238. assert obj.unlucky_number() == 4444
  239. assert obj.lucky_number() == 888.0
  240. assert obj.say_everything() == "B says hi 1 times 4444"
  241. class CCR(CR):
  242. def lucky_number(self):
  243. return CR.lucky_number(self) * 10
  244. obj = CCR()
  245. assert obj.say_something(3) == "B says hi 3 times"
  246. assert obj.unlucky_number() == 4444
  247. assert obj.lucky_number() == 8892.5
  248. assert obj.say_everything() == "B says hi 1 times 4444"
  249. class CCT(CT):
  250. def lucky_number(self):
  251. return CT.lucky_number(self) * 1000
  252. obj = CCT()
  253. assert obj.say_something(3) == "B says hi 3 times"
  254. assert obj.unlucky_number() == 4444
  255. assert obj.lucky_number() == 888000.0
  256. assert obj.say_everything() == "B says hi 1 times 4444"
  257. class DR(m.D_Repeat):
  258. def unlucky_number(self):
  259. return 123
  260. def lucky_number(self):
  261. return 42.0
  262. for obj in [m.D_Repeat(), m.D_Tpl()]:
  263. assert obj.say_something(3) == "B says hi 3 times"
  264. assert obj.unlucky_number() == 4444
  265. assert obj.lucky_number() == 888.0
  266. assert obj.say_everything() == "B says hi 1 times 4444"
  267. obj = DR()
  268. assert obj.say_something(3) == "B says hi 3 times"
  269. assert obj.unlucky_number() == 123
  270. assert obj.lucky_number() == 42.0
  271. assert obj.say_everything() == "B says hi 1 times 123"
  272. class DT(m.D_Tpl):
  273. def say_something(self, times):
  274. return "DT says:" + (' quack' * times)
  275. def unlucky_number(self):
  276. return 1234
  277. def lucky_number(self):
  278. return -4.25
  279. obj = DT()
  280. assert obj.say_something(3) == "DT says: quack quack quack"
  281. assert obj.unlucky_number() == 1234
  282. assert obj.lucky_number() == -4.25
  283. assert obj.say_everything() == "DT says: quack 1234"
  284. class DT2(DT):
  285. def say_something(self, times):
  286. return "DT2: " + ('QUACK' * times)
  287. def unlucky_number(self):
  288. return -3
  289. class BT(m.B_Tpl):
  290. def say_something(self, times):
  291. return "BT" * times
  292. def unlucky_number(self):
  293. return -7
  294. def lucky_number(self):
  295. return -1.375
  296. obj = BT()
  297. assert obj.say_something(3) == "BTBTBT"
  298. assert obj.unlucky_number() == -7
  299. assert obj.lucky_number() == -1.375
  300. assert obj.say_everything() == "BT -7"
  301. def test_issue_1454():
  302. # Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7)
  303. m.test_gil()
  304. m.test_gil_from_thread()