blob: c905766f8384e39313ea822a265543e5fec3a1e8 [file] [log] [blame]
Henry Schreinerd8c7ee02020-07-20 13:35:21 -04001# -*- coding: utf-8 -*-
Dean Moldovan83e328f2017-06-09 00:44:49 +02002import 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"
Vemund Handeland6e39b762019-12-19 12:16:24 +010018 if hasattr(m, "has_u8string"):
19 assert m.good_utf8_u8string() == u"Say utf8β€½ πŸŽ‚ 𝐀"
Dean Moldovan83e328f2017-06-09 00:44:49 +020020
21 with pytest.raises(UnicodeDecodeError):
22 m.bad_utf8_string()
23
24 with pytest.raises(UnicodeDecodeError):
25 m.bad_utf16_string()
26
27 # These are provided only if they actually fail (they don't when 32-bit and under Python 2.7)
28 if hasattr(m, "bad_utf32_string"):
29 with pytest.raises(UnicodeDecodeError):
30 m.bad_utf32_string()
31 if hasattr(m, "bad_wchar_string"):
32 with pytest.raises(UnicodeDecodeError):
33 m.bad_wchar_string()
Vemund Handeland6e39b762019-12-19 12:16:24 +010034 if hasattr(m, "has_u8string"):
35 with pytest.raises(UnicodeDecodeError):
36 m.bad_utf8_u8string()
Dean Moldovan83e328f2017-06-09 00:44:49 +020037
38 assert m.u8_Z() == 'Z'
39 assert m.u8_eacute() == u'Γ©'
40 assert m.u16_ibang() == u'β€½'
41 assert m.u32_mathbfA() == u'𝐀'
42 assert m.wchar_heart() == u'β™₯'
Vemund Handeland6e39b762019-12-19 12:16:24 +010043 if hasattr(m, "has_u8string"):
44 assert m.u8_char8_Z() == 'Z'
Dean Moldovan83e328f2017-06-09 00:44:49 +020045
46
47def test_single_char_arguments():
48 """Tests failures for passing invalid inputs to char-accepting functions"""
49 def toobig_message(r):
50 return "Character code point not in range({0:#x})".format(r)
51 toolong_message = "Expected a character, but multi-character string found"
52
53 assert m.ord_char(u'a') == 0x61 # simple ASCII
Jason Rhinelander1b08df52017-10-06 11:50:10 -030054 assert m.ord_char_lv(u'b') == 0x62
Dean Moldovan83e328f2017-06-09 00:44:49 +020055 assert m.ord_char(u'Γ©') == 0xE9 # requires 2 bytes in utf-8, but can be stuffed in a char
56 with pytest.raises(ValueError) as excinfo:
57 assert m.ord_char(u'Δ€') == 0x100 # requires 2 bytes, doesn't fit in a char
58 assert str(excinfo.value) == toobig_message(0x100)
59 with pytest.raises(ValueError) as excinfo:
60 assert m.ord_char(u'ab')
61 assert str(excinfo.value) == toolong_message
62
63 assert m.ord_char16(u'a') == 0x61
64 assert m.ord_char16(u'Γ©') == 0xE9
Jason Rhinelander1b08df52017-10-06 11:50:10 -030065 assert m.ord_char16_lv(u'Γͺ') == 0xEA
Dean Moldovan83e328f2017-06-09 00:44:49 +020066 assert m.ord_char16(u'Δ€') == 0x100
67 assert m.ord_char16(u'β€½') == 0x203d
68 assert m.ord_char16(u'β™₯') == 0x2665
Jason Rhinelander1b08df52017-10-06 11:50:10 -030069 assert m.ord_char16_lv(u'β™‘') == 0x2661
Dean Moldovan83e328f2017-06-09 00:44:49 +020070 with pytest.raises(ValueError) as excinfo:
71 assert m.ord_char16(u'πŸŽ‚') == 0x1F382 # requires surrogate pair
72 assert str(excinfo.value) == toobig_message(0x10000)
73 with pytest.raises(ValueError) as excinfo:
74 assert m.ord_char16(u'aa')
75 assert str(excinfo.value) == toolong_message
76
77 assert m.ord_char32(u'a') == 0x61
78 assert m.ord_char32(u'Γ©') == 0xE9
79 assert m.ord_char32(u'Δ€') == 0x100
80 assert m.ord_char32(u'β€½') == 0x203d
81 assert m.ord_char32(u'β™₯') == 0x2665
82 assert m.ord_char32(u'πŸŽ‚') == 0x1F382
83 with pytest.raises(ValueError) as excinfo:
84 assert m.ord_char32(u'aa')
85 assert str(excinfo.value) == toolong_message
86
87 assert m.ord_wchar(u'a') == 0x61
88 assert m.ord_wchar(u'Γ©') == 0xE9
89 assert m.ord_wchar(u'Δ€') == 0x100
90 assert m.ord_wchar(u'β€½') == 0x203d
91 assert m.ord_wchar(u'β™₯') == 0x2665
92 if m.wchar_size == 2:
93 with pytest.raises(ValueError) as excinfo:
94 assert m.ord_wchar(u'πŸŽ‚') == 0x1F382 # requires surrogate pair
95 assert str(excinfo.value) == toobig_message(0x10000)
96 else:
97 assert m.ord_wchar(u'πŸŽ‚') == 0x1F382
98 with pytest.raises(ValueError) as excinfo:
99 assert m.ord_wchar(u'aa')
100 assert str(excinfo.value) == toolong_message
101
Vemund Handeland6e39b762019-12-19 12:16:24 +0100102 if hasattr(m, "has_u8string"):
103 assert m.ord_char8(u'a') == 0x61 # simple ASCII
104 assert m.ord_char8_lv(u'b') == 0x62
105 assert m.ord_char8(u'Γ©') == 0xE9 # requires 2 bytes in utf-8, but can be stuffed in a char
106 with pytest.raises(ValueError) as excinfo:
107 assert m.ord_char8(u'Δ€') == 0x100 # requires 2 bytes, doesn't fit in a char
108 assert str(excinfo.value) == toobig_message(0x100)
109 with pytest.raises(ValueError) as excinfo:
110 assert m.ord_char8(u'ab')
111 assert str(excinfo.value) == toolong_message
112
Dean Moldovan83e328f2017-06-09 00:44:49 +0200113
114def test_bytes_to_string():
115 """Tests the ability to pass bytes to C++ string-accepting functions. Note that this is
116 one-way: the only way to return bytes to Python is via the pybind11::bytes class."""
117 # Issue #816
Dean Moldovan83e328f2017-06-09 00:44:49 +0200118
Eric Cousineauebdd0d32020-08-14 14:03:43 -0400119 def to_bytes(s):
120 if pytest.PY2:
121 b = s
122 else:
123 b = s.encode("utf8")
124 assert isinstance(b, bytes)
125 return b
126
127 assert m.strlen(to_bytes("hi")) == 2
128 assert m.string_length(to_bytes("world")) == 5
129 assert m.string_length(to_bytes("a\x00b")) == 3
130 assert m.strlen(to_bytes("a\x00b")) == 1 # C-string limitation
Dean Moldovan83e328f2017-06-09 00:44:49 +0200131
132 # passing in a utf8 encoded string should work
133 assert m.string_length(u'πŸ’©'.encode("utf8")) == 4
134
135
136@pytest.mark.skipif(not hasattr(m, "has_string_view"), reason="no <string_view>")
137def test_string_view(capture):
138 """Tests support for C++17 string_view arguments and return values"""
139 assert m.string_view_chars("Hi") == [72, 105]
140 assert m.string_view_chars("Hi πŸŽ‚") == [72, 105, 32, 0xf0, 0x9f, 0x8e, 0x82]
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700141 assert m.string_view16_chars(u"Hi πŸŽ‚") == [72, 105, 32, 0xd83c, 0xdf82]
142 assert m.string_view32_chars(u"Hi πŸŽ‚") == [72, 105, 32, 127874]
Vemund Handeland6e39b762019-12-19 12:16:24 +0100143 if hasattr(m, "has_u8string"):
144 assert m.string_view8_chars("Hi") == [72, 105]
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700145 assert m.string_view8_chars(u"Hi πŸŽ‚") == [72, 105, 32, 0xf0, 0x9f, 0x8e, 0x82]
Dean Moldovan83e328f2017-06-09 00:44:49 +0200146
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700147 assert m.string_view_return() == u"utf8 secret πŸŽ‚"
148 assert m.string_view16_return() == u"utf16 secret πŸŽ‚"
149 assert m.string_view32_return() == u"utf32 secret πŸŽ‚"
Vemund Handeland6e39b762019-12-19 12:16:24 +0100150 if hasattr(m, "has_u8string"):
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700151 assert m.string_view8_return() == u"utf8 secret πŸŽ‚"
Dean Moldovan83e328f2017-06-09 00:44:49 +0200152
153 with capture:
154 m.string_view_print("Hi")
155 m.string_view_print("utf8 πŸŽ‚")
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700156 m.string_view16_print(u"utf16 πŸŽ‚")
157 m.string_view32_print(u"utf32 πŸŽ‚")
158 assert capture == u"""
Dean Moldovan83e328f2017-06-09 00:44:49 +0200159 Hi 2
160 utf8 πŸŽ‚ 9
161 utf16 πŸŽ‚ 8
162 utf32 πŸŽ‚ 7
163 """
Vemund Handeland6e39b762019-12-19 12:16:24 +0100164 if hasattr(m, "has_u8string"):
165 with capture:
166 m.string_view8_print("Hi")
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700167 m.string_view8_print(u"utf8 πŸŽ‚")
168 assert capture == u"""
Vemund Handeland6e39b762019-12-19 12:16:24 +0100169 Hi 2
170 utf8 πŸŽ‚ 9
171 """
Dean Moldovan83e328f2017-06-09 00:44:49 +0200172
173 with capture:
174 m.string_view_print("Hi, ascii")
175 m.string_view_print("Hi, utf8 πŸŽ‚")
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700176 m.string_view16_print(u"Hi, utf16 πŸŽ‚")
177 m.string_view32_print(u"Hi, utf32 πŸŽ‚")
178 assert capture == u"""
Dean Moldovan83e328f2017-06-09 00:44:49 +0200179 Hi, ascii 9
180 Hi, utf8 πŸŽ‚ 13
181 Hi, utf16 πŸŽ‚ 12
182 Hi, utf32 πŸŽ‚ 11
183 """
Vemund Handeland6e39b762019-12-19 12:16:24 +0100184 if hasattr(m, "has_u8string"):
185 with capture:
186 m.string_view8_print("Hi, ascii")
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700187 m.string_view8_print(u"Hi, utf8 πŸŽ‚")
188 assert capture == u"""
Vemund Handeland6e39b762019-12-19 12:16:24 +0100189 Hi, ascii 9
190 Hi, utf8 πŸŽ‚ 13
191 """
Dean Moldovan83e328f2017-06-09 00:44:49 +0200192
193
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400194def test_integer_casting():
195 """Issue #929 - out-of-range integer values shouldn't be accepted"""
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400196 assert m.i32_str(-1) == "-1"
197 assert m.i64_str(-1) == "-1"
198 assert m.i32_str(2000000000) == "2000000000"
199 assert m.u32_str(2000000000) == "2000000000"
Eric Cousineauebdd0d32020-08-14 14:03:43 -0400200 if pytest.PY2:
Jason Rhinelanderb468a3c2017-07-25 21:46:54 -0400201 assert m.i32_str(long(-1)) == "-1" # noqa: F821 undefined name 'long'
202 assert m.i64_str(long(-1)) == "-1" # noqa: F821 undefined name 'long'
203 assert m.i64_str(long(-999999999999)) == "-999999999999" # noqa: F821 undefined name
204 assert m.u64_str(long(999999999999)) == "999999999999" # noqa: F821 undefined name 'long'
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400205 else:
206 assert m.i64_str(-999999999999) == "-999999999999"
207 assert m.u64_str(999999999999) == "999999999999"
208
209 with pytest.raises(TypeError) as excinfo:
210 m.u32_str(-1)
211 assert "incompatible function arguments" in str(excinfo.value)
212 with pytest.raises(TypeError) as excinfo:
213 m.u64_str(-1)
214 assert "incompatible function arguments" in str(excinfo.value)
215 with pytest.raises(TypeError) as excinfo:
216 m.i32_str(-3000000000)
217 assert "incompatible function arguments" in str(excinfo.value)
218 with pytest.raises(TypeError) as excinfo:
219 m.i32_str(3000000000)
220 assert "incompatible function arguments" in str(excinfo.value)
221
Eric Cousineauebdd0d32020-08-14 14:03:43 -0400222 if pytest.PY2:
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400223 with pytest.raises(TypeError) as excinfo:
Jason Rhinelanderb468a3c2017-07-25 21:46:54 -0400224 m.u32_str(long(-1)) # noqa: F821 undefined name 'long'
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400225 assert "incompatible function arguments" in str(excinfo.value)
226 with pytest.raises(TypeError) as excinfo:
Jason Rhinelanderb468a3c2017-07-25 21:46:54 -0400227 m.u64_str(long(-1)) # noqa: F821 undefined name 'long'
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400228 assert "incompatible function arguments" in str(excinfo.value)
229
230
Dean Moldovan83e328f2017-06-09 00:44:49 +0200231def test_tuple(doc):
232 """std::pair <-> tuple & std::tuple <-> tuple"""
233 assert m.pair_passthrough((True, "test")) == ("test", True)
234 assert m.tuple_passthrough((True, "test", 5)) == (5, "test", True)
235 # Any sequence can be cast to a std::pair or std::tuple
236 assert m.pair_passthrough([True, "test"]) == ("test", True)
237 assert m.tuple_passthrough([True, "test", 5]) == (5, "test", True)
Jason Rhinelander897d7162017-07-04 14:57:41 -0400238 assert m.empty_tuple() == ()
Dean Moldovan83e328f2017-06-09 00:44:49 +0200239
240 assert doc(m.pair_passthrough) == """
241 pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool]
242
243 Return a pair in reversed order
244 """
245 assert doc(m.tuple_passthrough) == """
246 tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool]
247
248 Return a triple in reversed order
249 """
250
Jason Rhinelanderb57281b2017-07-03 19:12:09 -0400251 assert m.rvalue_pair() == ("rvalue", "rvalue")
252 assert m.lvalue_pair() == ("lvalue", "lvalue")
253 assert m.rvalue_tuple() == ("rvalue", "rvalue", "rvalue")
254 assert m.lvalue_tuple() == ("lvalue", "lvalue", "lvalue")
255 assert m.rvalue_nested() == ("rvalue", ("rvalue", ("rvalue", "rvalue")))
256 assert m.lvalue_nested() == ("lvalue", ("lvalue", ("lvalue", "lvalue")))
257
Marcin Wojdyr8e40e382020-07-28 21:44:19 +0200258 assert m.int_string_pair() == (2, "items")
259
Dean Moldovan83e328f2017-06-09 00:44:49 +0200260
261def test_builtins_cast_return_none():
262 """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
263 assert m.return_none_string() is None
264 assert m.return_none_char() is None
265 assert m.return_none_bool() is None
266 assert m.return_none_int() is None
267 assert m.return_none_float() is None
Marcin Wojdyr8e40e382020-07-28 21:44:19 +0200268 assert m.return_none_pair() is None
Dean Moldovan83e328f2017-06-09 00:44:49 +0200269
270
271def test_none_deferred():
272 """None passed as various argument types should defer to other overloads"""
273 assert not m.defer_none_cstring("abc")
274 assert m.defer_none_cstring(None)
275 assert not m.defer_none_custom(UserType())
276 assert m.defer_none_custom(None)
277 assert m.nodefer_none_void(None)
278
279
280def test_void_caster():
281 assert m.load_nullptr_t(None) is None
282 assert m.cast_nullptr_t() is None
283
284
285def test_reference_wrapper():
286 """std::reference_wrapper for builtin and user types"""
287 assert m.refwrap_builtin(42) == 420
288 assert m.refwrap_usertype(UserType(42)) == 42
289
290 with pytest.raises(TypeError) as excinfo:
291 m.refwrap_builtin(None)
292 assert "incompatible function arguments" in str(excinfo.value)
293
294 with pytest.raises(TypeError) as excinfo:
295 m.refwrap_usertype(None)
296 assert "incompatible function arguments" in str(excinfo.value)
297
298 a1 = m.refwrap_list(copy=True)
299 a2 = m.refwrap_list(copy=True)
300 assert [x.value for x in a1] == [2, 3]
301 assert [x.value for x in a2] == [2, 3]
302 assert not a1[0] is a2[0] and not a1[1] is a2[1]
303
304 b1 = m.refwrap_list(copy=False)
305 b2 = m.refwrap_list(copy=False)
306 assert [x.value for x in b1] == [1, 2]
307 assert [x.value for x in b2] == [1, 2]
308 assert b1[0] is b2[0] and b1[1] is b2[1]
309
310 assert m.refwrap_iiw(IncType(5)) == 5
311 assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
312
313
314def test_complex_cast():
315 """std::complex casts"""
316 assert m.complex_cast(1) == "1.0"
317 assert m.complex_cast(2j) == "(0.0, 2.0)"
Ivan Smirnove07f7582017-07-23 16:02:43 +0100318
319
320def test_bool_caster():
321 """Test bool caster implicit conversions."""
322 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
323
324 def require_implicit(v):
325 pytest.raises(TypeError, noconvert, v)
326
327 def cant_convert(v):
328 pytest.raises(TypeError, convert, v)
329
330 # straight up bool
331 assert convert(True) is True
332 assert convert(False) is False
333 assert noconvert(True) is True
334 assert noconvert(False) is False
335
336 # None requires implicit conversion
337 require_implicit(None)
338 assert convert(None) is False
339
340 class A(object):
341 def __init__(self, x):
342 self.x = x
343
344 def __nonzero__(self):
345 return self.x
346
347 def __bool__(self):
348 return self.x
349
350 class B(object):
351 pass
352
353 # Arbitrary objects are not accepted
354 cant_convert(object())
355 cant_convert(B())
356
357 # Objects with __nonzero__ / __bool__ defined can be converted
358 require_implicit(A(True))
359 assert convert(A(True)) is True
360 assert convert(A(False)) is False
361
362
363@pytest.requires_numpy
364def test_numpy_bool():
365 import numpy as np
366 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
367
Yannick Jadoul55ff4642019-11-14 08:55:34 +0100368 def cant_convert(v):
369 pytest.raises(TypeError, convert, v)
370
Ivan Smirnove07f7582017-07-23 16:02:43 +0100371 # np.bool_ is not considered implicit
372 assert convert(np.bool_(True)) is True
373 assert convert(np.bool_(False)) is False
374 assert noconvert(np.bool_(True)) is True
375 assert noconvert(np.bool_(False)) is False
Yannick Jadoul55ff4642019-11-14 08:55:34 +0100376 cant_convert(np.zeros(2, dtype='int'))
Henry Schreinercf0d0f92017-11-30 11:33:24 -0600377
378
379def test_int_long():
380 """In Python 2, a C++ int should return a Python int rather than long
381 if possible: longs are not always accepted where ints are used (such
382 as the argument to sys.exit()). A C++ long long is always a Python
383 long."""
384
385 import sys
386 must_be_long = type(getattr(sys, 'maxint', 1) + 1)
387 assert isinstance(m.int_cast(), int)
388 assert isinstance(m.long_cast(), int)
389 assert isinstance(m.longlong_cast(), must_be_long)
Wenzel Jakobcea42462018-11-11 19:32:09 +0100390
391
392def test_void_caster_2():
393 assert m.test_void_caster()