You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

363 lines
11 KiB

2 months ago
  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. assert capture == """
  107. PyA2.PyA2()
  108. PyA2.f()
  109. A2.f()
  110. PyA2.~PyA2()
  111. """
  112. # Python subclass version
  113. with capture:
  114. b2 = B2()
  115. m.call_f(b2)
  116. del b2
  117. pytest.gc_collect()
  118. assert capture == """
  119. PyA2.PyA2()
  120. PyA2.f()
  121. In python B2.f()
  122. PyA2.~PyA2()
  123. """
  124. def test_inheriting_repeat():
  125. class AR(m.A_Repeat):
  126. def unlucky_number(self):
  127. return 99
  128. class AT(m.A_Tpl):
  129. def unlucky_number(self):
  130. return 999
  131. obj = AR()
  132. assert obj.say_something(3) == "hihihi"
  133. assert obj.unlucky_number() == 99
  134. assert obj.say_everything() == "hi 99"
  135. obj = AT()
  136. assert obj.say_something(3) == "hihihi"
  137. assert obj.unlucky_number() == 999
  138. assert obj.say_everything() == "hi 999"
  139. for obj in [m.B_Repeat(), m.B_Tpl()]:
  140. assert obj.say_something(3) == "B says hi 3 times"
  141. assert obj.unlucky_number() == 13
  142. assert obj.lucky_number() == 7.0
  143. assert obj.say_everything() == "B says hi 1 times 13"
  144. for obj in [m.C_Repeat(), m.C_Tpl()]:
  145. assert obj.say_something(3) == "B says hi 3 times"
  146. assert obj.unlucky_number() == 4444
  147. assert obj.lucky_number() == 888.0
  148. assert obj.say_everything() == "B says hi 1 times 4444"
  149. class CR(m.C_Repeat):
  150. def lucky_number(self):
  151. return m.C_Repeat.lucky_number(self) + 1.25
  152. obj = CR()
  153. assert obj.say_something(3) == "B says hi 3 times"
  154. assert obj.unlucky_number() == 4444
  155. assert obj.lucky_number() == 889.25
  156. assert obj.say_everything() == "B says hi 1 times 4444"
  157. class CT(m.C_Tpl):
  158. pass
  159. obj = CT()
  160. assert obj.say_something(3) == "B says hi 3 times"
  161. assert obj.unlucky_number() == 4444
  162. assert obj.lucky_number() == 888.0
  163. assert obj.say_everything() == "B says hi 1 times 4444"
  164. class CCR(CR):
  165. def lucky_number(self):
  166. return CR.lucky_number(self) * 10
  167. obj = CCR()
  168. assert obj.say_something(3) == "B says hi 3 times"
  169. assert obj.unlucky_number() == 4444
  170. assert obj.lucky_number() == 8892.5
  171. assert obj.say_everything() == "B says hi 1 times 4444"
  172. class CCT(CT):
  173. def lucky_number(self):
  174. return CT.lucky_number(self) * 1000
  175. obj = CCT()
  176. assert obj.say_something(3) == "B says hi 3 times"
  177. assert obj.unlucky_number() == 4444
  178. assert obj.lucky_number() == 888000.0
  179. assert obj.say_everything() == "B says hi 1 times 4444"
  180. class DR(m.D_Repeat):
  181. def unlucky_number(self):
  182. return 123
  183. def lucky_number(self):
  184. return 42.0
  185. for obj in [m.D_Repeat(), m.D_Tpl()]:
  186. assert obj.say_something(3) == "B says hi 3 times"
  187. assert obj.unlucky_number() == 4444
  188. assert obj.lucky_number() == 888.0
  189. assert obj.say_everything() == "B says hi 1 times 4444"
  190. obj = DR()
  191. assert obj.say_something(3) == "B says hi 3 times"
  192. assert obj.unlucky_number() == 123
  193. assert obj.lucky_number() == 42.0
  194. assert obj.say_everything() == "B says hi 1 times 123"
  195. class DT(m.D_Tpl):
  196. def say_something(self, times):
  197. return "DT says:" + (' quack' * times)
  198. def unlucky_number(self):
  199. return 1234
  200. def lucky_number(self):
  201. return -4.25
  202. obj = DT()
  203. assert obj.say_something(3) == "DT says: quack quack quack"
  204. assert obj.unlucky_number() == 1234
  205. assert obj.lucky_number() == -4.25
  206. assert obj.say_everything() == "DT says: quack 1234"
  207. class DT2(DT):
  208. def say_something(self, times):
  209. return "DT2: " + ('QUACK' * times)
  210. def unlucky_number(self):
  211. return -3
  212. class BT(m.B_Tpl):
  213. def say_something(self, times):
  214. return "BT" * times
  215. def unlucky_number(self):
  216. return -7
  217. def lucky_number(self):
  218. return -1.375
  219. obj = BT()
  220. assert obj.say_something(3) == "BTBTBT"
  221. assert obj.unlucky_number() == -7
  222. assert obj.lucky_number() == -1.375
  223. assert obj.say_everything() == "BT -7"
  224. # PyPy: Reference count > 1 causes call with noncopyable instance
  225. # to fail in ncv1.print_nc()
  226. @pytest.unsupported_on_pypy
  227. @pytest.mark.skipif(not hasattr(m, "NCVirt"), reason="NCVirt test broken on ICPC")
  228. def test_move_support():
  229. class NCVirtExt(m.NCVirt):
  230. def get_noncopyable(self, a, b):
  231. # Constructs and returns a new instance:
  232. nc = m.NonCopyable(a * a, b * b)
  233. return nc
  234. def get_movable(self, a, b):
  235. # Return a referenced copy
  236. self.movable = m.Movable(a, b)
  237. return self.movable
  238. class NCVirtExt2(m.NCVirt):
  239. def get_noncopyable(self, a, b):
  240. # Keep a reference: this is going to throw an exception
  241. self.nc = m.NonCopyable(a, b)
  242. return self.nc
  243. def get_movable(self, a, b):
  244. # Return a new instance without storing it
  245. return m.Movable(a, b)
  246. ncv1 = NCVirtExt()
  247. assert ncv1.print_nc(2, 3) == "36"
  248. assert ncv1.print_movable(4, 5) == "9"
  249. ncv2 = NCVirtExt2()
  250. assert ncv2.print_movable(7, 7) == "14"
  251. # Don't check the exception message here because it differs under debug/non-debug mode
  252. with pytest.raises(RuntimeError):
  253. ncv2.print_nc(9, 9)
  254. nc_stats = ConstructorStats.get(m.NonCopyable)
  255. mv_stats = ConstructorStats.get(m.Movable)
  256. assert nc_stats.alive() == 1
  257. assert mv_stats.alive() == 1
  258. del ncv1, ncv2
  259. assert nc_stats.alive() == 0
  260. assert mv_stats.alive() == 0
  261. assert nc_stats.values() == ['4', '9', '9', '9']
  262. assert mv_stats.values() == ['4', '5', '7', '7']
  263. assert nc_stats.copy_constructions == 0
  264. assert mv_stats.copy_constructions == 1
  265. assert nc_stats.move_constructions >= 0
  266. assert mv_stats.move_constructions >= 0
  267. def test_dispatch_issue(msg):
  268. """#159: virtual function dispatch has problems with similar-named functions"""
  269. class PyClass1(m.DispatchIssue):
  270. def dispatch(self):
  271. return "Yay.."
  272. class PyClass2(m.DispatchIssue):
  273. def dispatch(self):
  274. with pytest.raises(RuntimeError) as excinfo:
  275. super(PyClass2, self).dispatch()
  276. assert msg(excinfo.value) == 'Tried to call pure virtual function "Base::dispatch"'
  277. p = PyClass1()
  278. return m.dispatch_issue_go(p)
  279. b = PyClass2()
  280. assert m.dispatch_issue_go(b) == "Yay.."
  281. def test_override_ref():
  282. """#392/397: overridding reference-returning functions"""
  283. o = m.OverrideTest("asdf")
  284. # Not allowed (see associated .cpp comment)
  285. # i = o.str_ref()
  286. # assert o.str_ref() == "asdf"
  287. assert o.str_value() == "asdf"
  288. assert o.A_value().value == "hi"
  289. a = o.A_ref()
  290. assert a.value == "hi"
  291. a.value = "bye"
  292. assert a.value == "bye"