blob: 6fa5b157a79ec335073ad281bcdb2c32063f893a [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()
Yannick Jadoulf980d762020-07-09 00:14:41 +0200112 expected = ["m.class_.Pet.__init__() must be called when overriding __init__",
113 "Pet.__init__() must be called when overriding __init__"] # PyPy?
114 # TODO: fix PyPy error message wrt. tp_name/__qualname__?
115 assert msg(exc_info.value) in expected
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400116
117 # Multiple bases
118 class RabbitHamster(m.Rabbit, m.Hamster):
119 def __init__(self):
120 m.Rabbit.__init__(self, "RabbitHamster")
121
122 with pytest.raises(TypeError) as exc_info:
123 RabbitHamster()
Yannick Jadoulf980d762020-07-09 00:14:41 +0200124 expected = ["m.class_.Hamster.__init__() must be called when overriding __init__",
125 "Hamster.__init__() must be called when overriding __init__"] # PyPy
126 assert msg(exc_info.value) in expected
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400127
128
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200129def test_automatic_upcasting():
130 assert type(m.return_class_1()).__name__ == "DerivedClass1"
131 assert type(m.return_class_2()).__name__ == "DerivedClass2"
132 assert type(m.return_none()).__name__ == "NoneType"
133 # Repeat these a few times in a random order to ensure no invalid caching is applied
134 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
135 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
136 assert type(m.return_class_n(0)).__name__ == "BaseClass"
137 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
138 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
139 assert type(m.return_class_n(0)).__name__ == "BaseClass"
140 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
141
142
143def test_isinstance():
144 objects = [tuple(), dict(), m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
145 expected = (True, True, True, True, True, False, False)
146 assert m.check_instances(objects) == expected
147
148
149def test_mismatched_holder():
150 import re
151
152 with pytest.raises(RuntimeError) as excinfo:
153 m.mismatched_holder_1()
154 assert re.match('generic_type: type ".*MismatchDerived1" does not have a non-default '
155 'holder type while its base ".*MismatchBase1" does', str(excinfo.value))
156
157 with pytest.raises(RuntimeError) as excinfo:
158 m.mismatched_holder_2()
159 assert re.match('generic_type: type ".*MismatchDerived2" has a non-default holder type '
160 'while its base ".*MismatchBase2" does not', str(excinfo.value))
161
162
163def test_override_static():
164 """#511: problem with inheritance + overwritten def_static"""
165 b = m.MyBase.make()
166 d1 = m.MyDerived.make2()
167 d2 = m.MyDerived.make()
168
169 assert isinstance(b, m.MyBase)
170 assert isinstance(d1, m.MyDerived)
171 assert isinstance(d2, m.MyDerived)
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200172
173
174def test_implicit_conversion_life_support():
175 """Ensure the lifetime of temporary objects created for implicit conversions"""
176 assert m.implicitly_convert_argument(UserType(5)) == 5
177 assert m.implicitly_convert_variable(UserType(5)) == 5
178
179 assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400180
181
182def test_operator_new_delete(capture):
183 """Tests that class-specific operator new/delete functions are invoked"""
184
185 class SubAliased(m.AliasedHasOpNewDelSize):
186 pass
187
188 with capture:
189 a = m.HasOpNewDel()
190 b = m.HasOpNewDelSize()
191 d = m.HasOpNewDelBoth()
192 assert capture == """
193 A new 8
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400194 B new 4
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400195 D new 32
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400196 """
197 sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
198 sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
199 with capture:
200 c = m.AliasedHasOpNewDelSize()
201 c2 = SubAliased()
202 assert capture == (
Jason Rhinelanderc4e18002017-08-17 00:01:42 -0400203 "C new " + sz_noalias + "\n" +
204 "C new " + sz_alias + "\n"
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400205 )
206
207 with capture:
208 del a
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400209 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400210 del b
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400211 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400212 del d
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400213 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400214 assert capture == """
215 A delete
216 B delete 4
217 D delete
218 """
219
220 with capture:
221 del c
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400222 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400223 del c2
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400224 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400225 assert capture == (
226 "C delete " + sz_noalias + "\n" +
227 "C delete " + sz_alias + "\n"
228 )
Dean Moldovan234f7c32017-08-17 17:03:46 +0200229
230
231def test_bind_protected_functions():
232 """Expose protected member functions to Python using a helper class"""
233 a = m.ProtectedA()
234 assert a.foo() == 42
235
236 b = m.ProtectedB()
237 assert b.foo() == 42
238
239 class C(m.ProtectedB):
240 def __init__(self):
241 m.ProtectedB.__init__(self)
242
243 def foo(self):
244 return 0
245
246 c = C()
247 assert c.foo() == 0
Wenzel Jakob4336a7d2017-08-21 22:48:28 +0200248
249
250def test_brace_initialization():
251 """ Tests that simple POD classes can be constructed using C++11 brace initialization """
252 a = m.BraceInitialization(123, "test")
253 assert a.field1 == 123
254 assert a.field2 == "test"
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200255
Jason Rhinelanderadbc8112018-01-11 13:22:13 -0400256 # Tests that a non-simple class doesn't get brace initialization (if the
257 # class defines an initializer_list constructor, in particular, it would
258 # win over the expected constructor).
259 b = m.NoBraceInitialization([123, 456])
260 assert b.vec == [123, 456]
261
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200262
263@pytest.unsupported_on_pypy
264def test_class_refcount():
265 """Instances must correctly increase/decrease the reference count of their types (#1029)"""
266 from sys import getrefcount
267
268 class PyDog(m.Dog):
269 pass
270
271 for cls in m.Dog, PyDog:
272 refcount_1 = getrefcount(cls)
273 molly = [cls("Molly") for _ in range(10)]
274 refcount_2 = getrefcount(cls)
275
276 del molly
277 pytest.gc_collect()
278 refcount_3 = getrefcount(cls)
279
280 assert refcount_1 == refcount_3
281 assert refcount_2 > refcount_1
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200282
283
284def test_reentrant_implicit_conversion_failure(msg):
285 # ensure that there is no runaway reentrant implicit conversion (#1035)
286 with pytest.raises(TypeError) as excinfo:
287 m.BogusImplicitConversion(0)
Jason Rhinelander71178922017-11-07 12:33:05 -0400288 assert msg(excinfo.value) == '''
289 __init__(): incompatible constructor arguments. The following argument types are supported:
290 1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200291
Jason Rhinelander71178922017-11-07 12:33:05 -0400292 Invoked with: 0
293 '''
oremanje7761e32018-09-25 14:55:18 -0700294
295
296def test_error_after_conversions():
297 with pytest.raises(TypeError) as exc_info:
298 m.test_error_after_conversions("hello")
299 assert str(exc_info.value).startswith(
300 "Unable to convert function return value to a Python type!")
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +0100301
302
303def test_aligned():
304 if hasattr(m, "Aligned"):
305 p = m.Aligned().ptr()
306 assert p % 1024 == 0
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400307
308
309# https://bitbucket.org/pypy/pypy/issues/2742
310@pytest.unsupported_on_pypy
311def test_final():
312 with pytest.raises(TypeError) as exc_info:
313 class PyFinalChild(m.IsFinal):
314 pass
315 assert str(exc_info.value).endswith("is not an acceptable base type")
316
317
318# https://bitbucket.org/pypy/pypy/issues/2742
319@pytest.unsupported_on_pypy
320def test_non_final_final():
321 with pytest.raises(TypeError) as exc_info:
322 class PyNonFinalFinalChild(m.IsNonFinalFinal):
323 pass
324 assert str(exc_info.value).endswith("is not an acceptable base type")