cppyabm  1.0.17
An agent-based library to integrate C++ and Python
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(
138  not hasattr(m, "has_exp_optional"), reason="no <experimental/optional>"
139 )
141  assert m.double_or_zero_exp(None) == 0
142  assert m.double_or_zero_exp(42) == 84
143  pytest.raises(TypeError, m.double_or_zero_exp, "foo")
144 
145  assert m.half_or_none_exp(0) is None
146  assert m.half_or_none_exp(42) == 21
147  pytest.raises(TypeError, m.half_or_none_exp, "foo")
148 
149  assert m.test_nullopt_exp() == 42
150  assert m.test_nullopt_exp(None) == 42
151  assert m.test_nullopt_exp(42) == 42
152  assert m.test_nullopt_exp(43) == 43
153 
154  assert m.test_no_assign_exp() == 42
155  assert m.test_no_assign_exp(None) == 42
156  assert m.test_no_assign_exp(m.NoAssign(43)) == 43
157  pytest.raises(TypeError, m.test_no_assign_exp, 43)
158 
159  holder = m.OptionalExpHolder()
160  mvalue = holder.member
161  assert mvalue.initialized
162  assert holder.member_initialized()
163 
164 
165 @pytest.mark.skipif(not hasattr(m, "load_variant"), reason="no <variant>")
166 def test_variant(doc):
167  assert m.load_variant(1) == "int"
168  assert m.load_variant("1") == "std::string"
169  assert m.load_variant(1.0) == "double"
170  assert m.load_variant(None) == "std::nullptr_t"
171 
172  assert m.load_variant_2pass(1) == "int"
173  assert m.load_variant_2pass(1.0) == "double"
174 
175  assert m.cast_variant() == (5, "Hello")
176 
177  assert (
178  doc(m.load_variant) == "load_variant(arg0: Union[int, str, float, None]) -> str"
179  )
180 
181 
183  """#171: Can't return reference wrappers (or STL structures containing them)"""
184  assert (
185  str(m.return_vec_of_reference_wrapper(UserType(4)))
186  == "[UserType(1), UserType(2), UserType(3), UserType(4)]"
187  )
188 
189 
191  """Passing nullptr or None to an STL container pointer is not expected to work"""
192  with pytest.raises(TypeError) as excinfo:
193  m.stl_pass_by_pointer() # default value is `nullptr`
194  assert (
195  msg(excinfo.value)
196  == """
197  stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
198  1. (v: List[int] = None) -> List[int]
199 
200  Invoked with:
201  """ # noqa: E501 line too long
202  )
203 
204  with pytest.raises(TypeError) as excinfo:
205  m.stl_pass_by_pointer(None)
206  assert (
207  msg(excinfo.value)
208  == """
209  stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
210  1. (v: List[int] = None) -> List[int]
211 
212  Invoked with: None
213  """ # noqa: E501 line too long
214  )
215 
216  assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]
217 
218 
220  """Trying convert `list` to a `std::vector`, or vice versa, without including
221  <pybind11/stl.h> should result in a helpful suggestion in the error message"""
222  import pybind11_cross_module_tests as cm
223 
224  expected_message = (
225  "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
226  "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
227  "conversions are optional and require extra headers to be included\n"
228  "when compiling your pybind11 module."
229  )
230 
231  with pytest.raises(TypeError) as excinfo:
232  cm.missing_header_arg([1.0, 2.0, 3.0])
233  assert expected_message in str(excinfo.value)
234 
235  with pytest.raises(TypeError) as excinfo:
236  cm.missing_header_return()
237  assert expected_message in str(excinfo.value)
238 
239 
241  """Check if a string is NOT implicitly converted to a list, which was the
242  behavior before fix of issue #1258"""
243  assert m.func_with_string_or_vector_string_arg_overload(("A", "B")) == 2
244  assert m.func_with_string_or_vector_string_arg_overload(["A", "B"]) == 2
245  assert m.func_with_string_or_vector_string_arg_overload("A") == 3
246 
247 
249  cstats = ConstructorStats.get(m.Placeholder)
250  assert cstats.alive() == 0
251  r = m.test_stl_ownership()
252  assert len(r) == 1
253  del r
254  assert cstats.alive() == 0
255 
256 
258  assert m.array_cast_sequence((1, 2, 3)) == [1, 2, 3]
259 
260 
262  """ check fix for issue #1561 """
263  bar = m.Issue1561Outer()
264  bar.list = [m.Issue1561Inner("bar")]
265  bar.list
266  assert bar.list[0].data == "bar"
test_stl.test_optional
def test_optional()
Definition: test_stl.py:110
test_stl.test_stl_ownership
def test_stl_ownership()
Definition: test_stl.py:248
test_stl.test_function_with_string_and_vector_string_arg
def test_function_with_string_and_vector_string_arg()
Definition: test_stl.py:240
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:405
test_stl.test_valarray
def test_valarray(doc)
Definition: test_stl.py:46
test_stl.test_vec_of_reference_wrapper
def test_vec_of_reference_wrapper()
Definition: test_stl.py:182
test_stl.test_map
def test_map(doc)
Definition: test_stl.py:56
ConstructorStats::get
static ConstructorStats & get(std::type_index type)
Definition: constructor_stats.h:154
test_stl.test_move_out_container
def test_move_out_container()
Definition: test_stl.py:99
doc
Annotation for documentation.
Definition: attr.h:33
test_stl.test_variant
def test_variant(doc)
Definition: test_stl.py:166
test_stl.test_issue_1561
def test_issue_1561()
Definition: test_stl.py:261
test_stl.test_missing_header_message
def test_missing_header_message()
Definition: test_stl.py:219
test_stl.test_set
def test_set(doc)
Definition: test_stl.py:69
test_stl.test_array
def test_array(doc)
Definition: test_stl.py:36
str
Definition: pytypes.h:946
test_stl.test_deque
def test_deque(doc)
Definition: test_stl.py:27
test_stl.test_exp_optional
def test_exp_optional()
Definition: test_stl.py:140
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:257
tuple
Definition: pytypes.h:1276
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:1560
test_stl.test_stl_pass_by_pointer
def test_stl_pass_by_pointer(msg)
Definition: test_stl.py:190
test_stl.test_recursive_casting
def test_recursive_casting()
Definition: test_stl.py:80
setup.msg
msg
Definition: setup.py:47