blob: 2c5e995f3b6dfcf4b73a2d23a1d7ff6fa2982b27 [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
26def test_array(doc):
27 """std::array <-> list"""
Jason Rhinelander5c7a2902017-10-24 20:39:46 -030028 lst = m.cast_array()
29 assert lst == [1, 2]
30 assert m.load_array(lst)
Dean Moldovan83e328f2017-06-09 00:44:49 +020031
32 assert doc(m.cast_array) == "cast_array() -> List[int[2]]"
33 assert doc(m.load_array) == "load_array(arg0: List[int[2]]) -> bool"
34
35
36def test_valarray(doc):
37 """std::valarray <-> list"""
Jason Rhinelander5c7a2902017-10-24 20:39:46 -030038 lst = m.cast_valarray()
39 assert lst == [1, 4, 9]
40 assert m.load_valarray(lst)
Dean Moldovan83e328f2017-06-09 00:44:49 +020041
42 assert doc(m.cast_valarray) == "cast_valarray() -> List[int]"
43 assert doc(m.load_valarray) == "load_valarray(arg0: List[int]) -> bool"
44
45
46def test_map(doc):
47 """std::map <-> dict"""
48 d = m.cast_map()
49 assert d == {"key": "value"}
50 d["key2"] = "value2"
51 assert m.load_map(d)
52
53 assert doc(m.cast_map) == "cast_map() -> Dict[str, str]"
54 assert doc(m.load_map) == "load_map(arg0: Dict[str, str]) -> bool"
55
56
57def test_set(doc):
58 """std::set <-> set"""
59 s = m.cast_set()
60 assert s == {"key1", "key2"}
61 s.add("key3")
62 assert m.load_set(s)
63
64 assert doc(m.cast_set) == "cast_set() -> Set[str]"
65 assert doc(m.load_set) == "load_set(arg0: Set[str]) -> bool"
66
67
Jason Rhinelanderb57281b2017-07-03 19:12:09 -040068def test_recursive_casting():
69 """Tests that stl casters preserve lvalue/rvalue context for container values"""
70 assert m.cast_rv_vector() == ["rvalue", "rvalue"]
71 assert m.cast_lv_vector() == ["lvalue", "lvalue"]
72 assert m.cast_rv_array() == ["rvalue", "rvalue", "rvalue"]
73 assert m.cast_lv_array() == ["lvalue", "lvalue"]
74 assert m.cast_rv_map() == {"a": "rvalue"}
75 assert m.cast_lv_map() == {"a": "lvalue", "b": "lvalue"}
76 assert m.cast_rv_nested() == [[[{"b": "rvalue", "c": "rvalue"}], [{"a": "rvalue"}]]]
77 assert m.cast_lv_nested() == {
78 "a": [[["lvalue", "lvalue"]], [["lvalue", "lvalue"]]],
79 "b": [[["lvalue", "lvalue"], ["lvalue", "lvalue"]]]
80 }
81
82 # Issue #853 test case:
83 z = m.cast_unique_ptr_vector()
84 assert z[0].value == 7 and z[1].value == 42
85
86
Dean Moldovan83e328f2017-06-09 00:44:49 +020087def test_move_out_container():
88 """Properties use the `reference_internal` policy by default. If the underlying function
89 returns an rvalue, the policy is automatically changed to `move` to avoid referencing
90 a temporary. In case the return value is a container of user-defined types, the policy
91 also needs to be applied to the elements, not just the container."""
92 c = m.MoveOutContainer()
93 moved_out_list = c.move_list
94 assert [x.value for x in moved_out_list] == [0, 1, 2]
95
96
97@pytest.mark.skipif(not hasattr(m, "has_optional"), reason='no <optional>')
98def test_optional():
99 assert m.double_or_zero(None) == 0
100 assert m.double_or_zero(42) == 84
101 pytest.raises(TypeError, m.double_or_zero, 'foo')
102
103 assert m.half_or_none(0) is None
104 assert m.half_or_none(42) == 21
105 pytest.raises(TypeError, m.half_or_none, 'foo')
106
107 assert m.test_nullopt() == 42
108 assert m.test_nullopt(None) == 42
109 assert m.test_nullopt(42) == 42
110 assert m.test_nullopt(43) == 43
111
112 assert m.test_no_assign() == 42
113 assert m.test_no_assign(None) == 42
114 assert m.test_no_assign(m.NoAssign(43)) == 43
115 pytest.raises(TypeError, m.test_no_assign, 43)
116
117 assert m.nodefer_none_optional(None)
118
119
120@pytest.mark.skipif(not hasattr(m, "has_exp_optional"), reason='no <experimental/optional>')
121def test_exp_optional():
122 assert m.double_or_zero_exp(None) == 0
123 assert m.double_or_zero_exp(42) == 84
124 pytest.raises(TypeError, m.double_or_zero_exp, 'foo')
125
126 assert m.half_or_none_exp(0) is None
127 assert m.half_or_none_exp(42) == 21
128 pytest.raises(TypeError, m.half_or_none_exp, 'foo')
129
130 assert m.test_nullopt_exp() == 42
131 assert m.test_nullopt_exp(None) == 42
132 assert m.test_nullopt_exp(42) == 42
133 assert m.test_nullopt_exp(43) == 43
134
135 assert m.test_no_assign_exp() == 42
136 assert m.test_no_assign_exp(None) == 42
137 assert m.test_no_assign_exp(m.NoAssign(43)) == 43
138 pytest.raises(TypeError, m.test_no_assign_exp, 43)
139
140
141@pytest.mark.skipif(not hasattr(m, "load_variant"), reason='no <variant>')
142def test_variant(doc):
143 assert m.load_variant(1) == "int"
144 assert m.load_variant("1") == "std::string"
145 assert m.load_variant(1.0) == "double"
146 assert m.load_variant(None) == "std::nullptr_t"
147
148 assert m.load_variant_2pass(1) == "int"
149 assert m.load_variant_2pass(1.0) == "double"
150
151 assert m.cast_variant() == (5, "Hello")
152
153 assert doc(m.load_variant) == "load_variant(arg0: Union[int, str, float, None]) -> str"
154
155
156def test_vec_of_reference_wrapper():
157 """#171: Can't return reference wrappers (or STL structures containing them)"""
158 assert str(m.return_vec_of_reference_wrapper(UserType(4))) == \
159 "[UserType(1), UserType(2), UserType(3), UserType(4)]"
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200160
161
162def test_stl_pass_by_pointer(msg):
163 """Passing nullptr or None to an STL container pointer is not expected to work"""
164 with pytest.raises(TypeError) as excinfo:
165 m.stl_pass_by_pointer() # default value is `nullptr`
166 assert msg(excinfo.value) == """
167 stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
Antony Lee0826b3c2017-11-26 20:00:35 -0800168 1. (v: List[int] = None) -> List[int]
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200169
170 Invoked with:
171 """ # noqa: E501 line too long
172
173 with pytest.raises(TypeError) as excinfo:
174 m.stl_pass_by_pointer(None)
175 assert msg(excinfo.value) == """
176 stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
Antony Lee0826b3c2017-11-26 20:00:35 -0800177 1. (v: List[int] = None) -> List[int]
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200178
179 Invoked with: None
180 """ # noqa: E501 line too long
181
182 assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200183
184
185def test_missing_header_message():
186 """Trying convert `list` to a `std::vector`, or vice versa, without including
187 <pybind11/stl.h> should result in a helpful suggestion in the error message"""
188 import pybind11_cross_module_tests as cm
189
190 expected_message = ("Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
191 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
192 "conversions are optional and require extra headers to be included\n"
193 "when compiling your pybind11 module.")
194
195 with pytest.raises(TypeError) as excinfo:
196 cm.missing_header_arg([1.0, 2.0, 3.0])
197 assert expected_message in str(excinfo.value)
198
199 with pytest.raises(TypeError) as excinfo:
200 cm.missing_header_return()
201 assert expected_message in str(excinfo.value)
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200202
203
204def test_stl_ownership():
205 cstats = ConstructorStats.get(m.Placeholder)
206 assert cstats.alive() == 0
207 r = m.test_stl_ownership()
208 assert len(r) == 1
209 del r
210 assert cstats.alive() == 0