blob: 33f8a43af56e05bef2a7005859733b4714bef018 [file] [log] [blame]
Wenzel Jakob17cdb062016-03-10 13:24:10 +01001/*
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02002 tests/test_issues.cpp -- collection of testcases for miscellaneous issues
Wenzel Jakob17cdb062016-03-10 13:24:10 +01003
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02004 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob17cdb062016-03-10 13:24:10 +01005
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
Dean Moldovana0c1ccf2016-08-12 13:50:00 +020010#include "pybind11_tests.h"
11#include "constructor_stats.h"
Wenzel Jakobf54ded72016-04-20 17:00:57 +020012#include <pybind11/stl.h>
Jason Rhinelander1b05ce52016-08-09 17:57:59 -040013#include <pybind11/operators.h>
Wenzel Jakobfe40dfe2016-11-07 15:59:01 +010014#include <pybind11/complex.h>
Wenzel Jakobd2b628b2016-04-30 23:02:39 +020015
Jason Rhinelander3f589372016-08-07 13:05:26 -040016#define TRACKERS(CLASS) CLASS() { print_default_created(this); } ~CLASS() { print_destroyed(this); }
17struct NestABase { int value = -2; TRACKERS(NestABase) };
18struct NestA : NestABase { int value = 3; NestA& operator+=(int i) { value += i; return *this; } TRACKERS(NestA) };
19struct NestB { NestA a; int value = 4; NestB& operator-=(int i) { value -= i; return *this; } TRACKERS(NestB) };
20struct NestC { NestB b; int value = 5; NestC& operator*=(int i) { value *= i; return *this; } TRACKERS(NestC) };
21
Wenzel Jakob382484a2016-09-10 15:28:37 +090022/// #393
23class OpTest1 {};
24class OpTest2 {};
25
26OpTest1 operator+(const OpTest1 &, const OpTest1 &) {
27 py::print("Add OpTest1 with OpTest1");
28 return OpTest1();
29}
30OpTest2 operator+(const OpTest2 &, const OpTest2 &) {
31 py::print("Add OpTest2 with OpTest2");
32 return OpTest2();
33}
34OpTest2 operator+(const OpTest2 &, const OpTest1 &) {
35 py::print("Add OpTest2 with OpTest1");
36 return OpTest2();
37}
38
Jason Rhinelander6873c202016-10-24 21:58:22 -040039// #461
40class Dupe1 {
41public:
42 Dupe1(int v) : v_{v} {}
43 int get_value() const { return v_; }
44private:
45 int v_;
46};
47class Dupe2 {};
48class Dupe3 {};
49class DupeException : public std::runtime_error {};
50
Jason Rhinelanderc07ec312016-11-06 13:12:48 -050051// #478
52template <typename T> class custom_unique_ptr {
53public:
54 custom_unique_ptr() { print_default_created(this); }
55 custom_unique_ptr(T *ptr) : _ptr{ptr} { print_created(this, ptr); }
56 custom_unique_ptr(custom_unique_ptr<T> &&move) : _ptr{move._ptr} { move._ptr = nullptr; print_move_created(this); }
57 custom_unique_ptr &operator=(custom_unique_ptr<T> &&move) { print_move_assigned(this); if (_ptr) destruct_ptr(); _ptr = move._ptr; move._ptr = nullptr; return *this; }
58 custom_unique_ptr(const custom_unique_ptr<T> &) = delete;
59 void operator=(const custom_unique_ptr<T> &copy) = delete;
60 ~custom_unique_ptr() { print_destroyed(this); if (_ptr) destruct_ptr(); }
61private:
62 T *_ptr = nullptr;
63 void destruct_ptr() { delete _ptr; }
64};
65PYBIND11_DECLARE_HOLDER_TYPE(T, custom_unique_ptr<T>);
66
67
68
Wenzel Jakob17cdb062016-03-10 13:24:10 +010069void init_issues(py::module &m) {
70 py::module m2 = m.def_submodule("issues");
71
Wenzel Jakob9059bd82016-05-01 10:39:45 +020072#if !defined(_MSC_VER)
73 // Visual Studio 2015 currently cannot compile this test
74 // (see the comment in type_caster_base::make_copy_constructor)
75 // #70 compilation issue if operator new is not public
76 class NonConstructible { private: void *operator new(size_t bytes) throw(); };
77 py::class_<NonConstructible>(m, "Foo");
Wenzel Jakobbd57eb42016-05-01 14:42:20 +020078 m2.def("getstmt", []() -> NonConstructible * { return nullptr; },
Wenzel Jakob9059bd82016-05-01 10:39:45 +020079 py::return_value_policy::reference);
80#endif
81
Wenzel Jakob17cdb062016-03-10 13:24:10 +010082 // #137: const char* isn't handled properly
Dean Moldovan665e8802016-08-12 22:28:31 +020083 m2.def("print_cchar", [](const char *s) { return std::string(s); });
Wenzel Jakobd3349af2016-03-26 23:04:10 +010084
85 // #150: char bindings broken
Dean Moldovan665e8802016-08-12 22:28:31 +020086 m2.def("print_char", [](char c) { return std::string(1, c); });
Wenzel Jakobf5c154a2016-04-11 18:13:08 +020087
88 // #159: virtual function dispatch has problems with similar-named functions
Dean Moldovan665e8802016-08-12 22:28:31 +020089 struct Base { virtual std::string dispatch() const {
Wenzel Jakobd2b628b2016-04-30 23:02:39 +020090 /* for some reason MSVC2015 can't compile this if the function is pure virtual */
Dean Moldovan665e8802016-08-12 22:28:31 +020091 return {};
Wenzel Jakobd2b628b2016-04-30 23:02:39 +020092 }; };
Wenzel Jakobe7074972016-04-30 22:44:00 +020093
94 struct DispatchIssue : Base {
Dean Moldovan665e8802016-08-12 22:28:31 +020095 virtual std::string dispatch() const {
96 PYBIND11_OVERLOAD_PURE(std::string, Base, dispatch, /* no arguments */);
Wenzel Jakobe7074972016-04-30 22:44:00 +020097 }
98 };
99
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400100 py::class_<Base, DispatchIssue>(m2, "DispatchIssue")
Wenzel Jakobf54ded72016-04-20 17:00:57 +0200101 .def(py::init<>())
Wenzel Jakobf5c154a2016-04-11 18:13:08 +0200102 .def("dispatch", &Base::dispatch);
103
Dean Moldovan665e8802016-08-12 22:28:31 +0200104 m2.def("dispatch_issue_go", [](const Base * b) { return b->dispatch(); });
Wenzel Jakobe7074972016-04-30 22:44:00 +0200105
106 struct Placeholder { int i; Placeholder(int i) : i(i) { } };
Wenzel Jakobf54ded72016-04-20 17:00:57 +0200107
108 py::class_<Placeholder>(m2, "Placeholder")
Wenzel Jakobdbe43ff2016-04-21 12:21:14 +0200109 .def(py::init<int>())
Wenzel Jakobf54ded72016-04-20 17:00:57 +0200110 .def("__repr__", [](const Placeholder &p) { return "Placeholder[" + std::to_string(p.i) + "]"; });
111
112 // #171: Can't return reference wrappers (or STL datastructures containing them)
Wenzel Jakob85f07e12016-09-04 23:00:49 +0900113 m2.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<Placeholder> p4) {
Wenzel Jakobf54ded72016-04-20 17:00:57 +0200114 Placeholder *p1 = new Placeholder{1};
115 Placeholder *p2 = new Placeholder{2};
Wenzel Jakobdbe43ff2016-04-21 12:21:14 +0200116 Placeholder *p3 = new Placeholder{3};
Wenzel Jakobf54ded72016-04-20 17:00:57 +0200117 std::vector<std::reference_wrapper<Placeholder>> v;
118 v.push_back(std::ref(*p1));
119 v.push_back(std::ref(*p2));
120 v.push_back(std::ref(*p3));
Wenzel Jakobdbe43ff2016-04-21 12:21:14 +0200121 v.push_back(p4);
Wenzel Jakobf54ded72016-04-20 17:00:57 +0200122 return v;
123 });
Wenzel Jakob6ca6e822016-04-27 14:33:52 +0200124
125 // #181: iterator passthrough did not compile
126 m2.def("iterator_passthrough", [](py::iterator s) -> py::iterator {
127 return py::make_iterator(std::begin(s), std::end(s));
128 });
Wenzel Jakobd2b628b2016-04-30 23:02:39 +0200129
130 // #187: issue involving std::shared_ptr<> return value policy & garbage collection
131 struct ElementBase { virtual void foo() { } /* Force creation of virtual table */ };
132 struct ElementA : ElementBase {
133 ElementA(int v) : v(v) { }
134 int value() { return v; }
135 int v;
136 };
137
138 struct ElementList {
139 void add(std::shared_ptr<ElementBase> e) { l.push_back(e); }
140 std::vector<std::shared_ptr<ElementBase>> l;
141 };
142
143 py::class_<ElementBase, std::shared_ptr<ElementBase>> (m2, "ElementBase");
144
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400145 py::class_<ElementA, ElementBase, std::shared_ptr<ElementA>>(m2, "ElementA")
Wenzel Jakobd2b628b2016-04-30 23:02:39 +0200146 .def(py::init<int>())
147 .def("value", &ElementA::value);
148
149 py::class_<ElementList, std::shared_ptr<ElementList>>(m2, "ElementList")
150 .def(py::init<>())
151 .def("add", &ElementList::add)
Wenzel Jakob85f07e12016-09-04 23:00:49 +0900152 .def("get", [](ElementList &el) {
Wenzel Jakobd2b628b2016-04-30 23:02:39 +0200153 py::list list;
154 for (auto &e : el.l)
155 list.append(py::cast(e));
156 return list;
157 });
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200158
159 // (no id): should not be able to pass 'None' to a reference argument
Dean Moldovan99dbdc12016-08-19 13:45:36 +0200160 m2.def("get_element", [](ElementA &el) { return el.value(); });
Wenzel Jakob3f200fa2016-05-17 15:35:29 +0200161
162 // (no id): don't cast doubles to ints
163 m2.def("expect_float", [](float f) { return f; });
164 m2.def("expect_int", [](int i) { return i; });
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200165
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200166 try {
167 py::class_<Placeholder>(m2, "Placeholder");
168 throw std::logic_error("Expected an exception!");
Dean Moldovanf2b36c22016-06-01 23:03:10 +0200169 } catch (std::runtime_error &) {
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200170 /* All good */
171 }
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400172
173 // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid
174 class StrIssue {
175 public:
176 StrIssue(int i) : val{i} {}
177 StrIssue() : StrIssue(-1) {}
178 int value() const { return val; }
179 private:
180 int val;
181 };
182 py::class_<StrIssue> si(m2, "StrIssue");
183 si .def(py::init<int>())
184 .def(py::init<>())
Dean Moldovan99dbdc12016-08-19 13:45:36 +0200185 .def("__str__", [](const StrIssue &si) { return "StrIssue[" + std::to_string(si.value()) + "]"; })
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400186 ;
187
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400188 // Issue #328: first member in a class can't be used in operators
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -0400189 py::class_<NestABase>(m2, "NestABase").def(py::init<>()).def_readwrite("value", &NestABase::value);
190 py::class_<NestA>(m2, "NestA").def(py::init<>()).def(py::self += int())
191 .def("as_base", [](NestA &a) -> NestABase& { return (NestABase&) a; }, py::return_value_policy::reference_internal);
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400192 py::class_<NestB>(m2, "NestB").def(py::init<>()).def(py::self -= int()).def_readwrite("a", &NestB::a);
193 py::class_<NestC>(m2, "NestC").def(py::init<>()).def(py::self *= int()).def_readwrite("b", &NestC::b);
Dean Moldovan665e8802016-08-12 22:28:31 +0200194 m2.def("get_NestA", [](const NestA &a) { return a.value; });
195 m2.def("get_NestB", [](const NestB &b) { return b.value; });
196 m2.def("get_NestC", [](const NestC &c) { return c.value; });
Wenzel Jakobc84b37b2016-09-07 00:47:17 +0900197
198 // Issue 389: r_v_p::move should fall-through to copy on non-movable objects
199 class MoveIssue1 {
200 public:
201 MoveIssue1(int v) : v{v} {}
Dean Moldovan81511be2016-09-07 00:50:10 +0200202 MoveIssue1(const MoveIssue1 &c) { v = c.v; }
Wenzel Jakobc84b37b2016-09-07 00:47:17 +0900203 MoveIssue1(MoveIssue1 &&) = delete;
204 int v;
205 };
206 class MoveIssue2 {
207 public:
208 MoveIssue2(int v) : v{v} {}
209 MoveIssue2(MoveIssue2 &&) = default;
210 int v;
211 };
212 py::class_<MoveIssue1>(m2, "MoveIssue1").def(py::init<int>()).def_readwrite("value", &MoveIssue1::v);
213 py::class_<MoveIssue2>(m2, "MoveIssue2").def(py::init<int>()).def_readwrite("value", &MoveIssue2::v);
214 m2.def("get_moveissue1", [](int i) -> MoveIssue1 * { return new MoveIssue1(i); }, py::return_value_policy::move);
215 m2.def("get_moveissue2", [](int i) { return MoveIssue2(i); }, py::return_value_policy::move);
Jason Rhinelander56f71772016-09-07 13:32:49 -0400216
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400217 // Issues 392/397: overridding reference-returning functions
Jason Rhinelander56f71772016-09-07 13:32:49 -0400218 class OverrideTest {
219 public:
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400220 struct A { std::string value = "hi"; };
221 std::string v;
Jason Rhinelander56f71772016-09-07 13:32:49 -0400222 A a;
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400223 explicit OverrideTest(const std::string &v) : v{v} {}
224 virtual std::string str_value() { return v; }
225 virtual std::string &str_ref() { return v; }
Jason Rhinelander56f71772016-09-07 13:32:49 -0400226 virtual A A_value() { return a; }
227 virtual A &A_ref() { return a; }
228 };
229 class PyOverrideTest : public OverrideTest {
230 public:
231 using OverrideTest::OverrideTest;
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400232 std::string str_value() override { PYBIND11_OVERLOAD(std::string, OverrideTest, str_value); }
Jason Rhinelanderc03db9b2016-09-07 13:38:32 -0400233 // Not allowed (uncommenting should hit a static_assert failure): we can't get a reference
234 // to a python numeric value, since we only copy values in the numeric type caster:
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400235// std::string &str_ref() override { PYBIND11_OVERLOAD(std::string &, OverrideTest, str_ref); }
236 // But we can work around it like this:
237 private:
238 std::string _tmp;
239 std::string str_ref_helper() { PYBIND11_OVERLOAD(std::string, OverrideTest, str_ref); }
240 public:
241 std::string &str_ref() override { return _tmp = str_ref_helper(); }
242
Jason Rhinelander56f71772016-09-07 13:32:49 -0400243 A A_value() override { PYBIND11_OVERLOAD(A, OverrideTest, A_value); }
244 A &A_ref() override { PYBIND11_OVERLOAD(A &, OverrideTest, A_ref); }
245 };
246 py::class_<OverrideTest::A>(m2, "OverrideTest_A")
247 .def_readwrite("value", &OverrideTest::A::value);
248 py::class_<OverrideTest, PyOverrideTest>(m2, "OverrideTest")
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400249 .def(py::init<const std::string &>())
250 .def("str_value", &OverrideTest::str_value)
251// .def("str_ref", &OverrideTest::str_ref)
Jason Rhinelander56f71772016-09-07 13:32:49 -0400252 .def("A_value", &OverrideTest::A_value)
253 .def("A_ref", &OverrideTest::A_ref);
Jason Rhinelanderc03db9b2016-09-07 13:38:32 -0400254
Wenzel Jakob382484a2016-09-10 15:28:37 +0900255 /// Issue 393: need to return NotSupported to ensure correct arithmetic operator behavior
256 py::class_<OpTest1>(m2, "OpTest1")
257 .def(py::init<>())
258 .def(py::self + py::self);
259
260 py::class_<OpTest2>(m2, "OpTest2")
261 .def(py::init<>())
262 .def(py::self + py::self)
263 .def("__add__", [](const OpTest2& c2, const OpTest1& c1) { return c2 + c1; })
264 .def("__radd__", [](const OpTest2& c2, const OpTest1& c1) { return c2 + c1; });
Wenzel Jakobb212f6c2016-09-10 16:00:50 +0900265
266 // Issue 388: Can't make iterators via make_iterator() with different r/v policies
267 static std::vector<int> list = { 1, 2, 3 };
268 m2.def("make_iterator_1", []() { return py::make_iterator<py::return_value_policy::copy>(list); });
269 m2.def("make_iterator_2", []() { return py::make_iterator<py::return_value_policy::automatic>(list); });
Jason Rhinelander6873c202016-10-24 21:58:22 -0400270
271 static std::vector<std::string> nothrows;
272 // Issue 461: registering two things with the same name:
273 py::class_<Dupe1>(m2, "Dupe1")
274 .def("get_value", &Dupe1::get_value)
275 ;
276 m2.def("dupe1_factory", [](int v) { return new Dupe1(v); });
277
278 py::class_<Dupe2>(m2, "Dupe2");
279 py::exception<DupeException>(m2, "DupeException");
280
281 try {
282 m2.def("Dupe1", [](int v) { return new Dupe1(v); });
283 nothrows.emplace_back("Dupe1");
284 }
285 catch (std::runtime_error &) {}
286 try {
287 py::class_<Dupe3>(m2, "dupe1_factory");
288 nothrows.emplace_back("dupe1_factory");
289 }
290 catch (std::runtime_error &) {}
291 try {
292 py::exception<Dupe3>(m2, "Dupe2");
293 nothrows.emplace_back("Dupe2");
294 }
295 catch (std::runtime_error &) {}
296 try {
297 m2.def("DupeException", []() { return 30; });
298 nothrows.emplace_back("DupeException1");
299 }
300 catch (std::runtime_error &) {}
301 try {
302 py::class_<DupeException>(m2, "DupeException");
303 nothrows.emplace_back("DupeException2");
304 }
305 catch (std::runtime_error &) {}
306 m2.def("dupe_exception_failures", []() {
307 py::list l;
308 for (auto &e : nothrows) l.append(py::cast(e));
309 return l;
310 });
Wenzel Jakobbd560ac2016-11-03 11:53:35 +0100311
312 /// Issue #471: shared pointer instance not dellocated
313 class SharedChild : public std::enable_shared_from_this<SharedChild> {
314 public:
315 SharedChild() { print_created(this); }
316 ~SharedChild() { print_destroyed(this); }
317 };
318
319 class SharedParent {
320 public:
321 SharedParent() : child(std::make_shared<SharedChild>()) { }
322 const SharedChild &get_child() const { return *child; }
323
324 private:
325 std::shared_ptr<SharedChild> child;
326 };
327
328 py::class_<SharedChild, std::shared_ptr<SharedChild>>(m, "SharedChild");
329 py::class_<SharedParent, std::shared_ptr<SharedParent>>(m, "SharedParent")
330 .def(py::init<>())
331 .def("get_child", &SharedParent::get_child, py::return_value_policy::reference);
Jason Rhinelanderc07ec312016-11-06 13:12:48 -0500332
333 /// Issue/PR #478: unique ptrs constructed and freed without destruction
334 class SpecialHolderObj {
335 public:
336 int val = 0;
337 SpecialHolderObj *ch = nullptr;
338 SpecialHolderObj(int v, bool make_child = true) : val{v}, ch{make_child ? new SpecialHolderObj(val+1, false) : nullptr}
339 { print_created(this, val); }
340 ~SpecialHolderObj() { delete ch; print_destroyed(this); }
341 SpecialHolderObj *child() { return ch; }
342 };
343
344 py::class_<SpecialHolderObj, custom_unique_ptr<SpecialHolderObj>>(m, "SpecialHolderObj")
345 .def(py::init<int>())
346 .def("child", &SpecialHolderObj::child, pybind11::return_value_policy::reference_internal)
347 .def_readwrite("val", &SpecialHolderObj::val)
348 .def_static("holder_cstats", &ConstructorStats::get<custom_unique_ptr<SpecialHolderObj>>,
Wenzel Jakobfe40dfe2016-11-07 15:59:01 +0100349 py::return_value_policy::reference);
Jason Rhinelander52f4be82016-09-03 14:54:22 -0400350
Wenzel Jakobfe40dfe2016-11-07 15:59:01 +0100351 /// Issue #484: number conversion generates unhandled exceptions
352 m2.def("test_complex", [](float x) { py::print("{}"_s.format(x)); });
353 m2.def("test_complex", [](std::complex<float> x) { py::print("({}, {})"_s.format(x.real(), x.imag())); });
Wenzel Jakob7c2461e2016-11-20 05:26:02 +0100354
355 /// Issue #511: problem with inheritance + overwritten def_static
356 struct MyBase {
357 static std::unique_ptr<MyBase> make() {
358 return std::unique_ptr<MyBase>(new MyBase());
359 }
360 };
361
362 struct MyDerived : MyBase {
363 static std::unique_ptr<MyDerived> make() {
364 return std::unique_ptr<MyDerived>(new MyDerived());
365 }
366 };
367
368 py::class_<MyBase>(m2, "MyBase")
369 .def_static("make", &MyBase::make);
370
371 py::class_<MyDerived, MyBase>(m2, "MyDerived")
372 .def_static("make", &MyDerived::make)
373 .def_static("make2", &MyDerived::make);
Wenzel Jakobfe40dfe2016-11-07 15:59:01 +0100374}
Jason Rhinelander6873c202016-10-24 21:58:22 -0400375
Jason Rhinelander52f4be82016-09-03 14:54:22 -0400376// MSVC workaround: trying to use a lambda here crashes MSCV
377test_initializer issues(&init_issues);