blob: b7d52a1b5b8ac5f9ca63c490a30589797becec9d [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
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +010015#if defined(_MSC_VER)
16# pragma warning(disable: 4324) // warning C4324: structure was padded due to alignment specifier
17#endif
18
Jason Rhinelanderadbc8112018-01-11 13:22:13 -040019// test_brace_initialization
20struct NoBraceInitialization {
21 NoBraceInitialization(std::vector<int> v) : vec{std::move(v)} {}
22 template <typename T>
23 NoBraceInitialization(std::initializer_list<T> l) : vec(l) {}
24
25 std::vector<int> vec;
26};
Jason Rhinelander5fffe202016-09-06 12:17:06 -040027
Dean Moldovan83e328f2017-06-09 00:44:49 +020028TEST_SUBMODULE(class_, m) {
29 // test_instance
30 struct NoConstructor {
Francesco Biscaniba33b2f2017-11-20 14:19:53 +010031 NoConstructor() = default;
32 NoConstructor(const NoConstructor &) = default;
33 NoConstructor(NoConstructor &&) = default;
Dean Moldovan83e328f2017-06-09 00:44:49 +020034 static NoConstructor *new_instance() {
35 auto *ptr = new NoConstructor();
36 print_created(ptr, "via new_instance");
37 return ptr;
38 }
39 ~NoConstructor() { print_destroyed(this); }
40 };
41
42 py::class_<NoConstructor>(m, "NoConstructor")
43 .def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
Dean Moldovan0bc272b2017-06-22 23:42:11 +020044
45 // test_inheritance
46 class Pet {
47 public:
48 Pet(const std::string &name, const std::string &species)
49 : m_name(name), m_species(species) {}
50 std::string name() const { return m_name; }
51 std::string species() const { return m_species; }
52 private:
53 std::string m_name;
54 std::string m_species;
55 };
56
57 class Dog : public Pet {
58 public:
59 Dog(const std::string &name) : Pet(name, "dog") {}
60 std::string bark() const { return "Woof!"; }
61 };
62
63 class Rabbit : public Pet {
64 public:
65 Rabbit(const std::string &name) : Pet(name, "parrot") {}
66 };
67
68 class Hamster : public Pet {
69 public:
70 Hamster(const std::string &name) : Pet(name, "rodent") {}
71 };
72
73 class Chimera : public Pet {
74 Chimera() : Pet("Kimmy", "chimera") {}
75 };
76
77 py::class_<Pet> pet_class(m, "Pet");
78 pet_class
79 .def(py::init<std::string, std::string>())
80 .def("name", &Pet::name)
81 .def("species", &Pet::species);
82
83 /* One way of declaring a subclass relationship: reference parent's class_ object */
84 py::class_<Dog>(m, "Dog", pet_class)
85 .def(py::init<std::string>());
86
87 /* Another way of declaring a subclass relationship: reference parent's C++ type */
88 py::class_<Rabbit, Pet>(m, "Rabbit")
89 .def(py::init<std::string>());
90
91 /* And another: list parent in class template arguments */
92 py::class_<Hamster, Pet>(m, "Hamster")
93 .def(py::init<std::string>());
94
95 /* Constructors are not inherited by default */
96 py::class_<Chimera, Pet>(m, "Chimera");
97
98 m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
99 m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
100
101 // test_automatic_upcasting
Francesco Biscaniba33b2f2017-11-20 14:19:53 +0100102 struct BaseClass {
103 BaseClass() = default;
104 BaseClass(const BaseClass &) = default;
105 BaseClass(BaseClass &&) = default;
106 virtual ~BaseClass() {}
107 };
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200108 struct DerivedClass1 : BaseClass { };
109 struct DerivedClass2 : BaseClass { };
110
111 py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
112 py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
113 py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
114
115 m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
116 m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
117 m.def("return_class_n", [](int n) -> BaseClass* {
118 if (n == 1) return new DerivedClass1();
119 if (n == 2) return new DerivedClass2();
120 return new BaseClass();
121 });
122 m.def("return_none", []() -> BaseClass* { return nullptr; });
123
124 // test_isinstance
125 m.def("check_instances", [](py::list l) {
126 return py::make_tuple(
127 py::isinstance<py::tuple>(l[0]),
128 py::isinstance<py::dict>(l[1]),
129 py::isinstance<Pet>(l[2]),
130 py::isinstance<Pet>(l[3]),
131 py::isinstance<Dog>(l[4]),
132 py::isinstance<Rabbit>(l[5]),
133 py::isinstance<UnregisteredType>(l[6])
134 );
135 });
136
Henry Schreinerf12ec002020-09-14 18:06:26 -0400137 struct Invalid {};
138
139 // test_type
140 m.def("check_type", [](int category) {
141 // Currently not supported (via a fail at compile time)
142 // See https://github.com/pybind/pybind11/issues/2486
143 // if (category == 2)
144 // return py::type::of<int>();
145 if (category == 1)
146 return py::type::of<DerivedClass1>();
147 else
148 return py::type::of<Invalid>();
149 });
150
151 m.def("get_type_of", [](py::object ob) {
152 return py::type::of(ob);
153 });
154
155 m.def("as_type", [](py::object ob) {
156 auto tp = py::type(ob);
157 if (py::isinstance<py::type>(ob))
158 return tp;
159 else
160 throw std::runtime_error("Invalid type");
161 });
162
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200163 // test_mismatched_holder
164 struct MismatchBase1 { };
165 struct MismatchDerived1 : MismatchBase1 { };
166
167 struct MismatchBase2 { };
168 struct MismatchDerived2 : MismatchBase2 { };
169
170 m.def("mismatched_holder_1", []() {
171 auto mod = py::module::import("__main__");
172 py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
173 py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
174 });
175 m.def("mismatched_holder_2", []() {
176 auto mod = py::module::import("__main__");
177 py::class_<MismatchBase2>(mod, "MismatchBase2");
178 py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
179 MismatchBase2>(mod, "MismatchDerived2");
180 });
181
182 // test_override_static
183 // #511: problem with inheritance + overwritten def_static
184 struct MyBase {
185 static std::unique_ptr<MyBase> make() {
186 return std::unique_ptr<MyBase>(new MyBase());
187 }
188 };
189
190 struct MyDerived : MyBase {
191 static std::unique_ptr<MyDerived> make() {
192 return std::unique_ptr<MyDerived>(new MyDerived());
193 }
194 };
195
196 py::class_<MyBase>(m, "MyBase")
197 .def_static("make", &MyBase::make);
198
199 py::class_<MyDerived, MyBase>(m, "MyDerived")
200 .def_static("make", &MyDerived::make)
201 .def_static("make2", &MyDerived::make);
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200202
203 // test_implicit_conversion_life_support
204 struct ConvertibleFromUserType {
205 int i;
206
207 ConvertibleFromUserType(UserType u) : i(u.value()) { }
208 };
209
210 py::class_<ConvertibleFromUserType>(m, "AcceptsUserType")
211 .def(py::init<UserType>());
212 py::implicitly_convertible<UserType, ConvertibleFromUserType>();
213
214 m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
215 m.def("implicitly_convert_variable", [](py::object o) {
216 // `o` is `UserType` and `r` is a reference to a temporary created by implicit
217 // conversion. This is valid when called inside a bound function because the temp
218 // object is attached to the same life support system as the arguments.
219 const auto &r = o.cast<const ConvertibleFromUserType &>();
220 return r.i;
221 });
222 m.add_object("implicitly_convert_variable_fail", [&] {
223 auto f = [](PyObject *, PyObject *args) -> PyObject * {
224 auto o = py::reinterpret_borrow<py::tuple>(args)[0];
225 try { // It should fail here because there is no life support.
226 o.cast<const ConvertibleFromUserType &>();
227 } catch (const py::cast_error &e) {
228 return py::str(e.what()).release().ptr();
229 }
230 return py::str().release().ptr();
231 };
232
233 auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
234 return py::reinterpret_steal<py::object>(PyCFunction_NewEx(def, nullptr, m.ptr()));
235 }());
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400236
237 // test_operator_new_delete
238 struct HasOpNewDel {
239 std::uint64_t i;
240 static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); }
241 static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; }
242 static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); }
243 };
244 struct HasOpNewDelSize {
245 std::uint32_t i;
246 static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); }
247 static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; }
248 static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); }
249 };
250 struct AliasedHasOpNewDelSize {
251 std::uint64_t i;
252 static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); }
253 static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; }
254 static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); }
255 virtual ~AliasedHasOpNewDelSize() = default;
Henry Schreinere428a7f2020-07-23 21:16:54 -0400256 AliasedHasOpNewDelSize() = default;
257 AliasedHasOpNewDelSize(const AliasedHasOpNewDelSize&) = delete;
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400258 };
259 struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
260 PyAliasedHasOpNewDelSize() = default;
261 PyAliasedHasOpNewDelSize(int) { }
262 std::uint64_t j;
263 };
264 struct HasOpNewDelBoth {
265 std::uint32_t i[8];
266 static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); }
267 static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; }
268 static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); }
269 static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); }
270 };
271 py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
272 py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
273 py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
274 py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m, "AliasedHasOpNewDelSize");
275 aliased.def(py::init<>());
276 aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
277 aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
Jason Rhinelander7437c692017-07-28 22:03:44 -0400278
279 // This test is actually part of test_local_bindings (test_duplicate_local), but we need a
280 // definition in a different compilation unit within the same module:
281 bind_local<LocalExternal, 17>(m, "LocalExternal", py::module_local());
Dean Moldovan234f7c32017-08-17 17:03:46 +0200282
283 // test_bind_protected_functions
284 class ProtectedA {
285 protected:
286 int foo() const { return value; }
287
288 private:
289 int value = 42;
290 };
291
292 class PublicistA : public ProtectedA {
293 public:
294 using ProtectedA::foo;
295 };
296
297 py::class_<ProtectedA>(m, "ProtectedA")
298 .def(py::init<>())
299#if !defined(_MSC_VER) || _MSC_VER >= 1910
300 .def("foo", &PublicistA::foo);
301#else
302 .def("foo", static_cast<int (ProtectedA::*)() const>(&PublicistA::foo));
303#endif
304
305 class ProtectedB {
306 public:
307 virtual ~ProtectedB() = default;
Henry Schreinere428a7f2020-07-23 21:16:54 -0400308 ProtectedB() = default;
309 ProtectedB(const ProtectedB &) = delete;
Dean Moldovan234f7c32017-08-17 17:03:46 +0200310
311 protected:
312 virtual int foo() const { return value; }
313
314 private:
315 int value = 42;
316 };
317
318 class TrampolineB : public ProtectedB {
319 public:
320 int foo() const override { PYBIND11_OVERLOAD(int, ProtectedB, foo, ); }
321 };
322
323 class PublicistB : public ProtectedB {
324 public:
325 using ProtectedB::foo;
326 };
327
328 py::class_<ProtectedB, TrampolineB>(m, "ProtectedB")
329 .def(py::init<>())
330#if !defined(_MSC_VER) || _MSC_VER >= 1910
331 .def("foo", &PublicistB::foo);
332#else
333 .def("foo", static_cast<int (ProtectedB::*)() const>(&PublicistB::foo));
334#endif
Wenzel Jakob4336a7d2017-08-21 22:48:28 +0200335
336 // test_brace_initialization
337 struct BraceInitialization {
338 int field1;
339 std::string field2;
340 };
341
342 py::class_<BraceInitialization>(m, "BraceInitialization")
343 .def(py::init<int, const std::string &>())
344 .def_readwrite("field1", &BraceInitialization::field1)
345 .def_readwrite("field2", &BraceInitialization::field2);
Jason Rhinelanderadbc8112018-01-11 13:22:13 -0400346 // We *don't* want to construct using braces when the given constructor argument maps to a
347 // constructor, because brace initialization could go to the wrong place (in particular when
348 // there is also an `initializer_list<T>`-accept constructor):
349 py::class_<NoBraceInitialization>(m, "NoBraceInitialization")
350 .def(py::init<std::vector<int>>())
351 .def_readonly("vec", &NoBraceInitialization::vec);
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200352
353 // test_reentrant_implicit_conversion_failure
354 // #1035: issue with runaway reentrant implicit conversion
355 struct BogusImplicitConversion {
356 BogusImplicitConversion(const BogusImplicitConversion &) { }
357 };
358
359 py::class_<BogusImplicitConversion>(m, "BogusImplicitConversion")
360 .def(py::init<const BogusImplicitConversion &>());
361
362 py::implicitly_convertible<int, BogusImplicitConversion>();
Jason Rhinelander71178922017-11-07 12:33:05 -0400363
364 // test_qualname
365 // #1166: nested class docstring doesn't show nested name
366 // Also related: tests that __qualname__ is set properly
367 struct NestBase {};
368 struct Nested {};
369 py::class_<NestBase> base(m, "NestBase");
370 base.def(py::init<>());
371 py::class_<Nested>(base, "Nested")
372 .def(py::init<>())
373 .def("fn", [](Nested &, int, NestBase &, Nested &) {})
374 .def("fa", [](Nested &, int, NestBase &, Nested &) {},
375 "a"_a, "b"_a, "c"_a);
376 base.def("g", [](NestBase &, Nested &) {});
377 base.def("h", []() { return NestBase(); });
oremanje7761e32018-09-25 14:55:18 -0700378
379 // test_error_after_conversion
380 // The second-pass path through dispatcher() previously didn't
381 // remember which overload was used, and would crash trying to
382 // generate a useful error message
383
384 struct NotRegistered {};
385 struct StringWrapper { std::string str; };
386 m.def("test_error_after_conversions", [](int) {});
387 m.def("test_error_after_conversions",
388 [](StringWrapper) -> NotRegistered { return {}; });
389 py::class_<StringWrapper>(m, "StringWrapper").def(py::init<std::string>());
390 py::implicitly_convertible<std::string, StringWrapper>();
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +0100391
392 #if defined(PYBIND11_CPP17)
393 struct alignas(1024) Aligned {
394 std::uintptr_t ptr() const { return (uintptr_t) this; }
395 };
396 py::class_<Aligned>(m, "Aligned")
397 .def(py::init<>())
398 .def("ptr", &Aligned::ptr);
399 #endif
Dustin Spicuzza0dfffcf2020-04-05 02:34:00 -0400400
401 // test_final
402 struct IsFinal final {};
403 py::class_<IsFinal>(m, "IsFinal", py::is_final());
404
405 // test_non_final_final
406 struct IsNonFinalFinal {};
407 py::class_<IsNonFinalFinal>(m, "IsNonFinalFinal", py::is_final());
jbarlow834d90f1a2020-07-31 17:46:12 -0700408
409 struct PyPrintDestructor {
410 PyPrintDestructor() {}
411 ~PyPrintDestructor() {
412 py::print("Print from destructor");
413 }
414 void throw_something() { throw std::runtime_error("error"); }
415 };
416 py::class_<PyPrintDestructor>(m, "PyPrintDestructor")
417 .def(py::init<>())
418 .def("throw_something", &PyPrintDestructor::throw_something);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200419}
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400420
Henry Schreinere428a7f2020-07-23 21:16:54 -0400421template <int N> class BreaksBase { public:
422 virtual ~BreaksBase() = default;
423 BreaksBase() = default;
424 BreaksBase(const BreaksBase&) = delete;
425};
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400426template <int N> class BreaksTramp : public BreaksBase<N> {};
427// These should all compile just fine:
428typedef py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>> DoesntBreak1;
429typedef py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>> DoesntBreak2;
430typedef py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>> DoesntBreak3;
431typedef py::class_<BreaksBase<4>, BreaksTramp<4>> DoesntBreak4;
432typedef py::class_<BreaksBase<5>> DoesntBreak5;
433typedef py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>> DoesntBreak6;
434typedef py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>> DoesntBreak7;
435typedef py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>> DoesntBreak8;
436#define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
437 "DoesntBreak" #N " has wrong type!")
438CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
439#define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
440 "DoesntBreak" #N " has wrong type_alias!")
441#define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
442 "DoesntBreak" #N " has type alias, but shouldn't!")
443CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
444#define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
445 "DoesntBreak" #N " has wrong holder_type!")
446CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
447CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
448
449// There's no nice way to test that these fail because they fail to compile; leave them here,
450// though, so that they can be manually tested by uncommenting them (and seeing that compilation
451// failures occurs).
452
453// We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
454#define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
455 "Breaks1 has wrong type!");
456
457//// Two holder classes:
458//typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
459//CHECK_BROKEN(1);
460//// Two aliases:
461//typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
462//CHECK_BROKEN(2);
463//// Holder + 2 aliases
464//typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
465//CHECK_BROKEN(3);
466//// Alias + 2 holders
467//typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
468//CHECK_BROKEN(4);
469//// Invalid option (not a subclass or holder)
470//typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
471//CHECK_BROKEN(5);
472//// Invalid option: multiple inheritance not supported:
473//template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
474//typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
475//CHECK_BROKEN(8);