"vscode:/vscode.git/clone" did not exist on "d0b49a144f20b5b132bbb6c11f9f8f73c37633a3"
test_stl.py 8.64 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
3
4
5
import pytest

from pybind11_tests import stl as m
from pybind11_tests import UserType
6
from pybind11_tests import ConstructorStats
7
8
9
10


def test_vector(doc):
    """std::vector <-> list"""
11
12
13
14
15
    lst = m.cast_vector()
    assert lst == [1]
    lst.append(2)
    assert m.load_vector(lst)
    assert m.load_vector(tuple(lst))
16

17
18
19
    assert m.cast_bool_vector() == [True, False]
    assert m.load_bool_vector([True, False])

20
21
22
    assert doc(m.cast_vector) == "cast_vector() -> List[int]"
    assert doc(m.load_vector) == "load_vector(arg0: List[int]) -> bool"

23
24
25
    # Test regression caused by 936: pointers to stl containers weren't castable
    assert m.cast_ptr_vector() == ["lvalue", "lvalue"]

26

27
28
29
30
31
32
33
34
35
def test_deque(doc):
    """std::deque <-> list"""
    lst = m.cast_deque()
    assert lst == [1]
    lst.append(2)
    assert m.load_deque(lst)
    assert m.load_deque(tuple(lst))


36
37
def test_array(doc):
    """std::array <-> list"""
38
39
40
    lst = m.cast_array()
    assert lst == [1, 2]
    assert m.load_array(lst)
41
42
43
44
45
46
47

    assert doc(m.cast_array) == "cast_array() -> List[int[2]]"
    assert doc(m.load_array) == "load_array(arg0: List[int[2]]) -> bool"


def test_valarray(doc):
    """std::valarray <-> list"""
48
49
50
    lst = m.cast_valarray()
    assert lst == [1, 4, 9]
    assert m.load_valarray(lst)
51
52
53
54
55
56
57
58
59

    assert doc(m.cast_valarray) == "cast_valarray() -> List[int]"
    assert doc(m.load_valarray) == "load_valarray(arg0: List[int]) -> bool"


def test_map(doc):
    """std::map <-> dict"""
    d = m.cast_map()
    assert d == {"key": "value"}
60
    assert "key" in d
61
    d["key2"] = "value2"
62
    assert "key2" in d
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    assert m.load_map(d)

    assert doc(m.cast_map) == "cast_map() -> Dict[str, str]"
    assert doc(m.load_map) == "load_map(arg0: Dict[str, str]) -> bool"


def test_set(doc):
    """std::set <-> set"""
    s = m.cast_set()
    assert s == {"key1", "key2"}
    s.add("key3")
    assert m.load_set(s)

    assert doc(m.cast_set) == "cast_set() -> Set[str]"
    assert doc(m.load_set) == "load_set(arg0: Set[str]) -> bool"


80
81
82
83
84
85
86
87
88
89
90
def test_recursive_casting():
    """Tests that stl casters preserve lvalue/rvalue context for container values"""
    assert m.cast_rv_vector() == ["rvalue", "rvalue"]
    assert m.cast_lv_vector() == ["lvalue", "lvalue"]
    assert m.cast_rv_array() == ["rvalue", "rvalue", "rvalue"]
    assert m.cast_lv_array() == ["lvalue", "lvalue"]
    assert m.cast_rv_map() == {"a": "rvalue"}
    assert m.cast_lv_map() == {"a": "lvalue", "b": "lvalue"}
    assert m.cast_rv_nested() == [[[{"b": "rvalue", "c": "rvalue"}], [{"a": "rvalue"}]]]
    assert m.cast_lv_nested() == {
        "a": [[["lvalue", "lvalue"]], [["lvalue", "lvalue"]]],
91
        "b": [[["lvalue", "lvalue"], ["lvalue", "lvalue"]]],
92
93
94
95
96
97
98
    }

    # Issue #853 test case:
    z = m.cast_unique_ptr_vector()
    assert z[0].value == 7 and z[1].value == 42


99
100
101
102
103
104
105
106
107
108
def test_move_out_container():
    """Properties use the `reference_internal` policy by default. If the underlying function
    returns an rvalue, the policy is automatically changed to `move` to avoid referencing
    a temporary. In case the return value is a container of user-defined types, the policy
    also needs to be applied to the elements, not just the container."""
    c = m.MoveOutContainer()
    moved_out_list = c.move_list
    assert [x.value for x in moved_out_list] == [0, 1, 2]


109
@pytest.mark.skipif(not hasattr(m, "has_optional"), reason="no <optional>")
110
111
112
def test_optional():
    assert m.double_or_zero(None) == 0
    assert m.double_or_zero(42) == 84
113
    pytest.raises(TypeError, m.double_or_zero, "foo")
114
115
116

    assert m.half_or_none(0) is None
    assert m.half_or_none(42) == 21
117
    pytest.raises(TypeError, m.half_or_none, "foo")
118
119
120
121
122
123
124
125
126
127
128
129
130

    assert m.test_nullopt() == 42
    assert m.test_nullopt(None) == 42
    assert m.test_nullopt(42) == 42
    assert m.test_nullopt(43) == 43

    assert m.test_no_assign() == 42
    assert m.test_no_assign(None) == 42
    assert m.test_no_assign(m.NoAssign(43)) == 43
    pytest.raises(TypeError, m.test_no_assign, 43)

    assert m.nodefer_none_optional(None)

fatvlady's avatar
fatvlady committed
131
132
133
134
135
    holder = m.OptionalHolder()
    mvalue = holder.member
    assert mvalue.initialized
    assert holder.member_initialized()

136

137
138
139
@pytest.mark.skipif(
    not hasattr(m, "has_exp_optional"), reason="no <experimental/optional>"
)
140
141
142
def test_exp_optional():
    assert m.double_or_zero_exp(None) == 0
    assert m.double_or_zero_exp(42) == 84
143
    pytest.raises(TypeError, m.double_or_zero_exp, "foo")
144
145
146

    assert m.half_or_none_exp(0) is None
    assert m.half_or_none_exp(42) == 21
147
    pytest.raises(TypeError, m.half_or_none_exp, "foo")
148
149
150
151
152
153
154
155
156
157
158

    assert m.test_nullopt_exp() == 42
    assert m.test_nullopt_exp(None) == 42
    assert m.test_nullopt_exp(42) == 42
    assert m.test_nullopt_exp(43) == 43

    assert m.test_no_assign_exp() == 42
    assert m.test_no_assign_exp(None) == 42
    assert m.test_no_assign_exp(m.NoAssign(43)) == 43
    pytest.raises(TypeError, m.test_no_assign_exp, 43)

fatvlady's avatar
fatvlady committed
159
160
161
162
163
    holder = m.OptionalExpHolder()
    mvalue = holder.member
    assert mvalue.initialized
    assert holder.member_initialized()

164

165
@pytest.mark.skipif(not hasattr(m, "load_variant"), reason="no <variant>")
166
167
168
169
170
171
172
173
174
175
176
def test_variant(doc):
    assert m.load_variant(1) == "int"
    assert m.load_variant("1") == "std::string"
    assert m.load_variant(1.0) == "double"
    assert m.load_variant(None) == "std::nullptr_t"

    assert m.load_variant_2pass(1) == "int"
    assert m.load_variant_2pass(1.0) == "double"

    assert m.cast_variant() == (5, "Hello")

177
178
179
    assert (
        doc(m.load_variant) == "load_variant(arg0: Union[int, str, float, None]) -> str"
    )
180
181
182
183


def test_vec_of_reference_wrapper():
    """#171: Can't return reference wrappers (or STL structures containing them)"""
184
185
186
187
    assert (
        str(m.return_vec_of_reference_wrapper(UserType(4)))
        == "[UserType(1), UserType(2), UserType(3), UserType(4)]"
    )
188
189
190
191
192
193


def test_stl_pass_by_pointer(msg):
    """Passing nullptr or None to an STL container pointer is not expected to work"""
    with pytest.raises(TypeError) as excinfo:
        m.stl_pass_by_pointer()  # default value is `nullptr`
194
195
196
    assert (
        msg(excinfo.value)
        == """
197
        stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
198
            1. (v: List[int] = None) -> List[int]
199
200
201

        Invoked with:
    """  # noqa: E501 line too long
202
    )
203
204
205

    with pytest.raises(TypeError) as excinfo:
        m.stl_pass_by_pointer(None)
206
207
208
    assert (
        msg(excinfo.value)
        == """
209
        stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:
210
            1. (v: List[int] = None) -> List[int]
211
212
213

        Invoked with: None
    """  # noqa: E501 line too long
214
    )
215
216

    assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]
217
218
219
220
221
222
223


def test_missing_header_message():
    """Trying convert `list` to a `std::vector`, or vice versa, without including
    <pybind11/stl.h> should result in a helpful suggestion in the error message"""
    import pybind11_cross_module_tests as cm

224
225
226
227
228
229
    expected_message = (
        "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
        "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
        "conversions are optional and require extra headers to be included\n"
        "when compiling your pybind11 module."
    )
230
231
232
233
234
235
236
237

    with pytest.raises(TypeError) as excinfo:
        cm.missing_header_arg([1.0, 2.0, 3.0])
    assert expected_message in str(excinfo.value)

    with pytest.raises(TypeError) as excinfo:
        cm.missing_header_return()
    assert expected_message in str(excinfo.value)
238
239


Allan Leal's avatar
Allan Leal committed
240
241
242
def test_function_with_string_and_vector_string_arg():
    """Check if a string is NOT implicitly converted to a list, which was the
    behavior before fix of issue #1258"""
243
244
245
    assert m.func_with_string_or_vector_string_arg_overload(("A", "B")) == 2
    assert m.func_with_string_or_vector_string_arg_overload(["A", "B"]) == 2
    assert m.func_with_string_or_vector_string_arg_overload("A") == 3
Allan Leal's avatar
Allan Leal committed
246
247


248
249
def test_bytes_to_vector_uint8_t():
    """Check if a bytes is implicitly converted to std::vector<uint8_t>, issue #1807"""
250
    assert m.func_with_vector_uint8_t_arg([ord(c) for c in b'abc']) == 3
251
252
253
254
    with pytest.raises(TypeError):
        m.func_with_vector_uint8_t_arg('stringval')


255
256
257
258
259
260
261
def test_stl_ownership():
    cstats = ConstructorStats.get(m.Placeholder)
    assert cstats.alive() == 0
    r = m.test_stl_ownership()
    assert len(r) == 1
    del r
    assert cstats.alive() == 0
262
263
264
265


def test_array_cast_sequence():
    assert m.array_cast_sequence((1, 2, 3)) == [1, 2, 3]
266
267
268
269
270


def test_issue_1561():
    """ check fix for issue #1561 """
    bar = m.Issue1561Outer()
271
    bar.list = [m.Issue1561Inner("bar")]
272
    bar.list
273
    assert bar.list[0].data == "bar"