blob: 64f49419588d6c474f64b1cf5a5de1670be0d93e [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 Jadoulf980d762020-07-09 00:14:41 +0200155 expected = ["m.class_.Pet.__init__() must be called when overriding __init__",
156 "Pet.__init__() must be called when overriding __init__"] # PyPy?
157 # TODO: fix PyPy error message wrt. tp_name/__qualname__?
158 assert msg(exc_info.value) in expected
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400159
160 # Multiple bases
161 class RabbitHamster(m.Rabbit, m.Hamster):
162 def __init__(self):
163 m.Rabbit.__init__(self, "RabbitHamster")
164
165 with pytest.raises(TypeError) as exc_info:
166 RabbitHamster()
Yannick Jadoulf980d762020-07-09 00:14:41 +0200167 expected = ["m.class_.Hamster.__init__() must be called when overriding __init__",
168 "Hamster.__init__() must be called when overriding __init__"] # PyPy
169 assert msg(exc_info.value) in expected
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400170
171
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200172def test_automatic_upcasting():
173 assert type(m.return_class_1()).__name__ == "DerivedClass1"
174 assert type(m.return_class_2()).__name__ == "DerivedClass2"
175 assert type(m.return_none()).__name__ == "NoneType"
176 # Repeat these a few times in a random order to ensure no invalid caching is applied
177 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
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(2)).__name__ == "DerivedClass2"
181 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
182 assert type(m.return_class_n(0)).__name__ == "BaseClass"
183 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
184
185
186def test_isinstance():
187 objects = [tuple(), dict(), m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
188 expected = (True, True, True, True, True, False, False)
189 assert m.check_instances(objects) == expected
190
191
192def test_mismatched_holder():
193 import re
194
195 with pytest.raises(RuntimeError) as excinfo:
196 m.mismatched_holder_1()
197 assert re.match('generic_type: type ".*MismatchDerived1" does not have a non-default '
198 'holder type while its base ".*MismatchBase1" does', str(excinfo.value))
199
200 with pytest.raises(RuntimeError) as excinfo:
201 m.mismatched_holder_2()
202 assert re.match('generic_type: type ".*MismatchDerived2" has a non-default holder type '
203 'while its base ".*MismatchBase2" does not', str(excinfo.value))
204
205
206def test_override_static():
207 """#511: problem with inheritance + overwritten def_static"""
208 b = m.MyBase.make()
209 d1 = m.MyDerived.make2()
210 d2 = m.MyDerived.make()
211
212 assert isinstance(b, m.MyBase)
213 assert isinstance(d1, m.MyDerived)
214 assert isinstance(d2, m.MyDerived)
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200215
216
217def test_implicit_conversion_life_support():
218 """Ensure the lifetime of temporary objects created for implicit conversions"""
219 assert m.implicitly_convert_argument(UserType(5)) == 5
220 assert m.implicitly_convert_variable(UserType(5)) == 5
221
222 assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400223
224
225def test_operator_new_delete(capture):
226 """Tests that class-specific operator new/delete functions are invoked"""
227
228 class SubAliased(m.AliasedHasOpNewDelSize):
229 pass
230
231 with capture:
232 a = m.HasOpNewDel()
233 b = m.HasOpNewDelSize()
234 d = m.HasOpNewDelBoth()
235 assert capture == """
236 A new 8
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400237 B new 4
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400238 D new 32
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400239 """
240 sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
241 sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
242 with capture:
243 c = m.AliasedHasOpNewDelSize()
244 c2 = SubAliased()
245 assert capture == (
Jason Rhinelanderc4e18002017-08-17 00:01:42 -0400246 "C new " + sz_noalias + "\n" +
247 "C new " + sz_alias + "\n"
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400248 )
249
250 with capture:
251 del a
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400252 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400253 del b
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400254 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400255 del d
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400256 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400257 assert capture == """
258 A delete
259 B delete 4
260 D delete
261 """
262
263 with capture:
264 del c
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400265 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400266 del c2
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400267 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400268 assert capture == (
269 "C delete " + sz_noalias + "\n" +
270 "C delete " + sz_alias + "\n"
271 )
Dean Moldovan234f7c32017-08-17 17:03:46 +0200272
273
274def test_bind_protected_functions():
275 """Expose protected member functions to Python using a helper class"""
276 a = m.ProtectedA()
277 assert a.foo() == 42
278
279 b = m.ProtectedB()
280 assert b.foo() == 42
281
282 class C(m.ProtectedB):
283 def __init__(self):
284 m.ProtectedB.__init__(self)
285
286 def foo(self):
287 return 0
288
289 c = C()
290 assert c.foo() == 0
Wenzel Jakob4336a7d2017-08-21 22:48:28 +0200291
292
293def test_brace_initialization():
294 """ Tests that simple POD classes can be constructed using C++11 brace initialization """
295 a = m.BraceInitialization(123, "test")
296 assert a.field1 == 123
297 assert a.field2 == "test"
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200298
Jason Rhinelanderadbc8112018-01-11 13:22:13 -0400299 # Tests that a non-simple class doesn't get brace initialization (if the
300 # class defines an initializer_list constructor, in particular, it would
301 # win over the expected constructor).
302 b = m.NoBraceInitialization([123, 456])
303 assert b.vec == [123, 456]
304
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200305
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400306@pytest.mark.xfail("env.PYPY")
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200307def test_class_refcount():
308 """Instances must correctly increase/decrease the reference count of their types (#1029)"""
309 from sys import getrefcount
310
311 class PyDog(m.Dog):
312 pass
313
314 for cls in m.Dog, PyDog:
315 refcount_1 = getrefcount(cls)
316 molly = [cls("Molly") for _ in range(10)]
317 refcount_2 = getrefcount(cls)
318
319 del molly
320 pytest.gc_collect()
321 refcount_3 = getrefcount(cls)
322
323 assert refcount_1 == refcount_3
324 assert refcount_2 > refcount_1
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200325
326
327def test_reentrant_implicit_conversion_failure(msg):
328 # ensure that there is no runaway reentrant implicit conversion (#1035)
329 with pytest.raises(TypeError) as excinfo:
330 m.BogusImplicitConversion(0)
Jason Rhinelander71178922017-11-07 12:33:05 -0400331 assert msg(excinfo.value) == '''
332 __init__(): incompatible constructor arguments. The following argument types are supported:
333 1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200334
Jason Rhinelander71178922017-11-07 12:33:05 -0400335 Invoked with: 0
336 '''
oremanje7761e32018-09-25 14:55:18 -0700337
338
339def test_error_after_conversions():
340 with pytest.raises(TypeError) as exc_info:
341 m.test_error_after_conversions("hello")
342 assert str(exc_info.value).startswith(
343 "Unable to convert function return value to a Python type!")
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +0100344
345
346def test_aligned():
347 if hasattr(m, "Aligned"):
348 p = m.Aligned().ptr()
349 assert p % 1024 == 0
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400350
351
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400352# https://foss.heptapod.net/pypy/pypy/-/issues/2742
353@pytest.mark.xfail("env.PYPY")
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400354def test_final():
355 with pytest.raises(TypeError) as exc_info:
356 class PyFinalChild(m.IsFinal):
357 pass
358 assert str(exc_info.value).endswith("is not an acceptable base type")
359
360
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400361# https://foss.heptapod.net/pypy/pypy/-/issues/2742
362@pytest.mark.xfail("env.PYPY")
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400363def test_non_final_final():
364 with pytest.raises(TypeError) as exc_info:
365 class PyNonFinalFinalChild(m.IsNonFinalFinal):
366 pass
367 assert str(exc_info.value).endswith("is not an acceptable base type")
jbarlow834d90f1a2020-07-31 17:46:12 -0700368
369
370# https://github.com/pybind/pybind11/issues/1878
371def test_exception_rvalue_abort():
372 with pytest.raises(RuntimeError):
373 m.PyPrintDestructor().throw_something()