test_stl.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. from pybind11_tests import stl as m
  4. from pybind11_tests import UserType
  5. from pybind11_tests import ConstructorStats
  6. def test_vector(doc):
  7. """std::vector <-> list"""
  8. lst = m.cast_vector()
  9. assert lst == [1]
  10. lst.append(2)
  11. assert m.load_vector(lst)
  12. assert m.load_vector(tuple(lst))
  13. assert m.cast_bool_vector() == [True, False]
  14. assert m.load_bool_vector([True, False])
  15. assert doc(m.cast_vector) == "cast_vector() -> List[int]"
  16. assert doc(m.load_vector) == "load_vector(arg0: List[int]) -> bool"
  17. # Test regression caused by 936: pointers to stl containers weren't castable
  18. assert m.cast_ptr_vector() == ["lvalue", "lvalue"]
  19. def test_deque(doc):
  20. """std::deque <-> list"""
  21. lst = m.cast_deque()
  22. assert lst == [1]
  23. lst.append(2)
  24. assert m.load_deque(lst)
  25. assert m.load_deque(tuple(lst))
  26. def test_array(doc):
  27. """std::array <-> list"""
  28. lst = m.cast_array()
  29. assert lst == [1, 2]
  30. assert m.load_array(lst)
  31. assert doc(m.cast_array) == "cast_array() -> List[int[2]]"
  32. assert doc(m.load_array) == "load_array(arg0: List[int[2]]) -> bool"
  33. def test_valarray(doc):
  34. """std::valarray <-> list"""
  35. lst = m.cast_valarray()
  36. assert lst == [1, 4, 9]
  37. assert m.load_valarray(lst)
  38. assert doc(m.cast_valarray) == "cast_valarray() -> List[int]"
  39. assert doc(m.load_valarray) == "load_valarray(arg0: List[int]) -> bool"
  40. def test_map(doc):
  41. """std::map <-> dict"""
  42. d = m.cast_map()
  43. assert d == {"key": "value"}
  44. assert "key" in d
  45. d["key2"] = "value2"
  46. assert "key2" in d
  47. assert m.load_map(d)
  48. assert doc(m.cast_map) == "cast_map() -> Dict[str, str]"
  49. assert doc(m.load_map) == "load_map(arg0: Dict[str, str]) -> bool"
  50. def test_set(doc):
  51. """std::set <-> set"""
  52. s = m.cast_set()
  53. assert s == {"key1", "key2"}
  54. s.add("key3")
  55. assert m.load_set(s)
  56. assert doc(m.cast_set) == "cast_set() -> Set[str]"
  57. assert doc(m.load_set) == "load_set(arg0: Set[str]) -> bool"
  58. def test_recursive_casting():
  59. """Tests that stl casters preserve lvalue/rvalue context for container values"""
  60. assert m.cast_rv_vector() == ["rvalue", "rvalue"]
  61. assert m.cast_lv_vector() == ["lvalue", "lvalue"]
  62. assert m.cast_rv_array() == ["rvalue", "rvalue", "rvalue"]
  63. assert m.cast_lv_array() == ["lvalue", "lvalue"]
  64. assert m.cast_rv_map() == {"a": "rvalue"}
  65. assert m.cast_lv_map() == {"a": "lvalue", "b": "lvalue"}
  66. assert m.cast_rv_nested() == [[[{"b": "rvalue", "c": "rvalue"}], [{"a": "rvalue"}]]]
  67. assert m.cast_lv_nested() == {
  68. "a": [[["lvalue", "lvalue"]], [["lvalue", "lvalue"]]],
  69. "b": [[["lvalue", "lvalue"], ["lvalue", "lvalue"]]],
  70. }
  71. # Issue #853 test case:
  72. z = m.cast_unique_ptr_vector()
  73. assert z[0].value == 7 and z[1].value == 42
  74. def test_move_out_container():
  75. """Properties use the `reference_internal` policy by default. If the underlying function
  76. returns an rvalue, the policy is automatically changed to `move` to avoid referencing
  77. a temporary. In case the return value is a container of user-defined types, the policy
  78. also needs to be applied to the elements, not just the container."""
  79. c = m.MoveOutContainer()
  80. moved_out_list = c.move_list
  81. assert [x.value for x in moved_out_list] == [0, 1, 2]
  82. @pytest.mark.skipif(not hasattr(m, "has_optional"), reason="no <optional>")
  83. def test_optional():
  84. assert m.double_or_zero(None) == 0
  85. assert m.double_or_zero(42) == 84
  86. pytest.raises(TypeError, m.double_or_zero, "foo")
  87. assert m.half_or_none(0) is None
  88. assert m.half_or_none(42) == 21
  89. pytest.raises(TypeError, m.half_or_none, "foo")
  90. assert m.test_nullopt() == 42
  91. assert m.test_nullopt(None) == 42
  92. assert m.test_nullopt(42) == 42
  93. assert m.test_nullopt(43) == 43
  94. assert m.test_no_assign() == 42
  95. assert m.test_no_assign(None) == 42
  96. assert m.test_no_assign(m.NoAssign(43)) == 43
  97. pytest.raises(TypeError, m.test_no_assign, 43)
  98. assert m.nodefer_none_optional(None)
  99. holder = m.OptionalHolder()
  100. mvalue = holder.member
  101. assert mvalue.initialized
  102. assert holder.member_initialized()
  103. @pytest.mark.skipif(
  104. not hasattr(m, "has_exp_optional"), reason="no <experimental/optional>"
  105. )
  106. def test_exp_optional():
  107. assert m.double_or_zero_exp(None) == 0
  108. assert m.double_or_zero_exp(42) == 84
  109. pytest.raises(TypeError, m.double_or_zero_exp, "foo")
  110. assert m.half_or_none_exp(0) is None
  111. assert m.half_or_none_exp(42) == 21
  112. pytest.raises(TypeError, m.half_or_none_exp, "foo")
  113. assert m.test_nullopt_exp() == 42
  114. assert m.test_nullopt_exp(None) == 42
  115. assert m.test_nullopt_exp(42) == 42
  116. assert m.test_nullopt_exp(43) == 43
  117. assert m.test_no_assign_exp() == 42
  118. assert m.test_no_assign_exp(None) == 42
  119. assert m.test_no_assign_exp(m.NoAssign(43)) == 43
  120. pytest.raises(TypeError, m.test_no_assign_exp, 43)
  121. holder = m.OptionalExpHolder()
  122. mvalue = holder.member
  123. assert mvalue.initialized
  124. assert holder.member_initialized()
  125. @pytest.mark.skipif(not hasattr(m, "load_variant"), reason="no <variant>")
  126. def test_variant(doc):
  127. assert m.load_variant(1) == "int"
  128. assert m.load_variant("1") == "std::string"
  129. assert m.load_variant(1.0) == "double"
  130. assert m.load_variant(None) == "std::nullptr_t"
  131. assert m.load_variant_2pass(1) == "int"
  132. assert m.load_variant_2pass(1.0) == "double"
  133. assert m.cast_variant() == (5, "Hello")
  134. assert (
  135. doc(m.load_variant) == "load_variant(arg0: Union[int, str, float, None]) -> str"
  136. )
  137. def test_vec_of_reference_wrapper():
  138. """#171: Can't return reference wrappers (or STL structures containing them)"""
  139. assert (
  140. str(m.return_vec_of_reference_wrapper(UserType(4)))
  141. == "[UserType(1), UserType(2), UserType(3), UserType(4)]"
  142. )
  143. def test_stl_pass_by_pointer(msg):
  144. """Passing nullptr or None to an STL container pointer is not expected to work"""
  145. with pytest.raises(TypeError) as excinfo:
  146. m.stl_pass_by_pointer() # default value is `nullptr`
  147. assert (
  148. msg(excinfo.value)
  149. == """
  150. stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
  151. 1. (v: List[int] = None) -> List[int]
  152. Invoked with:
  153. """ # noqa: E501 line too long
  154. )
  155. with pytest.raises(TypeError) as excinfo:
  156. m.stl_pass_by_pointer(None)
  157. assert (
  158. msg(excinfo.value)
  159. == """
  160. stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
  161. 1. (v: List[int] = None) -> List[int]
  162. Invoked with: None
  163. """ # noqa: E501 line too long
  164. )
  165. assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]
  166. def test_missing_header_message():
  167. """Trying convert `list` to a `std::vector`, or vice versa, without including
  168. <pybind11/stl.h> should result in a helpful suggestion in the error message"""
  169. import pybind11_cross_module_tests as cm
  170. expected_message = (
  171. "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
  172. "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
  173. "conversions are optional and require extra headers to be included\n"
  174. "when compiling your pybind11 module."
  175. )
  176. with pytest.raises(TypeError) as excinfo:
  177. cm.missing_header_arg([1.0, 2.0, 3.0])
  178. assert expected_message in str(excinfo.value)
  179. with pytest.raises(TypeError) as excinfo:
  180. cm.missing_header_return()
  181. assert expected_message in str(excinfo.value)
  182. def test_function_with_string_and_vector_string_arg():
  183. """Check if a string is NOT implicitly converted to a list, which was the
  184. behavior before fix of issue #1258"""
  185. assert m.func_with_string_or_vector_string_arg_overload(("A", "B")) == 2
  186. assert m.func_with_string_or_vector_string_arg_overload(["A", "B"]) == 2
  187. assert m.func_with_string_or_vector_string_arg_overload("A") == 3
  188. def test_stl_ownership():
  189. cstats = ConstructorStats.get(m.Placeholder)
  190. assert cstats.alive() == 0
  191. r = m.test_stl_ownership()
  192. assert len(r) == 1
  193. del r
  194. assert cstats.alive() == 0
  195. def test_array_cast_sequence():
  196. assert m.array_cast_sequence((1, 2, 3)) == [1, 2, 3]
  197. def test_issue_1561():
  198. """ check fix for issue #1561 """
  199. bar = m.Issue1561Outer()
  200. bar.list = [m.Issue1561Inner("bar")]
  201. bar.list
  202. assert bar.list[0].data == "bar"