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
16int dummy_function(int i) { return i + 1; }
17
18TEST_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 { public: virtual unsigned int func() = 0; };
121    m.def("func_accepting_func_accepting_base", [](std::function<double(AbstractBase&)>) { });
122
123    struct MovableObject {
124        bool valid = true;
125
126        MovableObject() = default;
127        MovableObject(const MovableObject &) = default;
128        MovableObject &operator=(const MovableObject &) = default;
129        MovableObject(MovableObject &&o) : valid(o.valid) { o.valid = false; }
130        MovableObject &operator=(MovableObject &&o) {
131            valid = o.valid;
132            o.valid = false;
133            return *this;
134        }
135    };
136    py::class_<MovableObject>(m, "MovableObject");
137
138    // test_movable_object
139    m.def("callback_with_movable", [](std::function<void(MovableObject &)> f) {
140        auto x = MovableObject();
141        f(x); // lvalue reference shouldn't move out object
142        return x.valid; // must still return `true`
143    });
144
145    // test_bound_method_callback
146    struct CppBoundMethodTest {};
147    py::class_<CppBoundMethodTest>(m, "CppBoundMethodTest")
148        .def(py::init<>())
149        .def("triple", [](CppBoundMethodTest &, int val) { return 3 * val; });
150
151    // test async Python callbacks
152    using callback_f = std::function<void(int)>;
153    m.def("test_async_callback", [](callback_f f, py::list work) {
154        // make detached thread that calls `f` with piece of work after a little delay
155        auto start_f = [f](int j) {
156            auto invoke_f = [f, j] {
157                std::this_thread::sleep_for(std::chrono::milliseconds(50));
158                f(j);
159            };
160            auto t = std::thread(std::move(invoke_f));
161            t.detach();
162        };
163
164        // spawn worker threads
165        for (auto i : work)
166            start_f(py::cast<int>(i));
167    });
168}
169