test_virtual_functions.py 11 KB

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