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


gtsam
Author(s):
autogenerated on Sat May 8 2021 02:46:04