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


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:37:45