test_virtual_functions.py 10.8 KB
Newer Older
Dean Moldovan's avatar
Dean Moldovan committed
1
import pytest
2
3

from pybind11_tests import virtual_functions as m
Dean Moldovan's avatar
Dean Moldovan committed
4
5
6
7
from pybind11_tests import ConstructorStats


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

        def run(self, value):
            print('ExtendedExampleVirt::run(%i), calling parent..' % value)
            return super(ExtendedExampleVirt, self).run(value + 1)

        def run_bool(self):
            print('ExtendedExampleVirt::run_bool()')
            return False

21
22
23
        def get_string1(self):
            return "override1"

Dean Moldovan's avatar
Dean Moldovan committed
24
25
26
        def pure_virtual(self):
            print('ExtendedExampleVirt::pure_virtual(): %s' % self.data)

27
28
29
30
31
32
33
    class ExtendedExampleVirt2(ExtendedExampleVirt):
        def __init__(self, state):
            super(ExtendedExampleVirt2, self).__init__(state + 1)

        def get_string2(self):
            return "override2"

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

    with pytest.raises(RuntimeError) as excinfo:
42
        m.runExampleVirtVirtual(ex12)
Dean Moldovan's avatar
Dean Moldovan committed
43
44
45
46
    assert msg(excinfo.value) == 'Tried to call pure virtual function "ExampleVirt::pure_virtual"'

    ex12p = ExtendedExampleVirt(10)
    with capture:
47
        assert m.runExampleVirt(ex12p, 20) == 32
Dean Moldovan's avatar
Dean Moldovan committed
48
49
    assert capture == """
        ExtendedExampleVirt::run(20), calling parent..
50
        Original implementation of ExampleVirt::run(state=11, value=21, str1=override1, str2=default2)
51
    """  # noqa: E501 line too long
Dean Moldovan's avatar
Dean Moldovan committed
52
    with capture:
53
        assert m.runExampleVirtBool(ex12p) is False
Dean Moldovan's avatar
Dean Moldovan committed
54
55
    assert capture == "ExtendedExampleVirt::run_bool()"
    with capture:
56
        m.runExampleVirtVirtual(ex12p)
Dean Moldovan's avatar
Dean Moldovan committed
57
58
    assert capture == "ExtendedExampleVirt::pure_virtual(): Hello world"

59
60
    ex12p2 = ExtendedExampleVirt2(15)
    with capture:
61
        assert m.runExampleVirt(ex12p2, 50) == 68
62
63
64
    assert capture == """
        ExtendedExampleVirt::run(50), calling parent..
        Original implementation of ExampleVirt::run(state=17, value=51, str1=override1, str2=override2)
65
    """  # noqa: E501 line too long
66

67
    cstats = ConstructorStats.get(m.ExampleVirt)
68
69
    assert cstats.alive() == 3
    del ex12, ex12p, ex12p2
Dean Moldovan's avatar
Dean Moldovan committed
70
    assert cstats.alive() == 0
71
    assert cstats.values() == ['10', '11', '17']
Dean Moldovan's avatar
Dean Moldovan committed
72
73
74
75
    assert cstats.copy_constructions == 0
    assert cstats.move_constructions >= 0


76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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).
    """
    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()
    assert capture == """
        PyA.PyA()
        PyA.f()
        In python f()
        PyA.~PyA()
    """


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.
    """
    class B2(m.A2):
        def __init__(self):
            super(B2, self).__init__()
Dean Moldovan's avatar
Dean Moldovan committed
121

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        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()
    assert capture == """
        PyA2.PyA2()
        PyA2.f()
        A2.f()
        PyA2.~PyA2()
    """

    # Python subclass version
    with capture:
        b2 = B2()
        m.call_f(b2)
        del b2
        pytest.gc_collect()
    assert capture == """
        PyA2.PyA2()
        PyA2.f()
        In python B2.f()
        PyA2.~PyA2()
    """


def test_inheriting_repeat():
    class AR(m.A_Repeat):
Dean Moldovan's avatar
Dean Moldovan committed
154
155
156
        def unlucky_number(self):
            return 99

157
    class AT(m.A_Tpl):
Dean Moldovan's avatar
Dean Moldovan committed
158
159
160
        def unlucky_number(self):
            return 999

161
    obj = AR()
162
    assert obj.say_something(3) == "hihihi"
Dean Moldovan's avatar
Dean Moldovan committed
163
    assert obj.unlucky_number() == 99
164
    assert obj.say_everything() == "hi 99"
Dean Moldovan's avatar
Dean Moldovan committed
165

166
    obj = AT()
167
    assert obj.say_something(3) == "hihihi"
Dean Moldovan's avatar
Dean Moldovan committed
168
    assert obj.unlucky_number() == 999
169
    assert obj.say_everything() == "hi 999"
Dean Moldovan's avatar
Dean Moldovan committed
170

171
    for obj in [m.B_Repeat(), m.B_Tpl()]:
172
        assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
173
174
        assert obj.unlucky_number() == 13
        assert obj.lucky_number() == 7.0
175
        assert obj.say_everything() == "B says hi 1 times 13"
Dean Moldovan's avatar
Dean Moldovan committed
176

177
    for obj in [m.C_Repeat(), m.C_Tpl()]:
178
        assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
179
180
        assert obj.unlucky_number() == 4444
        assert obj.lucky_number() == 888.0
181
        assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
182

183
    class CR(m.C_Repeat):
Dean Moldovan's avatar
Dean Moldovan committed
184
        def lucky_number(self):
185
            return m.C_Repeat.lucky_number(self) + 1.25
Dean Moldovan's avatar
Dean Moldovan committed
186

187
    obj = CR()
188
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
189
190
    assert obj.unlucky_number() == 4444
    assert obj.lucky_number() == 889.25
191
    assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
192

193
    class CT(m.C_Tpl):
Dean Moldovan's avatar
Dean Moldovan committed
194
195
        pass

196
    obj = CT()
197
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
198
199
    assert obj.unlucky_number() == 4444
    assert obj.lucky_number() == 888.0
200
    assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
201

202
    class CCR(CR):
Dean Moldovan's avatar
Dean Moldovan committed
203
        def lucky_number(self):
204
            return CR.lucky_number(self) * 10
Dean Moldovan's avatar
Dean Moldovan committed
205

206
    obj = CCR()
207
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
208
209
    assert obj.unlucky_number() == 4444
    assert obj.lucky_number() == 8892.5
210
    assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
211

212
    class CCT(CT):
Dean Moldovan's avatar
Dean Moldovan committed
213
        def lucky_number(self):
214
            return CT.lucky_number(self) * 1000
Dean Moldovan's avatar
Dean Moldovan committed
215

216
    obj = CCT()
217
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
218
219
    assert obj.unlucky_number() == 4444
    assert obj.lucky_number() == 888000.0
220
    assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
221

222
    class DR(m.D_Repeat):
Dean Moldovan's avatar
Dean Moldovan committed
223
224
225
226
227
228
        def unlucky_number(self):
            return 123

        def lucky_number(self):
            return 42.0

229
    for obj in [m.D_Repeat(), m.D_Tpl()]:
230
        assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
231
232
        assert obj.unlucky_number() == 4444
        assert obj.lucky_number() == 888.0
233
        assert obj.say_everything() == "B says hi 1 times 4444"
Dean Moldovan's avatar
Dean Moldovan committed
234

235
    obj = DR()
236
    assert obj.say_something(3) == "B says hi 3 times"
Dean Moldovan's avatar
Dean Moldovan committed
237
238
    assert obj.unlucky_number() == 123
    assert obj.lucky_number() == 42.0
239
    assert obj.say_everything() == "B says hi 1 times 123"
Dean Moldovan's avatar
Dean Moldovan committed
240

241
    class DT(m.D_Tpl):
Dean Moldovan's avatar
Dean Moldovan committed
242
        def say_something(self, times):
243
            return "DT says:" + (' quack' * times)
Dean Moldovan's avatar
Dean Moldovan committed
244
245
246
247
248
249
250

        def unlucky_number(self):
            return 1234

        def lucky_number(self):
            return -4.25

251
252
    obj = DT()
    assert obj.say_something(3) == "DT says: quack quack quack"
Dean Moldovan's avatar
Dean Moldovan committed
253
254
    assert obj.unlucky_number() == 1234
    assert obj.lucky_number() == -4.25
255
    assert obj.say_everything() == "DT says: quack 1234"
256

257
    class DT2(DT):
258
        def say_something(self, times):
259
            return "DT2: " + ('QUACK' * times)
260
261
262
263

        def unlucky_number(self):
            return -3

264
    class BT(m.B_Tpl):
265
        def say_something(self, times):
266
267
            return "BT" * times

268
269
        def unlucky_number(self):
            return -7
270

271
272
273
        def lucky_number(self):
            return -1.375

274
275
    obj = BT()
    assert obj.say_something(3) == "BTBTBT"
276
277
    assert obj.unlucky_number() == -7
    assert obj.lucky_number() == -1.375
278
279
    assert obj.say_everything() == "BT -7"

Dean Moldovan's avatar
Dean Moldovan committed
280

Wenzel Jakob's avatar
Wenzel Jakob committed
281
282
283
# PyPy: Reference count > 1 causes call with noncopyable instance
# to fail in ncv1.print_nc()
@pytest.unsupported_on_pypy
284
@pytest.mark.skipif(not hasattr(m, "NCVirt"), reason="NCVirt test broken on ICPC")
285
def test_move_support():
286
    class NCVirtExt(m.NCVirt):
Dean Moldovan's avatar
Dean Moldovan committed
287
288
        def get_noncopyable(self, a, b):
            # Constructs and returns a new instance:
289
            nc = m.NonCopyable(a * a, b * b)
Dean Moldovan's avatar
Dean Moldovan committed
290
291
292
293
            return nc

        def get_movable(self, a, b):
            # Return a referenced copy
294
            self.movable = m.Movable(a, b)
Dean Moldovan's avatar
Dean Moldovan committed
295
296
            return self.movable

297
    class NCVirtExt2(m.NCVirt):
Dean Moldovan's avatar
Dean Moldovan committed
298
299
        def get_noncopyable(self, a, b):
            # Keep a reference: this is going to throw an exception
300
            self.nc = m.NonCopyable(a, b)
Dean Moldovan's avatar
Dean Moldovan committed
301
302
303
304
            return self.nc

        def get_movable(self, a, b):
            # Return a new instance without storing it
305
            return m.Movable(a, b)
Dean Moldovan's avatar
Dean Moldovan committed
306
307

    ncv1 = NCVirtExt()
308
309
    assert ncv1.print_nc(2, 3) == "36"
    assert ncv1.print_movable(4, 5) == "9"
Dean Moldovan's avatar
Dean Moldovan committed
310
    ncv2 = NCVirtExt2()
311
    assert ncv2.print_movable(7, 7) == "14"
Dean Moldovan's avatar
Dean Moldovan committed
312
313
314
315
    # Don't check the exception message here because it differs under debug/non-debug mode
    with pytest.raises(RuntimeError):
        ncv2.print_nc(9, 9)

316
317
    nc_stats = ConstructorStats.get(m.NonCopyable)
    mv_stats = ConstructorStats.get(m.Movable)
Dean Moldovan's avatar
Dean Moldovan committed
318
319
320
321
322
323
324
325
326
327
328
    assert nc_stats.alive() == 1
    assert mv_stats.alive() == 1
    del ncv1, ncv2
    assert nc_stats.alive() == 0
    assert mv_stats.alive() == 0
    assert nc_stats.values() == ['4', '9', '9', '9']
    assert mv_stats.values() == ['4', '5', '7', '7']
    assert nc_stats.copy_constructions == 0
    assert mv_stats.copy_constructions == 1
    assert nc_stats.move_constructions >= 0
    assert mv_stats.move_constructions >= 0
329
330
331
332


def test_dispatch_issue(msg):
    """#159: virtual function dispatch has problems with similar-named functions"""
333
    class PyClass1(m.DispatchIssue):
334
335
336
        def dispatch(self):
            return "Yay.."

337
    class PyClass2(m.DispatchIssue):
338
339
340
341
342
343
        def dispatch(self):
            with pytest.raises(RuntimeError) as excinfo:
                super(PyClass2, self).dispatch()
            assert msg(excinfo.value) == 'Tried to call pure virtual function "Base::dispatch"'

            p = PyClass1()
344
            return m.dispatch_issue_go(p)
345
346

    b = PyClass2()
347
    assert m.dispatch_issue_go(b) == "Yay.."
348
349
350
351


def test_override_ref():
    """#392/397: overridding reference-returning functions"""
352
    o = m.OverrideTest("asdf")
353
354
355
356
357
358
359
360
361
362
363

    # 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"