blob: 4e0dd6237fd23a00c32371d589d4080ceea9fa53 [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 Moldovan83e328f2017-06-09 00:44:49 +0200153}
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400154
155template <int N> class BreaksBase {};
156template <int N> class BreaksTramp : public BreaksBase<N> {};
157// These should all compile just fine:
158typedef py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>> DoesntBreak1;
159typedef py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>> DoesntBreak2;
160typedef py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>> DoesntBreak3;
161typedef py::class_<BreaksBase<4>, BreaksTramp<4>> DoesntBreak4;
162typedef py::class_<BreaksBase<5>> DoesntBreak5;
163typedef py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>> DoesntBreak6;
164typedef py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>> DoesntBreak7;
165typedef py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>> DoesntBreak8;
166#define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
167 "DoesntBreak" #N " has wrong type!")
168CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
169#define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
170 "DoesntBreak" #N " has wrong type_alias!")
171#define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
172 "DoesntBreak" #N " has type alias, but shouldn't!")
173CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
174#define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
175 "DoesntBreak" #N " has wrong holder_type!")
176CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
177CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
178
179// There's no nice way to test that these fail because they fail to compile; leave them here,
180// though, so that they can be manually tested by uncommenting them (and seeing that compilation
181// failures occurs).
182
183// We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
184#define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
185 "Breaks1 has wrong type!");
186
187//// Two holder classes:
188//typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
189//CHECK_BROKEN(1);
190//// Two aliases:
191//typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
192//CHECK_BROKEN(2);
193//// Holder + 2 aliases
194//typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
195//CHECK_BROKEN(3);
196//// Alias + 2 holders
197//typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
198//CHECK_BROKEN(4);
199//// Invalid option (not a subclass or holder)
200//typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
201//CHECK_BROKEN(5);
202//// Invalid option: multiple inheritance not supported:
203//template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
204//typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
205//CHECK_BROKEN(8);