test_callbacks.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. from pybind11_tests import callbacks as m
  4. from threading import Thread
  5. def test_callbacks():
  6. from functools import partial
  7. def func1():
  8. return "func1"
  9. def func2(a, b, c, d):
  10. return "func2", a, b, c, d
  11. def func3(a):
  12. return "func3({})".format(a)
  13. assert m.test_callback1(func1) == "func1"
  14. assert m.test_callback2(func2) == ("func2", "Hello", "x", True, 5)
  15. assert m.test_callback1(partial(func2, 1, 2, 3, 4)) == ("func2", 1, 2, 3, 4)
  16. assert m.test_callback1(partial(func3, "partial")) == "func3(partial)"
  17. assert m.test_callback3(lambda i: i + 1) == "func(43) = 44"
  18. f = m.test_callback4()
  19. assert f(43) == 44
  20. f = m.test_callback5()
  21. assert f(number=43) == 44
  22. def test_bound_method_callback():
  23. # Bound Python method:
  24. class MyClass:
  25. def double(self, val):
  26. return 2 * val
  27. z = MyClass()
  28. assert m.test_callback3(z.double) == "func(43) = 86"
  29. z = m.CppBoundMethodTest()
  30. assert m.test_callback3(z.triple) == "func(43) = 129"
  31. def test_keyword_args_and_generalized_unpacking():
  32. def f(*args, **kwargs):
  33. return args, kwargs
  34. assert m.test_tuple_unpacking(f) == (("positional", 1, 2, 3, 4, 5, 6), {})
  35. assert m.test_dict_unpacking(f) == (
  36. ("positional", 1),
  37. {"key": "value", "a": 1, "b": 2},
  38. )
  39. assert m.test_keyword_args(f) == ((), {"x": 10, "y": 20})
  40. assert m.test_unpacking_and_keywords1(f) == ((1, 2), {"c": 3, "d": 4})
  41. assert m.test_unpacking_and_keywords2(f) == (
  42. ("positional", 1, 2, 3, 4, 5),
  43. {"key": "value", "a": 1, "b": 2, "c": 3, "d": 4, "e": 5},
  44. )
  45. with pytest.raises(TypeError) as excinfo:
  46. m.test_unpacking_error1(f)
  47. assert "Got multiple values for keyword argument" in str(excinfo.value)
  48. with pytest.raises(TypeError) as excinfo:
  49. m.test_unpacking_error2(f)
  50. assert "Got multiple values for keyword argument" in str(excinfo.value)
  51. with pytest.raises(RuntimeError) as excinfo:
  52. m.test_arg_conversion_error1(f)
  53. assert "Unable to convert call argument" in str(excinfo.value)
  54. with pytest.raises(RuntimeError) as excinfo:
  55. m.test_arg_conversion_error2(f)
  56. assert "Unable to convert call argument" in str(excinfo.value)
  57. def test_lambda_closure_cleanup():
  58. m.test_cleanup()
  59. cstats = m.payload_cstats()
  60. assert cstats.alive() == 0
  61. assert cstats.copy_constructions == 1
  62. assert cstats.move_constructions >= 1
  63. def test_cpp_function_roundtrip():
  64. """Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer"""
  65. assert (
  66. m.test_dummy_function(m.dummy_function) == "matches dummy_function: eval(1) = 2"
  67. )
  68. assert (
  69. m.test_dummy_function(m.roundtrip(m.dummy_function))
  70. == "matches dummy_function: eval(1) = 2"
  71. )
  72. assert m.roundtrip(None, expect_none=True) is None
  73. assert (
  74. m.test_dummy_function(lambda x: x + 2)
  75. == "can't convert to function pointer: eval(1) = 3"
  76. )
  77. with pytest.raises(TypeError) as excinfo:
  78. m.test_dummy_function(m.dummy_function2)
  79. assert "incompatible function arguments" in str(excinfo.value)
  80. with pytest.raises(TypeError) as excinfo:
  81. m.test_dummy_function(lambda x, y: x + y)
  82. assert any(
  83. s in str(excinfo.value)
  84. for s in ("missing 1 required positional argument", "takes exactly 2 arguments")
  85. )
  86. def test_function_signatures(doc):
  87. assert doc(m.test_callback3) == "test_callback3(arg0: Callable[[int], int]) -> str"
  88. assert doc(m.test_callback4) == "test_callback4() -> Callable[[int], int]"
  89. def test_movable_object():
  90. assert m.callback_with_movable(lambda _: None) is True
  91. def test_async_callbacks():
  92. # serves as state for async callback
  93. class Item:
  94. def __init__(self, value):
  95. self.value = value
  96. res = []
  97. # generate stateful lambda that will store result in `res`
  98. def gen_f():
  99. s = Item(3)
  100. return lambda j: res.append(s.value + j)
  101. # do some work async
  102. work = [1, 2, 3, 4]
  103. m.test_async_callback(gen_f(), work)
  104. # wait until work is done
  105. from time import sleep
  106. sleep(0.5)
  107. assert sum(res) == sum([x + 3 for x in work])
  108. def test_async_async_callbacks():
  109. t = Thread(target=test_async_callbacks)
  110. t.start()
  111. t.join()