test_virtual_functions.py 11.4 KB
Newer Older
1
# -*- coding: utf-8 -*-
Dean Moldovan's avatar
Dean Moldovan committed
2
import pytest
3

4
5
import env  # noqa: F401

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


def test_override(capture, msg):
11
    class ExtendedExampleVirt(m.ExampleVirt):
Dean Moldovan's avatar
Dean Moldovan committed
12
13
14
15
16
        def __init__(self, state):
            super(ExtendedExampleVirt, self).__init__(state + 1)
            self.data = "Hello world"

        def run(self, value):
17
            print("ExtendedExampleVirt::run(%i), calling parent.." % value)
Dean Moldovan's avatar
Dean Moldovan committed
18
19
20
            return super(ExtendedExampleVirt, self).run(value + 1)

        def run_bool(self):
21
            print("ExtendedExampleVirt::run_bool()")
Dean Moldovan's avatar
Dean Moldovan committed
22
23
            return False

24
25
26
        def get_string1(self):
            return "override1"

Dean Moldovan's avatar
Dean Moldovan committed
27
        def pure_virtual(self):
28
            print("ExtendedExampleVirt::pure_virtual(): %s" % self.data)
Dean Moldovan's avatar
Dean Moldovan committed
29

30
31
32
33
34
35
36
    class ExtendedExampleVirt2(ExtendedExampleVirt):
        def __init__(self, state):
            super(ExtendedExampleVirt2, self).__init__(state + 1)

        def get_string2(self):
            return "override2"

37
    ex12 = m.ExampleVirt(10)
Dean Moldovan's avatar
Dean Moldovan committed
38
    with capture:
39
        assert m.runExampleVirt(ex12, 20) == 30
40
41
42
    assert (
        capture
        == """
43
44
        Original implementation of ExampleVirt::run(state=10, value=20, str1=default1, str2=default2)
    """  # noqa: E501 line too long
45
    )
Dean Moldovan's avatar
Dean Moldovan committed
46
47

    with pytest.raises(RuntimeError) as excinfo:
48
        m.runExampleVirtVirtual(ex12)
49
50
51
52
    assert (
        msg(excinfo.value)
        == 'Tried to call pure virtual function "ExampleVirt::pure_virtual"'
    )
Dean Moldovan's avatar
Dean Moldovan committed
53
54
55

    ex12p = ExtendedExampleVirt(10)
    with capture:
56
        assert m.runExampleVirt(ex12p, 20) == 32
57
58
59
    assert (
        capture
        == """
Dean Moldovan's avatar
Dean Moldovan committed
60
        ExtendedExampleVirt::run(20), calling parent..
61
        Original implementation of ExampleVirt::run(state=11, value=21, str1=override1, str2=default2)
62
    """  # noqa: E501 line too long
63
    )
Dean Moldovan's avatar
Dean Moldovan committed
64
    with capture:
65
        assert m.runExampleVirtBool(ex12p) is False
Dean Moldovan's avatar
Dean Moldovan committed
66
67
    assert capture == "ExtendedExampleVirt::run_bool()"
    with capture:
68
        m.runExampleVirtVirtual(ex12p)
Dean Moldovan's avatar
Dean Moldovan committed
69
70
    assert capture == "ExtendedExampleVirt::pure_virtual(): Hello world"

71
72
    ex12p2 = ExtendedExampleVirt2(15)
    with capture:
73
        assert m.runExampleVirt(ex12p2, 50) == 68
74
75
76
    assert (
        capture
        == """
77
78
        ExtendedExampleVirt::run(50), calling parent..
        Original implementation of ExampleVirt::run(state=17, value=51, str1=override1, str2=override2)
79
    """  # noqa: E501 line too long
80
    )
81

82
    cstats = ConstructorStats.get(m.ExampleVirt)
83
84
    assert cstats.alive() == 3
    del ex12, ex12p, ex12p2
Dean Moldovan's avatar
Dean Moldovan committed
85
    assert cstats.alive() == 0
86
    assert cstats.values() == ["10", "11", "17"]
Dean Moldovan's avatar
Dean Moldovan committed
87
88
89
90
    assert cstats.copy_constructions == 0
    assert cstats.move_constructions >= 0


91
92
93
94
95
96
def test_alias_delay_initialization1(capture):
    """`A` only initializes its trampoline class when we inherit from it

    If we just create and use an A instance directly, the trampoline initialization is
    bypassed and we only initialize an A() instead (for performance reasons).
    """
97

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    class B(m.A):
        def __init__(self):
            super(B, self).__init__()

        def f(self):
            print("In python f()")

    # C++ version
    with capture:
        a = m.A()
        m.call_f(a)
        del a
        pytest.gc_collect()
    assert capture == "A.f()"

    # Python version
    with capture:
        b = B()
        m.call_f(b)
        del b
        pytest.gc_collect()
119
120
121
    assert (
        capture
        == """
122
123
124
125
126
        PyA.PyA()
        PyA.f()
        In python f()
        PyA.~PyA()
    """
127
    )
128
129
130
131
132
133
134
135
136


def test_alias_delay_initialization2(capture):
    """`A2`, unlike the above, is configured to always initialize the alias

    While the extra initialization and extra class layer has small virtual dispatch
    performance penalty, it also allows us to do more things with the trampoline
    class such as defining local variables and performing construction/destruction.
    """
137

138
139
140
    class B2(m.A2):
        def __init__(self):
            super(B2, self).__init__()
Dean Moldovan's avatar
Dean Moldovan committed
141

142
143
144
145
146
147
148
149
150
        def f(self):
            print("In python B2.f()")

    # No python subclass version
    with capture:
        a2 = m.A2()
        m.call_f(a2)
        del a2
        pytest.gc_collect()
151
152
153
154
        a3 = m.A2(1)
        m.call_f(a3)
        del a3
        pytest.gc_collect()
155
156
157
    assert (
        capture
        == """
158
159
160
161
        PyA2.PyA2()
        PyA2.f()
        A2.f()
        PyA2.~PyA2()
162
163
164
165
        PyA2.PyA2()
        PyA2.f()
        A2.f()
        PyA2.~PyA2()
166
    """
167
    )
168
169
170
171
172
173
174

    # Python subclass version
    with capture:
        b2 = B2()
        m.call_f(b2)
        del b2
        pytest.gc_collect()
175
176
177
    assert (
        capture
        == """
178
179
180
181
182
        PyA2.PyA2()
        PyA2.f()
        In python B2.f()
        PyA2.~PyA2()
    """
183
    )
184
185


186
187
# PyPy: Reference count > 1 causes call with noncopyable instance
# to fail in ncv1.print_nc()
188
@pytest.mark.xfail("env.PYPY")
189
@pytest.mark.skipif(
190
    not hasattr(m, "NCVirt"), reason="NCVirt does not work on Intel/PGI/NVCC compilers"
191
)
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def test_move_support():
    class NCVirtExt(m.NCVirt):
        def get_noncopyable(self, a, b):
            # Constructs and returns a new instance:
            nc = m.NonCopyable(a * a, b * b)
            return nc

        def get_movable(self, a, b):
            # Return a referenced copy
            self.movable = m.Movable(a, b)
            return self.movable

    class NCVirtExt2(m.NCVirt):
        def get_noncopyable(self, a, b):
            # Keep a reference: this is going to throw an exception
            self.nc = m.NonCopyable(a, b)
            return self.nc

        def get_movable(self, a, b):
            # Return a new instance without storing it
            return m.Movable(a, b)

    ncv1 = NCVirtExt()
    assert ncv1.print_nc(2, 3) == "36"
    assert ncv1.print_movable(4, 5) == "9"
    ncv2 = NCVirtExt2()
    assert ncv2.print_movable(7, 7) == "14"
    # Don't check the exception message here because it differs under debug/non-debug mode
    with pytest.raises(RuntimeError):
        ncv2.print_nc(9, 9)

    nc_stats = ConstructorStats.get(m.NonCopyable)
    mv_stats = ConstructorStats.get(m.Movable)
    assert nc_stats.alive() == 1
    assert mv_stats.alive() == 1
    del ncv1, ncv2
    assert nc_stats.alive() == 0
    assert mv_stats.alive() == 0
230
231
    assert nc_stats.values() == ["4", "9", "9", "9"]
    assert mv_stats.values() == ["4", "5", "7", "7"]
232
    assert nc_stats.copy_constructions == 0
233
    assert mv_stats.copy_constructions in (1, 0)  # SMART_HOLDER_WIP
234
235
236
237
238
239
    assert nc_stats.move_constructions >= 0
    assert mv_stats.move_constructions >= 0


def test_dispatch_issue(msg):
    """#159: virtual function dispatch has problems with similar-named functions"""
240

241
242
243
244
245
246
247
248
    class PyClass1(m.DispatchIssue):
        def dispatch(self):
            return "Yay.."

    class PyClass2(m.DispatchIssue):
        def dispatch(self):
            with pytest.raises(RuntimeError) as excinfo:
                super(PyClass2, self).dispatch()
249
250
251
252
            assert (
                msg(excinfo.value)
                == 'Tried to call pure virtual function "Base::dispatch"'
            )
253

254
            return m.dispatch_issue_go(PyClass1())
255
256
257
258
259
260

    b = PyClass2()
    assert m.dispatch_issue_go(b) == "Yay.."


def test_override_ref():
Unknown's avatar
Unknown committed
261
    """#392/397: overriding reference-returning functions"""
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    o = m.OverrideTest("asdf")

    # Not allowed (see associated .cpp comment)
    # i = o.str_ref()
    # assert o.str_ref() == "asdf"
    assert o.str_value() == "asdf"

    assert o.A_value().value == "hi"
    a = o.A_ref()
    assert a.value == "hi"
    a.value = "bye"
    assert a.value == "bye"


def test_inherited_virtuals():
277
    class AR(m.A_Repeat):
Dean Moldovan's avatar
Dean Moldovan committed
278
279
280
        def unlucky_number(self):
            return 99

281
    class AT(m.A_Tpl):
Dean Moldovan's avatar
Dean Moldovan committed
282
283
284
        def unlucky_number(self):
            return 999

285
    obj = AR()
286
    assert obj.say_something(3) == "hihihi"
Dean Moldovan's avatar
Dean Moldovan committed
287
    assert obj.unlucky_number() == 99
288
    assert obj.say_everything() == "hi 99"
Dean Moldovan's avatar
Dean Moldovan committed
289

290
    obj = AT()
291
    assert obj.say_something(3) == "hihihi"
Dean Moldovan's avatar
Dean Moldovan committed
292
    assert obj.unlucky_number() == 999
293
    assert obj.say_everything() == "hi 999"
Dean Moldovan's avatar
Dean Moldovan committed
294

295
    for obj in [m.B_Repeat(), m.B_Tpl()]:
296
        assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
297
298
        assert obj.unlucky_number() == 13
        assert obj.lucky_number() == 7.0
299
        assert obj.say_everything() == "B says hi 1 times 13"
Dean Moldovan's avatar
Dean Moldovan committed
300

301
    for obj in [m.C_Repeat(), m.C_Tpl()]:
302
        assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
303
304
        assert obj.unlucky_number() == 4444
        assert obj.lucky_number() == 888.0
305
        assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
306

307
    class CR(m.C_Repeat):
Dean Moldovan's avatar
Dean Moldovan committed
308
        def lucky_number(self):
309
            return m.C_Repeat.lucky_number(self) + 1.25
Dean Moldovan's avatar
Dean Moldovan committed
310

311
    obj = CR()
312
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
313
314
    assert obj.unlucky_number() == 4444
    assert obj.lucky_number() == 889.25
315
    assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
316

317
    class CT(m.C_Tpl):
Dean Moldovan's avatar
Dean Moldovan committed
318
319
        pass

320
    obj = CT()
321
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
322
323
    assert obj.unlucky_number() == 4444
    assert obj.lucky_number() == 888.0
324
    assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
325

326
    class CCR(CR):
Dean Moldovan's avatar
Dean Moldovan committed
327
        def lucky_number(self):
328
            return CR.lucky_number(self) * 10
Dean Moldovan's avatar
Dean Moldovan committed
329

330
    obj = CCR()
331
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
332
333
    assert obj.unlucky_number() == 4444
    assert obj.lucky_number() == 8892.5
334
    assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
335

336
    class CCT(CT):
Dean Moldovan's avatar
Dean Moldovan committed
337
        def lucky_number(self):
338
            return CT.lucky_number(self) * 1000
Dean Moldovan's avatar
Dean Moldovan committed
339

340
    obj = CCT()
341
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
342
343
    assert obj.unlucky_number() == 4444
    assert obj.lucky_number() == 888000.0
344
    assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
345

346
    class DR(m.D_Repeat):
Dean Moldovan's avatar
Dean Moldovan committed
347
348
349
350
351
352
        def unlucky_number(self):
            return 123

        def lucky_number(self):
            return 42.0

353
    for obj in [m.D_Repeat(), m.D_Tpl()]:
354
        assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
355
356
        assert obj.unlucky_number() == 4444
        assert obj.lucky_number() == 888.0
357
        assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
358

359
    obj = DR()
360
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
361
362
    assert obj.unlucky_number() == 123
    assert obj.lucky_number() == 42.0
363
    assert obj.say_everything() == "B says hi 1 times 123"
Dean Moldovan's avatar
Dean Moldovan committed
364

365
    class DT(m.D_Tpl):
Dean Moldovan's avatar
Dean Moldovan committed
366
        def say_something(self, times):
367
            return "DT says:" + (" quack" * times)
Dean Moldovan's avatar
Dean Moldovan committed
368
369
370
371
372
373
374

        def unlucky_number(self):
            return 1234

        def lucky_number(self):
            return -4.25

375
376
    obj = DT()
    assert obj.say_something(3) == "DT says: quack quack quack"
Dean Moldovan's avatar
Dean Moldovan committed
377
378
    assert obj.unlucky_number() == 1234
    assert obj.lucky_number() == -4.25
379
    assert obj.say_everything() == "DT says: quack 1234"
380

381
    class DT2(DT):
382
        def say_something(self, times):
383
            return "DT2: " + ("QUACK" * times)
384
385
386
387

        def unlucky_number(self):
            return -3

388
    class BT(m.B_Tpl):
389
        def say_something(self, times):
390
391
            return "BT" * times

392
393
        def unlucky_number(self):
            return -7
394

395
396
397
        def lucky_number(self):
            return -1.375

398
399
    obj = BT()
    assert obj.say_something(3) == "BTBTBT"
400
401
    assert obj.unlucky_number() == -7
    assert obj.lucky_number() == -1.375
402
    assert obj.say_everything() == "BT -7"
403
404
405
406
407
408


def test_issue_1454():
    # Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7)
    m.test_gil()
    m.test_gil_from_thread()