blob: a13acd5b9729d90109e21f32a3e6e67f2bc8536b [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
118 import sys
119 byte = bytes if sys.version_info[0] < 3 else str
120
121 assert m.strlen(byte("hi")) == 2
122 assert m.string_length(byte("world")) == 5
123 assert m.string_length(byte("a\x00b")) == 3
124 assert m.strlen(byte("a\x00b")) == 1 # C-string limitation
125
126 # passing in a utf8 encoded string should work
127 assert m.string_length(u'πŸ’©'.encode("utf8")) == 4
128
129
130@pytest.mark.skipif(not hasattr(m, "has_string_view"), reason="no <string_view>")
131def test_string_view(capture):
132 """Tests support for C++17 string_view arguments and return values"""
133 assert m.string_view_chars("Hi") == [72, 105]
134 assert m.string_view_chars("Hi πŸŽ‚") == [72, 105, 32, 0xf0, 0x9f, 0x8e, 0x82]
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700135 assert m.string_view16_chars(u"Hi πŸŽ‚") == [72, 105, 32, 0xd83c, 0xdf82]
136 assert m.string_view32_chars(u"Hi πŸŽ‚") == [72, 105, 32, 127874]
Vemund Handeland6e39b762019-12-19 12:16:24 +0100137 if hasattr(m, "has_u8string"):
138 assert m.string_view8_chars("Hi") == [72, 105]
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700139 assert m.string_view8_chars(u"Hi πŸŽ‚") == [72, 105, 32, 0xf0, 0x9f, 0x8e, 0x82]
Dean Moldovan83e328f2017-06-09 00:44:49 +0200140
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700141 assert m.string_view_return() == u"utf8 secret πŸŽ‚"
142 assert m.string_view16_return() == u"utf16 secret πŸŽ‚"
143 assert m.string_view32_return() == u"utf32 secret πŸŽ‚"
Vemund Handeland6e39b762019-12-19 12:16:24 +0100144 if hasattr(m, "has_u8string"):
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700145 assert m.string_view8_return() == u"utf8 secret πŸŽ‚"
Dean Moldovan83e328f2017-06-09 00:44:49 +0200146
147 with capture:
148 m.string_view_print("Hi")
149 m.string_view_print("utf8 πŸŽ‚")
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700150 m.string_view16_print(u"utf16 πŸŽ‚")
151 m.string_view32_print(u"utf32 πŸŽ‚")
152 assert capture == u"""
Dean Moldovan83e328f2017-06-09 00:44:49 +0200153 Hi 2
154 utf8 πŸŽ‚ 9
155 utf16 πŸŽ‚ 8
156 utf32 πŸŽ‚ 7
157 """
Vemund Handeland6e39b762019-12-19 12:16:24 +0100158 if hasattr(m, "has_u8string"):
159 with capture:
160 m.string_view8_print("Hi")
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700161 m.string_view8_print(u"utf8 πŸŽ‚")
162 assert capture == u"""
Vemund Handeland6e39b762019-12-19 12:16:24 +0100163 Hi 2
164 utf8 πŸŽ‚ 9
165 """
Dean Moldovan83e328f2017-06-09 00:44:49 +0200166
167 with capture:
168 m.string_view_print("Hi, ascii")
169 m.string_view_print("Hi, utf8 πŸŽ‚")
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700170 m.string_view16_print(u"Hi, utf16 πŸŽ‚")
171 m.string_view32_print(u"Hi, utf32 πŸŽ‚")
172 assert capture == u"""
Dean Moldovan83e328f2017-06-09 00:44:49 +0200173 Hi, ascii 9
174 Hi, utf8 πŸŽ‚ 13
175 Hi, utf16 πŸŽ‚ 12
176 Hi, utf32 πŸŽ‚ 11
177 """
Vemund Handeland6e39b762019-12-19 12:16:24 +0100178 if hasattr(m, "has_u8string"):
179 with capture:
180 m.string_view8_print("Hi, ascii")
Ralf W. Grosse-Kunstleve96c67632020-07-22 12:05:16 -0700181 m.string_view8_print(u"Hi, utf8 πŸŽ‚")
182 assert capture == u"""
Vemund Handeland6e39b762019-12-19 12:16:24 +0100183 Hi, ascii 9
184 Hi, utf8 πŸŽ‚ 13
185 """
Dean Moldovan83e328f2017-06-09 00:44:49 +0200186
187
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400188def test_integer_casting():
189 """Issue #929 - out-of-range integer values shouldn't be accepted"""
190 import sys
191 assert m.i32_str(-1) == "-1"
192 assert m.i64_str(-1) == "-1"
193 assert m.i32_str(2000000000) == "2000000000"
194 assert m.u32_str(2000000000) == "2000000000"
195 if sys.version_info < (3,):
Jason Rhinelanderb468a3c2017-07-25 21:46:54 -0400196 assert m.i32_str(long(-1)) == "-1" # noqa: F821 undefined name 'long'
197 assert m.i64_str(long(-1)) == "-1" # noqa: F821 undefined name 'long'
198 assert m.i64_str(long(-999999999999)) == "-999999999999" # noqa: F821 undefined name
199 assert m.u64_str(long(999999999999)) == "999999999999" # noqa: F821 undefined name 'long'
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400200 else:
201 assert m.i64_str(-999999999999) == "-999999999999"
202 assert m.u64_str(999999999999) == "999999999999"
203
204 with pytest.raises(TypeError) as excinfo:
205 m.u32_str(-1)
206 assert "incompatible function arguments" in str(excinfo.value)
207 with pytest.raises(TypeError) as excinfo:
208 m.u64_str(-1)
209 assert "incompatible function arguments" in str(excinfo.value)
210 with pytest.raises(TypeError) as excinfo:
211 m.i32_str(-3000000000)
212 assert "incompatible function arguments" in str(excinfo.value)
213 with pytest.raises(TypeError) as excinfo:
214 m.i32_str(3000000000)
215 assert "incompatible function arguments" in str(excinfo.value)
216
217 if sys.version_info < (3,):
218 with pytest.raises(TypeError) as excinfo:
Jason Rhinelanderb468a3c2017-07-25 21:46:54 -0400219 m.u32_str(long(-1)) # noqa: F821 undefined name 'long'
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400220 assert "incompatible function arguments" in str(excinfo.value)
221 with pytest.raises(TypeError) as excinfo:
Jason Rhinelanderb468a3c2017-07-25 21:46:54 -0400222 m.u64_str(long(-1)) # noqa: F821 undefined name 'long'
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400223 assert "incompatible function arguments" in str(excinfo.value)
224
225
Dean Moldovan83e328f2017-06-09 00:44:49 +0200226def test_tuple(doc):
227 """std::pair <-> tuple & std::tuple <-> tuple"""
228 assert m.pair_passthrough((True, "test")) == ("test", True)
229 assert m.tuple_passthrough((True, "test", 5)) == (5, "test", True)
230 # Any sequence can be cast to a std::pair or std::tuple
231 assert m.pair_passthrough([True, "test"]) == ("test", True)
232 assert m.tuple_passthrough([True, "test", 5]) == (5, "test", True)
Jason Rhinelander897d7162017-07-04 14:57:41 -0400233 assert m.empty_tuple() == ()
Dean Moldovan83e328f2017-06-09 00:44:49 +0200234
235 assert doc(m.pair_passthrough) == """
236 pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool]
237
238 Return a pair in reversed order
239 """
240 assert doc(m.tuple_passthrough) == """
241 tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool]
242
243 Return a triple in reversed order
244 """
245
Jason Rhinelanderb57281b2017-07-03 19:12:09 -0400246 assert m.rvalue_pair() == ("rvalue", "rvalue")
247 assert m.lvalue_pair() == ("lvalue", "lvalue")
248 assert m.rvalue_tuple() == ("rvalue", "rvalue", "rvalue")
249 assert m.lvalue_tuple() == ("lvalue", "lvalue", "lvalue")
250 assert m.rvalue_nested() == ("rvalue", ("rvalue", ("rvalue", "rvalue")))
251 assert m.lvalue_nested() == ("lvalue", ("lvalue", ("lvalue", "lvalue")))
252
Dean Moldovan83e328f2017-06-09 00:44:49 +0200253
254def test_builtins_cast_return_none():
255 """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
256 assert m.return_none_string() is None
257 assert m.return_none_char() is None
258 assert m.return_none_bool() is None
259 assert m.return_none_int() is None
260 assert m.return_none_float() is None
261
262
263def test_none_deferred():
264 """None passed as various argument types should defer to other overloads"""
265 assert not m.defer_none_cstring("abc")
266 assert m.defer_none_cstring(None)
267 assert not m.defer_none_custom(UserType())
268 assert m.defer_none_custom(None)
269 assert m.nodefer_none_void(None)
270
271
272def test_void_caster():
273 assert m.load_nullptr_t(None) is None
274 assert m.cast_nullptr_t() is None
275
276
277def test_reference_wrapper():
278 """std::reference_wrapper for builtin and user types"""
279 assert m.refwrap_builtin(42) == 420
280 assert m.refwrap_usertype(UserType(42)) == 42
281
282 with pytest.raises(TypeError) as excinfo:
283 m.refwrap_builtin(None)
284 assert "incompatible function arguments" in str(excinfo.value)
285
286 with pytest.raises(TypeError) as excinfo:
287 m.refwrap_usertype(None)
288 assert "incompatible function arguments" in str(excinfo.value)
289
290 a1 = m.refwrap_list(copy=True)
291 a2 = m.refwrap_list(copy=True)
292 assert [x.value for x in a1] == [2, 3]
293 assert [x.value for x in a2] == [2, 3]
294 assert not a1[0] is a2[0] and not a1[1] is a2[1]
295
296 b1 = m.refwrap_list(copy=False)
297 b2 = m.refwrap_list(copy=False)
298 assert [x.value for x in b1] == [1, 2]
299 assert [x.value for x in b2] == [1, 2]
300 assert b1[0] is b2[0] and b1[1] is b2[1]
301
302 assert m.refwrap_iiw(IncType(5)) == 5
303 assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
304
305
306def test_complex_cast():
307 """std::complex casts"""
308 assert m.complex_cast(1) == "1.0"
309 assert m.complex_cast(2j) == "(0.0, 2.0)"
Ivan Smirnove07f7582017-07-23 16:02:43 +0100310
311
312def test_bool_caster():
313 """Test bool caster implicit conversions."""
314 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
315
316 def require_implicit(v):
317 pytest.raises(TypeError, noconvert, v)
318
319 def cant_convert(v):
320 pytest.raises(TypeError, convert, v)
321
322 # straight up bool
323 assert convert(True) is True
324 assert convert(False) is False
325 assert noconvert(True) is True
326 assert noconvert(False) is False
327
328 # None requires implicit conversion
329 require_implicit(None)
330 assert convert(None) is False
331
332 class A(object):
333 def __init__(self, x):
334 self.x = x
335
336 def __nonzero__(self):
337 return self.x
338
339 def __bool__(self):
340 return self.x
341
342 class B(object):
343 pass
344
345 # Arbitrary objects are not accepted
346 cant_convert(object())
347 cant_convert(B())
348
349 # Objects with __nonzero__ / __bool__ defined can be converted
350 require_implicit(A(True))
351 assert convert(A(True)) is True
352 assert convert(A(False)) is False
353
354
355@pytest.requires_numpy
356def test_numpy_bool():
357 import numpy as np
358 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
359
Yannick Jadoul55ff4642019-11-14 08:55:34 +0100360 def cant_convert(v):
361 pytest.raises(TypeError, convert, v)
362
Ivan Smirnove07f7582017-07-23 16:02:43 +0100363 # np.bool_ is not considered implicit
364 assert convert(np.bool_(True)) is True
365 assert convert(np.bool_(False)) is False
366 assert noconvert(np.bool_(True)) is True
367 assert noconvert(np.bool_(False)) is False
Yannick Jadoul55ff4642019-11-14 08:55:34 +0100368 cant_convert(np.zeros(2, dtype='int'))
Henry Schreinercf0d0f92017-11-30 11:33:24 -0600369
370
371def test_int_long():
372 """In Python 2, a C++ int should return a Python int rather than long
373 if possible: longs are not always accepted where ints are used (such
374 as the argument to sys.exit()). A C++ long long is always a Python
375 long."""
376
377 import sys
378 must_be_long = type(getattr(sys, 'maxint', 1) + 1)
379 assert isinstance(m.int_cast(), int)
380 assert isinstance(m.long_cast(), int)
381 assert isinstance(m.longlong_cast(), must_be_long)
Wenzel Jakobcea42462018-11-11 19:32:09 +0100382
383
384def test_void_caster_2():
385 assert m.test_void_caster()