test_methods_and_attributes.py revision 12391:ceeca8b41e4b
1import pytest
2from pybind11_tests import methods_and_attributes as m
3from pybind11_tests import ConstructorStats
4
5
6def test_methods_and_attributes():
7    instance1 = m.ExampleMandA()
8    instance2 = m.ExampleMandA(32)
9
10    instance1.add1(instance2)
11    instance1.add2(instance2)
12    instance1.add3(instance2)
13    instance1.add4(instance2)
14    instance1.add5(instance2)
15    instance1.add6(32)
16    instance1.add7(32)
17    instance1.add8(32)
18    instance1.add9(32)
19    instance1.add10(32)
20
21    assert str(instance1) == "ExampleMandA[value=320]"
22    assert str(instance2) == "ExampleMandA[value=32]"
23    assert str(instance1.self1()) == "ExampleMandA[value=320]"
24    assert str(instance1.self2()) == "ExampleMandA[value=320]"
25    assert str(instance1.self3()) == "ExampleMandA[value=320]"
26    assert str(instance1.self4()) == "ExampleMandA[value=320]"
27    assert str(instance1.self5()) == "ExampleMandA[value=320]"
28
29    assert instance1.internal1() == 320
30    assert instance1.internal2() == 320
31    assert instance1.internal3() == 320
32    assert instance1.internal4() == 320
33    assert instance1.internal5() == 320
34
35    assert instance1.overloaded() == "()"
36    assert instance1.overloaded(0) == "(int)"
37    assert instance1.overloaded(1, 1.0) == "(int, float)"
38    assert instance1.overloaded(2.0, 2) == "(float, int)"
39    assert instance1.overloaded(3,   3) == "(int, int)"
40    assert instance1.overloaded(4., 4.) == "(float, float)"
41    assert instance1.overloaded_const(-3) == "(int) const"
42    assert instance1.overloaded_const(5, 5.0) == "(int, float) const"
43    assert instance1.overloaded_const(6.0, 6) == "(float, int) const"
44    assert instance1.overloaded_const(7,   7) == "(int, int) const"
45    assert instance1.overloaded_const(8., 8.) == "(float, float) const"
46    assert instance1.overloaded_float(1, 1) == "(float, float)"
47    assert instance1.overloaded_float(1, 1.) == "(float, float)"
48    assert instance1.overloaded_float(1., 1) == "(float, float)"
49    assert instance1.overloaded_float(1., 1.) == "(float, float)"
50
51    assert instance1.value == 320
52    instance1.value = 100
53    assert str(instance1) == "ExampleMandA[value=100]"
54
55    cstats = ConstructorStats.get(m.ExampleMandA)
56    assert cstats.alive() == 2
57    del instance1, instance2
58    assert cstats.alive() == 0
59    assert cstats.values() == ["32"]
60    assert cstats.default_constructions == 1
61    assert cstats.copy_constructions == 3
62    assert cstats.move_constructions >= 1
63    assert cstats.copy_assignments == 0
64    assert cstats.move_assignments == 0
65
66
67def test_copy_method():
68    """Issue #443: calling copied methods fails in Python 3"""
69
70    m.ExampleMandA.add2c = m.ExampleMandA.add2
71    m.ExampleMandA.add2d = m.ExampleMandA.add2b
72    a = m.ExampleMandA(123)
73    assert a.value == 123
74    a.add2(m.ExampleMandA(-100))
75    assert a.value == 23
76    a.add2b(m.ExampleMandA(20))
77    assert a.value == 43
78    a.add2c(m.ExampleMandA(6))
79    assert a.value == 49
80    a.add2d(m.ExampleMandA(-7))
81    assert a.value == 42
82
83
84def test_properties():
85    instance = m.TestProperties()
86
87    assert instance.def_readonly == 1
88    with pytest.raises(AttributeError):
89        instance.def_readonly = 2
90
91    instance.def_readwrite = 2
92    assert instance.def_readwrite == 2
93
94    assert instance.def_property_readonly == 2
95    with pytest.raises(AttributeError):
96        instance.def_property_readonly = 3
97
98    instance.def_property = 3
99    assert instance.def_property == 3
100
101
102def test_static_properties():
103    assert m.TestProperties.def_readonly_static == 1
104    with pytest.raises(AttributeError) as excinfo:
105        m.TestProperties.def_readonly_static = 2
106    assert "can't set attribute" in str(excinfo)
107
108    m.TestProperties.def_readwrite_static = 2
109    assert m.TestProperties.def_readwrite_static == 2
110
111    assert m.TestProperties.def_property_readonly_static == 2
112    with pytest.raises(AttributeError) as excinfo:
113        m.TestProperties.def_property_readonly_static = 3
114    assert "can't set attribute" in str(excinfo)
115
116    m.TestProperties.def_property_static = 3
117    assert m.TestProperties.def_property_static == 3
118
119    # Static property read and write via instance
120    instance = m.TestProperties()
121
122    m.TestProperties.def_readwrite_static = 0
123    assert m.TestProperties.def_readwrite_static == 0
124    assert instance.def_readwrite_static == 0
125
126    instance.def_readwrite_static = 2
127    assert m.TestProperties.def_readwrite_static == 2
128    assert instance.def_readwrite_static == 2
129
130    # It should be possible to override properties in derived classes
131    assert m.TestPropertiesOverride().def_readonly == 99
132    assert m.TestPropertiesOverride.def_readonly_static == 99
133
134
135def test_static_cls():
136    """Static property getter and setters expect the type object as the their only argument"""
137
138    instance = m.TestProperties()
139    assert m.TestProperties.static_cls is m.TestProperties
140    assert instance.static_cls is m.TestProperties
141
142    def check_self(self):
143        assert self is m.TestProperties
144
145    m.TestProperties.static_cls = check_self
146    instance.static_cls = check_self
147
148
149def test_metaclass_override():
150    """Overriding pybind11's default metaclass changes the behavior of `static_property`"""
151
152    assert type(m.ExampleMandA).__name__ == "pybind11_type"
153    assert type(m.MetaclassOverride).__name__ == "type"
154
155    assert m.MetaclassOverride.readonly == 1
156    assert type(m.MetaclassOverride.__dict__["readonly"]).__name__ == "pybind11_static_property"
157
158    # Regular `type` replaces the property instead of calling `__set__()`
159    m.MetaclassOverride.readonly = 2
160    assert m.MetaclassOverride.readonly == 2
161    assert isinstance(m.MetaclassOverride.__dict__["readonly"], int)
162
163
164def test_no_mixed_overloads():
165    from pybind11_tests import debug_enabled
166
167    with pytest.raises(RuntimeError) as excinfo:
168        m.ExampleMandA.add_mixed_overloads1()
169    assert (str(excinfo.value) ==
170            "overloading a method with both static and instance methods is not supported; " +
171            ("compile in debug mode for more details" if not debug_enabled else
172             "error while attempting to bind static method ExampleMandA.overload_mixed1"
173             "(arg0: float) -> str")
174            )
175
176    with pytest.raises(RuntimeError) as excinfo:
177        m.ExampleMandA.add_mixed_overloads2()
178    assert (str(excinfo.value) ==
179            "overloading a method with both static and instance methods is not supported; " +
180            ("compile in debug mode for more details" if not debug_enabled else
181             "error while attempting to bind instance method ExampleMandA.overload_mixed2"
182             "(self: pybind11_tests.methods_and_attributes.ExampleMandA, arg0: int, arg1: int)"
183             " -> str")
184            )
185
186
187@pytest.mark.parametrize("access", ["ro", "rw", "static_ro", "static_rw"])
188def test_property_return_value_policies(access):
189    if not access.startswith("static"):
190        obj = m.TestPropRVP()
191    else:
192        obj = m.TestPropRVP
193
194    ref = getattr(obj, access + "_ref")
195    assert ref.value == 1
196    ref.value = 2
197    assert getattr(obj, access + "_ref").value == 2
198    ref.value = 1  # restore original value for static properties
199
200    copy = getattr(obj, access + "_copy")
201    assert copy.value == 1
202    copy.value = 2
203    assert getattr(obj, access + "_copy").value == 1
204
205    copy = getattr(obj, access + "_func")
206    assert copy.value == 1
207    copy.value = 2
208    assert getattr(obj, access + "_func").value == 1
209
210
211def test_property_rvalue_policy():
212    """When returning an rvalue, the return value policy is automatically changed from
213    `reference(_internal)` to `move`. The following would not work otherwise."""
214
215    instance = m.TestPropRVP()
216    o = instance.rvalue
217    assert o.value == 1
218
219    os = m.TestPropRVP.static_rvalue
220    assert os.value == 1
221
222
223# https://bitbucket.org/pypy/pypy/issues/2447
224@pytest.unsupported_on_pypy
225def test_dynamic_attributes():
226    instance = m.DynamicClass()
227    assert not hasattr(instance, "foo")
228    assert "foo" not in dir(instance)
229
230    # Dynamically add attribute
231    instance.foo = 42
232    assert hasattr(instance, "foo")
233    assert instance.foo == 42
234    assert "foo" in dir(instance)
235
236    # __dict__ should be accessible and replaceable
237    assert "foo" in instance.__dict__
238    instance.__dict__ = {"bar": True}
239    assert not hasattr(instance, "foo")
240    assert hasattr(instance, "bar")
241
242    with pytest.raises(TypeError) as excinfo:
243        instance.__dict__ = []
244    assert str(excinfo.value) == "__dict__ must be set to a dictionary, not a 'list'"
245
246    cstats = ConstructorStats.get(m.DynamicClass)
247    assert cstats.alive() == 1
248    del instance
249    assert cstats.alive() == 0
250
251    # Derived classes should work as well
252    class PythonDerivedDynamicClass(m.DynamicClass):
253        pass
254
255    for cls in m.CppDerivedDynamicClass, PythonDerivedDynamicClass:
256        derived = cls()
257        derived.foobar = 100
258        assert derived.foobar == 100
259
260        assert cstats.alive() == 1
261        del derived
262        assert cstats.alive() == 0
263
264
265# https://bitbucket.org/pypy/pypy/issues/2447
266@pytest.unsupported_on_pypy
267def test_cyclic_gc():
268    # One object references itself
269    instance = m.DynamicClass()
270    instance.circular_reference = instance
271
272    cstats = ConstructorStats.get(m.DynamicClass)
273    assert cstats.alive() == 1
274    del instance
275    assert cstats.alive() == 0
276
277    # Two object reference each other
278    i1 = m.DynamicClass()
279    i2 = m.DynamicClass()
280    i1.cycle = i2
281    i2.cycle = i1
282
283    assert cstats.alive() == 2
284    del i1, i2
285    assert cstats.alive() == 0
286
287
288def test_noconvert_args(msg):
289    a = m.ArgInspector()
290    assert msg(a.f("hi")) == """
291        loading ArgInspector1 argument WITH conversion allowed.  Argument value = hi
292    """
293    assert msg(a.g("this is a", "this is b")) == """
294        loading ArgInspector1 argument WITHOUT conversion allowed.  Argument value = this is a
295        loading ArgInspector1 argument WITH conversion allowed.  Argument value = this is b
296        13
297        loading ArgInspector2 argument WITH conversion allowed.  Argument value = (default arg inspector 2)
298    """  # noqa: E501 line too long
299    assert msg(a.g("this is a", "this is b", 42)) == """
300        loading ArgInspector1 argument WITHOUT conversion allowed.  Argument value = this is a
301        loading ArgInspector1 argument WITH conversion allowed.  Argument value = this is b
302        42
303        loading ArgInspector2 argument WITH conversion allowed.  Argument value = (default arg inspector 2)
304    """  # noqa: E501 line too long
305    assert msg(a.g("this is a", "this is b", 42, "this is d")) == """
306        loading ArgInspector1 argument WITHOUT conversion allowed.  Argument value = this is a
307        loading ArgInspector1 argument WITH conversion allowed.  Argument value = this is b
308        42
309        loading ArgInspector2 argument WITH conversion allowed.  Argument value = this is d
310    """
311    assert (a.h("arg 1") ==
312            "loading ArgInspector2 argument WITHOUT conversion allowed.  Argument value = arg 1")
313    assert msg(m.arg_inspect_func("A1", "A2")) == """
314        loading ArgInspector2 argument WITH conversion allowed.  Argument value = A1
315        loading ArgInspector1 argument WITHOUT conversion allowed.  Argument value = A2
316    """
317
318    assert m.floats_preferred(4) == 2.0
319    assert m.floats_only(4.0) == 2.0
320    with pytest.raises(TypeError) as excinfo:
321        m.floats_only(4)
322    assert msg(excinfo.value) == """
323        floats_only(): incompatible function arguments. The following argument types are supported:
324            1. (f: float) -> float
325
326        Invoked with: 4
327    """
328
329    assert m.ints_preferred(4) == 2
330    assert m.ints_preferred(True) == 0
331    with pytest.raises(TypeError) as excinfo:
332        m.ints_preferred(4.0)
333    assert msg(excinfo.value) == """
334        ints_preferred(): incompatible function arguments. The following argument types are supported:
335            1. (i: int) -> int
336
337        Invoked with: 4.0
338    """  # noqa: E501 line too long
339
340    assert m.ints_only(4) == 2
341    with pytest.raises(TypeError) as excinfo:
342        m.ints_only(4.0)
343    assert msg(excinfo.value) == """
344        ints_only(): incompatible function arguments. The following argument types are supported:
345            1. (i: int) -> int
346
347        Invoked with: 4.0
348    """
349
350
351def test_bad_arg_default(msg):
352    from pybind11_tests import debug_enabled
353
354    with pytest.raises(RuntimeError) as excinfo:
355        m.bad_arg_def_named()
356    assert msg(excinfo.value) == (
357        "arg(): could not convert default argument 'a: UnregisteredType' in function "
358        "'should_fail' into a Python object (type not registered yet?)"
359        if debug_enabled else
360        "arg(): could not convert default argument into a Python object (type not registered "
361        "yet?). Compile in debug mode for more information."
362    )
363
364    with pytest.raises(RuntimeError) as excinfo:
365        m.bad_arg_def_unnamed()
366    assert msg(excinfo.value) == (
367        "arg(): could not convert default argument 'UnregisteredType' in function "
368        "'should_fail' into a Python object (type not registered yet?)"
369        if debug_enabled else
370        "arg(): could not convert default argument into a Python object (type not registered "
371        "yet?). Compile in debug mode for more information."
372    )
373
374
375def test_accepts_none(msg):
376    a = m.NoneTester()
377    assert m.no_none1(a) == 42
378    assert m.no_none2(a) == 42
379    assert m.no_none3(a) == 42
380    assert m.no_none4(a) == 42
381    assert m.no_none5(a) == 42
382    assert m.ok_none1(a) == 42
383    assert m.ok_none2(a) == 42
384    assert m.ok_none3(a) == 42
385    assert m.ok_none4(a) == 42
386    assert m.ok_none5(a) == 42
387
388    with pytest.raises(TypeError) as excinfo:
389        m.no_none1(None)
390    assert "incompatible function arguments" in str(excinfo.value)
391    with pytest.raises(TypeError) as excinfo:
392        m.no_none2(None)
393    assert "incompatible function arguments" in str(excinfo.value)
394    with pytest.raises(TypeError) as excinfo:
395        m.no_none3(None)
396    assert "incompatible function arguments" in str(excinfo.value)
397    with pytest.raises(TypeError) as excinfo:
398        m.no_none4(None)
399    assert "incompatible function arguments" in str(excinfo.value)
400    with pytest.raises(TypeError) as excinfo:
401        m.no_none5(None)
402    assert "incompatible function arguments" in str(excinfo.value)
403
404    # The first one still raises because you can't pass None as a lvalue reference arg:
405    with pytest.raises(TypeError) as excinfo:
406        assert m.ok_none1(None) == -1
407    assert msg(excinfo.value) == """
408        ok_none1(): incompatible function arguments. The following argument types are supported:
409            1. (arg0: m.methods_and_attributes.NoneTester) -> int
410
411        Invoked with: None
412    """
413
414    # The rest take the argument as pointer or holder, and accept None:
415    assert m.ok_none2(None) == -1
416    assert m.ok_none3(None) == -1
417    assert m.ok_none4(None) == -1
418    assert m.ok_none5(None) == -1
419
420
421def test_str_issue(msg):
422    """#283: __str__ called on uninitialized instance when constructor arguments invalid"""
423
424    assert str(m.StrIssue(3)) == "StrIssue[3]"
425
426    with pytest.raises(TypeError) as excinfo:
427        str(m.StrIssue("no", "such", "constructor"))
428    assert msg(excinfo.value) == """
429        __init__(): incompatible constructor arguments. The following argument types are supported:
430            1. m.methods_and_attributes.StrIssue(arg0: int)
431            2. m.methods_and_attributes.StrIssue()
432
433        Invoked with: 'no', 'such', 'constructor'
434    """
435
436
437def test_unregistered_base_implementations():
438    a = m.RegisteredDerived()
439    a.do_nothing()
440    assert a.rw_value == 42
441    assert a.ro_value == 1.25
442    a.rw_value += 5
443    assert a.sum() == 48.25
444    a.increase_value()
445    assert a.rw_value == 48
446    assert a.ro_value == 1.5
447    assert a.sum() == 49.5
448    assert a.rw_value_prop == 48
449    a.rw_value_prop += 1
450    assert a.rw_value_prop == 49
451    a.increase_value()
452    assert a.ro_value_prop == 1.75
453
454
455def test_custom_caster_destruction():
456    """Tests that returning a pointer to a type that gets converted with a custom type caster gets
457    destroyed when the function has py::return_value_policy::take_ownership policy applied."""
458
459    cstats = m.destruction_tester_cstats()
460    # This one *doesn't* have take_ownership: the pointer should be used but not destroyed:
461    z = m.custom_caster_no_destroy()
462    assert cstats.alive() == 1 and cstats.default_constructions == 1
463    assert z
464
465    # take_ownership applied: this constructs a new object, casts it, then destroys it:
466    z = m.custom_caster_destroy()
467    assert z
468    assert cstats.default_constructions == 2
469
470    # Same, but with a const pointer return (which should *not* inhibit destruction):
471    z = m.custom_caster_destroy_const()
472    assert z
473    assert cstats.default_constructions == 3
474
475    # Make sure we still only have the original object (from ..._no_destroy()) alive:
476    assert cstats.alive() == 1
477