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 (
187  hasattr(m.TestPropertiesOverride, "def_readonly_static")
188  and 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  if not access.startswith("static"):
260  obj = m.TestPropRVP()
261  else:
262  obj = m.TestPropRVP
263 
264  ref = getattr(obj, access + "_ref")
265  assert ref.value == 1
266  ref.value = 2
267  assert getattr(obj, access + "_ref").value == 2
268  ref.value = 1 # restore original value for static properties
269 
270  copy = getattr(obj, access + "_copy")
271  assert copy.value == 1
272  copy.value = 2
273  assert getattr(obj, access + "_copy").value == 1
274 
275  copy = getattr(obj, access + "_func")
276  assert copy.value == 1
277  copy.value = 2
278  assert getattr(obj, access + "_func").value == 1
279 
280 
282  """When returning an rvalue, the return value policy is automatically changed from
283  `reference(_internal)` to `move`. The following would not work otherwise."""
284 
285  instance = m.TestPropRVP()
286  o = instance.rvalue
287  assert o.value == 1
288 
289  os = m.TestPropRVP.static_rvalue
290  assert os.value == 1
291 
292 
293 # https://foss.heptapod.net/pypy/pypy/-/issues/2447
294 @pytest.mark.xfail("env.PYPY")
296  instance = m.DynamicClass()
297  assert not hasattr(instance, "foo")
298  assert "foo" not in dir(instance)
299 
300  # Dynamically add attribute
301  instance.foo = 42
302  assert hasattr(instance, "foo")
303  assert instance.foo == 42
304  assert "foo" in dir(instance)
305 
306  # __dict__ should be accessible and replaceable
307  assert "foo" in instance.__dict__
308  instance.__dict__ = {"bar": True}
309  assert not hasattr(instance, "foo")
310  assert hasattr(instance, "bar")
311 
312  with pytest.raises(TypeError) as excinfo:
313  instance.__dict__ = []
314  assert str(excinfo.value) == "__dict__ must be set to a dictionary, not a 'list'"
315 
316  cstats = ConstructorStats.get(m.DynamicClass)
317  assert cstats.alive() == 1
318  del instance
319  assert cstats.alive() == 0
320 
321  # Derived classes should work as well
322  class PythonDerivedDynamicClass(m.DynamicClass):
323  pass
324 
325  for cls in m.CppDerivedDynamicClass, PythonDerivedDynamicClass:
326  derived = cls()
327  derived.foobar = 100
328  assert derived.foobar == 100
329 
330  assert cstats.alive() == 1
331  del derived
332  assert cstats.alive() == 0
333 
334 
335 # https://foss.heptapod.net/pypy/pypy/-/issues/2447
336 @pytest.mark.xfail("env.PYPY")
338  # One object references itself
339  instance = m.DynamicClass()
340  instance.circular_reference = instance
341 
342  cstats = ConstructorStats.get(m.DynamicClass)
343  assert cstats.alive() == 1
344  del instance
345  assert cstats.alive() == 0
346 
347  # Two object reference each other
348  i1 = m.DynamicClass()
349  i2 = m.DynamicClass()
350  i1.cycle = i2
351  i2.cycle = i1
352 
353  assert cstats.alive() == 2
354  del i1, i2
355  assert cstats.alive() == 0
356 
357 
359  from pybind11_tests import detailed_error_messages_enabled
360 
361  with pytest.raises(RuntimeError) as excinfo:
362  m.bad_arg_def_named()
363  assert msg(excinfo.value) == (
364  "arg(): could not convert default argument 'a: UnregisteredType' in function "
365  "'should_fail' into a Python object (type not registered yet?)"
366  if detailed_error_messages_enabled
367  else "arg(): could not convert default argument into a Python object (type not registered "
368  "yet?). #define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more information."
369  )
370 
371  with pytest.raises(RuntimeError) as excinfo:
372  m.bad_arg_def_unnamed()
373  assert msg(excinfo.value) == (
374  "arg(): could not convert default argument 'UnregisteredType' in function "
375  "'should_fail' into a Python object (type not registered yet?)"
376  if detailed_error_messages_enabled
377  else "arg(): could not convert default argument into a Python object (type not registered "
378  "yet?). #define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more information."
379  )
380 
381 
383  a = m.NoneTester()
384  assert m.no_none1(a) == 42
385  assert m.no_none2(a) == 42
386  assert m.no_none3(a) == 42
387  assert m.no_none4(a) == 42
388  assert m.no_none5(a) == 42
389  assert m.ok_none1(a) == 42
390  assert m.ok_none2(a) == 42
391  assert m.ok_none3(a) == 42
392  assert m.ok_none4(a) == 42
393  assert m.ok_none5(a) == 42
394 
395  with pytest.raises(TypeError) as excinfo:
396  m.no_none1(None)
397  assert "incompatible function arguments" in str(excinfo.value)
398  with pytest.raises(TypeError) as excinfo:
399  m.no_none2(None)
400  assert "incompatible function arguments" in str(excinfo.value)
401  with pytest.raises(TypeError) as excinfo:
402  m.no_none3(None)
403  assert "incompatible function arguments" in str(excinfo.value)
404  with pytest.raises(TypeError) as excinfo:
405  m.no_none4(None)
406  assert "incompatible function arguments" in str(excinfo.value)
407  with pytest.raises(TypeError) as excinfo:
408  m.no_none5(None)
409  assert "incompatible function arguments" in str(excinfo.value)
410 
411  # The first one still raises because you can't pass None as a lvalue reference arg:
412  with pytest.raises(TypeError) as excinfo:
413  assert m.ok_none1(None) == -1
414  assert (
415  msg(excinfo.value)
416  == """
417  ok_none1(): incompatible function arguments. The following argument types are supported:
418  1. (arg0: m.methods_and_attributes.NoneTester) -> int
419 
420  Invoked with: None
421  """
422  )
423 
424  # The rest take the argument as pointer or holder, and accept None:
425  assert m.ok_none2(None) == -1
426  assert m.ok_none3(None) == -1
427  assert m.ok_none4(None) == -1
428  assert m.ok_none5(None) == -1
429 
430  with pytest.raises(TypeError) as excinfo:
431  m.no_none_kwarg(None)
432  assert "incompatible function arguments" in str(excinfo.value)
433  with pytest.raises(TypeError) as excinfo:
434  m.no_none_kwarg(a=None)
435  assert "incompatible function arguments" in str(excinfo.value)
436  with pytest.raises(TypeError) as excinfo:
437  m.no_none_kwarg_kw_only(None)
438  assert "incompatible function arguments" in str(excinfo.value)
439  with pytest.raises(TypeError) as excinfo:
440  m.no_none_kwarg_kw_only(a=None)
441  assert "incompatible function arguments" in str(excinfo.value)
442 
443 
445  """#2778: implicit casting from None to object (not pointer)"""
446  a = m.NoneCastTester()
447  assert m.ok_obj_or_none(a) == -1
448  a = m.NoneCastTester(4)
449  assert m.ok_obj_or_none(a) == 4
450  a = m.NoneCastTester(None)
451  assert m.ok_obj_or_none(a) == -1
452  assert m.ok_obj_or_none(None) == -1
453 
454 
455 def test_str_issue(msg):
456  """#283: __str__ called on uninitialized instance when constructor arguments invalid"""
457 
458  assert str(m.StrIssue(3)) == "StrIssue[3]"
459 
460  with pytest.raises(TypeError) as excinfo:
461  str(m.StrIssue("no", "such", "constructor"))
462  assert (
463  msg(excinfo.value)
464  == """
465  __init__(): incompatible constructor arguments. The following argument types are supported:
466  1. m.methods_and_attributes.StrIssue(arg0: int)
467  2. m.methods_and_attributes.StrIssue()
468 
469  Invoked with: 'no', 'such', 'constructor'
470  """
471  )
472 
473 
475  a = m.RegisteredDerived()
476  a.do_nothing()
477  assert a.rw_value == 42
478  assert a.ro_value == 1.25
479  a.rw_value += 5
480  assert a.sum() == 48.25
481  a.increase_value()
482  assert a.rw_value == 48
483  assert a.ro_value == 1.5
484  assert a.sum() == 49.5
485  assert a.rw_value_prop == 48
486  a.rw_value_prop += 1
487  assert a.rw_value_prop == 49
488  a.increase_value()
489  assert a.ro_value_prop == 1.75
490 
491 
493  """Tests that explicit lvalue ref-qualified methods can be called just like their
494  non ref-qualified counterparts."""
495 
496  r = m.RefQualified()
497  assert r.value == 0
498  r.refQualified(17)
499  assert r.value == 17
500  assert r.constRefQualified(23) == 40
501 
502 
504  "Check to see if the normal overload order (first defined) and prepend overload order works"
505  assert m.overload_order("string") == 1
506  assert m.overload_order(0) == 4
507 
508  assert "1. overload_order(arg0: int) -> int" in m.overload_order.__doc__
509  assert "2. overload_order(arg0: str) -> int" in m.overload_order.__doc__
510  assert "3. overload_order(arg0: str) -> int" in m.overload_order.__doc__
511  assert "4. overload_order(arg0: int) -> int" in m.overload_order.__doc__
512 
513  with pytest.raises(TypeError) as err:
514  m.overload_order(1.1)
515 
516  assert "1. (arg0: int) -> int" in str(err.value)
517  assert "2. (arg0: str) -> int" in str(err.value)
518  assert "3. (arg0: str) -> int" in str(err.value)
519  assert "4. (arg0: int) -> int" in str(err.value)
520 
521 
523  r = m.RValueRefParam()
524  assert r.func1("123") == 3
525  assert r.func2("1234") == 4
526  assert r.func3("12345") == 5
527  assert r.func4("123456") == 6
bool hasattr(handle obj, handle name)
Definition: pytypes.h:728
bool isinstance(handle obj)
Definition: pytypes.h:700
static ConstructorStats & get(std::type_index type)
Definition: pytypes.h:1403
object getattr(handle obj, handle name)
Definition: pytypes.h:748
Definition: pytypes.h:1370


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:37:46