blob: 9807535e8e663c47baea80e0977d8ea1bd86fdab [file] [log] [blame]
Dean Moldovan83e328f2017-06-09 00:44:49 +02001import pytest
2
3from pybind11_tests import class_ as m
4from pybind11_tests import UserType, ConstructorStats
5
6
7def test_repr():
8 # In Python 3.3+, repr() accesses __qualname__
9 assert "pybind11_type" in repr(type(UserType))
10 assert "UserType" in repr(UserType)
11
12
13def test_instance(msg):
14 with pytest.raises(TypeError) as excinfo:
15 m.NoConstructor()
16 assert msg(excinfo.value) == "m.class_.NoConstructor: No constructor defined!"
17
18 instance = m.NoConstructor.new_instance()
19
20 cstats = ConstructorStats.get(m.NoConstructor)
21 assert cstats.alive() == 1
22 del instance
23 assert cstats.alive() == 0
24
25
26def test_docstrings(doc):
27 assert doc(UserType) == "A `py::class_` type for testing"
28 assert UserType.__name__ == "UserType"
29 assert UserType.__module__ == "pybind11_tests"
30 assert UserType.get_value.__name__ == "get_value"
31 assert UserType.get_value.__module__ == "pybind11_tests"
32
33 assert doc(UserType.get_value) == """
34 get_value(self: m.UserType) -> int
35
36 Get value using a method
37 """
Jason Rhinelander391c7542017-07-25 16:47:36 -040038 assert doc(UserType.value) == "Get/set value using a property"
Dean Moldovan83e328f2017-06-09 00:44:49 +020039
40 assert doc(m.NoConstructor.new_instance) == """
41 new_instance() -> m.class_.NoConstructor
42
43 Return an instance
44 """
Dean Moldovan0bc272b2017-06-22 23:42:11 +020045
46
Jason Rhinelander71178922017-11-07 12:33:05 -040047def test_qualname(doc):
48 """Tests that a properly qualified name is set in __qualname__ (even in pre-3.3, where we
49 backport the attribute) and that generated docstrings properly use it and the module name"""
50 assert m.NestBase.__qualname__ == "NestBase"
51 assert m.NestBase.Nested.__qualname__ == "NestBase.Nested"
52
53 assert doc(m.NestBase.__init__) == """
54 __init__(self: m.class_.NestBase) -> None
55 """
56 assert doc(m.NestBase.g) == """
57 g(self: m.class_.NestBase, arg0: m.class_.NestBase.Nested) -> None
58 """
59 assert doc(m.NestBase.Nested.__init__) == """
60 __init__(self: m.class_.NestBase.Nested) -> None
61 """
62 assert doc(m.NestBase.Nested.fn) == """
63 fn(self: m.class_.NestBase.Nested, arg0: int, arg1: m.class_.NestBase, arg2: m.class_.NestBase.Nested) -> None
64 """ # noqa: E501 line too long
65 assert doc(m.NestBase.Nested.fa) == """
66 fa(self: m.class_.NestBase.Nested, a: int, b: m.class_.NestBase, c: m.class_.NestBase.Nested) -> None
67 """ # noqa: E501 line too long
68 assert m.NestBase.__module__ == "pybind11_tests.class_"
69 assert m.NestBase.Nested.__module__ == "pybind11_tests.class_"
70
71
Dean Moldovan0bc272b2017-06-22 23:42:11 +020072def test_inheritance(msg):
73 roger = m.Rabbit('Rabbit')
74 assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
75 assert m.pet_name_species(roger) == "Rabbit is a parrot"
76
77 polly = m.Pet('Polly', 'parrot')
78 assert polly.name() + " is a " + polly.species() == "Polly is a parrot"
79 assert m.pet_name_species(polly) == "Polly is a parrot"
80
81 molly = m.Dog('Molly')
82 assert molly.name() + " is a " + molly.species() == "Molly is a dog"
83 assert m.pet_name_species(molly) == "Molly is a dog"
84
85 fred = m.Hamster('Fred')
86 assert fred.name() + " is a " + fred.species() == "Fred is a rodent"
87
88 assert m.dog_bark(molly) == "Woof!"
89
90 with pytest.raises(TypeError) as excinfo:
91 m.dog_bark(polly)
92 assert msg(excinfo.value) == """
93 dog_bark(): incompatible function arguments. The following argument types are supported:
94 1. (arg0: m.class_.Dog) -> str
95
96 Invoked with: <m.class_.Pet object at 0>
97 """
98
99 with pytest.raises(TypeError) as excinfo:
100 m.Chimera("lion", "goat")
101 assert "No constructor defined!" in str(excinfo.value)
102
103
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400104def test_inheritance_init(msg):
105
106 # Single base
107 class Python(m.Pet):
108 def __init__(self):
109 pass
110 with pytest.raises(TypeError) as exc_info:
111 Python()
112 assert msg(exc_info.value) == "m.class_.Pet.__init__() must be called when overriding __init__"
113
114 # Multiple bases
115 class RabbitHamster(m.Rabbit, m.Hamster):
116 def __init__(self):
117 m.Rabbit.__init__(self, "RabbitHamster")
118
119 with pytest.raises(TypeError) as exc_info:
120 RabbitHamster()
121 expected = "m.class_.Hamster.__init__() must be called when overriding __init__"
122 assert msg(exc_info.value) == expected
123
124
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200125def test_automatic_upcasting():
126 assert type(m.return_class_1()).__name__ == "DerivedClass1"
127 assert type(m.return_class_2()).__name__ == "DerivedClass2"
128 assert type(m.return_none()).__name__ == "NoneType"
129 # Repeat these a few times in a random order to ensure no invalid caching is applied
130 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
131 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
132 assert type(m.return_class_n(0)).__name__ == "BaseClass"
133 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
134 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
135 assert type(m.return_class_n(0)).__name__ == "BaseClass"
136 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
137
138
139def test_isinstance():
140 objects = [tuple(), dict(), m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
141 expected = (True, True, True, True, True, False, False)
142 assert m.check_instances(objects) == expected
143
144
145def test_mismatched_holder():
146 import re
147
148 with pytest.raises(RuntimeError) as excinfo:
149 m.mismatched_holder_1()
150 assert re.match('generic_type: type ".*MismatchDerived1" does not have a non-default '
151 'holder type while its base ".*MismatchBase1" does', str(excinfo.value))
152
153 with pytest.raises(RuntimeError) as excinfo:
154 m.mismatched_holder_2()
155 assert re.match('generic_type: type ".*MismatchDerived2" has a non-default holder type '
156 'while its base ".*MismatchBase2" does not', str(excinfo.value))
157
158
159def test_override_static():
160 """#511: problem with inheritance + overwritten def_static"""
161 b = m.MyBase.make()
162 d1 = m.MyDerived.make2()
163 d2 = m.MyDerived.make()
164
165 assert isinstance(b, m.MyBase)
166 assert isinstance(d1, m.MyDerived)
167 assert isinstance(d2, m.MyDerived)
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200168
169
170def test_implicit_conversion_life_support():
171 """Ensure the lifetime of temporary objects created for implicit conversions"""
172 assert m.implicitly_convert_argument(UserType(5)) == 5
173 assert m.implicitly_convert_variable(UserType(5)) == 5
174
175 assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400176
177
178def test_operator_new_delete(capture):
179 """Tests that class-specific operator new/delete functions are invoked"""
180
181 class SubAliased(m.AliasedHasOpNewDelSize):
182 pass
183
184 with capture:
185 a = m.HasOpNewDel()
186 b = m.HasOpNewDelSize()
187 d = m.HasOpNewDelBoth()
188 assert capture == """
189 A new 8
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400190 B new 4
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400191 D new 32
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400192 """
193 sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
194 sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
195 with capture:
196 c = m.AliasedHasOpNewDelSize()
197 c2 = SubAliased()
198 assert capture == (
Jason Rhinelanderc4e18002017-08-17 00:01:42 -0400199 "C new " + sz_noalias + "\n" +
200 "C new " + sz_alias + "\n"
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400201 )
202
203 with capture:
204 del a
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400205 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400206 del b
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400207 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400208 del d
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400209 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400210 assert capture == """
211 A delete
212 B delete 4
213 D delete
214 """
215
216 with capture:
217 del c
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400218 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400219 del c2
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400220 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400221 assert capture == (
222 "C delete " + sz_noalias + "\n" +
223 "C delete " + sz_alias + "\n"
224 )
Dean Moldovan234f7c32017-08-17 17:03:46 +0200225
226
227def test_bind_protected_functions():
228 """Expose protected member functions to Python using a helper class"""
229 a = m.ProtectedA()
230 assert a.foo() == 42
231
232 b = m.ProtectedB()
233 assert b.foo() == 42
234
235 class C(m.ProtectedB):
236 def __init__(self):
237 m.ProtectedB.__init__(self)
238
239 def foo(self):
240 return 0
241
242 c = C()
243 assert c.foo() == 0
Wenzel Jakob4336a7d2017-08-21 22:48:28 +0200244
245
246def test_brace_initialization():
247 """ Tests that simple POD classes can be constructed using C++11 brace initialization """
248 a = m.BraceInitialization(123, "test")
249 assert a.field1 == 123
250 assert a.field2 == "test"
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200251
Jason Rhinelanderadbc8112018-01-11 13:22:13 -0400252 # Tests that a non-simple class doesn't get brace initialization (if the
253 # class defines an initializer_list constructor, in particular, it would
254 # win over the expected constructor).
255 b = m.NoBraceInitialization([123, 456])
256 assert b.vec == [123, 456]
257
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200258
259@pytest.unsupported_on_pypy
260def test_class_refcount():
261 """Instances must correctly increase/decrease the reference count of their types (#1029)"""
262 from sys import getrefcount
263
264 class PyDog(m.Dog):
265 pass
266
267 for cls in m.Dog, PyDog:
268 refcount_1 = getrefcount(cls)
269 molly = [cls("Molly") for _ in range(10)]
270 refcount_2 = getrefcount(cls)
271
272 del molly
273 pytest.gc_collect()
274 refcount_3 = getrefcount(cls)
275
276 assert refcount_1 == refcount_3
277 assert refcount_2 > refcount_1
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200278
279
280def test_reentrant_implicit_conversion_failure(msg):
281 # ensure that there is no runaway reentrant implicit conversion (#1035)
282 with pytest.raises(TypeError) as excinfo:
283 m.BogusImplicitConversion(0)
Jason Rhinelander71178922017-11-07 12:33:05 -0400284 assert msg(excinfo.value) == '''
285 __init__(): incompatible constructor arguments. The following argument types are supported:
286 1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200287
Jason Rhinelander71178922017-11-07 12:33:05 -0400288 Invoked with: 0
289 '''
oremanje7761e32018-09-25 14:55:18 -0700290
291
292def test_error_after_conversions():
293 with pytest.raises(TypeError) as exc_info:
294 m.test_error_after_conversions("hello")
295 assert str(exc_info.value).startswith(
296 "Unable to convert function return value to a Python type!")
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +0100297
298
299def test_aligned():
300 if hasattr(m, "Aligned"):
301 p = m.Aligned().ptr()
302 assert p % 1024 == 0
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400303
304
305# https://bitbucket.org/pypy/pypy/issues/2742
306@pytest.unsupported_on_pypy
307def test_final():
308 with pytest.raises(TypeError) as exc_info:
309 class PyFinalChild(m.IsFinal):
310 pass
311 assert str(exc_info.value).endswith("is not an acceptable base type")
312
313
314# https://bitbucket.org/pypy/pypy/issues/2742
315@pytest.unsupported_on_pypy
316def test_non_final_final():
317 with pytest.raises(TypeError) as exc_info:
318 class PyNonFinalFinalChild(m.IsNonFinalFinal):
319 pass
320 assert str(exc_info.value).endswith("is not an acceptable base type")