test_class.py revision 12391:ceeca8b41e4b
1import pytest
2
3from pybind11_tests import class_ as m
4from pybind11_tests import UserType, ConstructorStats
5
6
7def test_repr():
8    # In Python 3.3+, repr() accesses __qualname__
9    assert "pybind11_type" in repr(type(UserType))
10    assert "UserType" in repr(UserType)
11
12
13def test_instance(msg):
14    with pytest.raises(TypeError) as excinfo:
15        m.NoConstructor()
16    assert msg(excinfo.value) == "m.class_.NoConstructor: No constructor defined!"
17
18    instance = m.NoConstructor.new_instance()
19
20    cstats = ConstructorStats.get(m.NoConstructor)
21    assert cstats.alive() == 1
22    del instance
23    assert cstats.alive() == 0
24
25
26def test_docstrings(doc):
27    assert doc(UserType) == "A `py::class_` type for testing"
28    assert UserType.__name__ == "UserType"
29    assert UserType.__module__ == "pybind11_tests"
30    assert UserType.get_value.__name__ == "get_value"
31    assert UserType.get_value.__module__ == "pybind11_tests"
32
33    assert doc(UserType.get_value) == """
34        get_value(self: m.UserType) -> int
35
36        Get value using a method
37    """
38    assert doc(UserType.value) == "Get/set value using a property"
39
40    assert doc(m.NoConstructor.new_instance) == """
41        new_instance() -> m.class_.NoConstructor
42
43        Return an instance
44    """
45
46
47def test_inheritance(msg):
48    roger = m.Rabbit('Rabbit')
49    assert roger.name() + " is a " + roger.species() == "Rabbit is a parrot"
50    assert m.pet_name_species(roger) == "Rabbit is a parrot"
51
52    polly = m.Pet('Polly', 'parrot')
53    assert polly.name() + " is a " + polly.species() == "Polly is a parrot"
54    assert m.pet_name_species(polly) == "Polly is a parrot"
55
56    molly = m.Dog('Molly')
57    assert molly.name() + " is a " + molly.species() == "Molly is a dog"
58    assert m.pet_name_species(molly) == "Molly is a dog"
59
60    fred = m.Hamster('Fred')
61    assert fred.name() + " is a " + fred.species() == "Fred is a rodent"
62
63    assert m.dog_bark(molly) == "Woof!"
64
65    with pytest.raises(TypeError) as excinfo:
66        m.dog_bark(polly)
67    assert msg(excinfo.value) == """
68        dog_bark(): incompatible function arguments. The following argument types are supported:
69            1. (arg0: m.class_.Dog) -> str
70
71        Invoked with: <m.class_.Pet object at 0>
72    """
73
74    with pytest.raises(TypeError) as excinfo:
75        m.Chimera("lion", "goat")
76    assert "No constructor defined!" in str(excinfo.value)
77
78
79def test_automatic_upcasting():
80    assert type(m.return_class_1()).__name__ == "DerivedClass1"
81    assert type(m.return_class_2()).__name__ == "DerivedClass2"
82    assert type(m.return_none()).__name__ == "NoneType"
83    # Repeat these a few times in a random order to ensure no invalid caching is applied
84    assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
85    assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
86    assert type(m.return_class_n(0)).__name__ == "BaseClass"
87    assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
88    assert type(m.return_class_n(2)).__name__ == "DerivedClass2"
89    assert type(m.return_class_n(0)).__name__ == "BaseClass"
90    assert type(m.return_class_n(1)).__name__ == "DerivedClass1"
91
92
93def test_isinstance():
94    objects = [tuple(), dict(), m.Pet("Polly", "parrot")] + [m.Dog("Molly")] * 4
95    expected = (True, True, True, True, True, False, False)
96    assert m.check_instances(objects) == expected
97
98
99def test_mismatched_holder():
100    import re
101
102    with pytest.raises(RuntimeError) as excinfo:
103        m.mismatched_holder_1()
104    assert re.match('generic_type: type ".*MismatchDerived1" does not have a non-default '
105                    'holder type while its base ".*MismatchBase1" does', str(excinfo.value))
106
107    with pytest.raises(RuntimeError) as excinfo:
108        m.mismatched_holder_2()
109    assert re.match('generic_type: type ".*MismatchDerived2" has a non-default holder type '
110                    'while its base ".*MismatchBase2" does not', str(excinfo.value))
111
112
113def test_override_static():
114    """#511: problem with inheritance + overwritten def_static"""
115    b = m.MyBase.make()
116    d1 = m.MyDerived.make2()
117    d2 = m.MyDerived.make()
118
119    assert isinstance(b, m.MyBase)
120    assert isinstance(d1, m.MyDerived)
121    assert isinstance(d2, m.MyDerived)
122
123
124def test_implicit_conversion_life_support():
125    """Ensure the lifetime of temporary objects created for implicit conversions"""
126    assert m.implicitly_convert_argument(UserType(5)) == 5
127    assert m.implicitly_convert_variable(UserType(5)) == 5
128
129    assert "outside a bound function" in m.implicitly_convert_variable_fail(UserType(5))
130
131
132def test_operator_new_delete(capture):
133    """Tests that class-specific operator new/delete functions are invoked"""
134
135    class SubAliased(m.AliasedHasOpNewDelSize):
136        pass
137
138    with capture:
139        a = m.HasOpNewDel()
140        b = m.HasOpNewDelSize()
141        d = m.HasOpNewDelBoth()
142    assert capture == """
143        A new 8
144        B new 4
145        D new 32
146    """
147    sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)
148    sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)
149    with capture:
150        c = m.AliasedHasOpNewDelSize()
151        c2 = SubAliased()
152    assert capture == (
153        "C new " + sz_noalias + "\n" +
154        "C new " + sz_alias + "\n"
155    )
156
157    with capture:
158        del a
159        pytest.gc_collect()
160        del b
161        pytest.gc_collect()
162        del d
163        pytest.gc_collect()
164    assert capture == """
165        A delete
166        B delete 4
167        D delete
168    """
169
170    with capture:
171        del c
172        pytest.gc_collect()
173        del c2
174        pytest.gc_collect()
175    assert capture == (
176        "C delete " + sz_noalias + "\n" +
177        "C delete " + sz_alias + "\n"
178    )
179
180
181def test_bind_protected_functions():
182    """Expose protected member functions to Python using a helper class"""
183    a = m.ProtectedA()
184    assert a.foo() == 42
185
186    b = m.ProtectedB()
187    assert b.foo() == 42
188
189    class C(m.ProtectedB):
190        def __init__(self):
191            m.ProtectedB.__init__(self)
192
193        def foo(self):
194            return 0
195
196    c = C()
197    assert c.foo() == 0
198
199
200def test_brace_initialization():
201    """ Tests that simple POD classes can be constructed using C++11 brace initialization """
202    a = m.BraceInitialization(123, "test")
203    assert a.field1 == 123
204    assert a.field2 == "test"
205
206
207@pytest.unsupported_on_pypy
208def test_class_refcount():
209    """Instances must correctly increase/decrease the reference count of their types (#1029)"""
210    from sys import getrefcount
211
212    class PyDog(m.Dog):
213        pass
214
215    for cls in m.Dog, PyDog:
216        refcount_1 = getrefcount(cls)
217        molly = [cls("Molly") for _ in range(10)]
218        refcount_2 = getrefcount(cls)
219
220        del molly
221        pytest.gc_collect()
222        refcount_3 = getrefcount(cls)
223
224        assert refcount_1 == refcount_3
225        assert refcount_2 > refcount_1
226
227
228def test_reentrant_implicit_conversion_failure(msg):
229    # ensure that there is no runaway reentrant implicit conversion (#1035)
230    with pytest.raises(TypeError) as excinfo:
231        m.BogusImplicitConversion(0)
232    assert msg(excinfo.value) == '''__init__(): incompatible constructor arguments. The following argument types are supported:
233    1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)
234
235Invoked with: 0'''
236