blob: f616ba7717d3a409c5a63c8284bdea821e8896d2 [file] [log] [blame]
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001/*
Dean Moldovan83e328f2017-06-09 00:44:49 +02002 tests/test_class.cpp -- test py::class_ definitions and basic functionality
Jason Rhinelander5fffe202016-09-06 12:17:06 -04003
4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
10#include "pybind11_tests.h"
Dean Moldovan83e328f2017-06-09 00:44:49 +020011#include "constructor_stats.h"
Jason Rhinelander5fffe202016-09-06 12:17:06 -040012
Dean Moldovan83e328f2017-06-09 00:44:49 +020013TEST_SUBMODULE(class_, m) {
14 // test_instance
15 struct NoConstructor {
16 static NoConstructor *new_instance() {
17 auto *ptr = new NoConstructor();
18 print_created(ptr, "via new_instance");
19 return ptr;
20 }
21 ~NoConstructor() { print_destroyed(this); }
22 };
23
24 py::class_<NoConstructor>(m, "NoConstructor")
25 .def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
Dean Moldovan0bc272b2017-06-22 23:42:11 +020026
27 // test_inheritance
28 class Pet {
29 public:
30 Pet(const std::string &name, const std::string &species)
31 : m_name(name), m_species(species) {}
32 std::string name() const { return m_name; }
33 std::string species() const { return m_species; }
34 private:
35 std::string m_name;
36 std::string m_species;
37 };
38
39 class Dog : public Pet {
40 public:
41 Dog(const std::string &name) : Pet(name, "dog") {}
42 std::string bark() const { return "Woof!"; }
43 };
44
45 class Rabbit : public Pet {
46 public:
47 Rabbit(const std::string &name) : Pet(name, "parrot") {}
48 };
49
50 class Hamster : public Pet {
51 public:
52 Hamster(const std::string &name) : Pet(name, "rodent") {}
53 };
54
55 class Chimera : public Pet {
56 Chimera() : Pet("Kimmy", "chimera") {}
57 };
58
59 py::class_<Pet> pet_class(m, "Pet");
60 pet_class
61 .def(py::init<std::string, std::string>())
62 .def("name", &Pet::name)
63 .def("species", &Pet::species);
64
65 /* One way of declaring a subclass relationship: reference parent's class_ object */
66 py::class_<Dog>(m, "Dog", pet_class)
67 .def(py::init<std::string>());
68
69 /* Another way of declaring a subclass relationship: reference parent's C++ type */
70 py::class_<Rabbit, Pet>(m, "Rabbit")
71 .def(py::init<std::string>());
72
73 /* And another: list parent in class template arguments */
74 py::class_<Hamster, Pet>(m, "Hamster")
75 .def(py::init<std::string>());
76
77 /* Constructors are not inherited by default */
78 py::class_<Chimera, Pet>(m, "Chimera");
79
80 m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
81 m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
82
83 // test_automatic_upcasting
84 struct BaseClass { virtual ~BaseClass() {} };
85 struct DerivedClass1 : BaseClass { };
86 struct DerivedClass2 : BaseClass { };
87
88 py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
89 py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
90 py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
91
92 m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
93 m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
94 m.def("return_class_n", [](int n) -> BaseClass* {
95 if (n == 1) return new DerivedClass1();
96 if (n == 2) return new DerivedClass2();
97 return new BaseClass();
98 });
99 m.def("return_none", []() -> BaseClass* { return nullptr; });
100
101 // test_isinstance
102 m.def("check_instances", [](py::list l) {
103 return py::make_tuple(
104 py::isinstance<py::tuple>(l[0]),
105 py::isinstance<py::dict>(l[1]),
106 py::isinstance<Pet>(l[2]),
107 py::isinstance<Pet>(l[3]),
108 py::isinstance<Dog>(l[4]),
109 py::isinstance<Rabbit>(l[5]),
110 py::isinstance<UnregisteredType>(l[6])
111 );
112 });
113
114 // test_mismatched_holder
115 struct MismatchBase1 { };
116 struct MismatchDerived1 : MismatchBase1 { };
117
118 struct MismatchBase2 { };
119 struct MismatchDerived2 : MismatchBase2 { };
120
121 m.def("mismatched_holder_1", []() {
122 auto mod = py::module::import("__main__");
123 py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
124 py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
125 });
126 m.def("mismatched_holder_2", []() {
127 auto mod = py::module::import("__main__");
128 py::class_<MismatchBase2>(mod, "MismatchBase2");
129 py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
130 MismatchBase2>(mod, "MismatchDerived2");
131 });
132
133 // test_override_static
134 // #511: problem with inheritance + overwritten def_static
135 struct MyBase {
136 static std::unique_ptr<MyBase> make() {
137 return std::unique_ptr<MyBase>(new MyBase());
138 }
139 };
140
141 struct MyDerived : MyBase {
142 static std::unique_ptr<MyDerived> make() {
143 return std::unique_ptr<MyDerived>(new MyDerived());
144 }
145 };
146
147 py::class_<MyBase>(m, "MyBase")
148 .def_static("make", &MyBase::make);
149
150 py::class_<MyDerived, MyBase>(m, "MyDerived")
151 .def_static("make", &MyDerived::make)
152 .def_static("make2", &MyDerived::make);
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200153
154 // test_implicit_conversion_life_support
155 struct ConvertibleFromUserType {
156 int i;
157
158 ConvertibleFromUserType(UserType u) : i(u.value()) { }
159 };
160
161 py::class_<ConvertibleFromUserType>(m, "AcceptsUserType")
162 .def(py::init<UserType>());
163 py::implicitly_convertible<UserType, ConvertibleFromUserType>();
164
165 m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
166 m.def("implicitly_convert_variable", [](py::object o) {
167 // `o` is `UserType` and `r` is a reference to a temporary created by implicit
168 // conversion. This is valid when called inside a bound function because the temp
169 // object is attached to the same life support system as the arguments.
170 const auto &r = o.cast<const ConvertibleFromUserType &>();
171 return r.i;
172 });
173 m.add_object("implicitly_convert_variable_fail", [&] {
174 auto f = [](PyObject *, PyObject *args) -> PyObject * {
175 auto o = py::reinterpret_borrow<py::tuple>(args)[0];
176 try { // It should fail here because there is no life support.
177 o.cast<const ConvertibleFromUserType &>();
178 } catch (const py::cast_error &e) {
179 return py::str(e.what()).release().ptr();
180 }
181 return py::str().release().ptr();
182 };
183
184 auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
185 return py::reinterpret_steal<py::object>(PyCFunction_NewEx(def, nullptr, m.ptr()));
186 }());
Dean Moldovan83e328f2017-06-09 00:44:49 +0200187}
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400188
189template <int N> class BreaksBase {};
190template <int N> class BreaksTramp : public BreaksBase<N> {};
191// These should all compile just fine:
192typedef py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>> DoesntBreak1;
193typedef py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>> DoesntBreak2;
194typedef py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>> DoesntBreak3;
195typedef py::class_<BreaksBase<4>, BreaksTramp<4>> DoesntBreak4;
196typedef py::class_<BreaksBase<5>> DoesntBreak5;
197typedef py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>> DoesntBreak6;
198typedef py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>> DoesntBreak7;
199typedef py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>> DoesntBreak8;
200#define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
201 "DoesntBreak" #N " has wrong type!")
202CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
203#define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
204 "DoesntBreak" #N " has wrong type_alias!")
205#define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
206 "DoesntBreak" #N " has type alias, but shouldn't!")
207CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
208#define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
209 "DoesntBreak" #N " has wrong holder_type!")
210CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
211CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
212
213// There's no nice way to test that these fail because they fail to compile; leave them here,
214// though, so that they can be manually tested by uncommenting them (and seeing that compilation
215// failures occurs).
216
217// We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
218#define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
219 "Breaks1 has wrong type!");
220
221//// Two holder classes:
222//typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
223//CHECK_BROKEN(1);
224//// Two aliases:
225//typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
226//CHECK_BROKEN(2);
227//// Holder + 2 aliases
228//typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
229//CHECK_BROKEN(3);
230//// Alias + 2 holders
231//typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
232//CHECK_BROKEN(4);
233//// Invalid option (not a subclass or holder)
234//typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
235//CHECK_BROKEN(5);
236//// Invalid option: multiple inheritance not supported:
237//template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
238//typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
239//CHECK_BROKEN(8);