μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
test_callbacks.py
Go to the documentation of this file.
1# -*- coding: utf-8 -*-
2import time
3from threading import Thread
4
5import pytest
6
7import env # noqa: F401
8from pybind11_tests import callbacks as m
9
10
12 from functools import partial
13
14 def func1():
15 return "func1"
16
17 def func2(a, b, c, d):
18 return "func2", a, b, c, d
19
20 def func3(a):
21 return "func3({})".format(a)
22
23 assert m.test_callback1(func1) == "func1"
24 assert m.test_callback2(func2) == ("func2", "Hello", "x", True, 5)
25 assert m.test_callback1(partial(func2, 1, 2, 3, 4)) == ("func2", 1, 2, 3, 4)
26 assert m.test_callback1(partial(func3, "partial")) == "func3(partial)"
27 assert m.test_callback3(lambda i: i + 1) == "func(43) = 44"
28
29 f = m.test_callback4()
30 assert f(43) == 44
31 f = m.test_callback5()
32 assert f(number=43) == 44
33
34
36 # Bound Python method:
37 class MyClass:
38 def double(self, val):
39 return 2 * val
40
41 z = MyClass()
42 assert m.test_callback3(z.double) == "func(43) = 86"
43
44 z = m.CppBoundMethodTest()
45 assert m.test_callback3(z.triple) == "func(43) = 129"
46
47
49 def f(*args, **kwargs):
50 return args, kwargs
51
52 assert m.test_tuple_unpacking(f) == (("positional", 1, 2, 3, 4, 5, 6), {})
53 assert m.test_dict_unpacking(f) == (
54 ("positional", 1),
55 {"key": "value", "a": 1, "b": 2},
56 )
57 assert m.test_keyword_args(f) == ((), {"x": 10, "y": 20})
58 assert m.test_unpacking_and_keywords1(f) == ((1, 2), {"c": 3, "d": 4})
59 assert m.test_unpacking_and_keywords2(f) == (
60 ("positional", 1, 2, 3, 4, 5),
61 {"key": "value", "a": 1, "b": 2, "c": 3, "d": 4, "e": 5},
62 )
63
64 with pytest.raises(TypeError) as excinfo:
65 m.test_unpacking_error1(f)
66 assert "Got multiple values for keyword argument" in str(excinfo.value)
67
68 with pytest.raises(TypeError) as excinfo:
69 m.test_unpacking_error2(f)
70 assert "Got multiple values for keyword argument" in str(excinfo.value)
71
72 with pytest.raises(RuntimeError) as excinfo:
73 m.test_arg_conversion_error1(f)
74 assert "Unable to convert call argument" in str(excinfo.value)
75
76 with pytest.raises(RuntimeError) as excinfo:
77 m.test_arg_conversion_error2(f)
78 assert "Unable to convert call argument" in str(excinfo.value)
79
80
82 m.test_lambda_closure_cleanup()
83 cstats = m.payload_cstats()
84 assert cstats.alive() == 0
85 assert cstats.copy_constructions == 1
86 assert cstats.move_constructions >= 1
87
88
90 alive_counts = m.test_cpp_callable_cleanup()
91 assert alive_counts == [0, 1, 2, 1, 2, 1, 0]
92
93
95 """Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer"""
96
97 assert (
98 m.test_dummy_function(m.dummy_function) == "matches dummy_function: eval(1) = 2"
99 )
100 assert (
101 m.test_dummy_function(m.roundtrip(m.dummy_function))
102 == "matches dummy_function: eval(1) = 2"
103 )
104 assert (
105 m.test_dummy_function(m.dummy_function_overloaded)
106 == "matches dummy_function: eval(1) = 2"
107 )
108 assert m.roundtrip(None, expect_none=True) is None
109 assert (
110 m.test_dummy_function(lambda x: x + 2)
111 == "can't convert to function pointer: eval(1) = 3"
112 )
113
114 with pytest.raises(TypeError) as excinfo:
115 m.test_dummy_function(m.dummy_function2)
116 assert "incompatible function arguments" in str(excinfo.value)
117
118 with pytest.raises(TypeError) as excinfo:
119 m.test_dummy_function(lambda x, y: x + y)
120 assert any(
121 s in str(excinfo.value)
122 for s in ("missing 1 required positional argument", "takes exactly 2 arguments")
123 )
124
125
127 assert doc(m.test_callback3) == "test_callback3(arg0: Callable[[int], int]) -> str"
128 assert doc(m.test_callback4) == "test_callback4() -> Callable[[int], int]"
129
130
132 assert m.callback_with_movable(lambda _: None) is True
133
134
135@pytest.mark.skipif(
136 "env.PYPY",
137 reason="PyPy segfaults on here. See discussion on #1413.",
138)
140 """Test if python builtins like sum() can be used as callbacks"""
141 assert m.test_sum_builtin(sum, [1, 2, 3]) == 6
142 assert m.test_sum_builtin(sum, []) == 0
143
144
146 # serves as state for async callback
147 class Item:
148 def __init__(self, value):
149 self.value = value
150
151 res = []
152
153 # generate stateful lambda that will store result in `res`
154 def gen_f():
155 s = Item(3)
156 return lambda j: res.append(s.value + j)
157
158 # do some work async
159 work = [1, 2, 3, 4]
160 m.test_async_callback(gen_f(), work)
161 # wait until work is done
162 from time import sleep
163
164 sleep(0.5)
165 assert sum(res) == sum(x + 3 for x in work)
166
167
169 t = Thread(target=test_async_callbacks)
170 t.start()
171 t.join()
172
173
175 # Super-simple micro-benchmarking related to PR #2919.
176 # Example runtimes (Intel Xeon 2.2GHz, fully optimized):
177 # num_millions 1, repeats 2: 0.1 secs
178 # num_millions 20, repeats 10: 11.5 secs
179 one_million = 1000000
180 num_millions = 1 # Try 20 for actual micro-benchmarking.
181 repeats = 2 # Try 10.
182 rates = []
183 for rep in range(repeats):
184 t0 = time.time()
185 m.callback_num_times(lambda: None, num_millions * one_million)
186 td = time.time() - t0
187 rate = num_millions / td if td else 0
188 rates.append(rate)
189 if not rep:
190 print()
191 print(
192 "callback_num_times: {:d} million / {:.3f} seconds = {:.3f} million / second".format(
193 num_millions, td, rate
194 )
195 )
196 if len(rates) > 1:
197 print("Min Mean Max")
198 print(
199 "{:6.3f} {:6.3f} {:6.3f}".format(
200 min(rates), sum(rates) / len(rates), max(rates)
201 )
202 )
Definition: pytypes.h:1200
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2002
def test_movable_object()
def test_keyword_args_and_generalized_unpacking()
def test_lambda_closure_cleanup()
def test_function_signatures(doc)
def test_callback_num_times()
def test_async_callbacks()
def test_cpp_callable_cleanup()
def test_bound_method_callback()
def test_python_builtins()
def test_cpp_function_roundtrip()
def test_async_async_callbacks()
Annotation for documentation.
Definition: attr.h:41