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


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