1 from __future__
import annotations
8 from pybind11_tests
import IncType, UserType
9 from pybind11_tests
import builtin_casters
as m
12 def test_simple_string():
13 assert m.string_roundtrip(
"const char *") ==
"const char *"
17 """Tests unicode conversion and error reporting."""
18 assert m.good_utf8_string() ==
"Say utf8β½ π π"
19 assert m.good_utf16_string() ==
"bβ½ππz"
20 assert m.good_utf32_string() ==
"aππβ½z"
21 assert m.good_wchar_string() ==
"aβΈπz"
23 assert m.good_utf8_u8string() ==
"Say utf8β½ π π"
25 with pytest.raises(UnicodeDecodeError):
28 with pytest.raises(UnicodeDecodeError):
32 if hasattr(m,
"bad_utf32_string"):
33 with pytest.raises(UnicodeDecodeError):
35 if hasattr(m,
"bad_wchar_string"):
36 with pytest.raises(UnicodeDecodeError):
39 with pytest.raises(UnicodeDecodeError):
42 assert m.u8_Z() ==
"Z"
43 assert m.u8_eacute() ==
"Γ©"
44 assert m.u16_ibang() ==
"β½"
45 assert m.u32_mathbfA() ==
"π"
46 assert m.wchar_heart() ==
"β₯"
48 assert m.u8_char8_Z() ==
"Z"
52 """Tests failures for passing invalid inputs to char-accepting functions"""
54 def toobig_message(r):
55 return f
"Character code point not in range({r:#x})"
57 toolong_message =
"Expected a character, but multi-character string found"
59 assert m.ord_char(
"a") == 0x61
60 assert m.ord_char_lv(
"b") == 0x62
62 m.ord_char(
"Γ©") == 0xE9
64 with pytest.raises(ValueError)
as excinfo:
65 assert m.ord_char(
"Δ") == 0x100
66 assert str(excinfo.value) == toobig_message(0x100)
67 with pytest.raises(ValueError)
as excinfo:
68 assert m.ord_char(
"ab")
69 assert str(excinfo.value) == toolong_message
71 assert m.ord_char16(
"a") == 0x61
72 assert m.ord_char16(
"Γ©") == 0xE9
73 assert m.ord_char16_lv(
"Γͺ") == 0xEA
74 assert m.ord_char16(
"Δ") == 0x100
75 assert m.ord_char16(
"β½") == 0x203D
76 assert m.ord_char16(
"β₯") == 0x2665
77 assert m.ord_char16_lv(
"β‘") == 0x2661
78 with pytest.raises(ValueError)
as excinfo:
79 assert m.ord_char16(
"π") == 0x1F382
80 assert str(excinfo.value) == toobig_message(0x10000)
81 with pytest.raises(ValueError)
as excinfo:
82 assert m.ord_char16(
"aa")
83 assert str(excinfo.value) == toolong_message
85 assert m.ord_char32(
"a") == 0x61
86 assert m.ord_char32(
"Γ©") == 0xE9
87 assert m.ord_char32(
"Δ") == 0x100
88 assert m.ord_char32(
"β½") == 0x203D
89 assert m.ord_char32(
"β₯") == 0x2665
90 assert m.ord_char32(
"π") == 0x1F382
91 with pytest.raises(ValueError)
as excinfo:
92 assert m.ord_char32(
"aa")
93 assert str(excinfo.value) == toolong_message
95 assert m.ord_wchar(
"a") == 0x61
96 assert m.ord_wchar(
"Γ©") == 0xE9
97 assert m.ord_wchar(
"Δ") == 0x100
98 assert m.ord_wchar(
"β½") == 0x203D
99 assert m.ord_wchar(
"β₯") == 0x2665
100 if m.wchar_size == 2:
101 with pytest.raises(ValueError)
as excinfo:
102 assert m.ord_wchar(
"π") == 0x1F382
103 assert str(excinfo.value) == toobig_message(0x10000)
105 assert m.ord_wchar(
"π") == 0x1F382
106 with pytest.raises(ValueError)
as excinfo:
107 assert m.ord_wchar(
"aa")
108 assert str(excinfo.value) == toolong_message
111 assert m.ord_char8(
"a") == 0x61
112 assert m.ord_char8_lv(
"b") == 0x62
114 m.ord_char8(
"Γ©") == 0xE9
116 with pytest.raises(ValueError)
as excinfo:
117 assert m.ord_char8(
"Δ") == 0x100
118 assert str(excinfo.value) == toobig_message(0x100)
119 with pytest.raises(ValueError)
as excinfo:
120 assert m.ord_char8(
"ab")
121 assert str(excinfo.value) == toolong_message
125 """Tests the ability to pass bytes to C++ string-accepting functions. Note that this is
126 one-way: the only way to return bytes to Python is via the pybind11::bytes class."""
129 assert m.strlen(b
"hi") == 2
130 assert m.string_length(b
"world") == 5
131 assert m.string_length(b
"a\x00b") == 3
132 assert m.strlen(b
"a\x00b") == 1
135 assert m.string_length(
"π©".
encode()) == 4
139 """Tests the ability to pass bytearray to C++ string-accepting functions"""
140 assert m.string_length(
bytearray(b
"Hi")) == 2
141 assert m.strlen(
bytearray(b
"bytearray")) == 9
143 assert m.string_length(
bytearray(
"π¦",
"utf-8",
"strict")) == 4
144 assert m.string_length(
bytearray(b
"\x80")) == 1
147 @pytest.mark.skipif(
not hasattr(m,
"has_string_view"), reason=
"no <string_view>")
149 """Tests support for C++17 string_view arguments and return values"""
150 assert m.string_view_chars(
"Hi") == [72, 105]
151 assert m.string_view_chars(
"Hi π") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82]
152 assert m.string_view16_chars(
"Hi π") == [72, 105, 32, 0xD83C, 0xDF82]
153 assert m.string_view32_chars(
"Hi π") == [72, 105, 32, 127874]
155 assert m.string_view8_chars(
"Hi") == [72, 105]
156 assert m.string_view8_chars(
"Hi π") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82]
158 assert m.string_view_return() ==
"utf8 secret π"
159 assert m.string_view16_return() ==
"utf16 secret π"
160 assert m.string_view32_return() ==
"utf32 secret π"
162 assert m.string_view8_return() ==
"utf8 secret π"
165 m.string_view_print(
"Hi")
166 m.string_view_print(
"utf8 π")
167 m.string_view16_print(
"utf16 π")
168 m.string_view32_print(
"utf32 π")
180 m.string_view8_print(
"Hi")
181 m.string_view8_print(
"utf8 π")
191 m.string_view_print(
"Hi, ascii")
192 m.string_view_print(
"Hi, utf8 π")
193 m.string_view16_print(
"Hi, utf16 π")
194 m.string_view32_print(
"Hi, utf32 π")
206 m.string_view8_print(
"Hi, ascii")
207 m.string_view8_print(
"Hi, utf8 π")
216 assert m.string_view_bytes() == b
"abc \x80\x80 def"
217 assert m.string_view_str() ==
"abc β½ def"
218 assert m.string_view_from_bytes(
"abc β½ def".
encode()) ==
"abc β½ def"
220 assert m.string_view8_str() ==
"abc β½ def"
221 assert m.string_view_memoryview() ==
"Have some π".
encode()
223 assert m.bytes_from_type_with_both_operator_string_and_string_view() == b
"success"
224 assert m.str_from_type_with_both_operator_string_and_string_view() ==
"success"
228 """Issue #929 - out-of-range integer values shouldn't be accepted"""
229 assert m.i32_str(-1) ==
"-1"
230 assert m.i64_str(-1) ==
"-1"
231 assert m.i32_str(2000000000) ==
"2000000000"
232 assert m.u32_str(2000000000) ==
"2000000000"
233 assert m.i64_str(-999999999999) ==
"-999999999999"
234 assert m.u64_str(999999999999) ==
"999999999999"
236 with pytest.raises(TypeError)
as excinfo:
238 assert "incompatible function arguments" in str(excinfo.value)
239 with pytest.raises(TypeError)
as excinfo:
241 assert "incompatible function arguments" in str(excinfo.value)
242 with pytest.raises(TypeError)
as excinfo:
243 m.i32_str(-3000000000)
244 assert "incompatible function arguments" in str(excinfo.value)
245 with pytest.raises(TypeError)
as excinfo:
246 m.i32_str(3000000000)
247 assert "incompatible function arguments" in str(excinfo.value)
273 class RaisingTypeErrorOnIndex:
280 class RaisingValueErrorOnIndex:
287 convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert
289 def requires_conversion(v):
290 pytest.raises(TypeError, noconvert, v)
293 pytest.raises(TypeError, convert, v)
296 assert noconvert(7) == 7
297 cant_convert(3.14159)
300 if (3, 8) <= sys.version_info < (3, 10)
and env.CPYTHON:
305 requires_conversion(
Int())
306 cant_convert(NotInt())
307 cant_convert(Float())
312 assert noconvert(
Index()) == 42
313 assert convert(IntAndIndex()) == 0
314 assert noconvert(IntAndIndex()) == 0
315 assert convert(RaisingTypeErrorOnIndex()) == 42
316 requires_conversion(RaisingTypeErrorOnIndex())
317 assert convert(RaisingValueErrorOnIndex()) == 42
318 requires_conversion(RaisingValueErrorOnIndex())
322 np = pytest.importorskip(
"numpy")
324 convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert
326 def require_implicit(v):
327 pytest.raises(TypeError, noconvert, v)
330 assert convert(np.intc(42)) == 42
331 assert noconvert(np.intc(42)) == 42
337 if (3, 8) <= sys.version_info < (3, 10)
and env.CPYTHON:
339 assert convert(np.float32(3.14159)) == 3
341 assert convert(np.float32(3.14159)) == 3
342 require_implicit(np.float32(3.14159))
346 """std::pair <-> tuple & std::tuple <-> tuple"""
347 assert m.pair_passthrough((
True,
"test")) == (
"test",
True)
348 assert m.tuple_passthrough((
True,
"test", 5)) == (5,
"test",
True)
350 assert m.pair_passthrough([
True,
"test"]) == (
"test",
True)
351 assert m.tuple_passthrough([
True,
"test", 5]) == (5,
"test",
True)
352 assert m.empty_tuple() == ()
355 doc(m.pair_passthrough)
357 pair_passthrough(arg0: tuple[bool, str]) -> tuple[str, bool]
359 Return a pair in reversed order
363 doc(m.tuple_passthrough)
365 tuple_passthrough(arg0: tuple[bool, str, int]) -> tuple[int, str, bool]
367 Return a triple in reversed order
371 assert m.rvalue_pair() == (
"rvalue",
"rvalue")
372 assert m.lvalue_pair() == (
"lvalue",
"lvalue")
373 assert m.rvalue_tuple() == (
"rvalue",
"rvalue",
"rvalue")
374 assert m.lvalue_tuple() == (
"lvalue",
"lvalue",
"lvalue")
375 assert m.rvalue_nested() == (
"rvalue", (
"rvalue", (
"rvalue",
"rvalue")))
376 assert m.lvalue_nested() == (
"lvalue", (
"lvalue", (
"lvalue",
"lvalue")))
378 assert m.int_string_pair() == (2,
"items")
382 """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
383 assert m.return_none_string()
is None
384 assert m.return_none_char()
is None
385 assert m.return_none_bool()
is None
386 assert m.return_none_int()
is None
387 assert m.return_none_float()
is None
388 assert m.return_none_pair()
is None
392 """None passed as various argument types should defer to other overloads"""
393 assert not m.defer_none_cstring(
"abc")
394 assert m.defer_none_cstring(
None)
395 assert not m.defer_none_custom(UserType())
396 assert m.defer_none_custom(
None)
397 assert m.nodefer_none_void(
None)
401 assert m.load_nullptr_t(
None)
is None
402 assert m.cast_nullptr_t()
is None
406 """std::reference_wrapper for builtin and user types"""
407 assert m.refwrap_builtin(42) == 420
408 assert m.refwrap_usertype(UserType(42)) == 42
409 assert m.refwrap_usertype_const(UserType(42)) == 42
411 with pytest.raises(TypeError)
as excinfo:
412 m.refwrap_builtin(
None)
413 assert "incompatible function arguments" in str(excinfo.value)
415 with pytest.raises(TypeError)
as excinfo:
416 m.refwrap_usertype(
None)
417 assert "incompatible function arguments" in str(excinfo.value)
419 assert m.refwrap_lvalue().value == 1
420 assert m.refwrap_lvalue_const().value == 1
422 a1 = m.refwrap_list(copy=
True)
423 a2 = m.refwrap_list(copy=
True)
424 assert [x.value
for x
in a1] == [2, 3]
425 assert [x.value
for x
in a2] == [2, 3]
426 assert a1[0]
is not a2[0]
427 assert a1[1]
is not a2[1]
429 b1 = m.refwrap_list(copy=
False)
430 b2 = m.refwrap_list(copy=
False)
431 assert [x.value
for x
in b1] == [1, 2]
432 assert [x.value
for x
in b2] == [1, 2]
433 assert b1[0]
is b2[0]
434 assert b1[1]
is b2[1]
436 assert m.refwrap_iiw(IncType(5)) == 5
437 assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
441 """std::complex casts"""
442 assert m.complex_cast(1) ==
"1.0"
443 assert m.complex_cast(2j) ==
"(0.0, 2.0)"
447 """Test bool caster implicit conversions."""
448 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
450 def require_implicit(v):
451 pytest.raises(TypeError, noconvert, v)
454 pytest.raises(TypeError, convert, v)
459 assert noconvert(
True)
is True
460 assert noconvert(
False)
is False
463 require_implicit(
None)
470 def __nonzero__(self):
484 require_implicit(
A(
True))
490 np = pytest.importorskip(
"numpy")
492 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
495 pytest.raises(TypeError, convert, v)
498 assert convert(np.bool_(
True))
is True
499 assert convert(np.bool_(
False))
is False
500 assert noconvert(np.bool_(
True))
is True
501 assert noconvert(np.bool_(
False))
is False
502 cant_convert(np.zeros(2, dtype=
"int"))
512 assert m.test_void_caster()
516 """Verifies that const-ref is propagated through type_caster cast_op.
517 The returned ConstRefCasted type is a minimal type that is constructed to
518 reference the casting mode used.
521 assert m.takes(x) == 1
522 assert m.takes_move(x) == 1
524 assert m.takes_ptr(x) == 3
525 assert m.takes_ref(x) == 2
526 assert m.takes_ref_wrap(x) == 2
528 assert m.takes_const_ptr(x) == 5
529 assert m.takes_const_ref(x) == 4
530 assert m.takes_const_ref_wrap(x) == 4