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