blob: fb90cfc7baea0ddffe6bb89462aadabfd6532344 [file] [log] [blame]
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001import pytest
Jason Rhinelanderec62d972016-09-09 02:42:51 -04002
Jason Rhinelanderec62d972016-09-09 02:42:51 -04003
Dean Moldovanbad17402016-11-20 21:21:54 +01004def test_alias_delay_initialization1(capture):
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01005 """
6 A only initializes its trampoline class when we inherit from it; if we just
7 create and use an A instance directly, the trampoline initialization is
8 bypassed and we only initialize an A() instead (for performance reasons).
Dean Moldovanbad17402016-11-20 21:21:54 +01009 """
Jason Rhinelanderec62d972016-09-09 02:42:51 -040010 from pybind11_tests import A, call_f
11
12 class B(A):
13 def __init__(self):
14 super(B, self).__init__()
15
16 def f(self):
17 print("In python f()")
18
19 # C++ version
20 with capture:
21 a = A()
22 call_f(a)
23 del a
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +010024 pytest.gc_collect()
Jason Rhinelanderec62d972016-09-09 02:42:51 -040025 assert capture == "A.f()"
26
27 # Python version
28 with capture:
29 b = B()
30 call_f(b)
31 del b
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +010032 pytest.gc_collect()
Jason Rhinelanderec62d972016-09-09 02:42:51 -040033 assert capture == """
34 PyA.PyA()
35 PyA.f()
36 In python f()
37 PyA.~PyA()
38 """
39
Jason Rhinelanderec62d972016-09-09 02:42:51 -040040
Dean Moldovanbad17402016-11-20 21:21:54 +010041def test_alias_delay_initialization2(capture):
42 """A2, unlike the above, is configured to always initialize the alias; while
43 the extra initialization and extra class layer has small virtual dispatch
44 performance penalty, it also allows us to do more things with the trampoline
45 class such as defining local variables and performing construction/destruction.
46 """
47 from pybind11_tests import A2, call_f
Jason Rhinelanderec62d972016-09-09 02:42:51 -040048
49 class B2(A2):
50 def __init__(self):
51 super(B2, self).__init__()
52
53 def f(self):
54 print("In python B2.f()")
55
56 # No python subclass version
57 with capture:
58 a2 = A2()
59 call_f(a2)
60 del a2
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +010061 pytest.gc_collect()
Jason Rhinelanderec62d972016-09-09 02:42:51 -040062 assert capture == """
63 PyA2.PyA2()
64 PyA2.f()
65 A2.f()
66 PyA2.~PyA2()
67 """
68
69 # Python subclass version
70 with capture:
71 b2 = B2()
72 call_f(b2)
73 del b2
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +010074 pytest.gc_collect()
Jason Rhinelanderec62d972016-09-09 02:42:51 -040075 assert capture == """
76 PyA2.PyA2()
77 PyA2.f()
78 In python B2.f()
79 PyA2.~PyA2()
80 """