blob: fb061d1a27b970865ab715fc3735e2890e68e450 [file] [log] [blame]
Henry Schreinerd8c7ee02020-07-20 13:35:21 -04001# -*- coding: utf-8 -*-
Dean Moldovan83e328f2017-06-09 00:44:49 +02002import pytest
3
Henry Schreiner4d9024e2020-08-16 16:02:12 -04004import env # noqa: F401
5
Dean Moldovan83e328f2017-06-09 00:44:49 +02006from pybind11_tests import class_ as m
7from pybind11_tests import UserType, ConstructorStats
8
9
10def test_repr():
11 # In Python 3.3+, repr() accesses __qualname__
12 assert "pybind11_type" in repr(type(UserType))
13 assert "UserType" in repr(UserType)
14
15
16def test_instance(msg):
17 with pytest.raises(TypeError) as excinfo:
18 m.NoConstructor()
19 assert msg(excinfo.value) == "m.class_.NoConstructor: No constructor defined!"
20
21 instance = m.NoConstructor.new_instance()
22
23 cstats = ConstructorStats.get(m.NoConstructor)
24 assert cstats.alive() == 1
25 del instance
26 assert cstats.alive() == 0
27
28
Henry Schreinerf12ec002020-09-14 18:06:26 -040029def test_type():
30 assert m.check_type(1) == m.DerivedClass1
31 with pytest.raises(RuntimeError) as execinfo:
32 m.check_type(0)
33
34 assert 'pybind11::detail::get_type_info: unable to find type info' in str(execinfo.value)
35 assert 'Invalid' in str(execinfo.value)
36
37 # Currently not supported
38 # See https://github.com/pybind/pybind11/issues/2486
39 # assert m.check_type(2) == int
40
41
42def test_type_of_py():
43 assert m.get_type_of(1) == int
44 assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1
45 assert m.get_type_of(int) == type
46
47
Henry Fredrick Schreiner11f756f2020-09-16 22:02:09 -040048def test_type_of_classic():
49 assert m.get_type_classic(1) == int
50 assert m.get_type_classic(m.DerivedClass1()) == m.DerivedClass1
51 assert m.get_type_classic(int) == type
52
53
Henry Schreinerf12ec002020-09-14 18:06:26 -040054def test_type_of_py_nodelete():
55 # If the above test deleted the class, this will segfault
56 assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1
57
58
59def test_as_type_py():
60 assert m.as_type(int) == int
61
62 with pytest.raises(RuntimeError):
63 assert m.as_type(1) == int
64
65 with pytest.raises(RuntimeError):
66 assert m.as_type(m.DerivedClass1()) == m.DerivedClass1
67
68
Dean Moldovan83e328f2017-06-09 00:44:49 +020069def test_docstrings(doc):
70 assert doc(UserType) == "A `py::class_` type for testing"
71 assert UserType.__name__ == "UserType"
72 assert UserType.__module__ == "pybind11_tests"
73 assert UserType.get_value.__name__ == "get_value"
74 assert UserType.get_value.__module__ == "pybind11_tests"
75
76 assert doc(UserType.get_value) == """
77 get_value(self: m.UserType) -> int
78
79 Get value using a method
80 """
Jason Rhinelander391c7542017-07-25 16:47:36 -040081 assert doc(UserType.value) == "Get/set value using a property"
Dean Moldovan83e328f2017-06-09 00:44:49 +020082
83 assert doc(m.NoConstructor.new_instance) == """
84 new_instance() -> m.class_.NoConstructor
85
86 Return an instance
87 """
Dean Moldovan0bc272b2017-06-22 23:42:11 +020088
89
Jason Rhinelander71178922017-11-07 12:33:05 -040090def test_qualname(doc):
91 """Tests that a properly qualified name is set in __qualname__ (even in pre-3.3, where we
92 backport the attribute) and that generated docstrings properly use it and the module name"""
93 assert m.NestBase.__qualname__ == "NestBase"
94 assert m.NestBase.Nested.__qualname__ == "NestBase.Nested"
95
96 assert doc(m.NestBase.__init__) == """
97 __init__(self: m.class_.NestBase) -> None
98 """
99 assert doc(m.NestBase.g) == """
100 g(self: m.class_.NestBase, arg0: m.class_.NestBase.Nested) -> None
101 """
102 assert doc(m.NestBase.Nested.__init__) == """
103 __init__(self: m.class_.NestBase.Nested) -> None
104 """
105 assert doc(m.NestBase.Nested.fn) == """
106 fn(self: m.class_.NestBase.Nested, arg0: int, arg1: m.class_.NestBase, arg2: m.class_.NestBase.Nested) -> None
107 """ # noqa: E501 line too long
108 assert doc(m.NestBase.Nested.fa) == """
109 fa(self: m.class_.NestBase.Nested, a: int, b: m.class_.NestBase, c: m.class_.NestBase.Nested) -> None
110 """ # noqa: E501 line too long
111 assert m.NestBase.__module__ == "pybind11_tests.class_"
112 assert m.NestBase.Nested.__module__ == "pybind11_tests.class_"
113
114
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200115def test_inheritance(msg):
116 roger = m.Rabbit('Rabbit')
117 assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
118 assert m.pet_name_species(roger) == "Rabbit is a parrot"
119
120 polly = m.Pet('Polly', 'parrot')
121 assert polly.name() + " is a " + polly.species() == "Polly is a parrot"
122 assert m.pet_name_species(polly) == "Polly is a parrot"
123
124 molly = m.Dog('Molly')
125 assert molly.name() + " is a " + molly.species() == "Molly is a dog"
126 assert m.pet_name_species(molly) == "Molly is a dog"
127
128 fred = m.Hamster('Fred')
129 assert fred.name() + " is a " + fred.species() == "Fred is a rodent"
130
131 assert m.dog_bark(molly) == "Woof!"
132
133 with pytest.raises(TypeError) as excinfo:
134 m.dog_bark(polly)
135 assert msg(excinfo.value) == """
136 dog_bark(): incompatible function arguments. The following argument types are supported:
137 1. (arg0: m.class_.Dog) -> str
138
139 Invoked with: <m.class_.Pet object at 0>
140 """
141
142 with pytest.raises(TypeError) as excinfo:
143 m.Chimera("lion", "goat")
144 assert "No constructor defined!" in str(excinfo.value)
145
146
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400147def test_inheritance_init(msg):
148
149 # Single base
150 class Python(m.Pet):
151 def __init__(self):
152 pass
153 with pytest.raises(TypeError) as exc_info:
154 Python()
Yannick Jadoulc72708a2020-10-02 04:57:25 +0200155 expected = "m.class_.Pet.__init__() must be called when overriding __init__"
156 assert msg(exc_info.value) == expected
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400157
158 # Multiple bases
159 class RabbitHamster(m.Rabbit, m.Hamster):
160 def __init__(self):
161 m.Rabbit.__init__(self, "RabbitHamster")
162
163 with pytest.raises(TypeError) as exc_info:
164 RabbitHamster()
Yannick Jadoulc72708a2020-10-02 04:57:25 +0200165 expected = "m.class_.Hamster.__init__() must be called when overriding __init__"
166 assert msg(exc_info.value) == expected
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400167
168
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200169def test_automatic_upcasting():
170 assert type(m.return_class_1()).__name__ == "DerivedClass1"
171 assert type(m.return_class_2()).__name__ == "DerivedClass2"
172 assert type(m.return_none()).__name__ == "NoneType"
173 # Repeat these a few times in a random order to ensure no invalid caching is applied
174 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
175 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
176 assert type(m.return_class_n(0)).__name__ == "BaseClass"
177 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
178 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
179 assert type(m.return_class_n(0)).__name__ == "BaseClass"
180 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
181
182
183def test_isinstance():
184 objects = [tuple(), dict(), m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
185 expected = (True, True, True, True, True, False, False)
186 assert m.check_instances(objects) == expected
187
188
189def test_mismatched_holder():
190 import re
191
192 with pytest.raises(RuntimeError) as excinfo:
193 m.mismatched_holder_1()
194 assert re.match('generic_type: type ".*MismatchDerived1" does not have a non-default '
195 'holder type while its base ".*MismatchBase1" does', str(excinfo.value))
196
197 with pytest.raises(RuntimeError) as excinfo:
198 m.mismatched_holder_2()
199 assert re.match('generic_type: type ".*MismatchDerived2" has a non-default holder type '
200 'while its base ".*MismatchBase2" does not', str(excinfo.value))
201
202
203def test_override_static():
204 """#511: problem with inheritance + overwritten def_static"""
205 b = m.MyBase.make()
206 d1 = m.MyDerived.make2()
207 d2 = m.MyDerived.make()
208
209 assert isinstance(b, m.MyBase)
210 assert isinstance(d1, m.MyDerived)
211 assert isinstance(d2, m.MyDerived)
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200212
213
214def test_implicit_conversion_life_support():
215 """Ensure the lifetime of temporary objects created for implicit conversions"""
216 assert m.implicitly_convert_argument(UserType(5)) == 5
217 assert m.implicitly_convert_variable(UserType(5)) == 5
218
219 assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400220
221
222def test_operator_new_delete(capture):
223 """Tests that class-specific operator new/delete functions are invoked"""
224
225 class SubAliased(m.AliasedHasOpNewDelSize):
226 pass
227
228 with capture:
229 a = m.HasOpNewDel()
230 b = m.HasOpNewDelSize()
231 d = m.HasOpNewDelBoth()
232 assert capture == """
233 A new 8
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400234 B new 4
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400235 D new 32
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400236 """
237 sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
238 sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
239 with capture:
240 c = m.AliasedHasOpNewDelSize()
241 c2 = SubAliased()
242 assert capture == (
Jason Rhinelanderc4e18002017-08-17 00:01:42 -0400243 "C new " + sz_noalias + "\n" +
244 "C new " + sz_alias + "\n"
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400245 )
246
247 with capture:
248 del a
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400249 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400250 del b
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400251 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400252 del d
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400253 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400254 assert capture == """
255 A delete
256 B delete 4
257 D delete
258 """
259
260 with capture:
261 del c
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400262 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400263 del c2
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400264 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400265 assert capture == (
266 "C delete " + sz_noalias + "\n" +
267 "C delete " + sz_alias + "\n"
268 )
Dean Moldovan234f7c32017-08-17 17:03:46 +0200269
270
271def test_bind_protected_functions():
272 """Expose protected member functions to Python using a helper class"""
273 a = m.ProtectedA()
274 assert a.foo() == 42
275
276 b = m.ProtectedB()
277 assert b.foo() == 42
278
279 class C(m.ProtectedB):
280 def __init__(self):
281 m.ProtectedB.__init__(self)
282
283 def foo(self):
284 return 0
285
286 c = C()
287 assert c.foo() == 0
Wenzel Jakob4336a7d2017-08-21 22:48:28 +0200288
289
290def test_brace_initialization():
291 """ Tests that simple POD classes can be constructed using C++11 brace initialization """
292 a = m.BraceInitialization(123, "test")
293 assert a.field1 == 123
294 assert a.field2 == "test"
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200295
Jason Rhinelanderadbc8112018-01-11 13:22:13 -0400296 # Tests that a non-simple class doesn't get brace initialization (if the
297 # class defines an initializer_list constructor, in particular, it would
298 # win over the expected constructor).
299 b = m.NoBraceInitialization([123, 456])
300 assert b.vec == [123, 456]
301
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200302
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400303@pytest.mark.xfail("env.PYPY")
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200304def test_class_refcount():
305 """Instances must correctly increase/decrease the reference count of their types (#1029)"""
306 from sys import getrefcount
307
308 class PyDog(m.Dog):
309 pass
310
311 for cls in m.Dog, PyDog:
312 refcount_1 = getrefcount(cls)
313 molly = [cls("Molly") for _ in range(10)]
314 refcount_2 = getrefcount(cls)
315
316 del molly
317 pytest.gc_collect()
318 refcount_3 = getrefcount(cls)
319
320 assert refcount_1 == refcount_3
321 assert refcount_2 > refcount_1
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200322
323
324def test_reentrant_implicit_conversion_failure(msg):
325 # ensure that there is no runaway reentrant implicit conversion (#1035)
326 with pytest.raises(TypeError) as excinfo:
327 m.BogusImplicitConversion(0)
Jason Rhinelander71178922017-11-07 12:33:05 -0400328 assert msg(excinfo.value) == '''
329 __init__(): incompatible constructor arguments. The following argument types are supported:
330 1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200331
Jason Rhinelander71178922017-11-07 12:33:05 -0400332 Invoked with: 0
333 '''
oremanje7761e32018-09-25 14:55:18 -0700334
335
336def test_error_after_conversions():
337 with pytest.raises(TypeError) as exc_info:
338 m.test_error_after_conversions("hello")
339 assert str(exc_info.value).startswith(
340 "Unable to convert function return value to a Python type!")
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +0100341
342
343def test_aligned():
344 if hasattr(m, "Aligned"):
345 p = m.Aligned().ptr()
346 assert p % 1024 == 0
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400347
348
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400349# https://foss.heptapod.net/pypy/pypy/-/issues/2742
350@pytest.mark.xfail("env.PYPY")
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400351def test_final():
352 with pytest.raises(TypeError) as exc_info:
353 class PyFinalChild(m.IsFinal):
354 pass
355 assert str(exc_info.value).endswith("is not an acceptable base type")
356
357
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400358# https://foss.heptapod.net/pypy/pypy/-/issues/2742
359@pytest.mark.xfail("env.PYPY")
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400360def test_non_final_final():
361 with pytest.raises(TypeError) as exc_info:
362 class PyNonFinalFinalChild(m.IsNonFinalFinal):
363 pass
364 assert str(exc_info.value).endswith("is not an acceptable base type")
jbarlow834d90f1a2020-07-31 17:46:12 -0700365
366
367# https://github.com/pybind/pybind11/issues/1878
368def test_exception_rvalue_abort():
369 with pytest.raises(RuntimeError):
370 m.PyPrintDestructor().throw_something()