test_class.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. import env # noqa: F401
  4. from pybind11_tests import class_ as m
  5. from pybind11_tests import UserType, ConstructorStats
  6. def test_repr():
  7. # In Python 3.3+, repr() accesses __qualname__
  8. assert "pybind11_type" in repr(type(UserType))
  9. assert "UserType" in repr(UserType)
  10. def test_instance(msg):
  11. with pytest.raises(TypeError) as excinfo:
  12. m.NoConstructor()
  13. assert msg(excinfo.value) == "m.class_.NoConstructor: No constructor defined!"
  14. instance = m.NoConstructor.new_instance()
  15. cstats = ConstructorStats.get(m.NoConstructor)
  16. assert cstats.alive() == 1
  17. del instance
  18. assert cstats.alive() == 0
  19. def test_type():
  20. assert m.check_type(1) == m.DerivedClass1
  21. with pytest.raises(RuntimeError) as execinfo:
  22. m.check_type(0)
  23. assert "pybind11::detail::get_type_info: unable to find type info" in str(
  24. execinfo.value
  25. )
  26. assert "Invalid" in str(execinfo.value)
  27. # Currently not supported
  28. # See https://github.com/pybind/pybind11/issues/2486
  29. # assert m.check_type(2) == int
  30. def test_type_of_py():
  31. assert m.get_type_of(1) == int
  32. assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1
  33. assert m.get_type_of(int) == type
  34. def test_type_of_classic():
  35. assert m.get_type_classic(1) == int
  36. assert m.get_type_classic(m.DerivedClass1()) == m.DerivedClass1
  37. assert m.get_type_classic(int) == type
  38. def test_type_of_py_nodelete():
  39. # If the above test deleted the class, this will segfault
  40. assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1
  41. def test_as_type_py():
  42. assert m.as_type(int) == int
  43. with pytest.raises(TypeError):
  44. assert m.as_type(1) == int
  45. with pytest.raises(TypeError):
  46. assert m.as_type(m.DerivedClass1()) == m.DerivedClass1
  47. def test_docstrings(doc):
  48. assert doc(UserType) == "A `py::class_` type for testing"
  49. assert UserType.__name__ == "UserType"
  50. assert UserType.__module__ == "pybind11_tests"
  51. assert UserType.get_value.__name__ == "get_value"
  52. assert UserType.get_value.__module__ == "pybind11_tests"
  53. assert (
  54. doc(UserType.get_value)
  55. == """
  56. get_value(self: m.UserType) -> int
  57. Get value using a method
  58. """
  59. )
  60. assert doc(UserType.value) == "Get/set value using a property"
  61. assert (
  62. doc(m.NoConstructor.new_instance)
  63. == """
  64. new_instance() -> m.class_.NoConstructor
  65. Return an instance
  66. """
  67. )
  68. def test_qualname(doc):
  69. """Tests that a properly qualified name is set in __qualname__ (even in pre-3.3, where we
  70. backport the attribute) and that generated docstrings properly use it and the module name"""
  71. assert m.NestBase.__qualname__ == "NestBase"
  72. assert m.NestBase.Nested.__qualname__ == "NestBase.Nested"
  73. assert (
  74. doc(m.NestBase.__init__)
  75. == """
  76. __init__(self: m.class_.NestBase) -> None
  77. """
  78. )
  79. assert (
  80. doc(m.NestBase.g)
  81. == """
  82. g(self: m.class_.NestBase, arg0: m.class_.NestBase.Nested) -> None
  83. """
  84. )
  85. assert (
  86. doc(m.NestBase.Nested.__init__)
  87. == """
  88. __init__(self: m.class_.NestBase.Nested) -> None
  89. """
  90. )
  91. assert (
  92. doc(m.NestBase.Nested.fn)
  93. == """
  94. fn(self: m.class_.NestBase.Nested, arg0: int, arg1: m.class_.NestBase, arg2: m.class_.NestBase.Nested) -> None
  95. """ # noqa: E501 line too long
  96. )
  97. assert (
  98. doc(m.NestBase.Nested.fa)
  99. == """
  100. fa(self: m.class_.NestBase.Nested, a: int, b: m.class_.NestBase, c: m.class_.NestBase.Nested) -> None
  101. """ # noqa: E501 line too long
  102. )
  103. assert m.NestBase.__module__ == "pybind11_tests.class_"
  104. assert m.NestBase.Nested.__module__ == "pybind11_tests.class_"
  105. def test_inheritance(msg):
  106. roger = m.Rabbit("Rabbit")
  107. assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
  108. assert m.pet_name_species(roger) == "Rabbit is a parrot"
  109. polly = m.Pet("Polly", "parrot")
  110. assert polly.name() + " is a " + polly.species() == "Polly is a parrot"
  111. assert m.pet_name_species(polly) == "Polly is a parrot"
  112. molly = m.Dog("Molly")
  113. assert molly.name() + " is a " + molly.species() == "Molly is a dog"
  114. assert m.pet_name_species(molly) == "Molly is a dog"
  115. fred = m.Hamster("Fred")
  116. assert fred.name() + " is a " + fred.species() == "Fred is a rodent"
  117. assert m.dog_bark(molly) == "Woof!"
  118. with pytest.raises(TypeError) as excinfo:
  119. m.dog_bark(polly)
  120. assert (
  121. msg(excinfo.value)
  122. == """
  123. dog_bark(): incompatible function arguments. The following argument types are supported:
  124. 1. (arg0: m.class_.Dog) -> str
  125. Invoked with: <m.class_.Pet object at 0>
  126. """
  127. )
  128. with pytest.raises(TypeError) as excinfo:
  129. m.Chimera("lion", "goat")
  130. assert "No constructor defined!" in str(excinfo.value)
  131. def test_inheritance_init(msg):
  132. # Single base
  133. class Python(m.Pet):
  134. def __init__(self):
  135. pass
  136. with pytest.raises(TypeError) as exc_info:
  137. Python()
  138. expected = "m.class_.Pet.__init__() must be called when overriding __init__"
  139. assert msg(exc_info.value) == expected
  140. # Multiple bases
  141. class RabbitHamster(m.Rabbit, m.Hamster):
  142. def __init__(self):
  143. m.Rabbit.__init__(self, "RabbitHamster")
  144. with pytest.raises(TypeError) as exc_info:
  145. RabbitHamster()
  146. expected = "m.class_.Hamster.__init__() must be called when overriding __init__"
  147. assert msg(exc_info.value) == expected
  148. def test_automatic_upcasting():
  149. assert type(m.return_class_1()).__name__ == "DerivedClass1"
  150. assert type(m.return_class_2()).__name__ == "DerivedClass2"
  151. assert type(m.return_none()).__name__ == "NoneType"
  152. # Repeat these a few times in a random order to ensure no invalid caching is applied
  153. assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
  154. assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
  155. assert type(m.return_class_n(0)).__name__ == "BaseClass"
  156. assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
  157. assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
  158. assert type(m.return_class_n(0)).__name__ == "BaseClass"
  159. assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
  160. def test_isinstance():
  161. objects = [tuple(), dict(), m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
  162. expected = (True, True, True, True, True, False, False)
  163. assert m.check_instances(objects) == expected
  164. def test_mismatched_holder():
  165. import re
  166. with pytest.raises(RuntimeError) as excinfo:
  167. m.mismatched_holder_1()
  168. assert re.match(
  169. 'generic_type: type ".*MismatchDerived1" does not have a non-default '
  170. 'holder type while its base ".*MismatchBase1" does',
  171. str(excinfo.value),
  172. )
  173. with pytest.raises(RuntimeError) as excinfo:
  174. m.mismatched_holder_2()
  175. assert re.match(
  176. 'generic_type: type ".*MismatchDerived2" has a non-default holder type '
  177. 'while its base ".*MismatchBase2" does not',
  178. str(excinfo.value),
  179. )
  180. def test_override_static():
  181. """#511: problem with inheritance + overwritten def_static"""
  182. b = m.MyBase.make()
  183. d1 = m.MyDerived.make2()
  184. d2 = m.MyDerived.make()
  185. assert isinstance(b, m.MyBase)
  186. assert isinstance(d1, m.MyDerived)
  187. assert isinstance(d2, m.MyDerived)
  188. def test_implicit_conversion_life_support():
  189. """Ensure the lifetime of temporary objects created for implicit conversions"""
  190. assert m.implicitly_convert_argument(UserType(5)) == 5
  191. assert m.implicitly_convert_variable(UserType(5)) == 5
  192. assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
  193. def test_operator_new_delete(capture):
  194. """Tests that class-specific operator new/delete functions are invoked"""
  195. class SubAliased(m.AliasedHasOpNewDelSize):
  196. pass
  197. with capture:
  198. a = m.HasOpNewDel()
  199. b = m.HasOpNewDelSize()
  200. d = m.HasOpNewDelBoth()
  201. assert (
  202. capture
  203. == """
  204. A new 8
  205. B new 4
  206. D new 32
  207. """
  208. )
  209. sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
  210. sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
  211. with capture:
  212. c = m.AliasedHasOpNewDelSize()
  213. c2 = SubAliased()
  214. assert capture == ("C new " + sz_noalias + "\n" + "C new " + sz_alias + "\n")
  215. with capture:
  216. del a
  217. pytest.gc_collect()
  218. del b
  219. pytest.gc_collect()
  220. del d
  221. pytest.gc_collect()
  222. assert (
  223. capture
  224. == """
  225. A delete
  226. B delete 4
  227. D delete
  228. """
  229. )
  230. with capture:
  231. del c
  232. pytest.gc_collect()
  233. del c2
  234. pytest.gc_collect()
  235. assert capture == ("C delete " + sz_noalias + "\n" + "C delete " + sz_alias + "\n")
  236. def test_bind_protected_functions():
  237. """Expose protected member functions to Python using a helper class"""
  238. a = m.ProtectedA()
  239. assert a.foo() == 42
  240. b = m.ProtectedB()
  241. assert b.foo() == 42
  242. class C(m.ProtectedB):
  243. def __init__(self):
  244. m.ProtectedB.__init__(self)
  245. def foo(self):
  246. return 0
  247. c = C()
  248. assert c.foo() == 0
  249. def test_brace_initialization():
  250. """ Tests that simple POD classes can be constructed using C++11 brace initialization """
  251. a = m.BraceInitialization(123, "test")
  252. assert a.field1 == 123
  253. assert a.field2 == "test"
  254. # Tests that a non-simple class doesn't get brace initialization (if the
  255. # class defines an initializer_list constructor, in particular, it would
  256. # win over the expected constructor).
  257. b = m.NoBraceInitialization([123, 456])
  258. assert b.vec == [123, 456]
  259. @pytest.mark.xfail("env.PYPY")
  260. def test_class_refcount():
  261. """Instances must correctly increase/decrease the reference count of their types (#1029)"""
  262. from sys import getrefcount
  263. class PyDog(m.Dog):
  264. pass
  265. for cls in m.Dog, PyDog:
  266. refcount_1 = getrefcount(cls)
  267. molly = [cls("Molly") for _ in range(10)]
  268. refcount_2 = getrefcount(cls)
  269. del molly
  270. pytest.gc_collect()
  271. refcount_3 = getrefcount(cls)
  272. assert refcount_1 == refcount_3
  273. assert refcount_2 > refcount_1
  274. def test_reentrant_implicit_conversion_failure(msg):
  275. # ensure that there is no runaway reentrant implicit conversion (#1035)
  276. with pytest.raises(TypeError) as excinfo:
  277. m.BogusImplicitConversion(0)
  278. assert (
  279. msg(excinfo.value)
  280. == """
  281. __init__(): incompatible constructor arguments. The following argument types are supported:
  282. 1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
  283. Invoked with: 0
  284. """
  285. )
  286. def test_error_after_conversions():
  287. with pytest.raises(TypeError) as exc_info:
  288. m.test_error_after_conversions("hello")
  289. assert str(exc_info.value).startswith(
  290. "Unable to convert function return value to a Python type!"
  291. )
  292. def test_aligned():
  293. if hasattr(m, "Aligned"):
  294. p = m.Aligned().ptr()
  295. assert p % 1024 == 0
  296. # https://foss.heptapod.net/pypy/pypy/-/issues/2742
  297. @pytest.mark.xfail("env.PYPY")
  298. def test_final():
  299. with pytest.raises(TypeError) as exc_info:
  300. class PyFinalChild(m.IsFinal):
  301. pass
  302. assert str(exc_info.value).endswith("is not an acceptable base type")
  303. # https://foss.heptapod.net/pypy/pypy/-/issues/2742
  304. @pytest.mark.xfail("env.PYPY")
  305. def test_non_final_final():
  306. with pytest.raises(TypeError) as exc_info:
  307. class PyNonFinalFinalChild(m.IsNonFinalFinal):
  308. pass
  309. assert str(exc_info.value).endswith("is not an acceptable base type")
  310. # https://github.com/pybind/pybind11/issues/1878
  311. def test_exception_rvalue_abort():
  312. with pytest.raises(RuntimeError):
  313. m.PyPrintDestructor().throw_something()
  314. # https://github.com/pybind/pybind11/issues/1568
  315. def test_multiple_instances_with_same_pointer(capture):
  316. n = 100
  317. instances = [m.SamePointer() for _ in range(n)]
  318. for i in range(n):
  319. # We need to reuse the same allocated memory for with a different type,
  320. # to ensure the bug in `deregister_instance_impl` is detected. Otherwise
  321. # `Py_TYPE(self) == Py_TYPE(it->second)` will still succeed, even though
  322. # the `instance` is already deleted.
  323. instances[i] = m.Empty()
  324. # No assert: if this does not trigger the error
  325. # pybind11_fail("pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
  326. # and just completes without crashing, we're good.
  327. # https://github.com/pybind/pybind11/issues/1624
  328. def test_base_and_derived_nested_scope():
  329. assert issubclass(m.DerivedWithNested, m.BaseWithNested)
  330. assert m.BaseWithNested.Nested != m.DerivedWithNested.Nested
  331. assert m.BaseWithNested.Nested.get_name() == "BaseWithNested::Nested"
  332. assert m.DerivedWithNested.Nested.get_name() == "DerivedWithNested::Nested"
  333. def test_register_duplicate_class():
  334. import types
  335. module_scope = types.ModuleType("module_scope")
  336. with pytest.raises(RuntimeError) as exc_info:
  337. m.register_duplicate_class_name(module_scope)
  338. expected = (
  339. 'generic_type: cannot initialize type "Duplicate": '
  340. "an object with that name is already defined"
  341. )
  342. assert str(exc_info.value) == expected
  343. with pytest.raises(RuntimeError) as exc_info:
  344. m.register_duplicate_class_type(module_scope)
  345. expected = 'generic_type: type "YetAnotherDuplicate" is already registered!'
  346. assert str(exc_info.value) == expected
  347. class ClassScope:
  348. pass
  349. with pytest.raises(RuntimeError) as exc_info:
  350. m.register_duplicate_nested_class_name(ClassScope)
  351. expected = (
  352. 'generic_type: cannot initialize type "DuplicateNested": '
  353. "an object with that name is already defined"
  354. )
  355. assert str(exc_info.value) == expected
  356. with pytest.raises(RuntimeError) as exc_info:
  357. m.register_duplicate_nested_class_type(ClassScope)
  358. expected = 'generic_type: type "YetAnotherDuplicateNested" is already registered!'
  359. assert str(exc_info.value) == expected