test_methods_and_attributes.py
Go to the documentation of this file.
1 from __future__ import annotations
2 
3 import sys
4 
5 import pytest
6 
7 import env # noqa: F401
8 from pybind11_tests import ConstructorStats
9 from pybind11_tests import methods_and_attributes as m
10 
11 NO_GETTER_MSG = (
12  "unreadable attribute" if sys.version_info < (3, 11) else "object has no getter"
13 )
14 NO_SETTER_MSG = (
15  "can't set attribute" if sys.version_info < (3, 11) else "object has no setter"
16 )
17 NO_DELETER_MSG = (
18  "can't delete attribute" if sys.version_info < (3, 11) else "object has no deleter"
19 )
20 
21 
23  instance1 = m.ExampleMandA()
24  instance2 = m.ExampleMandA(32)
25 
26  instance1.add1(instance2)
27  instance1.add2(instance2)
28  instance1.add3(instance2)
29  instance1.add4(instance2)
30  instance1.add5(instance2)
31  instance1.add6(32)
32  instance1.add7(32)
33  instance1.add8(32)
34  instance1.add9(32)
35  instance1.add10(32)
36 
37  assert str(instance1) == "ExampleMandA[value=320]"
38  assert str(instance2) == "ExampleMandA[value=32]"
39  assert str(instance1.self1()) == "ExampleMandA[value=320]"
40  assert str(instance1.self2()) == "ExampleMandA[value=320]"
41  assert str(instance1.self3()) == "ExampleMandA[value=320]"
42  assert str(instance1.self4()) == "ExampleMandA[value=320]"
43  assert str(instance1.self5()) == "ExampleMandA[value=320]"
44 
45  assert instance1.internal1() == 320
46  assert instance1.internal2() == 320
47  assert instance1.internal3() == 320
48  assert instance1.internal4() == 320
49  assert instance1.internal5() == 320
50 
51  assert instance1.overloaded() == "()"
52  assert instance1.overloaded(0) == "(int)"
53  assert instance1.overloaded(1, 1.0) == "(int, float)"
54  assert instance1.overloaded(2.0, 2) == "(float, int)"
55  assert instance1.overloaded(3, 3) == "(int, int)"
56  assert instance1.overloaded(4.0, 4.0) == "(float, float)"
57  assert instance1.overloaded_const(-3) == "(int) const"
58  assert instance1.overloaded_const(5, 5.0) == "(int, float) const"
59  assert instance1.overloaded_const(6.0, 6) == "(float, int) const"
60  assert instance1.overloaded_const(7, 7) == "(int, int) const"
61  assert instance1.overloaded_const(8.0, 8.0) == "(float, float) const"
62  assert instance1.overloaded_float(1, 1) == "(float, float)"
63  assert instance1.overloaded_float(1, 1.0) == "(float, float)"
64  assert instance1.overloaded_float(1.0, 1) == "(float, float)"
65  assert instance1.overloaded_float(1.0, 1.0) == "(float, float)"
66 
67  assert instance1.value == 320
68  instance1.value = 100
69  assert str(instance1) == "ExampleMandA[value=100]"
70 
71  cstats = ConstructorStats.get(m.ExampleMandA)
72  assert cstats.alive() == 2
73  del instance1, instance2
74  assert cstats.alive() == 0
75  assert cstats.values() == ["32"]
76  assert cstats.default_constructions == 1
77  assert cstats.copy_constructions == 2
78  assert cstats.move_constructions >= 2
79  assert cstats.copy_assignments == 0
80  assert cstats.move_assignments == 0
81 
82 
84  """Issue #443: calling copied methods fails in Python 3"""
85 
86  m.ExampleMandA.add2c = m.ExampleMandA.add2
87  m.ExampleMandA.add2d = m.ExampleMandA.add2b
88  a = m.ExampleMandA(123)
89  assert a.value == 123
90  a.add2(m.ExampleMandA(-100))
91  assert a.value == 23
92  a.add2b(m.ExampleMandA(20))
93  assert a.value == 43
94  a.add2c(m.ExampleMandA(6))
95  assert a.value == 49
96  a.add2d(m.ExampleMandA(-7))
97  assert a.value == 42
98 
99 
101  instance = m.TestProperties()
102 
103  assert instance.def_readonly == 1
104  with pytest.raises(AttributeError):
105  instance.def_readonly = 2
106 
107  instance.def_readwrite = 2
108  assert instance.def_readwrite == 2
109 
110  assert instance.def_property_readonly == 2
111  with pytest.raises(AttributeError):
112  instance.def_property_readonly = 3
113 
114  instance.def_property = 3
115  assert instance.def_property == 3
116 
117  with pytest.raises(AttributeError) as excinfo:
118  dummy = instance.def_property_writeonly # unused var
119  assert NO_GETTER_MSG in str(excinfo.value)
120 
121  instance.def_property_writeonly = 4
122  assert instance.def_property_readonly == 4
123 
124  with pytest.raises(AttributeError) as excinfo:
125  dummy = instance.def_property_impossible # noqa: F841 unused var
126  assert NO_GETTER_MSG in str(excinfo.value)
127 
128  with pytest.raises(AttributeError) as excinfo:
129  instance.def_property_impossible = 5
130  assert NO_SETTER_MSG in str(excinfo.value)
131 
132 
134  assert m.TestProperties.def_readonly_static == 1
135  with pytest.raises(AttributeError) as excinfo:
136  m.TestProperties.def_readonly_static = 2
137  assert NO_SETTER_MSG in str(excinfo.value)
138 
139  m.TestProperties.def_readwrite_static = 2
140  assert m.TestProperties.def_readwrite_static == 2
141 
142  with pytest.raises(AttributeError) as excinfo:
143  dummy = m.TestProperties.def_writeonly_static # unused var
144  assert NO_GETTER_MSG in str(excinfo.value)
145 
146  m.TestProperties.def_writeonly_static = 3
147  assert m.TestProperties.def_readonly_static == 3
148 
149  assert m.TestProperties.def_property_readonly_static == 3
150  with pytest.raises(AttributeError) as excinfo:
151  m.TestProperties.def_property_readonly_static = 99
152  assert NO_SETTER_MSG in str(excinfo.value)
153 
154  m.TestProperties.def_property_static = 4
155  assert m.TestProperties.def_property_static == 4
156 
157  with pytest.raises(AttributeError) as excinfo:
158  dummy = m.TestProperties.def_property_writeonly_static
159  assert NO_GETTER_MSG in str(excinfo.value)
160 
161  m.TestProperties.def_property_writeonly_static = 5
162  assert m.TestProperties.def_property_static == 5
163 
164  # Static property read and write via instance
165  instance = m.TestProperties()
166 
167  m.TestProperties.def_readwrite_static = 0
168  assert m.TestProperties.def_readwrite_static == 0
169  assert instance.def_readwrite_static == 0
170 
171  instance.def_readwrite_static = 2
172  assert m.TestProperties.def_readwrite_static == 2
173  assert instance.def_readwrite_static == 2
174 
175  with pytest.raises(AttributeError) as excinfo:
176  dummy = instance.def_property_writeonly_static # noqa: F841 unused var
177  assert NO_GETTER_MSG in str(excinfo.value)
178 
179  instance.def_property_writeonly_static = 4
180  assert instance.def_property_static == 4
181 
182  # It should be possible to override properties in derived classes
183  assert m.TestPropertiesOverride().def_readonly == 99
184  assert m.TestPropertiesOverride.def_readonly_static == 99
185 
186  # Only static attributes can be deleted
187  del m.TestPropertiesOverride.def_readonly_static
188  assert hasattr(m.TestPropertiesOverride, "def_readonly_static")
189  assert (
190  m.TestPropertiesOverride.def_readonly_static
191  is m.TestProperties.def_readonly_static
192  )
193  assert "def_readonly_static" not in m.TestPropertiesOverride.__dict__
194  properties_override = m.TestPropertiesOverride()
195  with pytest.raises(AttributeError) as excinfo:
196  del properties_override.def_readonly
197  assert NO_DELETER_MSG in str(excinfo.value)
198 
199 
201  """Static property getter and setters expect the type object as the their only argument"""
202 
203  instance = m.TestProperties()
204  assert m.TestProperties.static_cls is m.TestProperties
205  assert instance.static_cls is m.TestProperties
206 
207  def check_self(self):
208  assert self is m.TestProperties
209 
210  m.TestProperties.static_cls = check_self
211  instance.static_cls = check_self
212 
213 
215  """Overriding pybind11's default metaclass changes the behavior of `static_property`"""
216 
217  assert type(m.ExampleMandA).__name__ == "pybind11_type"
218  assert type(m.MetaclassOverride).__name__ == "type"
219 
220  assert m.MetaclassOverride.readonly == 1
221  assert (
222  type(m.MetaclassOverride.__dict__["readonly"]).__name__
223  == "pybind11_static_property"
224  )
225 
226  # Regular `type` replaces the property instead of calling `__set__()`
227  m.MetaclassOverride.readonly = 2
228  assert m.MetaclassOverride.readonly == 2
229  assert isinstance(m.MetaclassOverride.__dict__["readonly"], int)
230 
231 
233  from pybind11_tests import detailed_error_messages_enabled
234 
235  with pytest.raises(RuntimeError) as excinfo:
236  m.ExampleMandA.add_mixed_overloads1()
237  assert (
238  str(excinfo.value)
239  == "overloading a method with both static and instance methods is not supported; "
240  + (
241  "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more details"
242  if not detailed_error_messages_enabled
243  else "error while attempting to bind static method ExampleMandA.overload_mixed1"
244  "(arg0: float) -> str"
245  )
246  )
247 
248  with pytest.raises(RuntimeError) as excinfo:
249  m.ExampleMandA.add_mixed_overloads2()
250  assert (
251  str(excinfo.value)
252  == "overloading a method with both static and instance methods is not supported; "
253  + (
254  "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more details"
255  if not detailed_error_messages_enabled
256  else "error while attempting to bind instance method ExampleMandA.overload_mixed2"
257  "(self: pybind11_tests.methods_and_attributes.ExampleMandA, arg0: int, arg1: int)"
258  " -> str"
259  )
260  )
261 
262 
263 @pytest.mark.parametrize("access", ["ro", "rw", "static_ro", "static_rw"])
265  obj = m.TestPropRVP() if not access.startswith("static") else m.TestPropRVP
266 
267  ref = getattr(obj, access + "_ref")
268  assert ref.value == 1
269  ref.value = 2
270  assert getattr(obj, access + "_ref").value == 2
271  ref.value = 1 # restore original value for static properties
272 
273  copy = getattr(obj, access + "_copy")
274  assert copy.value == 1
275  copy.value = 2
276  assert getattr(obj, access + "_copy").value == 1
277 
278  copy = getattr(obj, access + "_func")
279  assert copy.value == 1
280  copy.value = 2
281  assert getattr(obj, access + "_func").value == 1
282 
283 
285  """When returning an rvalue, the return value policy is automatically changed from
286  `reference(_internal)` to `move`. The following would not work otherwise."""
287 
288  instance = m.TestPropRVP()
289  o = instance.rvalue
290  assert o.value == 1
291 
292  os = m.TestPropRVP.static_rvalue
293  assert os.value == 1
294 
295 
296 # https://foss.heptapod.net/pypy/pypy/-/issues/2447
297 @pytest.mark.xfail("env.PYPY")
299  instance = m.DynamicClass()
300  assert not hasattr(instance, "foo")
301  assert "foo" not in dir(instance)
302 
303  # Dynamically add attribute
304  instance.foo = 42
305  assert hasattr(instance, "foo")
306  assert instance.foo == 42
307  assert "foo" in dir(instance)
308 
309  # __dict__ should be accessible and replaceable
310  assert "foo" in instance.__dict__
311  instance.__dict__ = {"bar": True}
312  assert not hasattr(instance, "foo")
313  assert hasattr(instance, "bar")
314 
315  with pytest.raises(TypeError) as excinfo:
316  instance.__dict__ = []
317  assert str(excinfo.value) == "__dict__ must be set to a dictionary, not a 'list'"
318 
319  cstats = ConstructorStats.get(m.DynamicClass)
320  assert cstats.alive() == 1
321  del instance
322  assert cstats.alive() == 0
323 
324  # Derived classes should work as well
325  class PythonDerivedDynamicClass(m.DynamicClass):
326  pass
327 
328  for cls in m.CppDerivedDynamicClass, PythonDerivedDynamicClass:
329  derived = cls()
330  derived.foobar = 100
331  assert derived.foobar == 100
332 
333  assert cstats.alive() == 1
334  del derived
335  assert cstats.alive() == 0
336 
337 
338 # https://foss.heptapod.net/pypy/pypy/-/issues/2447
339 @pytest.mark.xfail("env.PYPY")
341  # One object references itself
342  instance = m.DynamicClass()
343  instance.circular_reference = instance
344 
345  cstats = ConstructorStats.get(m.DynamicClass)
346  assert cstats.alive() == 1
347  del instance
348  assert cstats.alive() == 0
349 
350  # Two object reference each other
351  i1 = m.DynamicClass()
352  i2 = m.DynamicClass()
353  i1.cycle = i2
354  i2.cycle = i1
355 
356  assert cstats.alive() == 2
357  del i1, i2
358  assert cstats.alive() == 0
359 
360 
362  from pybind11_tests import detailed_error_messages_enabled
363 
364  with pytest.raises(RuntimeError) as excinfo:
365  m.bad_arg_def_named()
366  assert msg(excinfo.value) == (
367  "arg(): could not convert default argument 'a: UnregisteredType' in function "
368  "'should_fail' into a Python object (type not registered yet?)"
369  if detailed_error_messages_enabled
370  else "arg(): could not convert default argument into a Python object (type not registered "
371  "yet?). #define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more information."
372  )
373 
374  with pytest.raises(RuntimeError) as excinfo:
375  m.bad_arg_def_unnamed()
376  assert msg(excinfo.value) == (
377  "arg(): could not convert default argument 'UnregisteredType' in function "
378  "'should_fail' into a Python object (type not registered yet?)"
379  if detailed_error_messages_enabled
380  else "arg(): could not convert default argument into a Python object (type not registered "
381  "yet?). #define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more information."
382  )
383 
384 
386  a = m.NoneTester()
387  assert m.no_none1(a) == 42
388  assert m.no_none2(a) == 42
389  assert m.no_none3(a) == 42
390  assert m.no_none4(a) == 42
391  assert m.no_none5(a) == 42
392  assert m.ok_none1(a) == 42
393  assert m.ok_none2(a) == 42
394  assert m.ok_none3(a) == 42
395  assert m.ok_none4(a) == 42
396  assert m.ok_none5(a) == 42
397 
398  with pytest.raises(TypeError) as excinfo:
399  m.no_none1(None)
400  assert "incompatible function arguments" in str(excinfo.value)
401  with pytest.raises(TypeError) as excinfo:
402  m.no_none2(None)
403  assert "incompatible function arguments" in str(excinfo.value)
404  with pytest.raises(TypeError) as excinfo:
405  m.no_none3(None)
406  assert "incompatible function arguments" in str(excinfo.value)
407  with pytest.raises(TypeError) as excinfo:
408  m.no_none4(None)
409  assert "incompatible function arguments" in str(excinfo.value)
410  with pytest.raises(TypeError) as excinfo:
411  m.no_none5(None)
412  assert "incompatible function arguments" in str(excinfo.value)
413 
414  # The first one still raises because you can't pass None as a lvalue reference arg:
415  with pytest.raises(TypeError) as excinfo:
416  assert m.ok_none1(None) == -1
417  assert (
418  msg(excinfo.value)
419  == """
420  ok_none1(): incompatible function arguments. The following argument types are supported:
421  1. (arg0: m.methods_and_attributes.NoneTester) -> int
422 
423  Invoked with: None
424  """
425  )
426 
427  # The rest take the argument as pointer or holder, and accept None:
428  assert m.ok_none2(None) == -1
429  assert m.ok_none3(None) == -1
430  assert m.ok_none4(None) == -1
431  assert m.ok_none5(None) == -1
432 
433  with pytest.raises(TypeError) as excinfo:
434  m.no_none_kwarg(None)
435  assert "incompatible function arguments" in str(excinfo.value)
436  with pytest.raises(TypeError) as excinfo:
437  m.no_none_kwarg(a=None)
438  assert "incompatible function arguments" in str(excinfo.value)
439  with pytest.raises(TypeError) as excinfo:
440  m.no_none_kwarg_kw_only(None)
441  assert "incompatible function arguments" in str(excinfo.value)
442  with pytest.raises(TypeError) as excinfo:
443  m.no_none_kwarg_kw_only(a=None)
444  assert "incompatible function arguments" in str(excinfo.value)
445 
446 
448  """#2778: implicit casting from None to object (not pointer)"""
449  a = m.NoneCastTester()
450  assert m.ok_obj_or_none(a) == -1
451  a = m.NoneCastTester(4)
452  assert m.ok_obj_or_none(a) == 4
453  a = m.NoneCastTester(None)
454  assert m.ok_obj_or_none(a) == -1
455  assert m.ok_obj_or_none(None) == -1
456 
457 
458 def test_str_issue(msg):
459  """#283: __str__ called on uninitialized instance when constructor arguments invalid"""
460 
461  assert str(m.StrIssue(3)) == "StrIssue[3]"
462 
463  with pytest.raises(TypeError) as excinfo:
464  str(m.StrIssue("no", "such", "constructor"))
465  assert (
466  msg(excinfo.value)
467  == """
468  __init__(): incompatible constructor arguments. The following argument types are supported:
469  1. m.methods_and_attributes.StrIssue(arg0: int)
470  2. m.methods_and_attributes.StrIssue()
471 
472  Invoked with: 'no', 'such', 'constructor'
473  """
474  )
475 
476 
478  a = m.RegisteredDerived()
479  a.do_nothing()
480  assert a.rw_value == 42
481  assert a.ro_value == 1.25
482  a.rw_value += 5
483  assert a.sum() == 48.25
484  a.increase_value()
485  assert a.rw_value == 48
486  assert a.ro_value == 1.5
487  assert a.sum() == 49.5
488  assert a.rw_value_prop == 48
489  a.rw_value_prop += 1
490  assert a.rw_value_prop == 49
491  a.increase_value()
492  assert a.ro_value_prop == 1.75
493 
494 
496  """Tests that explicit lvalue ref-qualified methods can be called just like their
497  non ref-qualified counterparts."""
498 
499  r = m.RefQualified()
500  assert r.value == 0
501  r.refQualified(17)
502  assert r.value == 17
503  assert r.constRefQualified(23) == 40
504 
505 
507  "Check to see if the normal overload order (first defined) and prepend overload order works"
508  assert m.overload_order("string") == 1
509  assert m.overload_order(0) == 4
510 
511  assert "1. overload_order(arg0: int) -> int" in m.overload_order.__doc__
512  assert "2. overload_order(arg0: str) -> int" in m.overload_order.__doc__
513  assert "3. overload_order(arg0: str) -> int" in m.overload_order.__doc__
514  assert "4. overload_order(arg0: int) -> int" in m.overload_order.__doc__
515 
516  with pytest.raises(TypeError) as err:
517  m.overload_order(1.1)
518 
519  assert "1. (arg0: int) -> int" in str(err.value)
520  assert "2. (arg0: str) -> int" in str(err.value)
521  assert "3. (arg0: str) -> int" in str(err.value)
522  assert "4. (arg0: int) -> int" in str(err.value)
523 
524 
526  r = m.RValueRefParam()
527  assert r.func1("123") == 3
528  assert r.func2("1234") == 4
529  assert r.func3("12345") == 5
530  assert r.func4("123456") == 6
531 
532 
534  fld = m.exercise_is_setter.Field()
535  assert fld.int_value == -99
536  setter_return = fld.int_value = 100
537  assert isinstance(setter_return, int)
538  assert setter_return == 100
539  assert fld.int_value == 100
test_methods_and_attributes.test_ref_qualified
def test_ref_qualified()
Definition: test_methods_and_attributes.py:495
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:870
test_methods_and_attributes.test_copy_method
def test_copy_method()
Definition: test_methods_and_attributes.py:83
type
Definition: pytypes.h:1525
getattr
object getattr(handle obj, handle name)
Definition: pytypes.h:890
test_methods_and_attributes.test_casts_none
def test_casts_none()
Definition: test_methods_and_attributes.py:447
test_methods_and_attributes.test_properties
def test_properties()
Definition: test_methods_and_attributes.py:100
test_methods_and_attributes.test_no_mixed_overloads
def test_no_mixed_overloads()
Definition: test_methods_and_attributes.py:232
test_methods_and_attributes.test_unregistered_base_implementations
def test_unregistered_base_implementations()
Definition: test_methods_and_attributes.py:477
test_methods_and_attributes.test_bad_arg_default
def test_bad_arg_default(msg)
Definition: test_methods_and_attributes.py:361
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:842
test_methods_and_attributes.test_static_properties
def test_static_properties()
Definition: test_methods_and_attributes.py:133
test_methods_and_attributes.test_cyclic_gc
def test_cyclic_gc()
Definition: test_methods_and_attributes.py:340
test_methods_and_attributes.test_property_return_value_policies
def test_property_return_value_policies(access)
Definition: test_methods_and_attributes.py:264
str
Definition: pytypes.h:1558
test_methods_and_attributes.test_static_cls
def test_static_cls()
Definition: test_methods_and_attributes.py:200
test_methods_and_attributes.test_property_rvalue_policy
def test_property_rvalue_policy()
Definition: test_methods_and_attributes.py:284
test_methods_and_attributes.test_metaclass_override
def test_metaclass_override()
Definition: test_methods_and_attributes.py:214
ConstructorStats::get
static ConstructorStats & get(std::type_index type)
Definition: constructor_stats.h:163
test_methods_and_attributes.test_overload_ordering
def test_overload_ordering()
Definition: test_methods_and_attributes.py:506
test_methods_and_attributes.test_str_issue
def test_str_issue(msg)
Definition: test_methods_and_attributes.py:458
test_methods_and_attributes.test_methods_and_attributes
def test_methods_and_attributes()
Definition: test_methods_and_attributes.py:22
test_methods_and_attributes.test_is_setter
def test_is_setter()
Definition: test_methods_and_attributes.py:533
test_methods_and_attributes.test_accepts_none
def test_accepts_none(msg)
Definition: test_methods_and_attributes.py:385
test_methods_and_attributes.test_dynamic_attributes
def test_dynamic_attributes()
Definition: test_methods_and_attributes.py:298
test_methods_and_attributes.test_rvalue_ref_param
def test_rvalue_ref_param()
Definition: test_methods_and_attributes.py:525
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:6


gtsam
Author(s):
autogenerated on Thu Jul 4 2024 03:06:01