You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

377 lines
14 KiB

  1. /*
  2. tests/test_issues.cpp -- collection of testcases for miscellaneous issues
  3. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include "pybind11_tests.h"
  8. #include "constructor_stats.h"
  9. #include <pybind11/stl.h>
  10. #include <pybind11/operators.h>
  11. #include <pybind11/complex.h>
  12. #define TRACKERS(CLASS) CLASS() { print_default_created(this); } ~CLASS() { print_destroyed(this); }
  13. struct NestABase { int value = -2; TRACKERS(NestABase) };
  14. struct NestA : NestABase { int value = 3; NestA& operator+=(int i) { value += i; return *this; } TRACKERS(NestA) };
  15. struct NestB { NestA a; int value = 4; NestB& operator-=(int i) { value -= i; return *this; } TRACKERS(NestB) };
  16. struct NestC { NestB b; int value = 5; NestC& operator*=(int i) { value *= i; return *this; } TRACKERS(NestC) };
  17. /// #393
  18. class OpTest1 {};
  19. class OpTest2 {};
  20. OpTest1 operator+(const OpTest1 &, const OpTest1 &) {
  21. py::print("Add OpTest1 with OpTest1");
  22. return OpTest1();
  23. }
  24. OpTest2 operator+(const OpTest2 &, const OpTest2 &) {
  25. py::print("Add OpTest2 with OpTest2");
  26. return OpTest2();
  27. }
  28. OpTest2 operator+(const OpTest2 &, const OpTest1 &) {
  29. py::print("Add OpTest2 with OpTest1");
  30. return OpTest2();
  31. }
  32. // #461
  33. class Dupe1 {
  34. public:
  35. Dupe1(int v) : v_{v} {}
  36. int get_value() const { return v_; }
  37. private:
  38. int v_;
  39. };
  40. class Dupe2 {};
  41. class Dupe3 {};
  42. class DupeException : public std::runtime_error {};
  43. // #478
  44. template <typename T> class custom_unique_ptr {
  45. public:
  46. custom_unique_ptr() { print_default_created(this); }
  47. custom_unique_ptr(T *ptr) : _ptr{ptr} { print_created(this, ptr); }
  48. custom_unique_ptr(custom_unique_ptr<T> &&move) : _ptr{move._ptr} { move._ptr = nullptr; print_move_created(this); }
  49. 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; }
  50. custom_unique_ptr(const custom_unique_ptr<T> &) = delete;
  51. void operator=(const custom_unique_ptr<T> &copy) = delete;
  52. ~custom_unique_ptr() { print_destroyed(this); if (_ptr) destruct_ptr(); }
  53. private:
  54. T *_ptr = nullptr;
  55. void destruct_ptr() { delete _ptr; }
  56. };
  57. PYBIND11_DECLARE_HOLDER_TYPE(T, custom_unique_ptr<T>);
  58. void init_issues(py::module &m) {
  59. py::module m2 = m.def_submodule("issues");
  60. #if !defined(_MSC_VER)
  61. // Visual Studio 2015 currently cannot compile this test
  62. // (see the comment in type_caster_base::make_copy_constructor)
  63. // #70 compilation issue if operator new is not public
  64. class NonConstructible { private: void *operator new(size_t bytes) throw(); };
  65. py::class_<NonConstructible>(m, "Foo");
  66. m2.def("getstmt", []() -> NonConstructible * { return nullptr; },
  67. py::return_value_policy::reference);
  68. #endif
  69. // #137: const char* isn't handled properly
  70. m2.def("print_cchar", [](const char *s) { return std::string(s); });
  71. // #150: char bindings broken
  72. m2.def("print_char", [](char c) { return std::string(1, c); });
  73. // #159: virtual function dispatch has problems with similar-named functions
  74. struct Base { virtual std::string dispatch() const {
  75. /* for some reason MSVC2015 can't compile this if the function is pure virtual */
  76. return {};
  77. }; };
  78. struct DispatchIssue : Base {
  79. virtual std::string dispatch() const {
  80. PYBIND11_OVERLOAD_PURE(std::string, Base, dispatch, /* no arguments */);
  81. }
  82. };
  83. py::class_<Base, DispatchIssue>(m2, "DispatchIssue")
  84. .def(py::init<>())
  85. .def("dispatch", &Base::dispatch);
  86. m2.def("dispatch_issue_go", [](const Base * b) { return b->dispatch(); });
  87. struct Placeholder { int i; Placeholder(int i) : i(i) { } };
  88. py::class_<Placeholder>(m2, "Placeholder")
  89. .def(py::init<int>())
  90. .def("__repr__", [](const Placeholder &p) { return "Placeholder[" + std::to_string(p.i) + "]"; });
  91. // #171: Can't return reference wrappers (or STL datastructures containing them)
  92. m2.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<Placeholder> p4) {
  93. Placeholder *p1 = new Placeholder{1};
  94. Placeholder *p2 = new Placeholder{2};
  95. Placeholder *p3 = new Placeholder{3};
  96. std::vector<std::reference_wrapper<Placeholder>> v;
  97. v.push_back(std::ref(*p1));
  98. v.push_back(std::ref(*p2));
  99. v.push_back(std::ref(*p3));
  100. v.push_back(p4);
  101. return v;
  102. });
  103. // #181: iterator passthrough did not compile
  104. m2.def("iterator_passthrough", [](py::iterator s) -> py::iterator {
  105. return py::make_iterator(std::begin(s), std::end(s));
  106. });
  107. // #187: issue involving std::shared_ptr<> return value policy & garbage collection
  108. struct ElementBase { virtual void foo() { } /* Force creation of virtual table */ };
  109. struct ElementA : ElementBase {
  110. ElementA(int v) : v(v) { }
  111. int value() { return v; }
  112. int v;
  113. };
  114. struct ElementList {
  115. void add(std::shared_ptr<ElementBase> e) { l.push_back(e); }
  116. std::vector<std::shared_ptr<ElementBase>> l;
  117. };
  118. py::class_<ElementBase, std::shared_ptr<ElementBase>> (m2, "ElementBase");
  119. py::class_<ElementA, ElementBase, std::shared_ptr<ElementA>>(m2, "ElementA")
  120. .def(py::init<int>())
  121. .def("value", &ElementA::value);
  122. py::class_<ElementList, std::shared_ptr<ElementList>>(m2, "ElementList")
  123. .def(py::init<>())
  124. .def("add", &ElementList::add)
  125. .def("get", [](ElementList &el) {
  126. py::list list;
  127. for (auto &e : el.l)
  128. list.append(py::cast(e));
  129. return list;
  130. });
  131. // (no id): should not be able to pass 'None' to a reference argument
  132. m2.def("get_element", [](ElementA &el) { return el.value(); });
  133. // (no id): don't cast doubles to ints
  134. m2.def("expect_float", [](float f) { return f; });
  135. m2.def("expect_int", [](int i) { return i; });
  136. try {
  137. py::class_<Placeholder>(m2, "Placeholder");
  138. throw std::logic_error("Expected an exception!");
  139. } catch (std::runtime_error &) {
  140. /* All good */
  141. }
  142. // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid
  143. class StrIssue {
  144. public:
  145. StrIssue(int i) : val{i} {}
  146. StrIssue() : StrIssue(-1) {}
  147. int value() const { return val; }
  148. private:
  149. int val;
  150. };
  151. py::class_<StrIssue> si(m2, "StrIssue");
  152. si .def(py::init<int>())
  153. .def(py::init<>())
  154. .def("__str__", [](const StrIssue &si) { return "StrIssue[" + std::to_string(si.value()) + "]"; })
  155. ;
  156. // Issue #328: first member in a class can't be used in operators
  157. py::class_<NestABase>(m2, "NestABase").def(py::init<>()).def_readwrite("value", &NestABase::value);
  158. py::class_<NestA>(m2, "NestA").def(py::init<>()).def(py::self += int())
  159. .def("as_base", [](NestA &a) -> NestABase& { return (NestABase&) a; }, py::return_value_policy::reference_internal);
  160. py::class_<NestB>(m2, "NestB").def(py::init<>()).def(py::self -= int()).def_readwrite("a", &NestB::a);
  161. py::class_<NestC>(m2, "NestC").def(py::init<>()).def(py::self *= int()).def_readwrite("b", &NestC::b);
  162. m2.def("get_NestA", [](const NestA &a) { return a.value; });
  163. m2.def("get_NestB", [](const NestB &b) { return b.value; });
  164. m2.def("get_NestC", [](const NestC &c) { return c.value; });
  165. // Issue 389: r_v_p::move should fall-through to copy on non-movable objects
  166. class MoveIssue1 {
  167. public:
  168. MoveIssue1(int v) : v{v} {}
  169. MoveIssue1(const MoveIssue1 &c) { v = c.v; }
  170. MoveIssue1(MoveIssue1 &&) = delete;
  171. int v;
  172. };
  173. class MoveIssue2 {
  174. public:
  175. MoveIssue2(int v) : v{v} {}
  176. MoveIssue2(MoveIssue2 &&) = default;
  177. int v;
  178. };
  179. py::class_<MoveIssue1>(m2, "MoveIssue1").def(py::init<int>()).def_readwrite("value", &MoveIssue1::v);
  180. py::class_<MoveIssue2>(m2, "MoveIssue2").def(py::init<int>()).def_readwrite("value", &MoveIssue2::v);
  181. m2.def("get_moveissue1", [](int i) -> MoveIssue1 * { return new MoveIssue1(i); }, py::return_value_policy::move);
  182. m2.def("get_moveissue2", [](int i) { return MoveIssue2(i); }, py::return_value_policy::move);
  183. // Issues 392/397: overridding reference-returning functions
  184. class OverrideTest {
  185. public:
  186. struct A { std::string value = "hi"; };
  187. std::string v;
  188. A a;
  189. explicit OverrideTest(const std::string &v) : v{v} {}
  190. virtual std::string str_value() { return v; }
  191. virtual std::string &str_ref() { return v; }
  192. virtual A A_value() { return a; }
  193. virtual A &A_ref() { return a; }
  194. };
  195. class PyOverrideTest : public OverrideTest {
  196. public:
  197. using OverrideTest::OverrideTest;
  198. std::string str_value() override { PYBIND11_OVERLOAD(std::string, OverrideTest, str_value); }
  199. // Not allowed (uncommenting should hit a static_assert failure): we can't get a reference
  200. // to a python numeric value, since we only copy values in the numeric type caster:
  201. // std::string &str_ref() override { PYBIND11_OVERLOAD(std::string &, OverrideTest, str_ref); }
  202. // But we can work around it like this:
  203. private:
  204. std::string _tmp;
  205. std::string str_ref_helper() { PYBIND11_OVERLOAD(std::string, OverrideTest, str_ref); }
  206. public:
  207. std::string &str_ref() override { return _tmp = str_ref_helper(); }
  208. A A_value() override { PYBIND11_OVERLOAD(A, OverrideTest, A_value); }
  209. A &A_ref() override { PYBIND11_OVERLOAD(A &, OverrideTest, A_ref); }
  210. };
  211. py::class_<OverrideTest::A>(m2, "OverrideTest_A")
  212. .def_readwrite("value", &OverrideTest::A::value);
  213. py::class_<OverrideTest, PyOverrideTest>(m2, "OverrideTest")
  214. .def(py::init<const std::string &>())
  215. .def("str_value", &OverrideTest::str_value)
  216. // .def("str_ref", &OverrideTest::str_ref)
  217. .def("A_value", &OverrideTest::A_value)
  218. .def("A_ref", &OverrideTest::A_ref);
  219. /// Issue 393: need to return NotSupported to ensure correct arithmetic operator behavior
  220. py::class_<OpTest1>(m2, "OpTest1")
  221. .def(py::init<>())
  222. .def(py::self + py::self);
  223. py::class_<OpTest2>(m2, "OpTest2")
  224. .def(py::init<>())
  225. .def(py::self + py::self)
  226. .def("__add__", [](const OpTest2& c2, const OpTest1& c1) { return c2 + c1; })
  227. .def("__radd__", [](const OpTest2& c2, const OpTest1& c1) { return c2 + c1; });
  228. // Issue 388: Can't make iterators via make_iterator() with different r/v policies
  229. static std::vector<int> list = { 1, 2, 3 };
  230. m2.def("make_iterator_1", []() { return py::make_iterator<py::return_value_policy::copy>(list); });
  231. m2.def("make_iterator_2", []() { return py::make_iterator<py::return_value_policy::automatic>(list); });
  232. static std::vector<std::string> nothrows;
  233. // Issue 461: registering two things with the same name:
  234. py::class_<Dupe1>(m2, "Dupe1")
  235. .def("get_value", &Dupe1::get_value)
  236. ;
  237. m2.def("dupe1_factory", [](int v) { return new Dupe1(v); });
  238. py::class_<Dupe2>(m2, "Dupe2");
  239. py::exception<DupeException>(m2, "DupeException");
  240. try {
  241. m2.def("Dupe1", [](int v) { return new Dupe1(v); });
  242. nothrows.emplace_back("Dupe1");
  243. }
  244. catch (std::runtime_error &) {}
  245. try {
  246. py::class_<Dupe3>(m2, "dupe1_factory");
  247. nothrows.emplace_back("dupe1_factory");
  248. }
  249. catch (std::runtime_error &) {}
  250. try {
  251. py::exception<Dupe3>(m2, "Dupe2");
  252. nothrows.emplace_back("Dupe2");
  253. }
  254. catch (std::runtime_error &) {}
  255. try {
  256. m2.def("DupeException", []() { return 30; });
  257. nothrows.emplace_back("DupeException1");
  258. }
  259. catch (std::runtime_error &) {}
  260. try {
  261. py::class_<DupeException>(m2, "DupeException");
  262. nothrows.emplace_back("DupeException2");
  263. }
  264. catch (std::runtime_error &) {}
  265. m2.def("dupe_exception_failures", []() {
  266. py::list l;
  267. for (auto &e : nothrows) l.append(py::cast(e));
  268. return l;
  269. });
  270. /// Issue #471: shared pointer instance not dellocated
  271. class SharedChild : public std::enable_shared_from_this<SharedChild> {
  272. public:
  273. SharedChild() { print_created(this); }
  274. ~SharedChild() { print_destroyed(this); }
  275. };
  276. class SharedParent {
  277. public:
  278. SharedParent() : child(std::make_shared<SharedChild>()) { }
  279. const SharedChild &get_child() const { return *child; }
  280. private:
  281. std::shared_ptr<SharedChild> child;
  282. };
  283. py::class_<SharedChild, std::shared_ptr<SharedChild>>(m, "SharedChild");
  284. py::class_<SharedParent, std::shared_ptr<SharedParent>>(m, "SharedParent")
  285. .def(py::init<>())
  286. .def("get_child", &SharedParent::get_child, py::return_value_policy::reference);
  287. /// Issue/PR #478: unique ptrs constructed and freed without destruction
  288. class SpecialHolderObj {
  289. public:
  290. int val = 0;
  291. SpecialHolderObj *ch = nullptr;
  292. SpecialHolderObj(int v, bool make_child = true) : val{v}, ch{make_child ? new SpecialHolderObj(val+1, false) : nullptr}
  293. { print_created(this, val); }
  294. ~SpecialHolderObj() { delete ch; print_destroyed(this); }
  295. SpecialHolderObj *child() { return ch; }
  296. };
  297. py::class_<SpecialHolderObj, custom_unique_ptr<SpecialHolderObj>>(m, "SpecialHolderObj")
  298. .def(py::init<int>())
  299. .def("child", &SpecialHolderObj::child, pybind11::return_value_policy::reference_internal)
  300. .def_readwrite("val", &SpecialHolderObj::val)
  301. .def_static("holder_cstats", &ConstructorStats::get<custom_unique_ptr<SpecialHolderObj>>,
  302. py::return_value_policy::reference);
  303. /// Issue #484: number conversion generates unhandled exceptions
  304. m2.def("test_complex", [](float x) { py::print("{}"_s.format(x)); });
  305. m2.def("test_complex", [](std::complex<float> x) { py::print("({}, {})"_s.format(x.real(), x.imag())); });
  306. /// Issue #511: problem with inheritance + overwritten def_static
  307. struct MyBase {
  308. static std::unique_ptr<MyBase> make() {
  309. return std::unique_ptr<MyBase>(new MyBase());
  310. }
  311. };
  312. struct MyDerived : MyBase {
  313. static std::unique_ptr<MyDerived> make() {
  314. return std::unique_ptr<MyDerived>(new MyDerived());
  315. }
  316. };
  317. py::class_<MyBase>(m2, "MyBase")
  318. .def_static("make", &MyBase::make);
  319. py::class_<MyDerived, MyBase>(m2, "MyDerived")
  320. .def_static("make", &MyDerived::make)
  321. .def_static("make2", &MyDerived::make);
  322. }
  323. // MSVC workaround: trying to use a lambda here crashes MSCV
  324. test_initializer issues(&init_issues);