• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2     tests/test_callbacks.cpp -- callbacks
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"
11 #include "constructor_stats.h"
12 #include <pybind11/functional.h>
13 #include <thread>
14 
15 
dummy_function(int i)16 int dummy_function(int i) { return i + 1; }
17 
TEST_SUBMODULE(callbacks,m)18 TEST_SUBMODULE(callbacks, m) {
19     // test_callbacks, test_function_signatures
20     m.def("test_callback1", [](py::object func) { return func(); });
21     m.def("test_callback2", [](py::object func) { return func("Hello", 'x', true, 5); });
22     m.def("test_callback3", [](const std::function<int(int)> &func) {
23         return "func(43) = " + std::to_string(func(43)); });
24     m.def("test_callback4", []() -> std::function<int(int)> { return [](int i) { return i+1; }; });
25     m.def("test_callback5", []() {
26         return py::cpp_function([](int i) { return i+1; }, py::arg("number"));
27     });
28 
29     // test_keyword_args_and_generalized_unpacking
30     m.def("test_tuple_unpacking", [](py::function f) {
31         auto t1 = py::make_tuple(2, 3);
32         auto t2 = py::make_tuple(5, 6);
33         return f("positional", 1, *t1, 4, *t2);
34     });
35 
36     m.def("test_dict_unpacking", [](py::function f) {
37         auto d1 = py::dict("key"_a="value", "a"_a=1);
38         auto d2 = py::dict();
39         auto d3 = py::dict("b"_a=2);
40         return f("positional", 1, **d1, **d2, **d3);
41     });
42 
43     m.def("test_keyword_args", [](py::function f) {
44         return f("x"_a=10, "y"_a=20);
45     });
46 
47     m.def("test_unpacking_and_keywords1", [](py::function f) {
48         auto args = py::make_tuple(2);
49         auto kwargs = py::dict("d"_a=4);
50         return f(1, *args, "c"_a=3, **kwargs);
51     });
52 
53     m.def("test_unpacking_and_keywords2", [](py::function f) {
54         auto kwargs1 = py::dict("a"_a=1);
55         auto kwargs2 = py::dict("c"_a=3, "d"_a=4);
56         return f("positional", *py::make_tuple(1), 2, *py::make_tuple(3, 4), 5,
57                  "key"_a="value", **kwargs1, "b"_a=2, **kwargs2, "e"_a=5);
58     });
59 
60     m.def("test_unpacking_error1", [](py::function f) {
61         auto kwargs = py::dict("x"_a=3);
62         return f("x"_a=1, "y"_a=2, **kwargs); // duplicate ** after keyword
63     });
64 
65     m.def("test_unpacking_error2", [](py::function f) {
66         auto kwargs = py::dict("x"_a=3);
67         return f(**kwargs, "x"_a=1); // duplicate keyword after **
68     });
69 
70     m.def("test_arg_conversion_error1", [](py::function f) {
71         f(234, UnregisteredType(), "kw"_a=567);
72     });
73 
74     m.def("test_arg_conversion_error2", [](py::function f) {
75         f(234, "expected_name"_a=UnregisteredType(), "kw"_a=567);
76     });
77 
78     // test_lambda_closure_cleanup
79     struct Payload {
80         Payload() { print_default_created(this); }
81         ~Payload() { print_destroyed(this); }
82         Payload(const Payload &) { print_copy_created(this); }
83         Payload(Payload &&) { print_move_created(this); }
84     };
85     // Export the payload constructor statistics for testing purposes:
86     m.def("payload_cstats", &ConstructorStats::get<Payload>);
87     /* Test cleanup of lambda closure */
88     m.def("test_cleanup", []() -> std::function<void(void)> {
89         Payload p;
90 
91         return [p]() {
92             /* p should be cleaned up when the returned function is garbage collected */
93             (void) p;
94         };
95     });
96 
97     // test_cpp_function_roundtrip
98     /* Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer */
99     m.def("dummy_function", &dummy_function);
100     m.def("dummy_function2", [](int i, int j) { return i + j; });
101     m.def("roundtrip", [](std::function<int(int)> f, bool expect_none = false) {
102         if (expect_none && f)
103             throw std::runtime_error("Expected None to be converted to empty std::function");
104         return f;
105     }, py::arg("f"), py::arg("expect_none")=false);
106     m.def("test_dummy_function", [](const std::function<int(int)> &f) -> std::string {
107         using fn_type = int (*)(int);
108         auto result = f.target<fn_type>();
109         if (!result) {
110             auto r = f(1);
111             return "can't convert to function pointer: eval(1) = " + std::to_string(r);
112         } else if (*result == dummy_function) {
113             auto r = (*result)(1);
114             return "matches dummy_function: eval(1) = " + std::to_string(r);
115         } else {
116             return "argument does NOT match dummy_function. This should never happen!";
117         }
118     });
119 
120     class AbstractBase {
121     public:
122         // [workaround(intel)] = default does not work here
123         // Defaulting this destructor results in linking errors with the Intel compiler
124         // (in Debug builds only, tested with icpc (ICC) 2021.1 Beta 20200827)
125         virtual ~AbstractBase() {};  // NOLINT(modernize-use-equals-default)
126         virtual unsigned int func() = 0;
127     };
128     m.def("func_accepting_func_accepting_base", [](std::function<double(AbstractBase&)>) { });
129 
130     struct MovableObject {
131         bool valid = true;
132 
133         MovableObject() = default;
134         MovableObject(const MovableObject &) = default;
135         MovableObject &operator=(const MovableObject &) = default;
136         MovableObject(MovableObject &&o) : valid(o.valid) { o.valid = false; }
137         MovableObject &operator=(MovableObject &&o) {
138             valid = o.valid;
139             o.valid = false;
140             return *this;
141         }
142     };
143     py::class_<MovableObject>(m, "MovableObject");
144 
145     // test_movable_object
146     m.def("callback_with_movable", [](std::function<void(MovableObject &)> f) {
147         auto x = MovableObject();
148         f(x); // lvalue reference shouldn't move out object
149         return x.valid; // must still return `true`
150     });
151 
152     // test_bound_method_callback
153     struct CppBoundMethodTest {};
154     py::class_<CppBoundMethodTest>(m, "CppBoundMethodTest")
155         .def(py::init<>())
156         .def("triple", [](CppBoundMethodTest &, int val) { return 3 * val; });
157 
158     // test async Python callbacks
159     using callback_f = std::function<void(int)>;
160     m.def("test_async_callback", [](callback_f f, py::list work) {
161         // make detached thread that calls `f` with piece of work after a little delay
162         auto start_f = [f](int j) {
163             auto invoke_f = [f, j] {
164                 std::this_thread::sleep_for(std::chrono::milliseconds(50));
165                 f(j);
166             };
167             auto t = std::thread(std::move(invoke_f));
168             t.detach();
169         };
170 
171         // spawn worker threads
172         for (auto i : work)
173             start_f(py::cast<int>(i));
174     });
175 }
176