test_stl.py 7.1 KB

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