test_callbacks.cpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. /*
  2. tests/test_callbacks.cpp -- callbacks
  3. Copyright (c) 2016 Wenzel Jakob <[email protected]>
  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/functional.h>
  10. int dummy_function(int i) { return i + 1; }
  11. TEST_SUBMODULE(callbacks, m) {
  12. // test_callbacks, test_function_signatures
  13. m.def("test_callback1", [](py::object func) { return func(); });
  14. m.def("test_callback2", [](py::object func) { return func("Hello", 'x', true, 5); });
  15. m.def("test_callback3", [](const std::function<int(int)> &func) {
  16. return "func(43) = " + std::to_string(func(43)); });
  17. m.def("test_callback4", []() -> std::function<int(int)> { return [](int i) { return i+1; }; });
  18. m.def("test_callback5", []() {
  19. return py::cpp_function([](int i) { return i+1; }, py::arg("number"));
  20. });
  21. // test_keyword_args_and_generalized_unpacking
  22. m.def("test_tuple_unpacking", [](py::function f) {
  23. auto t1 = py::make_tuple(2, 3);
  24. auto t2 = py::make_tuple(5, 6);
  25. return f("positional", 1, *t1, 4, *t2);
  26. });
  27. m.def("test_dict_unpacking", [](py::function f) {
  28. auto d1 = py::dict("key"_a="value", "a"_a=1);
  29. auto d2 = py::dict();
  30. auto d3 = py::dict("b"_a=2);
  31. return f("positional", 1, **d1, **d2, **d3);
  32. });
  33. m.def("test_keyword_args", [](py::function f) {
  34. return f("x"_a=10, "y"_a=20);
  35. });
  36. m.def("test_unpacking_and_keywords1", [](py::function f) {
  37. auto args = py::make_tuple(2);
  38. auto kwargs = py::dict("d"_a=4);
  39. return f(1, *args, "c"_a=3, **kwargs);
  40. });
  41. m.def("test_unpacking_and_keywords2", [](py::function f) {
  42. auto kwargs1 = py::dict("a"_a=1);
  43. auto kwargs2 = py::dict("c"_a=3, "d"_a=4);
  44. return f("positional", *py::make_tuple(1), 2, *py::make_tuple(3, 4), 5,
  45. "key"_a="value", **kwargs1, "b"_a=2, **kwargs2, "e"_a=5);
  46. });
  47. m.def("test_unpacking_error1", [](py::function f) {
  48. auto kwargs = py::dict("x"_a=3);
  49. return f("x"_a=1, "y"_a=2, **kwargs); // duplicate ** after keyword
  50. });
  51. m.def("test_unpacking_error2", [](py::function f) {
  52. auto kwargs = py::dict("x"_a=3);
  53. return f(**kwargs, "x"_a=1); // duplicate keyword after **
  54. });
  55. m.def("test_arg_conversion_error1", [](py::function f) {
  56. f(234, UnregisteredType(), "kw"_a=567);
  57. });
  58. m.def("test_arg_conversion_error2", [](py::function f) {
  59. f(234, "expected_name"_a=UnregisteredType(), "kw"_a=567);
  60. });
  61. // test_lambda_closure_cleanup
  62. struct Payload {
  63. Payload() { print_default_created(this); }
  64. ~Payload() { print_destroyed(this); }
  65. Payload(const Payload &) { print_copy_created(this); }
  66. Payload(Payload &&) { print_move_created(this); }
  67. };
  68. // Export the payload constructor statistics for testing purposes:
  69. m.def("payload_cstats", &ConstructorStats::get<Payload>);
  70. /* Test cleanup of lambda closure */
  71. m.def("test_cleanup", []() -> std::function<void(void)> {
  72. Payload p;
  73. return [p]() {
  74. /* p should be cleaned up when the returned function is garbage collected */
  75. (void) p;
  76. };
  77. });
  78. // test_cpp_function_roundtrip
  79. /* Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer */
  80. m.def("dummy_function", &dummy_function);
  81. m.def("dummy_function2", [](int i, int j) { return i + j; });
  82. m.def("roundtrip", [](std::function<int(int)> f, bool expect_none = false) {
  83. if (expect_none && f)
  84. throw std::runtime_error("Expected None to be converted to empty std::function");
  85. return f;
  86. }, py::arg("f"), py::arg("expect_none")=false);
  87. m.def("test_dummy_function", [](const std::function<int(int)> &f) -> std::string {
  88. using fn_type = int (*)(int);
  89. auto result = f.target<fn_type>();
  90. if (!result) {
  91. auto r = f(1);
  92. return "can't convert to function pointer: eval(1) = " + std::to_string(r);
  93. } else if (*result == dummy_function) {
  94. auto r = (*result)(1);
  95. return "matches dummy_function: eval(1) = " + std::to_string(r);
  96. } else {
  97. return "argument does NOT match dummy_function. This should never happen!";
  98. }
  99. });
  100. class AbstractBase { public: virtual unsigned int func() = 0; };
  101. m.def("func_accepting_func_accepting_base", [](std::function<double(AbstractBase&)>) { });
  102. struct MovableObject {
  103. bool valid = true;
  104. MovableObject() = default;
  105. MovableObject(const MovableObject &) = default;
  106. MovableObject &operator=(const MovableObject &) = default;
  107. MovableObject(MovableObject &&o) : valid(o.valid) { o.valid = false; }
  108. MovableObject &operator=(MovableObject &&o) {
  109. valid = o.valid;
  110. o.valid = false;
  111. return *this;
  112. }
  113. };
  114. py::class_<MovableObject>(m, "MovableObject");
  115. // test_movable_object
  116. m.def("callback_with_movable", [](std::function<void(MovableObject &)> f) {
  117. auto x = MovableObject();
  118. f(x); // lvalue reference shouldn't move out object
  119. return x.valid; // must still return `true`
  120. });
  121. // test_bound_method_callback
  122. struct CppBoundMethodTest {};
  123. py::class_<CppBoundMethodTest>(m, "CppBoundMethodTest")
  124. .def(py::init<>())
  125. .def("triple", [](CppBoundMethodTest &, int val) { return 3 * val; });
  126. }