test_class.py
Go to the documentation of this file.
1 import pytest
2 
3 import env
4 from pybind11_tests import ConstructorStats, UserType
5 from pybind11_tests import class_ as m
6 
7 
9  expected_name = "UserType" if env.PYPY else "pybind11_tests.UserType"
10  assert m.obj_class_name(UserType(1)) == expected_name
11  assert m.obj_class_name(UserType) == expected_name
12 
13 
14 def test_repr():
15  assert "pybind11_type" in repr(type(UserType))
16  assert "UserType" in repr(UserType)
17 
18 
19 def test_instance(msg):
20  with pytest.raises(TypeError) as excinfo:
21  m.NoConstructor()
22  assert msg(excinfo.value) == "m.class_.NoConstructor: No constructor defined!"
23 
24  instance = m.NoConstructor.new_instance()
25 
26  cstats = ConstructorStats.get(m.NoConstructor)
27  assert cstats.alive() == 1
28  del instance
29  assert cstats.alive() == 0
30 
31 
33  instance = m.NoConstructorNew() # .__new__(m.NoConstructor.__class__)
34  cstats = ConstructorStats.get(m.NoConstructorNew)
35  assert cstats.alive() == 1
36  del instance
37  assert cstats.alive() == 0
38 
39 
40 def test_type():
41  assert m.check_type(1) == m.DerivedClass1
42  with pytest.raises(RuntimeError) as execinfo:
43  m.check_type(0)
44 
45  assert "pybind11::detail::get_type_info: unable to find type info" in str(
46  execinfo.value
47  )
48  assert "Invalid" in str(execinfo.value)
49 
50  # Currently not supported
51  # See https://github.com/pybind/pybind11/issues/2486
52  # assert m.check_type(2) == int
53 
54 
56  assert m.get_type_of(1) == int
57  assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1
58  assert m.get_type_of(int) == type
59 
60 
62  assert m.get_type_classic(1) == int
63  assert m.get_type_classic(m.DerivedClass1()) == m.DerivedClass1
64  assert m.get_type_classic(int) == type
65 
66 
68  # If the above test deleted the class, this will segfault
69  assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1
70 
71 
73  assert m.as_type(int) == int
74 
75  with pytest.raises(TypeError):
76  assert m.as_type(1) == int
77 
78  with pytest.raises(TypeError):
79  assert m.as_type(m.DerivedClass1()) == m.DerivedClass1
80 
81 
82 def test_docstrings(doc):
83  assert doc(UserType) == "A `py::class_` type for testing"
84  assert UserType.__name__ == "UserType"
85  assert UserType.__module__ == "pybind11_tests"
86  assert UserType.get_value.__name__ == "get_value"
87  assert UserType.get_value.__module__ == "pybind11_tests"
88 
89  assert (
90  doc(UserType.get_value)
91  == """
92  get_value(self: m.UserType) -> int
93 
94  Get value using a method
95  """
96  )
97  assert doc(UserType.value) == "Get/set value using a property"
98 
99  assert (
100  doc(m.NoConstructor.new_instance)
101  == """
102  new_instance() -> m.class_.NoConstructor
103 
104  Return an instance
105  """
106  )
107 
108 
109 def test_qualname(doc):
110  """Tests that a properly qualified name is set in __qualname__ and that
111  generated docstrings properly use it and the module name"""
112  assert m.NestBase.__qualname__ == "NestBase"
113  assert m.NestBase.Nested.__qualname__ == "NestBase.Nested"
114 
115  assert (
116  doc(m.NestBase.__init__)
117  == """
118  __init__(self: m.class_.NestBase) -> None
119  """
120  )
121  assert (
122  doc(m.NestBase.g)
123  == """
124  g(self: m.class_.NestBase, arg0: m.class_.NestBase.Nested) -> None
125  """
126  )
127  assert (
128  doc(m.NestBase.Nested.__init__)
129  == """
130  __init__(self: m.class_.NestBase.Nested) -> None
131  """
132  )
133  assert (
134  doc(m.NestBase.Nested.fn)
135  == """
136  fn(self: m.class_.NestBase.Nested, arg0: int, arg1: m.class_.NestBase, arg2: m.class_.NestBase.Nested) -> None
137  """
138  )
139  assert (
140  doc(m.NestBase.Nested.fa)
141  == """
142  fa(self: m.class_.NestBase.Nested, a: int, b: m.class_.NestBase, c: m.class_.NestBase.Nested) -> None
143  """
144  )
145  assert m.NestBase.__module__ == "pybind11_tests.class_"
146  assert m.NestBase.Nested.__module__ == "pybind11_tests.class_"
147 
148 
150  roger = m.Rabbit("Rabbit")
151  assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
152  assert m.pet_name_species(roger) == "Rabbit is a parrot"
153 
154  polly = m.Pet("Polly", "parrot")
155  assert polly.name() + " is a " + polly.species() == "Polly is a parrot"
156  assert m.pet_name_species(polly) == "Polly is a parrot"
157 
158  molly = m.Dog("Molly")
159  assert molly.name() + " is a " + molly.species() == "Molly is a dog"
160  assert m.pet_name_species(molly) == "Molly is a dog"
161 
162  fred = m.Hamster("Fred")
163  assert fred.name() + " is a " + fred.species() == "Fred is a rodent"
164 
165  assert m.dog_bark(molly) == "Woof!"
166 
167  with pytest.raises(TypeError) as excinfo:
168  m.dog_bark(polly)
169  assert (
170  msg(excinfo.value)
171  == """
172  dog_bark(): incompatible function arguments. The following argument types are supported:
173  1. (arg0: m.class_.Dog) -> str
174 
175  Invoked with: <m.class_.Pet object at 0>
176  """
177  )
178 
179  with pytest.raises(TypeError) as excinfo:
180  m.Chimera("lion", "goat")
181  assert "No constructor defined!" in str(excinfo.value)
182 
183 
185  # Single base
186  class Python(m.Pet):
187  def __init__(self):
188  pass
189 
190  with pytest.raises(TypeError) as exc_info:
191  Python()
192  expected = "m.class_.Pet.__init__() must be called when overriding __init__"
193  assert msg(exc_info.value) == expected
194 
195  # Multiple bases
196  class RabbitHamster(m.Rabbit, m.Hamster):
197  def __init__(self):
198  m.Rabbit.__init__(self, "RabbitHamster")
199 
200  with pytest.raises(TypeError) as exc_info:
201  RabbitHamster()
202  expected = "m.class_.Hamster.__init__() must be called when overriding __init__"
203  assert msg(exc_info.value) == expected
204 
205 
207  assert type(m.return_class_1()).__name__ == "DerivedClass1"
208  assert type(m.return_class_2()).__name__ == "DerivedClass2"
209  assert type(m.return_none()).__name__ == "NoneType"
210  # Repeat these a few times in a random order to ensure no invalid caching is applied
211  assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
212  assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
213  assert type(m.return_class_n(0)).__name__ == "BaseClass"
214  assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
215  assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
216  assert type(m.return_class_n(0)).__name__ == "BaseClass"
217  assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
218 
219 
221  objects = [(), {}, m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
222  expected = (True, True, True, True, True, False, False)
223  assert m.check_instances(objects) == expected
224 
225 
227  import re
228 
229  with pytest.raises(RuntimeError) as excinfo:
230  m.mismatched_holder_1()
231  assert re.match(
232  'generic_type: type ".*MismatchDerived1" does not have a non-default '
233  'holder type while its base ".*MismatchBase1" does',
234  str(excinfo.value),
235  )
236 
237  with pytest.raises(RuntimeError) as excinfo:
238  m.mismatched_holder_2()
239  assert re.match(
240  'generic_type: type ".*MismatchDerived2" has a non-default holder type '
241  'while its base ".*MismatchBase2" does not',
242  str(excinfo.value),
243  )
244 
245 
247  """#511: problem with inheritance + overwritten def_static"""
248  b = m.MyBase.make()
249  d1 = m.MyDerived.make2()
250  d2 = m.MyDerived.make()
251 
252  assert isinstance(b, m.MyBase)
253  assert isinstance(d1, m.MyDerived)
254  assert isinstance(d2, m.MyDerived)
255 
256 
258  """Ensure the lifetime of temporary objects created for implicit conversions"""
259  assert m.implicitly_convert_argument(UserType(5)) == 5
260  assert m.implicitly_convert_variable(UserType(5)) == 5
261 
262  assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
263 
264 
266  """Tests that class-specific operator new/delete functions are invoked"""
267 
268  class SubAliased(m.AliasedHasOpNewDelSize):
269  pass
270 
271  with capture:
272  a = m.HasOpNewDel()
273  b = m.HasOpNewDelSize()
274  d = m.HasOpNewDelBoth()
275  assert (
276  capture
277  == """
278  A new 8
279  B new 4
280  D new 32
281  """
282  )
283  sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
284  sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
285  with capture:
286  c = m.AliasedHasOpNewDelSize()
287  c2 = SubAliased()
288  assert capture == ("C new " + sz_noalias + "\n" + "C new " + sz_alias + "\n")
289 
290  with capture:
291  del a
292  pytest.gc_collect()
293  del b
294  pytest.gc_collect()
295  del d
296  pytest.gc_collect()
297  assert (
298  capture
299  == """
300  A delete
301  B delete 4
302  D delete
303  """
304  )
305 
306  with capture:
307  del c
308  pytest.gc_collect()
309  del c2
310  pytest.gc_collect()
311  assert capture == ("C delete " + sz_noalias + "\n" + "C delete " + sz_alias + "\n")
312 
313 
315  """Expose protected member functions to Python using a helper class"""
316  a = m.ProtectedA()
317  assert a.foo() == 42
318 
319  b = m.ProtectedB()
320  assert b.foo() == 42
321  assert m.read_foo(b.void_foo()) == 42
322  assert m.pointers_equal(b.get_self(), b)
323 
324  class C(m.ProtectedB):
325  def __init__(self):
326  m.ProtectedB.__init__(self)
327 
328  def foo(self):
329  return 0
330 
331  c = C()
332  assert c.foo() == 0
333 
334 
336  """Tests that simple POD classes can be constructed using C++11 brace initialization"""
337  a = m.BraceInitialization(123, "test")
338  assert a.field1 == 123
339  assert a.field2 == "test"
340 
341  # Tests that a non-simple class doesn't get brace initialization (if the
342  # class defines an initializer_list constructor, in particular, it would
343  # win over the expected constructor).
344  b = m.NoBraceInitialization([123, 456])
345  assert b.vec == [123, 456]
346 
347 
348 @pytest.mark.xfail("env.PYPY")
350  """Instances must correctly increase/decrease the reference count of their types (#1029)"""
351  from sys import getrefcount
352 
353  class PyDog(m.Dog):
354  pass
355 
356  for cls in m.Dog, PyDog:
357  refcount_1 = getrefcount(cls)
358  molly = [cls("Molly") for _ in range(10)]
359  refcount_2 = getrefcount(cls)
360 
361  del molly
362  pytest.gc_collect()
363  refcount_3 = getrefcount(cls)
364 
365  assert refcount_1 == refcount_3
366  assert refcount_2 > refcount_1
367 
368 
370  # ensure that there is no runaway reentrant implicit conversion (#1035)
371  with pytest.raises(TypeError) as excinfo:
372  m.BogusImplicitConversion(0)
373  assert (
374  msg(excinfo.value)
375  == """
376  __init__(): incompatible constructor arguments. The following argument types are supported:
377  1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
378 
379  Invoked with: 0
380  """
381  )
382 
383 
385  with pytest.raises(TypeError) as exc_info:
386  m.test_error_after_conversions("hello")
387  assert str(exc_info.value).startswith(
388  "Unable to convert function return value to a Python type!"
389  )
390 
391 
393  if hasattr(m, "Aligned"):
394  p = m.Aligned().ptr()
395  assert p % 1024 == 0
396 
397 
398 # https://foss.heptapod.net/pypy/pypy/-/issues/2742
399 @pytest.mark.xfail("env.PYPY")
401  with pytest.raises(TypeError) as exc_info:
402 
403  class PyFinalChild(m.IsFinal):
404  pass
405 
406  assert str(exc_info.value).endswith("is not an acceptable base type")
407 
408 
409 # https://foss.heptapod.net/pypy/pypy/-/issues/2742
410 @pytest.mark.xfail("env.PYPY")
412  with pytest.raises(TypeError) as exc_info:
413 
414  class PyNonFinalFinalChild(m.IsNonFinalFinal):
415  pass
416 
417  assert str(exc_info.value).endswith("is not an acceptable base type")
418 
419 
420 # https://github.com/pybind/pybind11/issues/1878
422  with pytest.raises(RuntimeError):
423  m.PyPrintDestructor().throw_something()
424 
425 
426 # https://github.com/pybind/pybind11/issues/1568
428  n = 100
429  instances = [m.SamePointer() for _ in range(n)]
430  for i in range(n):
431  # We need to reuse the same allocated memory for with a different type,
432  # to ensure the bug in `deregister_instance_impl` is detected. Otherwise
433  # `Py_TYPE(self) == Py_TYPE(it->second)` will still succeed, even though
434  # the `instance` is already deleted.
435  instances[i] = m.Empty()
436  # No assert: if this does not trigger the error
437  # pybind11_fail("pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
438  # and just completes without crashing, we're good.
439 
440 
441 # https://github.com/pybind/pybind11/issues/1624
443  assert issubclass(m.DerivedWithNested, m.BaseWithNested)
444  assert m.BaseWithNested.Nested != m.DerivedWithNested.Nested
445  assert m.BaseWithNested.Nested.get_name() == "BaseWithNested::Nested"
446  assert m.DerivedWithNested.Nested.get_name() == "DerivedWithNested::Nested"
447 
448 
450  import types
451 
452  module_scope = types.ModuleType("module_scope")
453  with pytest.raises(RuntimeError) as exc_info:
454  m.register_duplicate_class_name(module_scope)
455  expected = (
456  'generic_type: cannot initialize type "Duplicate": '
457  "an object with that name is already defined"
458  )
459  assert str(exc_info.value) == expected
460  with pytest.raises(RuntimeError) as exc_info:
461  m.register_duplicate_class_type(module_scope)
462  expected = 'generic_type: type "YetAnotherDuplicate" is already registered!'
463  assert str(exc_info.value) == expected
464 
465  class ClassScope:
466  pass
467 
468  with pytest.raises(RuntimeError) as exc_info:
469  m.register_duplicate_nested_class_name(ClassScope)
470  expected = (
471  'generic_type: cannot initialize type "DuplicateNested": '
472  "an object with that name is already defined"
473  )
474  assert str(exc_info.value) == expected
475  with pytest.raises(RuntimeError) as exc_info:
476  m.register_duplicate_nested_class_type(ClassScope)
477  expected = 'generic_type: type "YetAnotherDuplicateNested" is already registered!'
478  assert str(exc_info.value) == expected
479 
480 
482  assert (
483  m.Empty0().get_msg()
484  == "This is really only meant to exercise successful compilation."
485  )
test_class.test_exception_rvalue_abort
def test_exception_rvalue_abort()
Definition: test_class.py:421
test_class.test_aligned
def test_aligned()
Definition: test_class.py:392
test_class.test_repr
def test_repr()
Definition: test_class.py:14
test_class.test_inheritance
def test_inheritance(msg)
Definition: test_class.py:149
test_class.test_qualname
def test_qualname(doc)
Definition: test_class.py:109
test_class.test_multiple_instances_with_same_pointer
def test_multiple_instances_with_same_pointer()
Definition: test_class.py:427
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:853
type
Definition: pytypes.h:1491
test_class.test_final
def test_final()
Definition: test_class.py:400
test_class.test_override_static
def test_override_static()
Definition: test_class.py:246
gtsam::range
Double_ range(const Point2_ &p, const Point2_ &q)
Definition: slam/expressions.h:30
test_class.test_non_final_final
def test_non_final_final()
Definition: test_class.py:411
doc
Annotation for documentation.
Definition: attr.h:45
test_class.test_as_type_py
def test_as_type_py()
Definition: test_class.py:72
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:825
test_class.test_type_of_classic
def test_type_of_classic()
Definition: test_class.py:61
test_class.test_instance_new
def test_instance_new()
Definition: test_class.py:32
test_class.test_register_duplicate_class
def test_register_duplicate_class()
Definition: test_class.py:449
test_class.test_type_of_py_nodelete
def test_type_of_py_nodelete()
Definition: test_class.py:67
test_class::pr4220_tripped_over_this::get_msg
std::string get_msg(const T &)
Definition: test_class.cpp:44
foo
void foo(CV_QUALIFIER Matrix3d &m)
Definition: block_nonconst_ctor_on_const_xpr_0.cpp:11
test_class.test_error_after_conversions
def test_error_after_conversions()
Definition: test_class.py:384
test_class.test_instance
def test_instance(msg)
Definition: test_class.py:19
gtwrap.interface_parser.function.__init__
def __init__(self, Union[Type, TemplatedType] ctype, str name, ParseResults default=None)
Definition: interface_parser/function.py:41
test_class.test_isinstance
def test_isinstance()
Definition: test_class.py:220
str
Definition: pytypes.h:1524
test_class.test_type_of_py
def test_type_of_py()
Definition: test_class.py:55
test_class.test_class_refcount
def test_class_refcount()
Definition: test_class.py:349
test_class.test_base_and_derived_nested_scope
def test_base_and_derived_nested_scope()
Definition: test_class.py:442
C
Matrix< Scalar, Dynamic, Dynamic > C
Definition: bench_gemm.cpp:50
ConstructorStats::get
static ConstructorStats & get(std::type_index type)
Definition: constructor_stats.h:163
test_class.test_docstrings
def test_docstrings(doc)
Definition: test_class.py:82
test_class.test_mismatched_holder
def test_mismatched_holder()
Definition: test_class.py:226
test_class.test_inheritance_init
def test_inheritance_init(msg)
Definition: test_class.py:184
test_class.test_automatic_upcasting
def test_automatic_upcasting()
Definition: test_class.py:206
test_class.test_bind_protected_functions
def test_bind_protected_functions()
Definition: test_class.py:314
test_class.test_brace_initialization
def test_brace_initialization()
Definition: test_class.py:335
test_class.test_implicit_conversion_life_support
def test_implicit_conversion_life_support()
Definition: test_class.py:257
test_class.test_obj_class_name
def test_obj_class_name()
Definition: test_class.py:8
test_class.test_operator_new_delete
def test_operator_new_delete(capture)
Definition: test_class.py:265
test_class.test_reentrant_implicit_conversion_failure
def test_reentrant_implicit_conversion_failure(msg)
Definition: test_class.py:369
test_class.test_pr4220_tripped_over_this
def test_pr4220_tripped_over_this()
Definition: test_class.py:481
test_class.test_type
def test_type()
Definition: test_class.py:40
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:4
repr
str repr(handle h)
Definition: pytypes.h:2420


gtsam
Author(s):
autogenerated on Tue Jun 25 2024 03:05:28