6from pybind11_tests
import IncType, UserType
7from pybind11_tests
import builtin_casters
as m
10def test_simple_string():
11 assert m.string_roundtrip(
"const char *") ==
"const char *"
14def test_unicode_conversion():
15 """Tests unicode conversion and error reporting."""
16 assert m.good_utf8_string() ==
"Say utf8β½ π π"
17 assert m.good_utf16_string() ==
"bβ½ππz"
18 assert m.good_utf32_string() ==
"aππβ½z"
19 assert m.good_wchar_string() ==
"aβΈπz"
21 assert m.good_utf8_u8string() ==
"Say utf8β½ π π"
23 with pytest.raises(UnicodeDecodeError):
26 with pytest.raises(UnicodeDecodeError):
30 if hasattr(m,
"bad_utf32_string"):
31 with pytest.raises(UnicodeDecodeError):
33 if hasattr(m,
"bad_wchar_string"):
34 with pytest.raises(UnicodeDecodeError):
37 with pytest.raises(UnicodeDecodeError):
40 assert m.u8_Z() ==
"Z"
41 assert m.u8_eacute() ==
"Γ©"
42 assert m.u16_ibang() ==
"β½"
43 assert m.u32_mathbfA() ==
"π"
44 assert m.wchar_heart() ==
"β₯"
46 assert m.u8_char8_Z() ==
"Z"
49def test_single_char_arguments():
50 """Tests failures for passing invalid inputs to char-accepting functions"""
52 def toobig_message(r):
53 return f
"Character code point not in range({r:#x})"
55 toolong_message =
"Expected a character, but multi-character string found"
57 assert m.ord_char(
"a") == 0x61
58 assert m.ord_char_lv(
"b") == 0x62
60 m.ord_char(
"Γ©") == 0xE9
62 with pytest.raises(ValueError)
as excinfo:
63 assert m.ord_char(
"Δ") == 0x100
64 assert str(excinfo.value) == toobig_message(0x100)
65 with pytest.raises(ValueError)
as excinfo:
66 assert m.ord_char(
"ab")
67 assert str(excinfo.value) == toolong_message
69 assert m.ord_char16(
"a") == 0x61
70 assert m.ord_char16(
"Γ©") == 0xE9
71 assert m.ord_char16_lv(
"Γͺ") == 0xEA
72 assert m.ord_char16(
"Δ") == 0x100
73 assert m.ord_char16(
"β½") == 0x203D
74 assert m.ord_char16(
"β₯") == 0x2665
75 assert m.ord_char16_lv(
"β‘") == 0x2661
76 with pytest.raises(ValueError)
as excinfo:
77 assert m.ord_char16(
"π") == 0x1F382
78 assert str(excinfo.value) == toobig_message(0x10000)
79 with pytest.raises(ValueError)
as excinfo:
80 assert m.ord_char16(
"aa")
81 assert str(excinfo.value) == toolong_message
83 assert m.ord_char32(
"a") == 0x61
84 assert m.ord_char32(
"Γ©") == 0xE9
85 assert m.ord_char32(
"Δ") == 0x100
86 assert m.ord_char32(
"β½") == 0x203D
87 assert m.ord_char32(
"β₯") == 0x2665
88 assert m.ord_char32(
"π") == 0x1F382
89 with pytest.raises(ValueError)
as excinfo:
90 assert m.ord_char32(
"aa")
91 assert str(excinfo.value) == toolong_message
93 assert m.ord_wchar(
"a") == 0x61
94 assert m.ord_wchar(
"Γ©") == 0xE9
95 assert m.ord_wchar(
"Δ") == 0x100
96 assert m.ord_wchar(
"β½") == 0x203D
97 assert m.ord_wchar(
"β₯") == 0x2665
99 with pytest.raises(ValueError)
as excinfo:
100 assert m.ord_wchar(
"π") == 0x1F382
101 assert str(excinfo.value) == toobig_message(0x10000)
103 assert m.ord_wchar(
"π") == 0x1F382
104 with pytest.raises(ValueError)
as excinfo:
105 assert m.ord_wchar(
"aa")
106 assert str(excinfo.value) == toolong_message
109 assert m.ord_char8(
"a") == 0x61
110 assert m.ord_char8_lv(
"b") == 0x62
112 m.ord_char8(
"Γ©") == 0xE9
114 with pytest.raises(ValueError)
as excinfo:
115 assert m.ord_char8(
"Δ") == 0x100
116 assert str(excinfo.value) == toobig_message(0x100)
117 with pytest.raises(ValueError)
as excinfo:
118 assert m.ord_char8(
"ab")
119 assert str(excinfo.value) == toolong_message
122def test_bytes_to_string():
123 """Tests the ability to pass bytes to C++ string-accepting functions. Note that this is
124 one-way: the only way to
return bytes to Python
is via the pybind11::bytes
class.
"""
127 assert m.strlen(b
"hi") == 2
128 assert m.string_length(b
"world") == 5
129 assert m.string_length(
"a\x00b".encode()) == 3
130 assert m.strlen(
"a\x00b".encode()) == 1
133 assert m.string_length(
"π©".encode()) == 4
137 """Tests the ability to pass bytearray to C++ string-accepting functions"""
138 assert m.string_length(
bytearray(b
"Hi")) == 2
139 assert m.strlen(
bytearray(b
"bytearray")) == 9
141 assert m.string_length(
bytearray(
"π¦",
"utf-8",
"strict")) == 4
142 assert m.string_length(
bytearray(b
"\x80")) == 1
145@pytest.mark.skipif(not hasattr(m, "has_string_view"), reason=
"no <string_view>")
147 """Tests support for C++17 string_view arguments and return values"""
148 assert m.string_view_chars(
"Hi") == [72, 105]
149 assert m.string_view_chars(
"Hi π") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82]
150 assert m.string_view16_chars(
"Hi π") == [72, 105, 32, 0xD83C, 0xDF82]
151 assert m.string_view32_chars(
"Hi π") == [72, 105, 32, 127874]
153 assert m.string_view8_chars(
"Hi") == [72, 105]
154 assert m.string_view8_chars(
"Hi π") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82]
156 assert m.string_view_return() ==
"utf8 secret π"
157 assert m.string_view16_return() ==
"utf16 secret π"
158 assert m.string_view32_return() ==
"utf32 secret π"
160 assert m.string_view8_return() ==
"utf8 secret π"
163 m.string_view_print(
"Hi")
164 m.string_view_print(
"utf8 π")
165 m.string_view16_print(
"utf16 π")
166 m.string_view32_print(
"utf32 π")
178 m.string_view8_print(
"Hi")
179 m.string_view8_print(
"utf8 π")
189 m.string_view_print(
"Hi, ascii")
190 m.string_view_print(
"Hi, utf8 π")
191 m.string_view16_print(
"Hi, utf16 π")
192 m.string_view32_print(
"Hi, utf32 π")
204 m.string_view8_print(
"Hi, ascii")
205 m.string_view8_print(
"Hi, utf8 π")
214 assert m.string_view_bytes() == b
"abc \x80\x80 def"
215 assert m.string_view_str() ==
"abc β½ def"
216 assert m.string_view_from_bytes(
"abc β½ def".encode()) ==
"abc β½ def"
218 assert m.string_view8_str() ==
"abc β½ def"
219 assert m.string_view_memoryview() ==
"Have some π".encode()
221 assert m.bytes_from_type_with_both_operator_string_and_string_view() == b
"success"
222 assert m.str_from_type_with_both_operator_string_and_string_view() ==
"success"
226 """Issue #929 - out-of-range integer values shouldn't be accepted"""
227 assert m.i32_str(-1) ==
"-1"
228 assert m.i64_str(-1) ==
"-1"
229 assert m.i32_str(2000000000) ==
"2000000000"
230 assert m.u32_str(2000000000) ==
"2000000000"
231 assert m.i64_str(-999999999999) ==
"-999999999999"
232 assert m.u64_str(999999999999) ==
"999999999999"
234 with pytest.raises(TypeError)
as excinfo:
236 assert "incompatible function arguments" in str(excinfo.value)
237 with pytest.raises(TypeError)
as excinfo:
239 assert "incompatible function arguments" in str(excinfo.value)
240 with pytest.raises(TypeError)
as excinfo:
241 m.i32_str(-3000000000)
242 assert "incompatible function arguments" in str(excinfo.value)
243 with pytest.raises(TypeError)
as excinfo:
244 m.i32_str(3000000000)
245 assert "incompatible function arguments" in str(excinfo.value)
271 class RaisingTypeErrorOnIndex:
278 class RaisingValueErrorOnIndex:
285 convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert
287 def requires_conversion(v):
288 pytest.raises(TypeError, noconvert, v)
291 pytest.raises(TypeError, convert, v)
293 assert convert(7) == 7
294 assert noconvert(7) == 7
295 cant_convert(3.14159)
298 if (3, 8) <= sys.version_info < (3, 10)
and env.CPYTHON:
300 assert convert(Int()) == 42
302 assert convert(Int()) == 42
303 requires_conversion(Int())
304 cant_convert(NotInt())
305 cant_convert(Float())
309 assert convert(Index()) == 42
310 assert noconvert(Index()) == 42
311 assert convert(IntAndIndex()) == 0
312 assert noconvert(IntAndIndex()) == 0
313 assert convert(RaisingTypeErrorOnIndex()) == 42
314 requires_conversion(RaisingTypeErrorOnIndex())
315 assert convert(RaisingValueErrorOnIndex()) == 42
316 requires_conversion(RaisingValueErrorOnIndex())
320 np = pytest.importorskip(
"numpy")
322 convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert
324 def require_implicit(v):
325 pytest.raises(TypeError, noconvert, v)
328 assert convert(np.intc(42)) == 42
329 assert noconvert(np.intc(42)) == 42
335 if (3, 8) <= sys.version_info < (3, 10)
and env.CPYTHON:
337 assert convert(np.float32(3.14159)) == 3
339 assert convert(np.float32(3.14159)) == 3
340 require_implicit(np.float32(3.14159))
344 """std::pair <-> tuple & std::tuple <-> tuple"""
345 assert m.pair_passthrough((
True,
"test")) == (
"test",
True)
346 assert m.tuple_passthrough((
True,
"test", 5)) == (5,
"test",
True)
348 assert m.pair_passthrough([
True,
"test"]) == (
"test",
True)
349 assert m.tuple_passthrough([
True,
"test", 5]) == (5,
"test",
True)
350 assert m.empty_tuple() == ()
353 doc(m.pair_passthrough)
355 pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool]
357 Return a pair in reversed order
361 doc(m.tuple_passthrough)
363 tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool]
365 Return a triple in reversed order
369 assert m.rvalue_pair() == (
"rvalue",
"rvalue")
370 assert m.lvalue_pair() == (
"lvalue",
"lvalue")
371 assert m.rvalue_tuple() == (
"rvalue",
"rvalue",
"rvalue")
372 assert m.lvalue_tuple() == (
"lvalue",
"lvalue",
"lvalue")
373 assert m.rvalue_nested() == (
"rvalue", (
"rvalue", (
"rvalue",
"rvalue")))
374 assert m.lvalue_nested() == (
"lvalue", (
"lvalue", (
"lvalue",
"lvalue")))
376 assert m.int_string_pair() == (2,
"items")
380 """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
381 assert m.return_none_string()
is None
382 assert m.return_none_char()
is None
383 assert m.return_none_bool()
is None
384 assert m.return_none_int()
is None
385 assert m.return_none_float()
is None
386 assert m.return_none_pair()
is None
390 """None passed as various argument types should defer to other overloads"""
391 assert not m.defer_none_cstring(
"abc")
392 assert m.defer_none_cstring(
None)
393 assert not m.defer_none_custom(
UserType())
394 assert m.defer_none_custom(
None)
395 assert m.nodefer_none_void(
None)
399 assert m.load_nullptr_t(
None)
is None
400 assert m.cast_nullptr_t()
is None
404 """std::reference_wrapper for builtin and user types"""
405 assert m.refwrap_builtin(42) == 420
406 assert m.refwrap_usertype(
UserType(42)) == 42
407 assert m.refwrap_usertype_const(
UserType(42)) == 42
409 with pytest.raises(TypeError)
as excinfo:
410 m.refwrap_builtin(
None)
411 assert "incompatible function arguments" in str(excinfo.value)
413 with pytest.raises(TypeError)
as excinfo:
414 m.refwrap_usertype(
None)
415 assert "incompatible function arguments" in str(excinfo.value)
417 assert m.refwrap_lvalue().value == 1
418 assert m.refwrap_lvalue_const().value == 1
420 a1 = m.refwrap_list(copy=
True)
421 a2 = m.refwrap_list(copy=
True)
422 assert [x.value
for x
in a1] == [2, 3]
423 assert [x.value
for x
in a2] == [2, 3]
424 assert not a1[0]
is a2[0]
and not a1[1]
is a2[1]
426 b1 = m.refwrap_list(copy=
False)
427 b2 = m.refwrap_list(copy=
False)
428 assert [x.value
for x
in b1] == [1, 2]
429 assert [x.value
for x
in b2] == [1, 2]
430 assert b1[0]
is b2[0]
and b1[1]
is b2[1]
432 assert m.refwrap_iiw(
IncType(5)) == 5
433 assert m.refwrap_call_iiw(
IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
437 """std::complex casts"""
438 assert m.complex_cast(1) ==
"1.0"
439 assert m.complex_cast(2j) ==
"(0.0, 2.0)"
443 """Test bool caster implicit conversions."""
444 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
446 def require_implicit(v):
447 pytest.raises(TypeError, noconvert, v)
450 pytest.raises(TypeError, convert, v)
453 assert convert(
True)
is True
454 assert convert(
False)
is False
455 assert noconvert(
True)
is True
456 assert noconvert(
False)
is False
459 require_implicit(
None)
460 assert convert(
None)
is False
463 def __init__(self, x):
466 def __nonzero__(self):
480 require_implicit(
A(
True))
481 assert convert(
A(
True))
is True
482 assert convert(
A(
False))
is False
486 np = pytest.importorskip(
"numpy")
488 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
491 pytest.raises(TypeError, convert, v)
494 assert convert(np.bool_(
True))
is True
495 assert convert(np.bool_(
False))
is False
496 assert noconvert(np.bool_(
True))
is True
497 assert noconvert(np.bool_(
False))
is False
498 cant_convert(np.zeros(2, dtype=
"int"))
508 assert m.test_void_caster()
512 """Verifies that const-ref is propagated through type_caster cast_op.
513 The returned ConstRefCasted type is a minimal type that
is constructed to
514 reference the casting mode used.
517 assert m.takes(x) == 1
518 assert m.takes_move(x) == 1
520 assert m.takes_ptr(x) == 3
521 assert m.takes_ref(x) == 2
522 assert m.takes_ref_wrap(x) == 2
524 assert m.takes_const_ptr(x) == 5
525 assert m.takes_const_ref(x) == 4
526 assert m.takes_const_ref_wrap(x) == 4
Like UserType, but increments value on copy for quick reference vs. copy tests.
A user-defined type which is exported and can be used by any test.
\rst Holds a reference to a Python object (with reference counting)
bool hasattr(handle obj, handle name)
bool isinstance(handle obj)
\rst Return true if obj is an instance of T.
def test_const_ref_caster()
def test_builtins_cast_return_none()
def test_string_view(capture)
def test_numpy_int_convert()
def test_integer_casting()
def test_reference_wrapper()
def test_bytearray_to_string()
Annotation for documentation.