blob: 8761f26504fb1dff67d53de35d6055cedde68e56 [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 }());
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400187
188 // test_operator_new_delete
189 struct HasOpNewDel {
190 std::uint64_t i;
191 static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); }
192 static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; }
193 static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); }
194 };
195 struct HasOpNewDelSize {
196 std::uint32_t i;
197 static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); }
198 static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; }
199 static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); }
200 };
201 struct AliasedHasOpNewDelSize {
202 std::uint64_t i;
203 static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); }
204 static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; }
205 static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); }
206 virtual ~AliasedHasOpNewDelSize() = default;
207 };
208 struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
209 PyAliasedHasOpNewDelSize() = default;
210 PyAliasedHasOpNewDelSize(int) { }
211 std::uint64_t j;
212 };
213 struct HasOpNewDelBoth {
214 std::uint32_t i[8];
215 static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); }
216 static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; }
217 static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); }
218 static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); }
219 };
220 py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
221 py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
222 py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
223 py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m, "AliasedHasOpNewDelSize");
224 aliased.def(py::init<>());
225 aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
226 aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
Dean Moldovan83e328f2017-06-09 00:44:49 +0200227}
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400228
229template <int N> class BreaksBase {};
230template <int N> class BreaksTramp : public BreaksBase<N> {};
231// These should all compile just fine:
232typedef py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>> DoesntBreak1;
233typedef py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>> DoesntBreak2;
234typedef py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>> DoesntBreak3;
235typedef py::class_<BreaksBase<4>, BreaksTramp<4>> DoesntBreak4;
236typedef py::class_<BreaksBase<5>> DoesntBreak5;
237typedef py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>> DoesntBreak6;
238typedef py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>> DoesntBreak7;
239typedef py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>> DoesntBreak8;
240#define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
241 "DoesntBreak" #N " has wrong type!")
242CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
243#define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
244 "DoesntBreak" #N " has wrong type_alias!")
245#define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
246 "DoesntBreak" #N " has type alias, but shouldn't!")
247CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
248#define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
249 "DoesntBreak" #N " has wrong holder_type!")
250CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
251CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
252
253// There's no nice way to test that these fail because they fail to compile; leave them here,
254// though, so that they can be manually tested by uncommenting them (and seeing that compilation
255// failures occurs).
256
257// We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
258#define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
259 "Breaks1 has wrong type!");
260
261//// Two holder classes:
262//typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
263//CHECK_BROKEN(1);
264//// Two aliases:
265//typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
266//CHECK_BROKEN(2);
267//// Holder + 2 aliases
268//typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
269//CHECK_BROKEN(3);
270//// Alias + 2 holders
271//typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
272//CHECK_BROKEN(4);
273//// Invalid option (not a subclass or holder)
274//typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
275//CHECK_BROKEN(5);
276//// Invalid option: multiple inheritance not supported:
277//template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
278//typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
279//CHECK_BROKEN(8);