test_builtin_casters.py revision 14299:2fbea9df56d2
1# Python < 3 needs this: coding=utf-8
2import pytest
3
4from pybind11_tests import builtin_casters as m
5from pybind11_tests import UserType, IncType
6
7
8def test_simple_string():
9    assert m.string_roundtrip("const char *") == "const char *"
10
11
12def test_unicode_conversion():
13    """Tests unicode conversion and error reporting."""
14    assert m.good_utf8_string() == u"Say utf8‽ �� ��"
15    assert m.good_utf16_string() == u"b‽����z"
16    assert m.good_utf32_string() == u"a����‽z"
17    assert m.good_wchar_string() == u"a⸘��z"
18
19    with pytest.raises(UnicodeDecodeError):
20        m.bad_utf8_string()
21
22    with pytest.raises(UnicodeDecodeError):
23        m.bad_utf16_string()
24
25    # These are provided only if they actually fail (they don't when 32-bit and under Python 2.7)
26    if hasattr(m, "bad_utf32_string"):
27        with pytest.raises(UnicodeDecodeError):
28            m.bad_utf32_string()
29    if hasattr(m, "bad_wchar_string"):
30        with pytest.raises(UnicodeDecodeError):
31            m.bad_wchar_string()
32
33    assert m.u8_Z() == 'Z'
34    assert m.u8_eacute() == u'é'
35    assert m.u16_ibang() == u'‽'
36    assert m.u32_mathbfA() == u'��'
37    assert m.wchar_heart() == u'♥'
38
39
40def test_single_char_arguments():
41    """Tests failures for passing invalid inputs to char-accepting functions"""
42    def toobig_message(r):
43        return "Character code point not in range({0:#x})".format(r)
44    toolong_message = "Expected a character, but multi-character string found"
45
46    assert m.ord_char(u'a') == 0x61  # simple ASCII
47    assert m.ord_char_lv(u'b') == 0x62
48    assert m.ord_char(u'é') == 0xE9  # requires 2 bytes in utf-8, but can be stuffed in a char
49    with pytest.raises(ValueError) as excinfo:
50        assert m.ord_char(u'Ā') == 0x100  # requires 2 bytes, doesn't fit in a char
51    assert str(excinfo.value) == toobig_message(0x100)
52    with pytest.raises(ValueError) as excinfo:
53        assert m.ord_char(u'ab')
54    assert str(excinfo.value) == toolong_message
55
56    assert m.ord_char16(u'a') == 0x61
57    assert m.ord_char16(u'é') == 0xE9
58    assert m.ord_char16_lv(u'ê') == 0xEA
59    assert m.ord_char16(u'Ā') == 0x100
60    assert m.ord_char16(u'‽') == 0x203d
61    assert m.ord_char16(u'♥') == 0x2665
62    assert m.ord_char16_lv(u'♡') == 0x2661
63    with pytest.raises(ValueError) as excinfo:
64        assert m.ord_char16(u'��') == 0x1F382  # requires surrogate pair
65    assert str(excinfo.value) == toobig_message(0x10000)
66    with pytest.raises(ValueError) as excinfo:
67        assert m.ord_char16(u'aa')
68    assert str(excinfo.value) == toolong_message
69
70    assert m.ord_char32(u'a') == 0x61
71    assert m.ord_char32(u'é') == 0xE9
72    assert m.ord_char32(u'Ā') == 0x100
73    assert m.ord_char32(u'‽') == 0x203d
74    assert m.ord_char32(u'♥') == 0x2665
75    assert m.ord_char32(u'��') == 0x1F382
76    with pytest.raises(ValueError) as excinfo:
77        assert m.ord_char32(u'aa')
78    assert str(excinfo.value) == toolong_message
79
80    assert m.ord_wchar(u'a') == 0x61
81    assert m.ord_wchar(u'é') == 0xE9
82    assert m.ord_wchar(u'Ā') == 0x100
83    assert m.ord_wchar(u'‽') == 0x203d
84    assert m.ord_wchar(u'♥') == 0x2665
85    if m.wchar_size == 2:
86        with pytest.raises(ValueError) as excinfo:
87            assert m.ord_wchar(u'��') == 0x1F382  # requires surrogate pair
88        assert str(excinfo.value) == toobig_message(0x10000)
89    else:
90        assert m.ord_wchar(u'��') == 0x1F382
91    with pytest.raises(ValueError) as excinfo:
92        assert m.ord_wchar(u'aa')
93    assert str(excinfo.value) == toolong_message
94
95
96def test_bytes_to_string():
97    """Tests the ability to pass bytes to C++ string-accepting functions.  Note that this is
98    one-way: the only way to return bytes to Python is via the pybind11::bytes class."""
99    # Issue #816
100    import sys
101    byte = bytes if sys.version_info[0] < 3 else str
102
103    assert m.strlen(byte("hi")) == 2
104    assert m.string_length(byte("world")) == 5
105    assert m.string_length(byte("a\x00b")) == 3
106    assert m.strlen(byte("a\x00b")) == 1  # C-string limitation
107
108    # passing in a utf8 encoded string should work
109    assert m.string_length(u'��'.encode("utf8")) == 4
110
111
112@pytest.mark.skipif(not hasattr(m, "has_string_view"), reason="no <string_view>")
113def test_string_view(capture):
114    """Tests support for C++17 string_view arguments and return values"""
115    assert m.string_view_chars("Hi") == [72, 105]
116    assert m.string_view_chars("Hi ��") == [72, 105, 32, 0xf0, 0x9f, 0x8e, 0x82]
117    assert m.string_view16_chars("Hi ��") == [72, 105, 32, 0xd83c, 0xdf82]
118    assert m.string_view32_chars("Hi ��") == [72, 105, 32, 127874]
119
120    assert m.string_view_return() == "utf8 secret ��"
121    assert m.string_view16_return() == "utf16 secret ��"
122    assert m.string_view32_return() == "utf32 secret ��"
123
124    with capture:
125        m.string_view_print("Hi")
126        m.string_view_print("utf8 ��")
127        m.string_view16_print("utf16 ��")
128        m.string_view32_print("utf32 ��")
129    assert capture == """
130        Hi 2
131        utf8 �� 9
132        utf16 �� 8
133        utf32 �� 7
134    """
135
136    with capture:
137        m.string_view_print("Hi, ascii")
138        m.string_view_print("Hi, utf8 ��")
139        m.string_view16_print("Hi, utf16 ��")
140        m.string_view32_print("Hi, utf32 ��")
141    assert capture == """
142        Hi, ascii 9
143        Hi, utf8 �� 13
144        Hi, utf16 �� 12
145        Hi, utf32 �� 11
146    """
147
148
149def test_integer_casting():
150    """Issue #929 - out-of-range integer values shouldn't be accepted"""
151    import sys
152    assert m.i32_str(-1) == "-1"
153    assert m.i64_str(-1) == "-1"
154    assert m.i32_str(2000000000) == "2000000000"
155    assert m.u32_str(2000000000) == "2000000000"
156    if sys.version_info < (3,):
157        assert m.i32_str(long(-1)) == "-1"  # noqa: F821 undefined name 'long'
158        assert m.i64_str(long(-1)) == "-1"  # noqa: F821 undefined name 'long'
159        assert m.i64_str(long(-999999999999)) == "-999999999999"  # noqa: F821 undefined name
160        assert m.u64_str(long(999999999999)) == "999999999999"  # noqa: F821 undefined name 'long'
161    else:
162        assert m.i64_str(-999999999999) == "-999999999999"
163        assert m.u64_str(999999999999) == "999999999999"
164
165    with pytest.raises(TypeError) as excinfo:
166        m.u32_str(-1)
167    assert "incompatible function arguments" in str(excinfo.value)
168    with pytest.raises(TypeError) as excinfo:
169        m.u64_str(-1)
170    assert "incompatible function arguments" in str(excinfo.value)
171    with pytest.raises(TypeError) as excinfo:
172        m.i32_str(-3000000000)
173    assert "incompatible function arguments" in str(excinfo.value)
174    with pytest.raises(TypeError) as excinfo:
175        m.i32_str(3000000000)
176    assert "incompatible function arguments" in str(excinfo.value)
177
178    if sys.version_info < (3,):
179        with pytest.raises(TypeError) as excinfo:
180            m.u32_str(long(-1))  # noqa: F821 undefined name 'long'
181        assert "incompatible function arguments" in str(excinfo.value)
182        with pytest.raises(TypeError) as excinfo:
183            m.u64_str(long(-1))  # noqa: F821 undefined name 'long'
184        assert "incompatible function arguments" in str(excinfo.value)
185
186
187def test_tuple(doc):
188    """std::pair <-> tuple & std::tuple <-> tuple"""
189    assert m.pair_passthrough((True, "test")) == ("test", True)
190    assert m.tuple_passthrough((True, "test", 5)) == (5, "test", True)
191    # Any sequence can be cast to a std::pair or std::tuple
192    assert m.pair_passthrough([True, "test"]) == ("test", True)
193    assert m.tuple_passthrough([True, "test", 5]) == (5, "test", True)
194    assert m.empty_tuple() == ()
195
196    assert doc(m.pair_passthrough) == """
197        pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool]
198
199        Return a pair in reversed order
200    """
201    assert doc(m.tuple_passthrough) == """
202        tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool]
203
204        Return a triple in reversed order
205    """
206
207    assert m.rvalue_pair() == ("rvalue", "rvalue")
208    assert m.lvalue_pair() == ("lvalue", "lvalue")
209    assert m.rvalue_tuple() == ("rvalue", "rvalue", "rvalue")
210    assert m.lvalue_tuple() == ("lvalue", "lvalue", "lvalue")
211    assert m.rvalue_nested() == ("rvalue", ("rvalue", ("rvalue", "rvalue")))
212    assert m.lvalue_nested() == ("lvalue", ("lvalue", ("lvalue", "lvalue")))
213
214
215def test_builtins_cast_return_none():
216    """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
217    assert m.return_none_string() is None
218    assert m.return_none_char() is None
219    assert m.return_none_bool() is None
220    assert m.return_none_int() is None
221    assert m.return_none_float() is None
222
223
224def test_none_deferred():
225    """None passed as various argument types should defer to other overloads"""
226    assert not m.defer_none_cstring("abc")
227    assert m.defer_none_cstring(None)
228    assert not m.defer_none_custom(UserType())
229    assert m.defer_none_custom(None)
230    assert m.nodefer_none_void(None)
231
232
233def test_void_caster():
234    assert m.load_nullptr_t(None) is None
235    assert m.cast_nullptr_t() is None
236
237
238def test_reference_wrapper():
239    """std::reference_wrapper for builtin and user types"""
240    assert m.refwrap_builtin(42) == 420
241    assert m.refwrap_usertype(UserType(42)) == 42
242
243    with pytest.raises(TypeError) as excinfo:
244        m.refwrap_builtin(None)
245    assert "incompatible function arguments" in str(excinfo.value)
246
247    with pytest.raises(TypeError) as excinfo:
248        m.refwrap_usertype(None)
249    assert "incompatible function arguments" in str(excinfo.value)
250
251    a1 = m.refwrap_list(copy=True)
252    a2 = m.refwrap_list(copy=True)
253    assert [x.value for x in a1] == [2, 3]
254    assert [x.value for x in a2] == [2, 3]
255    assert not a1[0] is a2[0] and not a1[1] is a2[1]
256
257    b1 = m.refwrap_list(copy=False)
258    b2 = m.refwrap_list(copy=False)
259    assert [x.value for x in b1] == [1, 2]
260    assert [x.value for x in b2] == [1, 2]
261    assert b1[0] is b2[0] and b1[1] is b2[1]
262
263    assert m.refwrap_iiw(IncType(5)) == 5
264    assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
265
266
267def test_complex_cast():
268    """std::complex casts"""
269    assert m.complex_cast(1) == "1.0"
270    assert m.complex_cast(2j) == "(0.0, 2.0)"
271
272
273def test_bool_caster():
274    """Test bool caster implicit conversions."""
275    convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
276
277    def require_implicit(v):
278        pytest.raises(TypeError, noconvert, v)
279
280    def cant_convert(v):
281        pytest.raises(TypeError, convert, v)
282
283    # straight up bool
284    assert convert(True) is True
285    assert convert(False) is False
286    assert noconvert(True) is True
287    assert noconvert(False) is False
288
289    # None requires implicit conversion
290    require_implicit(None)
291    assert convert(None) is False
292
293    class A(object):
294        def __init__(self, x):
295            self.x = x
296
297        def __nonzero__(self):
298            return self.x
299
300        def __bool__(self):
301            return self.x
302
303    class B(object):
304        pass
305
306    # Arbitrary objects are not accepted
307    cant_convert(object())
308    cant_convert(B())
309
310    # Objects with __nonzero__ / __bool__ defined can be converted
311    require_implicit(A(True))
312    assert convert(A(True)) is True
313    assert convert(A(False)) is False
314
315
316@pytest.requires_numpy
317def test_numpy_bool():
318    import numpy as np
319    convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
320
321    # np.bool_ is not considered implicit
322    assert convert(np.bool_(True)) is True
323    assert convert(np.bool_(False)) is False
324    assert noconvert(np.bool_(True)) is True
325    assert noconvert(np.bool_(False)) is False
326
327
328def test_int_long():
329    """In Python 2, a C++ int should return a Python int rather than long
330    if possible: longs are not always accepted where ints are used (such
331    as the argument to sys.exit()). A C++ long long is always a Python
332    long."""
333
334    import sys
335    must_be_long = type(getattr(sys, 'maxint', 1) + 1)
336    assert isinstance(m.int_cast(), int)
337    assert isinstance(m.long_cast(), int)
338    assert isinstance(m.longlong_cast(), must_be_long)
339
340
341def test_void_caster_2():
342    assert m.test_void_caster()
343