blob: 4214fe79d7fbab2b38a1f15ca39d41e7cd33a171 [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
29def test_docstrings(doc):
30 assert doc(UserType) == "A `py::class_` type for testing"
31 assert UserType.__name__ == "UserType"
32 assert UserType.__module__ == "pybind11_tests"
33 assert UserType.get_value.__name__ == "get_value"
34 assert UserType.get_value.__module__ == "pybind11_tests"
35
36 assert doc(UserType.get_value) == """
37 get_value(self: m.UserType) -> int
38
39 Get value using a method
40 """
Jason Rhinelander391c7542017-07-25 16:47:36 -040041 assert doc(UserType.value) == "Get/set value using a property"
Dean Moldovan83e328f2017-06-09 00:44:49 +020042
43 assert doc(m.NoConstructor.new_instance) == """
44 new_instance() -> m.class_.NoConstructor
45
46 Return an instance
47 """
Dean Moldovan0bc272b2017-06-22 23:42:11 +020048
49
Jason Rhinelander71178922017-11-07 12:33:05 -040050def test_qualname(doc):
51 """Tests that a properly qualified name is set in __qualname__ (even in pre-3.3, where we
52 backport the attribute) and that generated docstrings properly use it and the module name"""
53 assert m.NestBase.__qualname__ == "NestBase"
54 assert m.NestBase.Nested.__qualname__ == "NestBase.Nested"
55
56 assert doc(m.NestBase.__init__) == """
57 __init__(self: m.class_.NestBase) -> None
58 """
59 assert doc(m.NestBase.g) == """
60 g(self: m.class_.NestBase, arg0: m.class_.NestBase.Nested) -> None
61 """
62 assert doc(m.NestBase.Nested.__init__) == """
63 __init__(self: m.class_.NestBase.Nested) -> None
64 """
65 assert doc(m.NestBase.Nested.fn) == """
66 fn(self: m.class_.NestBase.Nested, arg0: int, arg1: m.class_.NestBase, arg2: m.class_.NestBase.Nested) -> None
67 """ # noqa: E501 line too long
68 assert doc(m.NestBase.Nested.fa) == """
69 fa(self: m.class_.NestBase.Nested, a: int, b: m.class_.NestBase, c: m.class_.NestBase.Nested) -> None
70 """ # noqa: E501 line too long
71 assert m.NestBase.__module__ == "pybind11_tests.class_"
72 assert m.NestBase.Nested.__module__ == "pybind11_tests.class_"
73
74
Dean Moldovan0bc272b2017-06-22 23:42:11 +020075def test_inheritance(msg):
76 roger = m.Rabbit('Rabbit')
77 assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
78 assert m.pet_name_species(roger) == "Rabbit is a parrot"
79
80 polly = m.Pet('Polly', 'parrot')
81 assert polly.name() + " is a " + polly.species() == "Polly is a parrot"
82 assert m.pet_name_species(polly) == "Polly is a parrot"
83
84 molly = m.Dog('Molly')
85 assert molly.name() + " is a " + molly.species() == "Molly is a dog"
86 assert m.pet_name_species(molly) == "Molly is a dog"
87
88 fred = m.Hamster('Fred')
89 assert fred.name() + " is a " + fred.species() == "Fred is a rodent"
90
91 assert m.dog_bark(molly) == "Woof!"
92
93 with pytest.raises(TypeError) as excinfo:
94 m.dog_bark(polly)
95 assert msg(excinfo.value) == """
96 dog_bark(): incompatible function arguments. The following argument types are supported:
97 1. (arg0: m.class_.Dog) -> str
98
99 Invoked with: <m.class_.Pet object at 0>
100 """
101
102 with pytest.raises(TypeError) as excinfo:
103 m.Chimera("lion", "goat")
104 assert "No constructor defined!" in str(excinfo.value)
105
106
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400107def test_inheritance_init(msg):
108
109 # Single base
110 class Python(m.Pet):
111 def __init__(self):
112 pass
113 with pytest.raises(TypeError) as exc_info:
114 Python()
Yannick Jadoulf980d762020-07-09 00:14:41 +0200115 expected = ["m.class_.Pet.__init__() must be called when overriding __init__",
116 "Pet.__init__() must be called when overriding __init__"] # PyPy?
117 # TODO: fix PyPy error message wrt. tp_name/__qualname__?
118 assert msg(exc_info.value) in expected
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400119
120 # Multiple bases
121 class RabbitHamster(m.Rabbit, m.Hamster):
122 def __init__(self):
123 m.Rabbit.__init__(self, "RabbitHamster")
124
125 with pytest.raises(TypeError) as exc_info:
126 RabbitHamster()
Yannick Jadoulf980d762020-07-09 00:14:41 +0200127 expected = ["m.class_.Hamster.__init__() must be called when overriding __init__",
128 "Hamster.__init__() must be called when overriding __init__"] # PyPy
129 assert msg(exc_info.value) in expected
Dustin Spicuzza1b0bf352020-07-07 06:04:06 -0400130
131
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200132def test_automatic_upcasting():
133 assert type(m.return_class_1()).__name__ == "DerivedClass1"
134 assert type(m.return_class_2()).__name__ == "DerivedClass2"
135 assert type(m.return_none()).__name__ == "NoneType"
136 # Repeat these a few times in a random order to ensure no invalid caching is applied
137 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
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(2)).__name__ == "DerivedClass2"
141 assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
142 assert type(m.return_class_n(0)).__name__ == "BaseClass"
143 assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
144
145
146def test_isinstance():
147 objects = [tuple(), dict(), m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
148 expected = (True, True, True, True, True, False, False)
149 assert m.check_instances(objects) == expected
150
151
152def test_mismatched_holder():
153 import re
154
155 with pytest.raises(RuntimeError) as excinfo:
156 m.mismatched_holder_1()
157 assert re.match('generic_type: type ".*MismatchDerived1" does not have a non-default '
158 'holder type while its base ".*MismatchBase1" does', str(excinfo.value))
159
160 with pytest.raises(RuntimeError) as excinfo:
161 m.mismatched_holder_2()
162 assert re.match('generic_type: type ".*MismatchDerived2" has a non-default holder type '
163 'while its base ".*MismatchBase2" does not', str(excinfo.value))
164
165
166def test_override_static():
167 """#511: problem with inheritance + overwritten def_static"""
168 b = m.MyBase.make()
169 d1 = m.MyDerived.make2()
170 d2 = m.MyDerived.make()
171
172 assert isinstance(b, m.MyBase)
173 assert isinstance(d1, m.MyDerived)
174 assert isinstance(d2, m.MyDerived)
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200175
176
177def test_implicit_conversion_life_support():
178 """Ensure the lifetime of temporary objects created for implicit conversions"""
179 assert m.implicitly_convert_argument(UserType(5)) == 5
180 assert m.implicitly_convert_variable(UserType(5)) == 5
181
182 assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400183
184
185def test_operator_new_delete(capture):
186 """Tests that class-specific operator new/delete functions are invoked"""
187
188 class SubAliased(m.AliasedHasOpNewDelSize):
189 pass
190
191 with capture:
192 a = m.HasOpNewDel()
193 b = m.HasOpNewDelSize()
194 d = m.HasOpNewDelBoth()
195 assert capture == """
196 A new 8
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400197 B new 4
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400198 D new 32
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400199 """
200 sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
201 sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
202 with capture:
203 c = m.AliasedHasOpNewDelSize()
204 c2 = SubAliased()
205 assert capture == (
Jason Rhinelanderc4e18002017-08-17 00:01:42 -0400206 "C new " + sz_noalias + "\n" +
207 "C new " + sz_alias + "\n"
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400208 )
209
210 with capture:
211 del a
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400212 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400213 del b
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400214 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400215 del d
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400216 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400217 assert capture == """
218 A delete
219 B delete 4
220 D delete
221 """
222
223 with capture:
224 del c
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400225 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400226 del c2
Jason Rhinelander9866a0f2017-07-26 13:52:53 -0400227 pytest.gc_collect()
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400228 assert capture == (
229 "C delete " + sz_noalias + "\n" +
230 "C delete " + sz_alias + "\n"
231 )
Dean Moldovan234f7c32017-08-17 17:03:46 +0200232
233
234def test_bind_protected_functions():
235 """Expose protected member functions to Python using a helper class"""
236 a = m.ProtectedA()
237 assert a.foo() == 42
238
239 b = m.ProtectedB()
240 assert b.foo() == 42
241
242 class C(m.ProtectedB):
243 def __init__(self):
244 m.ProtectedB.__init__(self)
245
246 def foo(self):
247 return 0
248
249 c = C()
250 assert c.foo() == 0
Wenzel Jakob4336a7d2017-08-21 22:48:28 +0200251
252
253def test_brace_initialization():
254 """ Tests that simple POD classes can be constructed using C++11 brace initialization """
255 a = m.BraceInitialization(123, "test")
256 assert a.field1 == 123
257 assert a.field2 == "test"
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200258
Jason Rhinelanderadbc8112018-01-11 13:22:13 -0400259 # Tests that a non-simple class doesn't get brace initialization (if the
260 # class defines an initializer_list constructor, in particular, it would
261 # win over the expected constructor).
262 b = m.NoBraceInitialization([123, 456])
263 assert b.vec == [123, 456]
264
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200265
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400266@pytest.mark.xfail("env.PYPY")
Wenzel Jakobc14c2762017-08-25 16:02:18 +0200267def test_class_refcount():
268 """Instances must correctly increase/decrease the reference count of their types (#1029)"""
269 from sys import getrefcount
270
271 class PyDog(m.Dog):
272 pass
273
274 for cls in m.Dog, PyDog:
275 refcount_1 = getrefcount(cls)
276 molly = [cls("Molly") for _ in range(10)]
277 refcount_2 = getrefcount(cls)
278
279 del molly
280 pytest.gc_collect()
281 refcount_3 = getrefcount(cls)
282
283 assert refcount_1 == refcount_3
284 assert refcount_2 > refcount_1
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200285
286
287def test_reentrant_implicit_conversion_failure(msg):
288 # ensure that there is no runaway reentrant implicit conversion (#1035)
289 with pytest.raises(TypeError) as excinfo:
290 m.BogusImplicitConversion(0)
Jason Rhinelander71178922017-11-07 12:33:05 -0400291 assert msg(excinfo.value) == '''
292 __init__(): incompatible constructor arguments. The following argument types are supported:
293 1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200294
Jason Rhinelander71178922017-11-07 12:33:05 -0400295 Invoked with: 0
296 '''
oremanje7761e32018-09-25 14:55:18 -0700297
298
299def test_error_after_conversions():
300 with pytest.raises(TypeError) as exc_info:
301 m.test_error_after_conversions("hello")
302 assert str(exc_info.value).startswith(
303 "Unable to convert function return value to a Python type!")
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +0100304
305
306def test_aligned():
307 if hasattr(m, "Aligned"):
308 p = m.Aligned().ptr()
309 assert p % 1024 == 0
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400310
311
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400312# https://foss.heptapod.net/pypy/pypy/-/issues/2742
313@pytest.mark.xfail("env.PYPY")
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400314def test_final():
315 with pytest.raises(TypeError) as exc_info:
316 class PyFinalChild(m.IsFinal):
317 pass
318 assert str(exc_info.value).endswith("is not an acceptable base type")
319
320
Henry Schreiner4d9024e2020-08-16 16:02:12 -0400321# https://foss.heptapod.net/pypy/pypy/-/issues/2742
322@pytest.mark.xfail("env.PYPY")
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400323def test_non_final_final():
324 with pytest.raises(TypeError) as exc_info:
325 class PyNonFinalFinalChild(m.IsNonFinalFinal):
326 pass
327 assert str(exc_info.value).endswith("is not an acceptable base type")
jbarlow834d90f1a2020-07-31 17:46:12 -0700328
329
330# https://github.com/pybind/pybind11/issues/1878
331def test_exception_rvalue_abort():
332 with pytest.raises(RuntimeError):
333 m.PyPrintDestructor().throw_something()