test_class.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import pytest
  2. from pybind11_tests import class_ as m
  3. from pybind11_tests import UserType, ConstructorStats
  4. def test_repr():
  5. # In Python 3.3+, repr() accesses __qualname__
  6. assert "pybind11_type" in repr(type(UserType))
  7. assert "UserType" in repr(UserType)
  8. def test_instance(msg):
  9. with pytest.raises(TypeError) as excinfo:
  10. m.NoConstructor()
  11. assert msg(excinfo.value) == "m.class_.NoConstructor: No constructor defined!"
  12. instance = m.NoConstructor.new_instance()
  13. cstats = ConstructorStats.get(m.NoConstructor)
  14. assert cstats.alive() == 1
  15. del instance
  16. assert cstats.alive() == 0
  17. def test_docstrings(doc):
  18. assert doc(UserType) == "A `py::class_` type for testing"
  19. assert UserType.__name__ == "UserType"
  20. assert UserType.__module__ == "pybind11_tests"
  21. assert UserType.get_value.__name__ == "get_value"
  22. assert UserType.get_value.__module__ == "pybind11_tests"
  23. assert doc(UserType.get_value) == """
  24. get_value(self: m.UserType) -> int
  25. Get value using a method
  26. """
  27. assert doc(UserType.value) == "Get/set value using a property"
  28. assert doc(m.NoConstructor.new_instance) == """
  29. new_instance() -> m.class_.NoConstructor
  30. Return an instance
  31. """
  32. def test_qualname(doc):
  33. """Tests that a properly qualified name is set in __qualname__ (even in pre-3.3, where we
  34. backport the attribute) and that generated docstrings properly use it and the module name"""
  35. assert m.NestBase.__qualname__ == "NestBase"
  36. assert m.NestBase.Nested.__qualname__ == "NestBase.Nested"
  37. assert doc(m.NestBase.__init__) == """
  38. __init__(self: m.class_.NestBase) -> None
  39. """
  40. assert doc(m.NestBase.g) == """
  41. g(self: m.class_.NestBase, arg0: m.class_.NestBase.Nested) -> None
  42. """
  43. assert doc(m.NestBase.Nested.__init__) == """
  44. __init__(self: m.class_.NestBase.Nested) -> None
  45. """
  46. assert doc(m.NestBase.Nested.fn) == """
  47. fn(self: m.class_.NestBase.Nested, arg0: int, arg1: m.class_.NestBase, arg2: m.class_.NestBase.Nested) -> None
  48. """ # noqa: E501 line too long
  49. assert doc(m.NestBase.Nested.fa) == """
  50. fa(self: m.class_.NestBase.Nested, a: int, b: m.class_.NestBase, c: m.class_.NestBase.Nested) -> None
  51. """ # noqa: E501 line too long
  52. assert m.NestBase.__module__ == "pybind11_tests.class_"
  53. assert m.NestBase.Nested.__module__ == "pybind11_tests.class_"
  54. def test_inheritance(msg):
  55. roger = m.Rabbit('Rabbit')
  56. assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
  57. assert m.pet_name_species(roger) == "Rabbit is a parrot"
  58. polly = m.Pet('Polly', 'parrot')
  59. assert polly.name() + " is a " + polly.species() == "Polly is a parrot"
  60. assert m.pet_name_species(polly) == "Polly is a parrot"
  61. molly = m.Dog('Molly')
  62. assert molly.name() + " is a " + molly.species() == "Molly is a dog"
  63. assert m.pet_name_species(molly) == "Molly is a dog"
  64. fred = m.Hamster('Fred')
  65. assert fred.name() + " is a " + fred.species() == "Fred is a rodent"
  66. assert m.dog_bark(molly) == "Woof!"
  67. with pytest.raises(TypeError) as excinfo:
  68. m.dog_bark(polly)
  69. assert msg(excinfo.value) == """
  70. dog_bark(): incompatible function arguments. The following argument types are supported:
  71. 1. (arg0: m.class_.Dog) -> str
  72. Invoked with: <m.class_.Pet object at 0>
  73. """
  74. with pytest.raises(TypeError) as excinfo:
  75. m.Chimera("lion", "goat")
  76. assert "No constructor defined!" in str(excinfo.value)
  77. def test_automatic_upcasting():
  78. assert type(m.return_class_1()).__name__ == "DerivedClass1"
  79. assert type(m.return_class_2()).__name__ == "DerivedClass2"
  80. assert type(m.return_none()).__name__ == "NoneType"
  81. # Repeat these a few times in a random order to ensure no invalid caching is applied
  82. assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
  83. assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
  84. assert type(m.return_class_n(0)).__name__ == "BaseClass"
  85. assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
  86. assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
  87. assert type(m.return_class_n(0)).__name__ == "BaseClass"
  88. assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
  89. def test_isinstance():
  90. objects = [tuple(), dict(), m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
  91. expected = (True, True, True, True, True, False, False)
  92. assert m.check_instances(objects) == expected
  93. def test_mismatched_holder():
  94. import re
  95. with pytest.raises(RuntimeError) as excinfo:
  96. m.mismatched_holder_1()
  97. assert re.match('generic_type: type ".*MismatchDerived1" does not have a non-default '
  98. 'holder type while its base ".*MismatchBase1" does', str(excinfo.value))
  99. with pytest.raises(RuntimeError) as excinfo:
  100. m.mismatched_holder_2()
  101. assert re.match('generic_type: type ".*MismatchDerived2" has a non-default holder type '
  102. 'while its base ".*MismatchBase2" does not', str(excinfo.value))
  103. def test_override_static():
  104. """#511: problem with inheritance + overwritten def_static"""
  105. b = m.MyBase.make()
  106. d1 = m.MyDerived.make2()
  107. d2 = m.MyDerived.make()
  108. assert isinstance(b, m.MyBase)
  109. assert isinstance(d1, m.MyDerived)
  110. assert isinstance(d2, m.MyDerived)
  111. def test_implicit_conversion_life_support():
  112. """Ensure the lifetime of temporary objects created for implicit conversions"""
  113. assert m.implicitly_convert_argument(UserType(5)) == 5
  114. assert m.implicitly_convert_variable(UserType(5)) == 5
  115. assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
  116. def test_operator_new_delete(capture):
  117. """Tests that class-specific operator new/delete functions are invoked"""
  118. class SubAliased(m.AliasedHasOpNewDelSize):
  119. pass
  120. with capture:
  121. a = m.HasOpNewDel()
  122. b = m.HasOpNewDelSize()
  123. d = m.HasOpNewDelBoth()
  124. assert capture == """
  125. A new 8
  126. B new 4
  127. D new 32
  128. """
  129. sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
  130. sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
  131. with capture:
  132. c = m.AliasedHasOpNewDelSize()
  133. c2 = SubAliased()
  134. assert capture == (
  135. "C new " + sz_noalias + "\n" +
  136. "C new " + sz_alias + "\n"
  137. )
  138. with capture:
  139. del a
  140. pytest.gc_collect()
  141. del b
  142. pytest.gc_collect()
  143. del d
  144. pytest.gc_collect()
  145. assert capture == """
  146. A delete
  147. B delete 4
  148. D delete
  149. """
  150. with capture:
  151. del c
  152. pytest.gc_collect()
  153. del c2
  154. pytest.gc_collect()
  155. assert capture == (
  156. "C delete " + sz_noalias + "\n" +
  157. "C delete " + sz_alias + "\n"
  158. )
  159. def test_bind_protected_functions():
  160. """Expose protected member functions to Python using a helper class"""
  161. a = m.ProtectedA()
  162. assert a.foo() == 42
  163. b = m.ProtectedB()
  164. assert b.foo() == 42
  165. class C(m.ProtectedB):
  166. def __init__(self):
  167. m.ProtectedB.__init__(self)
  168. def foo(self):
  169. return 0
  170. c = C()
  171. assert c.foo() == 0
  172. def test_brace_initialization():
  173. """ Tests that simple POD classes can be constructed using C++11 brace initialization """
  174. a = m.BraceInitialization(123, "test")
  175. assert a.field1 == 123
  176. assert a.field2 == "test"
  177. # Tests that a non-simple class doesn't get brace initialization (if the
  178. # class defines an initializer_list constructor, in particular, it would
  179. # win over the expected constructor).
  180. b = m.NoBraceInitialization([123, 456])
  181. assert b.vec == [123, 456]
  182. @pytest.unsupported_on_pypy
  183. def test_class_refcount():
  184. """Instances must correctly increase/decrease the reference count of their types (#1029)"""
  185. from sys import getrefcount
  186. class PyDog(m.Dog):
  187. pass
  188. for cls in m.Dog, PyDog:
  189. refcount_1 = getrefcount(cls)
  190. molly = [cls("Molly") for _ in range(10)]
  191. refcount_2 = getrefcount(cls)
  192. del molly
  193. pytest.gc_collect()
  194. refcount_3 = getrefcount(cls)
  195. assert refcount_1 == refcount_3
  196. assert refcount_2 > refcount_1
  197. def test_reentrant_implicit_conversion_failure(msg):
  198. # ensure that there is no runaway reentrant implicit conversion (#1035)
  199. with pytest.raises(TypeError) as excinfo:
  200. m.BogusImplicitConversion(0)
  201. assert msg(excinfo.value) == '''
  202. __init__(): incompatible constructor arguments. The following argument types are supported:
  203. 1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
  204. Invoked with: 0
  205. '''