test_smart_ptr.py 9.35 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
import pytest
3
4
5

m = pytest.importorskip("pybind11_tests.smart_ptr")
from pybind11_tests import ConstructorStats  # noqa: E402
Dean Moldovan's avatar
Dean Moldovan committed
6
7
8
9


def test_smart_ptr(capture):
    # Object1
10
11
12
    for i, o in enumerate(
        [m.make_object_1(), m.make_object_2(), m.MyObject1(3)], start=1
    ):
Dean Moldovan's avatar
Dean Moldovan committed
13
14
        assert o.getRefCount() == 1
        with capture:
15
16
17
18
            m.print_object_1(o)
            m.print_object_2(o)
            m.print_object_3(o)
            m.print_object_4(o)
Dean Moldovan's avatar
Dean Moldovan committed
19
20
        assert capture == "MyObject1[{i}]\n".format(i=i) * 4

21
22
23
    for i, o in enumerate(
        [m.make_myobject1_1(), m.make_myobject1_2(), m.MyObject1(6), 7], start=4
    ):
Dean Moldovan's avatar
Dean Moldovan committed
24
25
26
        print(o)
        with capture:
            if not isinstance(o, int):
27
28
29
30
31
32
33
34
                m.print_object_1(o)
                m.print_object_2(o)
                m.print_object_3(o)
                m.print_object_4(o)
            m.print_myobject1_1(o)
            m.print_myobject1_2(o)
            m.print_myobject1_3(o)
            m.print_myobject1_4(o)
35
36
37

        times = 4 if isinstance(o, int) else 8
        assert capture == "MyObject1[{i}]\n".format(i=i) * times
Dean Moldovan's avatar
Dean Moldovan committed
38

39
    cstats = ConstructorStats.get(m.MyObject1)
Dean Moldovan's avatar
Dean Moldovan committed
40
    assert cstats.alive() == 0
41
42
43
    expected_values = ["MyObject1[{}]".format(i) for i in range(1, 7)] + [
        "MyObject1[7]"
    ] * 4
Dean Moldovan's avatar
Dean Moldovan committed
44
45
46
47
48
49
50
51
    assert cstats.values() == expected_values
    assert cstats.default_constructions == 0
    assert cstats.copy_constructions == 0
    # assert cstats.move_constructions >= 0 # Doesn't invoke any
    assert cstats.copy_assignments == 0
    assert cstats.move_assignments == 0

    # Object2
52
53
54
    for i, o in zip(
        [8, 6, 7], [m.MyObject2(8), m.make_myobject2_1(), m.make_myobject2_2()]
    ):
Dean Moldovan's avatar
Dean Moldovan committed
55
56
        print(o)
        with capture:
57
58
59
60
            m.print_myobject2_1(o)
            m.print_myobject2_2(o)
            m.print_myobject2_3(o)
            m.print_myobject2_4(o)
Dean Moldovan's avatar
Dean Moldovan committed
61
62
        assert capture == "MyObject2[{i}]\n".format(i=i) * 4

63
    cstats = ConstructorStats.get(m.MyObject2)
Dean Moldovan's avatar
Dean Moldovan committed
64
65
66
    assert cstats.alive() == 1
    o = None
    assert cstats.alive() == 0
67
    assert cstats.values() == ["MyObject2[8]", "MyObject2[6]", "MyObject2[7]"]
Dean Moldovan's avatar
Dean Moldovan committed
68
69
70
71
72
73
74
    assert cstats.default_constructions == 0
    assert cstats.copy_constructions == 0
    # assert cstats.move_constructions >= 0 # Doesn't invoke any
    assert cstats.copy_assignments == 0
    assert cstats.move_assignments == 0

    # Object3
75
76
77
    for i, o in zip(
        [9, 8, 9], [m.MyObject3(9), m.make_myobject3_1(), m.make_myobject3_2()]
    ):
Dean Moldovan's avatar
Dean Moldovan committed
78
79
        print(o)
        with capture:
80
81
82
83
            m.print_myobject3_1(o)
            m.print_myobject3_2(o)
            m.print_myobject3_3(o)
            m.print_myobject3_4(o)
Dean Moldovan's avatar
Dean Moldovan committed
84
85
        assert capture == "MyObject3[{i}]\n".format(i=i) * 4

86
    cstats = ConstructorStats.get(m.MyObject3)
Dean Moldovan's avatar
Dean Moldovan committed
87
88
89
    assert cstats.alive() == 1
    o = None
    assert cstats.alive() == 0
90
    assert cstats.values() == ["MyObject3[9]", "MyObject3[8]", "MyObject3[9]"]
Dean Moldovan's avatar
Dean Moldovan committed
91
92
93
94
95
96
    assert cstats.default_constructions == 0
    assert cstats.copy_constructions == 0
    # assert cstats.move_constructions >= 0 # Doesn't invoke any
    assert cstats.copy_assignments == 0
    assert cstats.move_assignments == 0

97
98
    # Object
    cstats = ConstructorStats.get(m.Object)
Dean Moldovan's avatar
Dean Moldovan committed
99
100
101
102
103
104
105
106
    assert cstats.alive() == 0
    assert cstats.values() == []
    assert cstats.default_constructions == 10
    assert cstats.copy_constructions == 0
    # assert cstats.move_constructions >= 0 # Doesn't invoke any
    assert cstats.copy_assignments == 0
    assert cstats.move_assignments == 0

107
108
    # ref<>
    cstats = m.cstats_ref()
Dean Moldovan's avatar
Dean Moldovan committed
109
    assert cstats.alive() == 0
110
    assert cstats.values() == ["from pointer"] * 10
Dean Moldovan's avatar
Dean Moldovan committed
111
112
113
114
115
    assert cstats.default_constructions == 30
    assert cstats.copy_constructions == 12
    # assert cstats.move_constructions >= 0 # Doesn't invoke any
    assert cstats.copy_assignments == 30
    assert cstats.move_assignments == 0
116

117

118
def test_smart_ptr_refcounting():
119
    assert m.test_object1_refcounting()
120
121


122
@pytest.mark.skipif("True")  # ASAN:leak
123
def test_unique_nodelete():
124
    o = m.MyObject4(23)
125
    assert o.value == 23
126
    cstats = ConstructorStats.get(m.MyObject4)
127
128
    assert cstats.alive() == 1
    del o
129
    assert cstats.alive() == 1  # Leak, but that's intentional
130
131


132
@pytest.mark.skipif("True")  # ASAN:leak
133
134
135
136
137
138
139
140
141
142
143
144
145
def test_unique_nodelete4a():
    o = m.MyObject4a(23)
    assert o.value == 23
    cstats = ConstructorStats.get(m.MyObject4a)
    assert cstats.alive() == 1
    del o
    assert cstats.alive() == 1  # Leak, but that's intentional


def test_unique_deleter():
    o = m.MyObject4b(23)
    assert o.value == 23
    cstats4a = ConstructorStats.get(m.MyObject4a)
146
    # FAILSwithASAN assert cstats4a.alive() == 2  # Two because of previous test
147
148
149
    cstats4b = ConstructorStats.get(m.MyObject4b)
    assert cstats4b.alive() == 1
    del o
150
    # FAILSwithASAN assert cstats4a.alive() == 1  # Should now only be one leftover from previous test
151
152
153
    assert cstats4b.alive() == 0  # Should be deleted


154
def test_large_holder():
155
    o = m.MyObject5(5)
156
    assert o.value == 5
157
    cstats = ConstructorStats.get(m.MyObject5)
158
159
160
161
162
    assert cstats.alive() == 1
    del o
    assert cstats.alive() == 0


163
def test_shared_ptr_and_references():
164
165
    s = m.SharedPtrRef()
    stats = ConstructorStats.get(m.A)
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
    assert stats.alive() == 2

    ref = s.ref  # init_holder_helper(holder_ptr=false, owned=false)
    assert stats.alive() == 2
    assert s.set_ref(ref)
    with pytest.raises(RuntimeError) as excinfo:
        assert s.set_holder(ref)
    assert "Unable to cast from non-held to held instance" in str(excinfo.value)

    copy = s.copy  # init_holder_helper(holder_ptr=false, owned=true)
    assert stats.alive() == 3
    assert s.set_ref(copy)
    assert s.set_holder(copy)

    holder_ref = s.holder_ref  # init_holder_helper(holder_ptr=true, owned=false)
    assert stats.alive() == 3
    assert s.set_ref(holder_ref)
    assert s.set_holder(holder_ref)

    holder_copy = s.holder_copy  # init_holder_helper(holder_ptr=true, owned=true)
    assert stats.alive() == 3
    assert s.set_ref(holder_copy)
    assert s.set_holder(holder_copy)

    del ref, copy, holder_ref, holder_copy, s
    assert stats.alive() == 0


def test_shared_ptr_from_this_and_references():
195
196
    s = m.SharedFromThisRef()
    stats = ConstructorStats.get(m.B)
197
198
199
200
201
    assert stats.alive() == 2

    ref = s.ref  # init_holder_helper(holder_ptr=false, owned=false, bad_wp=false)
    assert stats.alive() == 2
    assert s.set_ref(ref)
202
203
204
    assert s.set_holder(
        ref
    )  # std::enable_shared_from_this can create a holder from a reference
205
206
207
208
209
210
211
212
213
214
215
216
217

    bad_wp = s.bad_wp  # init_holder_helper(holder_ptr=false, owned=false, bad_wp=true)
    assert stats.alive() == 2
    assert s.set_ref(bad_wp)
    with pytest.raises(RuntimeError) as excinfo:
        assert s.set_holder(bad_wp)
    assert "Unable to cast from non-held to held instance" in str(excinfo.value)

    copy = s.copy  # init_holder_helper(holder_ptr=false, owned=true, bad_wp=false)
    assert stats.alive() == 3
    assert s.set_ref(copy)
    assert s.set_holder(copy)

218
219
220
    holder_ref = (
        s.holder_ref
    )  # init_holder_helper(holder_ptr=true, owned=false, bad_wp=false)
221
222
223
224
    assert stats.alive() == 3
    assert s.set_ref(holder_ref)
    assert s.set_holder(holder_ref)

225
226
227
    holder_copy = (
        s.holder_copy
    )  # init_holder_helper(holder_ptr=true, owned=true, bad_wp=false)
228
229
230
231
232
233
    assert stats.alive() == 3
    assert s.set_ref(holder_copy)
    assert s.set_holder(holder_copy)

    del ref, bad_wp, copy, holder_ref, holder_copy, s
    assert stats.alive() == 0
234

235
236
    z = m.SharedFromThisVirt.get()
    y = m.SharedFromThisVirt.get()
237
238
    assert y is z

239
240

def test_move_only_holder():
241
    a = m.TypeWithMoveOnlyHolder.make()
242
    b = m.TypeWithMoveOnlyHolder.make_as_object()
243
    stats = ConstructorStats.get(m.TypeWithMoveOnlyHolder)
244
245
    assert stats.alive() == 2
    del b
246
247
248
    assert stats.alive() == 1
    del a
    assert stats.alive() == 0
249
250


251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def test_holder_with_addressof_operator():
    # this test must not throw exception from c++
    a = m.TypeForHolderWithAddressOf.make()
    a.print_object_1()
    a.print_object_2()
    a.print_object_3()
    a.print_object_4()

    stats = ConstructorStats.get(m.TypeForHolderWithAddressOf)
    assert stats.alive() == 1

    np = m.TypeForHolderWithAddressOf.make()
    assert stats.alive() == 2
    del a
    assert stats.alive() == 1
    del np
    assert stats.alive() == 0

    b = m.TypeForHolderWithAddressOf.make()
    c = b
    assert b.get() is c.get()
    assert stats.alive() == 1

    del b
    assert stats.alive() == 1

    del c
    assert stats.alive() == 0


def test_move_only_holder_with_addressof_operator():
    a = m.TypeForMoveOnlyHolderWithAddressOf.make()
    a.print_object()

    stats = ConstructorStats.get(m.TypeForMoveOnlyHolderWithAddressOf)
    assert stats.alive() == 1

    a.value = 42
    assert a.value == 42

    del a
    assert stats.alive() == 0


295
def test_smart_ptr_from_default():
296
    instance = m.HeldByDefaultHolder()
297
    with pytest.raises(RuntimeError) as excinfo:
298
        m.HeldByDefaultHolder.load_shared_ptr(instance)
299
300
301
302
    assert (
        "Unable to load a custom holder type from a "
        "default-holder instance" in str(excinfo.value)
    )
303
304
305
306


def test_shared_ptr_gc():
    """#187: issue involving std::shared_ptr<> return value policy & garbage collection"""
307
    el = m.ElementList()
308
    for i in range(10):
309
        el.add(m.ElementA(i))
310
311
312
    pytest.gc_collect()
    for i, v in enumerate(el.get()):
        assert i == v.value()