blob: 613796356f8b7934bf01f3f214a918824cd95d97 [file] [log] [blame]
Dean Moldovan83e328f2017-06-09 00:44:49 +02001import pytest
2
3from pybind11_tests import stl as m
4from pybind11_tests import UserType
Wenzel Jakobcbd16a82018-07-17 16:56:26 +02005from pybind11_tests import ConstructorStats
Dean Moldovan83e328f2017-06-09 00:44:49 +02006
7
8def test_vector(doc):
9 """std::vector <-> list"""
Jason Rhinelander5c7a2902017-10-24 20:39:46 -030010 lst = m.cast_vector()
11 assert lst == [1]
12 lst.append(2)
13 assert m.load_vector(lst)
14 assert m.load_vector(tuple(lst))
Dean Moldovan83e328f2017-06-09 00:44:49 +020015
Dean Moldovan3c4933c2017-09-01 21:42:20 +020016 assert m.cast_bool_vector() == [True, False]
17 assert m.load_bool_vector([True, False])
18
Dean Moldovan83e328f2017-06-09 00:44:49 +020019 assert doc(m.cast_vector) == "cast_vector() -> List[int]"
20 assert doc(m.load_vector) == "load_vector(arg0: List[int]) -> bool"
21
Jason Rhinelander67a0cc42017-07-06 20:41:52 -040022 # Test regression caused by 936: pointers to stl containers weren't castable
23 assert m.cast_ptr_vector() == ["lvalue", "lvalue"]
24
Dean Moldovan83e328f2017-06-09 00:44:49 +020025
voxmea17983e72018-11-16 00:45:19 -050026def test_deque(doc):
27 """std::deque <-> list"""
28 lst = m.cast_deque()
29 assert lst == [1]
30 lst.append(2)
31 assert m.load_deque(lst)
32 assert m.load_deque(tuple(lst))
33
34
Dean Moldovan83e328f2017-06-09 00:44:49 +020035def test_array(doc):
36 """std::array <-> list"""
Jason Rhinelander5c7a2902017-10-24 20:39:46 -030037 lst = m.cast_array()
38 assert lst == [1, 2]
39 assert m.load_array(lst)
Dean Moldovan83e328f2017-06-09 00:44:49 +020040
41 assert doc(m.cast_array) == "cast_array() -> List[int[2]]"
42 assert doc(m.load_array) == "load_array(arg0: List[int[2]]) -> bool"
43
44
45def test_valarray(doc):
46 """std::valarray <-> list"""
Jason Rhinelander5c7a2902017-10-24 20:39:46 -030047 lst = m.cast_valarray()
48 assert lst == [1, 4, 9]
49 assert m.load_valarray(lst)
Dean Moldovan83e328f2017-06-09 00:44:49 +020050
51 assert doc(m.cast_valarray) == "cast_valarray() -> List[int]"
52 assert doc(m.load_valarray) == "load_valarray(arg0: List[int]) -> bool"
53
54
55def test_map(doc):
56 """std::map <-> dict"""
57 d = m.cast_map()
58 assert d == {"key": "value"}
Blake Thompson30c03522019-06-10 14:01:11 -050059 assert "key" in d
Dean Moldovan83e328f2017-06-09 00:44:49 +020060 d["key2"] = "value2"
Blake Thompson30c03522019-06-10 14:01:11 -050061 assert "key2" in d
Dean Moldovan83e328f2017-06-09 00:44:49 +020062 assert m.load_map(d)
63
64 assert doc(m.cast_map) == "cast_map() -> Dict[str, str]"
65 assert doc(m.load_map) == "load_map(arg0: Dict[str, str]) -> bool"
66
67
68def test_set(doc):
69 """std::set <-> set"""
70 s = m.cast_set()
71 assert s == {"key1", "key2"}
72 s.add("key3")
73 assert m.load_set(s)
74
75 assert doc(m.cast_set) == "cast_set() -> Set[str]"
76 assert doc(m.load_set) == "load_set(arg0: Set[str]) -> bool"
77
78
Jason Rhinelanderb57281b2017-07-03 19:12:09 -040079def test_recursive_casting():
80 """Tests that stl casters preserve lvalue/rvalue context for container values"""
81 assert m.cast_rv_vector() == ["rvalue", "rvalue"]
82 assert m.cast_lv_vector() == ["lvalue", "lvalue"]
83 assert m.cast_rv_array() == ["rvalue", "rvalue", "rvalue"]
84 assert m.cast_lv_array() == ["lvalue", "lvalue"]
85 assert m.cast_rv_map() == {"a": "rvalue"}
86 assert m.cast_lv_map() == {"a": "lvalue", "b": "lvalue"}
87 assert m.cast_rv_nested() == [[[{"b": "rvalue", "c": "rvalue"}], [{"a": "rvalue"}]]]
88 assert m.cast_lv_nested() == {
89 "a": [[["lvalue", "lvalue"]], [["lvalue", "lvalue"]]],
90 "b": [[["lvalue", "lvalue"], ["lvalue", "lvalue"]]]
91 }
92
93 # Issue #853 test case:
94 z = m.cast_unique_ptr_vector()
95 assert z[0].value == 7 and z[1].value == 42
96
97
Dean Moldovan83e328f2017-06-09 00:44:49 +020098def test_move_out_container():
99 """Properties use the `reference_internal` policy by default. If the underlying function
100 returns an rvalue, the policy is automatically changed to `move` to avoid referencing
101 a temporary. In case the return value is a container of user-defined types, the policy
102 also needs to be applied to the elements, not just the container."""
103 c = m.MoveOutContainer()
104 moved_out_list = c.move_list
105 assert [x.value for x in moved_out_list] == [0, 1, 2]
106
107
108@pytest.mark.skipif(not hasattr(m, "has_optional"), reason='no <optional>')
109def test_optional():
110 assert m.double_or_zero(None) == 0
111 assert m.double_or_zero(42) == 84
112 pytest.raises(TypeError, m.double_or_zero, 'foo')
113
114 assert m.half_or_none(0) is None
115 assert m.half_or_none(42) == 21
116 pytest.raises(TypeError, m.half_or_none, 'foo')
117
118 assert m.test_nullopt() == 42
119 assert m.test_nullopt(None) == 42
120 assert m.test_nullopt(42) == 42
121 assert m.test_nullopt(43) == 43
122
123 assert m.test_no_assign() == 42
124 assert m.test_no_assign(None) == 42
125 assert m.test_no_assign(m.NoAssign(43)) == 43
126 pytest.raises(TypeError, m.test_no_assign, 43)
127
128 assert m.nodefer_none_optional(None)
129
fatvladya3daf872020-03-14 15:15:12 +0200130 holder = m.OptionalHolder()
131 mvalue = holder.member
132 assert mvalue.initialized
133 assert holder.member_initialized()
134
Dean Moldovan83e328f2017-06-09 00:44:49 +0200135
136@pytest.mark.skipif(not hasattr(m, "has_exp_optional"), reason='no <experimental/optional>')
137def test_exp_optional():
138 assert m.double_or_zero_exp(None) == 0
139 assert m.double_or_zero_exp(42) == 84
140 pytest.raises(TypeError, m.double_or_zero_exp, 'foo')
141
142 assert m.half_or_none_exp(0) is None
143 assert m.half_or_none_exp(42) == 21
144 pytest.raises(TypeError, m.half_or_none_exp, 'foo')
145
146 assert m.test_nullopt_exp() == 42
147 assert m.test_nullopt_exp(None) == 42
148 assert m.test_nullopt_exp(42) == 42
149 assert m.test_nullopt_exp(43) == 43
150
151 assert m.test_no_assign_exp() == 42
152 assert m.test_no_assign_exp(None) == 42
153 assert m.test_no_assign_exp(m.NoAssign(43)) == 43
154 pytest.raises(TypeError, m.test_no_assign_exp, 43)
155
fatvladya3daf872020-03-14 15:15:12 +0200156 holder = m.OptionalExpHolder()
157 mvalue = holder.member
158 assert mvalue.initialized
159 assert holder.member_initialized()
160
Dean Moldovan83e328f2017-06-09 00:44:49 +0200161
162@pytest.mark.skipif(not hasattr(m, "load_variant"), reason='no <variant>')
163def test_variant(doc):
164 assert m.load_variant(1) == "int"
165 assert m.load_variant("1") == "std::string"
166 assert m.load_variant(1.0) == "double"
167 assert m.load_variant(None) == "std::nullptr_t"
168
169 assert m.load_variant_2pass(1) == "int"
170 assert m.load_variant_2pass(1.0) == "double"
171
172 assert m.cast_variant() == (5, "Hello")
173
174 assert doc(m.load_variant) == "load_variant(arg0: Union[int, str, float, None]) -> str"
175
176
177def test_vec_of_reference_wrapper():
178 """#171: Can't return reference wrappers (or STL structures containing them)"""
179 assert str(m.return_vec_of_reference_wrapper(UserType(4))) == \
180 "[UserType(1), UserType(2), UserType(3), UserType(4)]"
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200181
182
183def test_stl_pass_by_pointer(msg):
184 """Passing nullptr or None to an STL container pointer is not expected to work"""
185 with pytest.raises(TypeError) as excinfo:
186 m.stl_pass_by_pointer() # default value is `nullptr`
187 assert msg(excinfo.value) == """
188 stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
Antony Lee0826b3c2017-11-26 20:00:35 -0800189 1. (v: List[int] = None) -> List[int]
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200190
191 Invoked with:
192 """ # noqa: E501 line too long
193
194 with pytest.raises(TypeError) as excinfo:
195 m.stl_pass_by_pointer(None)
196 assert msg(excinfo.value) == """
197 stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
Antony Lee0826b3c2017-11-26 20:00:35 -0800198 1. (v: List[int] = None) -> List[int]
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200199
200 Invoked with: None
201 """ # noqa: E501 line too long
202
203 assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200204
205
206def test_missing_header_message():
207 """Trying convert `list` to a `std::vector`, or vice versa, without including
208 <pybind11/stl.h> should result in a helpful suggestion in the error message"""
209 import pybind11_cross_module_tests as cm
210
211 expected_message = ("Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
212 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
213 "conversions are optional and require extra headers to be included\n"
214 "when compiling your pybind11 module.")
215
216 with pytest.raises(TypeError) as excinfo:
217 cm.missing_header_arg([1.0, 2.0, 3.0])
218 assert expected_message in str(excinfo.value)
219
220 with pytest.raises(TypeError) as excinfo:
221 cm.missing_header_return()
222 assert expected_message in str(excinfo.value)
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200223
224
Allan Leale76dff72018-10-11 10:28:12 +0200225def test_function_with_string_and_vector_string_arg():
226 """Check if a string is NOT implicitly converted to a list, which was the
227 behavior before fix of issue #1258"""
228 assert m.func_with_string_or_vector_string_arg_overload(('A', 'B', )) == 2
229 assert m.func_with_string_or_vector_string_arg_overload(['A', 'B']) == 2
230 assert m.func_with_string_or_vector_string_arg_overload('A') == 3
231
232
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200233def test_stl_ownership():
234 cstats = ConstructorStats.get(m.Placeholder)
235 assert cstats.alive() == 0
236 r = m.test_stl_ownership()
237 assert len(r) == 1
238 del r
239 assert cstats.alive() == 0
Wenzel Jakob9f730602018-11-09 12:32:48 +0100240
241
242def test_array_cast_sequence():
243 assert m.array_cast_sequence((1, 2, 3)) == [1, 2, 3]
Wenzel Jakobadc2cdd2018-11-09 20:12:46 +0100244
245
246def test_issue_1561():
247 """ check fix for issue #1561 """
248 bar = m.Issue1561Outer()
249 bar.list = [m.Issue1561Inner('bar')]
250 bar.list
251 assert bar.list[0].data == 'bar'