1 from __future__
import annotations
3 from unittest
import mock
8 from pybind11_tests
import PYBIND11_REFCNT_IMMORTAL, ConstructorStats, UserType
9 from pybind11_tests
import class_
as m
13 expected_name =
"UserType" if env.PYPY
else "pybind11_tests.UserType"
14 assert m.obj_class_name(UserType(1)) == expected_name
15 assert m.obj_class_name(UserType) == expected_name
19 assert "pybind11_type" in repr(
type(UserType))
20 assert "UserType" in repr(UserType)
24 with pytest.raises(TypeError)
as excinfo:
26 assert msg(excinfo.value) ==
"m.class_.NoConstructor: No constructor defined!"
28 instance = m.NoConstructor.new_instance()
31 assert cstats.alive() == 1
33 assert cstats.alive() == 0
37 instance = m.NoConstructorNew()
39 assert cstats.alive() == 1
41 assert cstats.alive() == 0
45 assert m.check_type(1) == m.DerivedClass1
46 with pytest.raises(RuntimeError)
as execinfo:
49 assert "pybind11::detail::get_type_info: unable to find type info" in str(
52 assert "Invalid" in str(execinfo.value)
60 assert m.get_type_of(1) == int
61 assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1
62 assert m.get_type_of(int) == type
66 assert m.get_type_classic(1) == int
67 assert m.get_type_classic(m.DerivedClass1()) == m.DerivedClass1
68 assert m.get_type_classic(int) == type
73 assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1
77 assert m.as_type(int) == int
79 with pytest.raises(TypeError):
80 assert m.as_type(1) == int
82 with pytest.raises(TypeError):
83 assert m.as_type(m.DerivedClass1()) == m.DerivedClass1
87 assert doc(UserType) ==
"A `py::class_` type for testing"
88 assert UserType.__name__ ==
"UserType"
89 assert UserType.__module__ ==
"pybind11_tests"
90 assert UserType.get_value.__name__ ==
"get_value"
91 assert UserType.get_value.__module__ ==
"pybind11_tests"
94 doc(UserType.get_value)
96 get_value(self: m.UserType) -> int
98 Get value using a method
101 assert doc(UserType.value) ==
"Get/set value using a property"
104 doc(m.NoConstructor.new_instance)
106 new_instance() -> m.class_.NoConstructor
114 """Tests that a properly qualified name is set in __qualname__ and that
115 generated docstrings properly use it and the module name"""
116 assert m.NestBase.__qualname__ ==
"NestBase"
117 assert m.NestBase.Nested.__qualname__ ==
"NestBase.Nested"
120 doc(m.NestBase.__init__)
122 __init__(self: m.class_.NestBase) -> None
128 g(self: m.class_.NestBase, arg0: m.class_.NestBase.Nested) -> None
132 doc(m.NestBase.Nested.__init__)
134 __init__(self: m.class_.NestBase.Nested) -> None
138 doc(m.NestBase.Nested.fn)
140 fn(self: m.class_.NestBase.Nested, arg0: int, arg1: m.class_.NestBase, arg2: m.class_.NestBase.Nested) -> None
144 doc(m.NestBase.Nested.fa)
146 fa(self: m.class_.NestBase.Nested, a: int, b: m.class_.NestBase, c: m.class_.NestBase.Nested) -> None
149 assert m.NestBase.__module__ ==
"pybind11_tests.class_"
150 assert m.NestBase.Nested.__module__ ==
"pybind11_tests.class_"
154 roger = m.Rabbit(
"Rabbit")
155 assert roger.name() +
" is a " + roger.species() ==
"Rabbit is a parrot"
156 assert m.pet_name_species(roger) ==
"Rabbit is a parrot"
158 polly = m.Pet(
"Polly",
"parrot")
159 assert polly.name() +
" is a " + polly.species() ==
"Polly is a parrot"
160 assert m.pet_name_species(polly) ==
"Polly is a parrot"
162 molly = m.Dog(
"Molly")
163 assert molly.name() +
" is a " + molly.species() ==
"Molly is a dog"
164 assert m.pet_name_species(molly) ==
"Molly is a dog"
166 fred = m.Hamster(
"Fred")
167 assert fred.name() +
" is a " + fred.species() ==
"Fred is a rodent"
169 assert m.dog_bark(molly) ==
"Woof!"
171 with pytest.raises(TypeError)
as excinfo:
176 dog_bark(): incompatible function arguments. The following argument types are supported:
177 1. (arg0: m.class_.Dog) -> str
179 Invoked with: <m.class_.Pet object at 0>
183 with pytest.raises(TypeError)
as excinfo:
184 m.Chimera(
"lion",
"goat")
185 assert "No constructor defined!" in str(excinfo.value)
194 with pytest.raises(TypeError)
as exc_info:
196 expected =
"m.class_.Pet.__init__() must be called when overriding __init__"
197 assert msg(exc_info.value) == expected
200 class RabbitHamster(m.Rabbit, m.Hamster):
202 m.Rabbit.__init__(self,
"RabbitHamster")
204 with pytest.raises(TypeError)
as exc_info:
206 expected =
"m.class_.Hamster.__init__() must be called when overriding __init__"
207 assert msg(exc_info.value) == expected
210 @pytest.mark.parametrize(
211 "mock_return_value", [
None, (1, 2, 3), m.Pet(
"Polly",
"parrot"), m.Dog(
"Molly")]
214 with mock.patch.object(
215 m.Pet,
"__new__", return_value=mock_return_value
217 obj = m.Pet(
"Noname",
"Nospecies")
218 assert obj
is mock_return_value
219 mock_new.assert_called_once_with(m.Pet,
"Noname",
"Nospecies")
223 assert type(m.return_class_1()).__name__ ==
"DerivedClass1"
224 assert type(m.return_class_2()).__name__ ==
"DerivedClass2"
225 assert type(m.return_none()).__name__ ==
"NoneType"
227 assert type(m.return_class_n(1)).__name__ ==
"DerivedClass1"
228 assert type(m.return_class_n(2)).__name__ ==
"DerivedClass2"
229 assert type(m.return_class_n(0)).__name__ ==
"BaseClass"
230 assert type(m.return_class_n(2)).__name__ ==
"DerivedClass2"
231 assert type(m.return_class_n(2)).__name__ ==
"DerivedClass2"
232 assert type(m.return_class_n(0)).__name__ ==
"BaseClass"
233 assert type(m.return_class_n(1)).__name__ ==
"DerivedClass1"
237 objects = [(), {}, m.Pet(
"Polly",
"parrot")] + [m.Dog(
"Molly")] * 4
238 expected = (
True,
True,
True,
True,
True,
False,
False)
239 assert m.check_instances(objects) == expected
245 with pytest.raises(RuntimeError)
as excinfo:
246 m.mismatched_holder_1()
248 'generic_type: type ".*MismatchDerived1" does not have a non-default '
249 'holder type while its base ".*MismatchBase1" does',
253 with pytest.raises(RuntimeError)
as excinfo:
254 m.mismatched_holder_2()
256 'generic_type: type ".*MismatchDerived2" has a non-default holder type '
257 'while its base ".*MismatchBase2" does not',
263 """#511: problem with inheritance + overwritten def_static"""
265 d1 = m.MyDerived.make2()
266 d2 = m.MyDerived.make()
274 """Ensure the lifetime of temporary objects created for implicit conversions"""
275 assert m.implicitly_convert_argument(UserType(5)) == 5
276 assert m.implicitly_convert_variable(UserType(5)) == 5
278 assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
282 """Tests that class-specific operator new/delete functions are invoked"""
284 class SubAliased(m.AliasedHasOpNewDelSize):
289 b = m.HasOpNewDelSize()
290 d = m.HasOpNewDelBoth()
299 sz_alias =
str(m.AliasedHasOpNewDelSize.size_alias)
300 sz_noalias =
str(m.AliasedHasOpNewDelSize.size_noalias)
302 c = m.AliasedHasOpNewDelSize()
304 assert capture == (
"C new " + sz_noalias +
"\n" +
"C new " + sz_alias +
"\n")
327 assert capture == (
"C delete " + sz_noalias +
"\n" +
"C delete " + sz_alias +
"\n")
331 """Expose protected member functions to Python using a helper class"""
337 assert m.read_foo(b.void_foo()) == 42
338 assert m.pointers_equal(b.get_self(), b)
340 class C(m.ProtectedB):
342 m.ProtectedB.__init__(self)
352 """Tests that simple POD classes can be constructed using C++11 brace initialization"""
353 a = m.BraceInitialization(123,
"test")
354 assert a.field1 == 123
355 assert a.field2 ==
"test"
360 b = m.NoBraceInitialization([123, 456])
361 assert b.vec == [123, 456]
364 @pytest.mark.xfail(
"env.PYPY")
366 """Instances must correctly increase/decrease the reference count of their types (#1029)"""
367 from sys
import getrefcount
372 for cls
in m.Dog, PyDog:
373 refcount_1 = getrefcount(cls)
374 molly = [cls(
"Molly")
for _
in range(10)]
375 refcount_2 = getrefcount(cls)
379 refcount_3 = getrefcount(cls)
381 assert refcount_1 == refcount_3
382 assert (refcount_2 > refcount_1)
or (
383 refcount_2 == refcount_1 == PYBIND11_REFCNT_IMMORTAL
389 with pytest.raises(TypeError)
as excinfo:
390 m.BogusImplicitConversion(0)
394 __init__(): incompatible constructor arguments. The following argument types are supported:
395 1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
403 with pytest.raises(TypeError)
as exc_info:
404 m.test_error_after_conversions(
"hello")
405 assert str(exc_info.value).startswith(
406 "Unable to convert function return value to a Python type!"
412 p = m.Aligned().ptr()
417 @pytest.mark.xfail(
"env.PYPY")
419 with pytest.raises(TypeError)
as exc_info:
421 class PyFinalChild(m.IsFinal):
424 assert str(exc_info.value).endswith(
"is not an acceptable base type")
428 @pytest.mark.xfail(
"env.PYPY")
430 with pytest.raises(TypeError)
as exc_info:
432 class PyNonFinalFinalChild(m.IsNonFinalFinal):
435 assert str(exc_info.value).endswith(
"is not an acceptable base type")
440 with pytest.raises(RuntimeError):
441 m.PyPrintDestructor().throw_something()
447 instances = [m.SamePointer()
for _
in range(n)]
453 instances[i] = m.Empty()
461 assert issubclass(m.DerivedWithNested, m.BaseWithNested)
462 assert m.BaseWithNested.Nested != m.DerivedWithNested.Nested
463 assert m.BaseWithNested.Nested.get_name() ==
"BaseWithNested::Nested"
464 assert m.DerivedWithNested.Nested.get_name() ==
"DerivedWithNested::Nested"
470 module_scope = types.ModuleType(
"module_scope")
471 with pytest.raises(RuntimeError)
as exc_info:
472 m.register_duplicate_class_name(module_scope)
474 'generic_type: cannot initialize type "Duplicate": '
475 "an object with that name is already defined"
477 assert str(exc_info.value) == expected
478 with pytest.raises(RuntimeError)
as exc_info:
479 m.register_duplicate_class_type(module_scope)
480 expected =
'generic_type: type "YetAnotherDuplicate" is already registered!'
481 assert str(exc_info.value) == expected
486 with pytest.raises(RuntimeError)
as exc_info:
487 m.register_duplicate_nested_class_name(ClassScope)
489 'generic_type: cannot initialize type "DuplicateNested": '
490 "an object with that name is already defined"
492 assert str(exc_info.value) == expected
493 with pytest.raises(RuntimeError)
as exc_info:
494 m.register_duplicate_nested_class_type(ClassScope)
495 expected =
'generic_type: type "YetAnotherDuplicateNested" is already registered!'
496 assert str(exc_info.value) == expected
502 ==
"This is really only meant to exercise successful compilation."