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.

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