test_stl.py
Go to the documentation of this file.
1 import pytest
2 
3 from pybind11_tests import ConstructorStats, UserType
4 from pybind11_tests import stl as m
5 
6 
7 def test_vector(doc):
8  """std::vector <-> list"""
9  lst = m.cast_vector()
10  assert lst == [1]
11  lst.append(2)
12  assert m.load_vector(lst)
13  assert m.load_vector(tuple(lst))
14 
15  assert m.cast_bool_vector() == [True, False]
16  assert m.load_bool_vector([True, False])
17  assert m.load_bool_vector((True, False))
18 
19  assert doc(m.cast_vector) == "cast_vector() -> List[int]"
20  assert doc(m.load_vector) == "load_vector(arg0: List[int]) -> bool"
21 
22  # Test regression caused by 936: pointers to stl containers weren't castable
23  assert m.cast_ptr_vector() == ["lvalue", "lvalue"]
24 
25 
26 def test_deque():
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 
35 def test_array(doc):
36  """std::array <-> list"""
37  lst = m.cast_array()
38  assert lst == [1, 2]
39  assert m.load_array(lst)
40  assert m.load_array(tuple(lst))
41 
42  assert doc(m.cast_array) == "cast_array() -> Annotated[List[int], FixedSize(2)]"
43  assert (
44  doc(m.load_array)
45  == "load_array(arg0: Annotated[List[int], FixedSize(2)]) -> bool"
46  )
47 
48 
49 def test_valarray(doc):
50  """std::valarray <-> list"""
51  lst = m.cast_valarray()
52  assert lst == [1, 4, 9]
53  assert m.load_valarray(lst)
54  assert m.load_valarray(tuple(lst))
55 
56  assert doc(m.cast_valarray) == "cast_valarray() -> List[int]"
57  assert doc(m.load_valarray) == "load_valarray(arg0: List[int]) -> bool"
58 
59 
60 def test_map(doc):
61  """std::map <-> dict"""
62  d = m.cast_map()
63  assert d == {"key": "value"}
64  assert "key" in d
65  d["key2"] = "value2"
66  assert "key2" in d
67  assert m.load_map(d)
68 
69  assert doc(m.cast_map) == "cast_map() -> Dict[str, str]"
70  assert doc(m.load_map) == "load_map(arg0: Dict[str, str]) -> bool"
71 
72 
73 def test_set(doc):
74  """std::set <-> set"""
75  s = m.cast_set()
76  assert s == {"key1", "key2"}
77  s.add("key3")
78  assert m.load_set(s)
79  assert m.load_set(frozenset(s))
80 
81  assert doc(m.cast_set) == "cast_set() -> Set[str]"
82  assert doc(m.load_set) == "load_set(arg0: Set[str]) -> bool"
83 
84 
86  """Tests that stl casters preserve lvalue/rvalue context for container values"""
87  assert m.cast_rv_vector() == ["rvalue", "rvalue"]
88  assert m.cast_lv_vector() == ["lvalue", "lvalue"]
89  assert m.cast_rv_array() == ["rvalue", "rvalue", "rvalue"]
90  assert m.cast_lv_array() == ["lvalue", "lvalue"]
91  assert m.cast_rv_map() == {"a": "rvalue"}
92  assert m.cast_lv_map() == {"a": "lvalue", "b": "lvalue"}
93  assert m.cast_rv_nested() == [[[{"b": "rvalue", "c": "rvalue"}], [{"a": "rvalue"}]]]
94  assert m.cast_lv_nested() == {
95  "a": [[["lvalue", "lvalue"]], [["lvalue", "lvalue"]]],
96  "b": [[["lvalue", "lvalue"], ["lvalue", "lvalue"]]],
97  }
98 
99  # Issue #853 test case:
100  z = m.cast_unique_ptr_vector()
101  assert z[0].value == 7
102  assert z[1].value == 42
103 
104 
106  """Properties use the `reference_internal` policy by default. If the underlying function
107  returns an rvalue, the policy is automatically changed to `move` to avoid referencing
108  a temporary. In case the return value is a container of user-defined types, the policy
109  also needs to be applied to the elements, not just the container."""
110  c = m.MoveOutContainer()
111  moved_out_list = c.move_list
112  assert [x.value for x in moved_out_list] == [0, 1, 2]
113 
114 
115 @pytest.mark.skipif(not hasattr(m, "has_optional"), reason="no <optional>")
117  assert m.double_or_zero(None) == 0
118  assert m.double_or_zero(42) == 84
119  pytest.raises(TypeError, m.double_or_zero, "foo")
120 
121  assert m.half_or_none(0) is None
122  assert m.half_or_none(42) == 21
123  pytest.raises(TypeError, m.half_or_none, "foo")
124 
125  assert m.test_nullopt() == 42
126  assert m.test_nullopt(None) == 42
127  assert m.test_nullopt(42) == 42
128  assert m.test_nullopt(43) == 43
129 
130  assert m.test_no_assign() == 42
131  assert m.test_no_assign(None) == 42
132  assert m.test_no_assign(m.NoAssign(43)) == 43
133  pytest.raises(TypeError, m.test_no_assign, 43)
134 
135  assert m.nodefer_none_optional(None)
136 
137  holder = m.OptionalHolder()
138  mvalue = holder.member
139  assert mvalue.initialized
140  assert holder.member_initialized()
141 
142  props = m.OptionalProperties()
143  assert int(props.access_by_ref) == 42
144  assert int(props.access_by_copy) == 42
145 
146 
147 @pytest.mark.skipif(
148  not hasattr(m, "has_exp_optional"), reason="no <experimental/optional>"
149 )
151  assert m.double_or_zero_exp(None) == 0
152  assert m.double_or_zero_exp(42) == 84
153  pytest.raises(TypeError, m.double_or_zero_exp, "foo")
154 
155  assert m.half_or_none_exp(0) is None
156  assert m.half_or_none_exp(42) == 21
157  pytest.raises(TypeError, m.half_or_none_exp, "foo")
158 
159  assert m.test_nullopt_exp() == 42
160  assert m.test_nullopt_exp(None) == 42
161  assert m.test_nullopt_exp(42) == 42
162  assert m.test_nullopt_exp(43) == 43
163 
164  assert m.test_no_assign_exp() == 42
165  assert m.test_no_assign_exp(None) == 42
166  assert m.test_no_assign_exp(m.NoAssign(43)) == 43
167  pytest.raises(TypeError, m.test_no_assign_exp, 43)
168 
169  holder = m.OptionalExpHolder()
170  mvalue = holder.member
171  assert mvalue.initialized
172  assert holder.member_initialized()
173 
174  props = m.OptionalExpProperties()
175  assert int(props.access_by_ref) == 42
176  assert int(props.access_by_copy) == 42
177 
178 
179 @pytest.mark.skipif(not hasattr(m, "has_boost_optional"), reason="no <boost/optional>")
181  assert m.double_or_zero_boost(None) == 0
182  assert m.double_or_zero_boost(42) == 84
183  pytest.raises(TypeError, m.double_or_zero_boost, "foo")
184 
185  assert m.half_or_none_boost(0) is None
186  assert m.half_or_none_boost(42) == 21
187  pytest.raises(TypeError, m.half_or_none_boost, "foo")
188 
189  assert m.test_nullopt_boost() == 42
190  assert m.test_nullopt_boost(None) == 42
191  assert m.test_nullopt_boost(42) == 42
192  assert m.test_nullopt_boost(43) == 43
193 
194  assert m.test_no_assign_boost() == 42
195  assert m.test_no_assign_boost(None) == 42
196  assert m.test_no_assign_boost(m.NoAssign(43)) == 43
197  pytest.raises(TypeError, m.test_no_assign_boost, 43)
198 
199  holder = m.OptionalBoostHolder()
200  mvalue = holder.member
201  assert mvalue.initialized
202  assert holder.member_initialized()
203 
204  props = m.OptionalBoostProperties()
205  assert int(props.access_by_ref) == 42
206  assert int(props.access_by_copy) == 42
207 
208 
210  assert m.double_or_zero_refsensitive(None) == 0
211  assert m.double_or_zero_refsensitive(42) == 84
212  pytest.raises(TypeError, m.double_or_zero_refsensitive, "foo")
213 
214  assert m.half_or_none_refsensitive(0) is None
215  assert m.half_or_none_refsensitive(42) == 21
216  pytest.raises(TypeError, m.half_or_none_refsensitive, "foo")
217 
218  assert m.test_nullopt_refsensitive() == 42
219  assert m.test_nullopt_refsensitive(None) == 42
220  assert m.test_nullopt_refsensitive(42) == 42
221  assert m.test_nullopt_refsensitive(43) == 43
222 
223  assert m.test_no_assign_refsensitive() == 42
224  assert m.test_no_assign_refsensitive(None) == 42
225  assert m.test_no_assign_refsensitive(m.NoAssign(43)) == 43
226  pytest.raises(TypeError, m.test_no_assign_refsensitive, 43)
227 
228  holder = m.OptionalRefSensitiveHolder()
229  mvalue = holder.member
230  assert mvalue.initialized
231  assert holder.member_initialized()
232 
233  props = m.OptionalRefSensitiveProperties()
234  assert int(props.access_by_ref) == 42
235  assert int(props.access_by_copy) == 42
236 
237 
238 @pytest.mark.skipif(not hasattr(m, "has_filesystem"), reason="no <filesystem>")
240  from pathlib import Path
241 
242  class PseudoStrPath:
243  def __fspath__(self):
244  return "foo/bar"
245 
246  class PseudoBytesPath:
247  def __fspath__(self):
248  return b"foo/bar"
249 
250  assert m.parent_path(Path("foo/bar")) == Path("foo")
251  assert m.parent_path("foo/bar") == Path("foo")
252  assert m.parent_path(b"foo/bar") == Path("foo")
253  assert m.parent_path(PseudoStrPath()) == Path("foo")
254  assert m.parent_path(PseudoBytesPath()) == Path("foo")
255 
256 
257 @pytest.mark.skipif(not hasattr(m, "load_variant"), reason="no <variant>")
258 def test_variant(doc):
259  assert m.load_variant(1) == "int"
260  assert m.load_variant("1") == "std::string"
261  assert m.load_variant(1.0) == "double"
262  assert m.load_variant(None) == "std::nullptr_t"
263 
264  assert m.load_variant_2pass(1) == "int"
265  assert m.load_variant_2pass(1.0) == "double"
266 
267  assert m.cast_variant() == (5, "Hello")
268 
269  assert (
270  doc(m.load_variant) == "load_variant(arg0: Union[int, str, float, None]) -> str"
271  )
272 
273 
274 @pytest.mark.skipif(
275  not hasattr(m, "load_monostate_variant"), reason="no std::monostate"
276 )
278  assert m.load_monostate_variant(None) == "std::monostate"
279  assert m.load_monostate_variant(1) == "int"
280  assert m.load_monostate_variant("1") == "std::string"
281 
282  assert m.cast_monostate_variant() == (None, 5, "Hello")
283 
284  assert (
285  doc(m.load_monostate_variant)
286  == "load_monostate_variant(arg0: Union[None, int, str]) -> str"
287  )
288 
289 
291  """#171: Can't return reference wrappers (or STL structures containing them)"""
292  assert (
293  str(m.return_vec_of_reference_wrapper(UserType(4)))
294  == "[UserType(1), UserType(2), UserType(3), UserType(4)]"
295  )
296 
297 
299  """Passing nullptr or None to an STL container pointer is not expected to work"""
300  with pytest.raises(TypeError) as excinfo:
301  m.stl_pass_by_pointer() # default value is `nullptr`
302  assert (
303  msg(excinfo.value)
304  == """
305  stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
306  1. (v: List[int] = None) -> List[int]
307 
308  Invoked with:
309  """
310  )
311 
312  with pytest.raises(TypeError) as excinfo:
313  m.stl_pass_by_pointer(None)
314  assert (
315  msg(excinfo.value)
316  == """
317  stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
318  1. (v: List[int] = None) -> List[int]
319 
320  Invoked with: None
321  """
322  )
323 
324  assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]
325 
326 
328  """Trying convert `list` to a `std::vector`, or vice versa, without including
329  <pybind11/stl.h> should result in a helpful suggestion in the error message"""
330  import pybind11_cross_module_tests as cm
331 
332  expected_message = (
333  "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
334  "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
335  "conversions are optional and require extra headers to be included\n"
336  "when compiling your pybind11 module."
337  )
338 
339  with pytest.raises(TypeError) as excinfo:
340  cm.missing_header_arg([1.0, 2.0, 3.0])
341  assert expected_message in str(excinfo.value)
342 
343  with pytest.raises(TypeError) as excinfo:
344  cm.missing_header_return()
345  assert expected_message in str(excinfo.value)
346 
347 
349  """Check if a string is NOT implicitly converted to a list, which was the
350  behavior before fix of issue #1258"""
351  assert m.func_with_string_or_vector_string_arg_overload(("A", "B")) == 2
352  assert m.func_with_string_or_vector_string_arg_overload(["A", "B"]) == 2
353  assert m.func_with_string_or_vector_string_arg_overload("A") == 3
354 
355 
357  cstats = ConstructorStats.get(m.Placeholder)
358  assert cstats.alive() == 0
359  r = m.test_stl_ownership()
360  assert len(r) == 1
361  del r
362  assert cstats.alive() == 0
363 
364 
366  assert m.array_cast_sequence((1, 2, 3)) == [1, 2, 3]
367 
368 
370  """check fix for issue #1561"""
371  bar = m.Issue1561Outer()
372  bar.list = [m.Issue1561Inner("bar")]
373  assert bar.list
374  assert bar.list[0].data == "bar"
375 
376 
378  # Add `while True:` for manual leak checking.
379  v = m.return_vector_bool_raw_ptr()
380  assert isinstance(v, list)
381  assert len(v) == 4513
test_stl.test_optional
def test_optional()
Definition: test_stl.py:116
gtsam.examples.DogLegOptimizerExample.int
int
Definition: DogLegOptimizerExample.py:111
test_stl.test_stl_ownership
def test_stl_ownership()
Definition: test_stl.py:356
test_stl.test_function_with_string_and_vector_string_arg
def test_function_with_string_and_vector_string_arg()
Definition: test_stl.py:348
test_stl.test_return_vector_bool_raw_ptr
def test_return_vector_bool_raw_ptr()
Definition: test_stl.py:377
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:853
test_stl.test_valarray
def test_valarray(doc)
Definition: test_stl.py:49
test_stl.test_deque
def test_deque()
Definition: test_stl.py:26
test_stl.test_vec_of_reference_wrapper
def test_vec_of_reference_wrapper()
Definition: test_stl.py:290
test_stl.test_map
def test_map(doc)
Definition: test_stl.py:60
test_stl.test_move_out_container
def test_move_out_container()
Definition: test_stl.py:105
doc
Annotation for documentation.
Definition: attr.h:45
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:825
test_stl.test_variant
def test_variant(doc)
Definition: test_stl.py:258
test_stl.test_issue_1561
def test_issue_1561()
Definition: test_stl.py:369
test_stl.test_missing_header_message
def test_missing_header_message()
Definition: test_stl.py:327
test_stl.test_set
def test_set(doc)
Definition: test_stl.py:73
test_stl.test_array
def test_array(doc)
Definition: test_stl.py:35
test_stl.test_variant_monostate
def test_variant_monostate(doc)
Definition: test_stl.py:277
str
Definition: pytypes.h:1524
test_stl.test_exp_optional
def test_exp_optional()
Definition: test_stl.py:150
test_stl.test_reference_sensitive_optional
def test_reference_sensitive_optional()
Definition: test_stl.py:209
test_stl.test_boost_optional
def test_boost_optional()
Definition: test_stl.py:180
test_stl.test_vector
def test_vector(doc)
Definition: test_stl.py:7
test_stl.test_array_cast_sequence
def test_array_cast_sequence()
Definition: test_stl.py:365
ConstructorStats::get
static ConstructorStats & get(std::type_index type)
Definition: constructor_stats.h:163
test_stl.test_fs_path
def test_fs_path()
Definition: test_stl.py:239
tuple
Definition: pytypes.h:2035
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2399
test_stl.test_stl_pass_by_pointer
def test_stl_pass_by_pointer(msg)
Definition: test_stl.py:298
frozenset
Definition: pytypes.h:2200
test_stl.test_recursive_casting
def test_recursive_casting()
Definition: test_stl.py:85
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:4


gtsam
Author(s):
autogenerated on Tue Jun 25 2024 03:05:31