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


gtsam
Author(s):
autogenerated on Fri Nov 1 2024 03:39:31