blob: 9265e2e3725c4bdf1219e1feb7f40c101b5951d5 [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 Rhinelander7437c692017-07-28 22:03:44 -040012#include "local_bindings.h"
Jason Rhinelanderadbc8112018-01-11 13:22:13 -040013#include <pybind11/stl.h>
14
15// test_brace_initialization
16struct NoBraceInitialization {
17 NoBraceInitialization(std::vector<int> v) : vec{std::move(v)} {}
18 template <typename T>
19 NoBraceInitialization(std::initializer_list<T> l) : vec(l) {}
20
21 std::vector<int> vec;
22};
Jason Rhinelander5fffe202016-09-06 12:17:06 -040023
Dean Moldovan83e328f2017-06-09 00:44:49 +020024TEST_SUBMODULE(class_, m) {
25 // test_instance
26 struct NoConstructor {
Francesco Biscaniba33b2f2017-11-20 14:19:53 +010027 NoConstructor() = default;
28 NoConstructor(const NoConstructor &) = default;
29 NoConstructor(NoConstructor &&) = default;
Dean Moldovan83e328f2017-06-09 00:44:49 +020030 static NoConstructor *new_instance() {
31 auto *ptr = new NoConstructor();
32 print_created(ptr, "via new_instance");
33 return ptr;
34 }
35 ~NoConstructor() { print_destroyed(this); }
36 };
37
38 py::class_<NoConstructor>(m, "NoConstructor")
39 .def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
Dean Moldovan0bc272b2017-06-22 23:42:11 +020040
41 // test_inheritance
42 class Pet {
43 public:
44 Pet(const std::string &name, const std::string &species)
45 : m_name(name), m_species(species) {}
46 std::string name() const { return m_name; }
47 std::string species() const { return m_species; }
48 private:
49 std::string m_name;
50 std::string m_species;
51 };
52
53 class Dog : public Pet {
54 public:
55 Dog(const std::string &name) : Pet(name, "dog") {}
56 std::string bark() const { return "Woof!"; }
57 };
58
59 class Rabbit : public Pet {
60 public:
61 Rabbit(const std::string &name) : Pet(name, "parrot") {}
62 };
63
64 class Hamster : public Pet {
65 public:
66 Hamster(const std::string &name) : Pet(name, "rodent") {}
67 };
68
69 class Chimera : public Pet {
70 Chimera() : Pet("Kimmy", "chimera") {}
71 };
72
73 py::class_<Pet> pet_class(m, "Pet");
74 pet_class
75 .def(py::init<std::string, std::string>())
76 .def("name", &Pet::name)
77 .def("species", &Pet::species);
78
79 /* One way of declaring a subclass relationship: reference parent's class_ object */
80 py::class_<Dog>(m, "Dog", pet_class)
81 .def(py::init<std::string>());
82
83 /* Another way of declaring a subclass relationship: reference parent's C++ type */
84 py::class_<Rabbit, Pet>(m, "Rabbit")
85 .def(py::init<std::string>());
86
87 /* And another: list parent in class template arguments */
88 py::class_<Hamster, Pet>(m, "Hamster")
89 .def(py::init<std::string>());
90
91 /* Constructors are not inherited by default */
92 py::class_<Chimera, Pet>(m, "Chimera");
93
94 m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
95 m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
96
97 // test_automatic_upcasting
Francesco Biscaniba33b2f2017-11-20 14:19:53 +010098 struct BaseClass {
99 BaseClass() = default;
100 BaseClass(const BaseClass &) = default;
101 BaseClass(BaseClass &&) = default;
102 virtual ~BaseClass() {}
103 };
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200104 struct DerivedClass1 : BaseClass { };
105 struct DerivedClass2 : BaseClass { };
106
107 py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
108 py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
109 py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
110
111 m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
112 m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
113 m.def("return_class_n", [](int n) -> BaseClass* {
114 if (n == 1) return new DerivedClass1();
115 if (n == 2) return new DerivedClass2();
116 return new BaseClass();
117 });
118 m.def("return_none", []() -> BaseClass* { return nullptr; });
119
120 // test_isinstance
121 m.def("check_instances", [](py::list l) {
122 return py::make_tuple(
123 py::isinstance<py::tuple>(l[0]),
124 py::isinstance<py::dict>(l[1]),
125 py::isinstance<Pet>(l[2]),
126 py::isinstance<Pet>(l[3]),
127 py::isinstance<Dog>(l[4]),
128 py::isinstance<Rabbit>(l[5]),
129 py::isinstance<UnregisteredType>(l[6])
130 );
131 });
132
133 // test_mismatched_holder
134 struct MismatchBase1 { };
135 struct MismatchDerived1 : MismatchBase1 { };
136
137 struct MismatchBase2 { };
138 struct MismatchDerived2 : MismatchBase2 { };
139
140 m.def("mismatched_holder_1", []() {
141 auto mod = py::module::import("__main__");
142 py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
143 py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
144 });
145 m.def("mismatched_holder_2", []() {
146 auto mod = py::module::import("__main__");
147 py::class_<MismatchBase2>(mod, "MismatchBase2");
148 py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
149 MismatchBase2>(mod, "MismatchDerived2");
150 });
151
152 // test_override_static
153 // #511: problem with inheritance + overwritten def_static
154 struct MyBase {
155 static std::unique_ptr<MyBase> make() {
156 return std::unique_ptr<MyBase>(new MyBase());
157 }
158 };
159
160 struct MyDerived : MyBase {
161 static std::unique_ptr<MyDerived> make() {
162 return std::unique_ptr<MyDerived>(new MyDerived());
163 }
164 };
165
166 py::class_<MyBase>(m, "MyBase")
167 .def_static("make", &MyBase::make);
168
169 py::class_<MyDerived, MyBase>(m, "MyDerived")
170 .def_static("make", &MyDerived::make)
171 .def_static("make2", &MyDerived::make);
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200172
173 // test_implicit_conversion_life_support
174 struct ConvertibleFromUserType {
175 int i;
176
177 ConvertibleFromUserType(UserType u) : i(u.value()) { }
178 };
179
180 py::class_<ConvertibleFromUserType>(m, "AcceptsUserType")
181 .def(py::init<UserType>());
182 py::implicitly_convertible<UserType, ConvertibleFromUserType>();
183
184 m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
185 m.def("implicitly_convert_variable", [](py::object o) {
186 // `o` is `UserType` and `r` is a reference to a temporary created by implicit
187 // conversion. This is valid when called inside a bound function because the temp
188 // object is attached to the same life support system as the arguments.
189 const auto &r = o.cast<const ConvertibleFromUserType &>();
190 return r.i;
191 });
192 m.add_object("implicitly_convert_variable_fail", [&] {
193 auto f = [](PyObject *, PyObject *args) -> PyObject * {
194 auto o = py::reinterpret_borrow<py::tuple>(args)[0];
195 try { // It should fail here because there is no life support.
196 o.cast<const ConvertibleFromUserType &>();
197 } catch (const py::cast_error &e) {
198 return py::str(e.what()).release().ptr();
199 }
200 return py::str().release().ptr();
201 };
202
203 auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
204 return py::reinterpret_steal<py::object>(PyCFunction_NewEx(def, nullptr, m.ptr()));
205 }());
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400206
207 // test_operator_new_delete
208 struct HasOpNewDel {
209 std::uint64_t i;
210 static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); }
211 static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; }
212 static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); }
213 };
214 struct HasOpNewDelSize {
215 std::uint32_t i;
216 static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); }
217 static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; }
218 static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); }
219 };
220 struct AliasedHasOpNewDelSize {
221 std::uint64_t i;
222 static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); }
223 static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; }
224 static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); }
225 virtual ~AliasedHasOpNewDelSize() = default;
226 };
227 struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
228 PyAliasedHasOpNewDelSize() = default;
229 PyAliasedHasOpNewDelSize(int) { }
230 std::uint64_t j;
231 };
232 struct HasOpNewDelBoth {
233 std::uint32_t i[8];
234 static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); }
235 static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; }
236 static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); }
237 static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); }
238 };
239 py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
240 py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
241 py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
242 py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m, "AliasedHasOpNewDelSize");
243 aliased.def(py::init<>());
244 aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
245 aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
Jason Rhinelander7437c692017-07-28 22:03:44 -0400246
247 // This test is actually part of test_local_bindings (test_duplicate_local), but we need a
248 // definition in a different compilation unit within the same module:
249 bind_local<LocalExternal, 17>(m, "LocalExternal", py::module_local());
Dean Moldovan234f7c32017-08-17 17:03:46 +0200250
251 // test_bind_protected_functions
252 class ProtectedA {
253 protected:
254 int foo() const { return value; }
255
256 private:
257 int value = 42;
258 };
259
260 class PublicistA : public ProtectedA {
261 public:
262 using ProtectedA::foo;
263 };
264
265 py::class_<ProtectedA>(m, "ProtectedA")
266 .def(py::init<>())
267#if !defined(_MSC_VER) || _MSC_VER >= 1910
268 .def("foo", &PublicistA::foo);
269#else
270 .def("foo", static_cast<int (ProtectedA::*)() const>(&PublicistA::foo));
271#endif
272
273 class ProtectedB {
274 public:
275 virtual ~ProtectedB() = default;
276
277 protected:
278 virtual int foo() const { return value; }
279
280 private:
281 int value = 42;
282 };
283
284 class TrampolineB : public ProtectedB {
285 public:
286 int foo() const override { PYBIND11_OVERLOAD(int, ProtectedB, foo, ); }
287 };
288
289 class PublicistB : public ProtectedB {
290 public:
291 using ProtectedB::foo;
292 };
293
294 py::class_<ProtectedB, TrampolineB>(m, "ProtectedB")
295 .def(py::init<>())
296#if !defined(_MSC_VER) || _MSC_VER >= 1910
297 .def("foo", &PublicistB::foo);
298#else
299 .def("foo", static_cast<int (ProtectedB::*)() const>(&PublicistB::foo));
300#endif
Wenzel Jakob4336a7d2017-08-21 22:48:28 +0200301
302 // test_brace_initialization
303 struct BraceInitialization {
304 int field1;
305 std::string field2;
306 };
307
308 py::class_<BraceInitialization>(m, "BraceInitialization")
309 .def(py::init<int, const std::string &>())
310 .def_readwrite("field1", &BraceInitialization::field1)
311 .def_readwrite("field2", &BraceInitialization::field2);
Jason Rhinelanderadbc8112018-01-11 13:22:13 -0400312 // We *don't* want to construct using braces when the given constructor argument maps to a
313 // constructor, because brace initialization could go to the wrong place (in particular when
314 // there is also an `initializer_list<T>`-accept constructor):
315 py::class_<NoBraceInitialization>(m, "NoBraceInitialization")
316 .def(py::init<std::vector<int>>())
317 .def_readonly("vec", &NoBraceInitialization::vec);
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200318
319 // test_reentrant_implicit_conversion_failure
320 // #1035: issue with runaway reentrant implicit conversion
321 struct BogusImplicitConversion {
322 BogusImplicitConversion(const BogusImplicitConversion &) { }
323 };
324
325 py::class_<BogusImplicitConversion>(m, "BogusImplicitConversion")
326 .def(py::init<const BogusImplicitConversion &>());
327
328 py::implicitly_convertible<int, BogusImplicitConversion>();
Jason Rhinelander71178922017-11-07 12:33:05 -0400329
330 // test_qualname
331 // #1166: nested class docstring doesn't show nested name
332 // Also related: tests that __qualname__ is set properly
333 struct NestBase {};
334 struct Nested {};
335 py::class_<NestBase> base(m, "NestBase");
336 base.def(py::init<>());
337 py::class_<Nested>(base, "Nested")
338 .def(py::init<>())
339 .def("fn", [](Nested &, int, NestBase &, Nested &) {})
340 .def("fa", [](Nested &, int, NestBase &, Nested &) {},
341 "a"_a, "b"_a, "c"_a);
342 base.def("g", [](NestBase &, Nested &) {});
343 base.def("h", []() { return NestBase(); });
Dean Moldovan83e328f2017-06-09 00:44:49 +0200344}
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400345
Jason Rhinelander42e5ddc2017-06-12 21:48:36 -0400346template <int N> class BreaksBase { public: virtual ~BreaksBase() = default; };
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400347template <int N> class BreaksTramp : public BreaksBase<N> {};
348// These should all compile just fine:
349typedef py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>> DoesntBreak1;
350typedef py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>> DoesntBreak2;
351typedef py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>> DoesntBreak3;
352typedef py::class_<BreaksBase<4>, BreaksTramp<4>> DoesntBreak4;
353typedef py::class_<BreaksBase<5>> DoesntBreak5;
354typedef py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>> DoesntBreak6;
355typedef py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>> DoesntBreak7;
356typedef py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>> DoesntBreak8;
357#define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
358 "DoesntBreak" #N " has wrong type!")
359CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
360#define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
361 "DoesntBreak" #N " has wrong type_alias!")
362#define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
363 "DoesntBreak" #N " has type alias, but shouldn't!")
364CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
365#define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
366 "DoesntBreak" #N " has wrong holder_type!")
367CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
368CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
369
370// There's no nice way to test that these fail because they fail to compile; leave them here,
371// though, so that they can be manually tested by uncommenting them (and seeing that compilation
372// failures occurs).
373
374// We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
375#define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
376 "Breaks1 has wrong type!");
377
378//// Two holder classes:
379//typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
380//CHECK_BROKEN(1);
381//// Two aliases:
382//typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
383//CHECK_BROKEN(2);
384//// Holder + 2 aliases
385//typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
386//CHECK_BROKEN(3);
387//// Alias + 2 holders
388//typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
389//CHECK_BROKEN(4);
390//// Invalid option (not a subclass or holder)
391//typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
392//CHECK_BROKEN(5);
393//// Invalid option: multiple inheritance not supported:
394//template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
395//typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
396//CHECK_BROKEN(8);