5from pybind11_tests
import IncType, UserType
6from pybind11_tests
import builtin_casters
as m
10 assert m.string_roundtrip(
"const char *") ==
"const char *"
14 """Tests unicode conversion and error reporting."""
15 assert m.good_utf8_string() ==
u"Say utf8β½ π π"
16 assert m.good_utf16_string() ==
u"bβ½ππz"
17 assert m.good_utf32_string() ==
u"aππβ½z"
18 assert m.good_wchar_string() ==
u"aβΈπz"
20 assert m.good_utf8_u8string() ==
u"Say utf8β½ π π"
22 with pytest.raises(UnicodeDecodeError):
25 with pytest.raises(UnicodeDecodeError):
29 if hasattr(m,
"bad_utf32_string"):
30 with pytest.raises(UnicodeDecodeError):
32 if hasattr(m,
"bad_wchar_string"):
33 with pytest.raises(UnicodeDecodeError):
36 with pytest.raises(UnicodeDecodeError):
39 assert m.u8_Z() ==
"Z"
40 assert m.u8_eacute() ==
u"Γ©"
41 assert m.u16_ibang() ==
u"β½"
42 assert m.u32_mathbfA() ==
u"π"
43 assert m.wchar_heart() ==
u"β₯"
45 assert m.u8_char8_Z() ==
"Z"
49 """Tests failures for passing invalid inputs to char-accepting functions"""
51 def toobig_message(r):
52 return "Character code point not in range({:#x})".format(r)
54 toolong_message =
"Expected a character, but multi-character string found"
56 assert m.ord_char(
u"a") == 0x61
57 assert m.ord_char_lv(
u"b") == 0x62
59 m.ord_char(
u"Γ©") == 0xE9
61 with pytest.raises(ValueError)
as excinfo:
62 assert m.ord_char(
u"Δ") == 0x100
63 assert str(excinfo.value) == toobig_message(0x100)
64 with pytest.raises(ValueError)
as excinfo:
65 assert m.ord_char(
u"ab")
66 assert str(excinfo.value) == toolong_message
68 assert m.ord_char16(
u"a") == 0x61
69 assert m.ord_char16(
u"Γ©") == 0xE9
70 assert m.ord_char16_lv(
u"Γͺ") == 0xEA
71 assert m.ord_char16(
u"Δ") == 0x100
72 assert m.ord_char16(
u"β½") == 0x203D
73 assert m.ord_char16(
u"β₯") == 0x2665
74 assert m.ord_char16_lv(
u"β‘") == 0x2661
75 with pytest.raises(ValueError)
as excinfo:
76 assert m.ord_char16(
u"π") == 0x1F382
77 assert str(excinfo.value) == toobig_message(0x10000)
78 with pytest.raises(ValueError)
as excinfo:
79 assert m.ord_char16(
u"aa")
80 assert str(excinfo.value) == toolong_message
82 assert m.ord_char32(
u"a") == 0x61
83 assert m.ord_char32(
u"Γ©") == 0xE9
84 assert m.ord_char32(
u"Δ") == 0x100
85 assert m.ord_char32(
u"β½") == 0x203D
86 assert m.ord_char32(
u"β₯") == 0x2665
87 assert m.ord_char32(
u"π") == 0x1F382
88 with pytest.raises(ValueError)
as excinfo:
89 assert m.ord_char32(
u"aa")
90 assert str(excinfo.value) == toolong_message
92 assert m.ord_wchar(
u"a") == 0x61
93 assert m.ord_wchar(
u"Γ©") == 0xE9
94 assert m.ord_wchar(
u"Δ") == 0x100
95 assert m.ord_wchar(
u"β½") == 0x203D
96 assert m.ord_wchar(
u"β₯") == 0x2665
98 with pytest.raises(ValueError)
as excinfo:
99 assert m.ord_wchar(
u"π") == 0x1F382
100 assert str(excinfo.value) == toobig_message(0x10000)
102 assert m.ord_wchar(
u"π") == 0x1F382
103 with pytest.raises(ValueError)
as excinfo:
104 assert m.ord_wchar(
u"aa")
105 assert str(excinfo.value) == toolong_message
108 assert m.ord_char8(
u"a") == 0x61
109 assert m.ord_char8_lv(
u"b") == 0x62
111 m.ord_char8(
u"Γ©") == 0xE9
113 with pytest.raises(ValueError)
as excinfo:
114 assert m.ord_char8(
u"Δ") == 0x100
115 assert str(excinfo.value) == toobig_message(0x100)
116 with pytest.raises(ValueError)
as excinfo:
117 assert m.ord_char8(
u"ab")
118 assert str(excinfo.value) == toolong_message
122 """Tests the ability to pass bytes to C++ string-accepting functions. Note that this is
123 one-way: the only way to
return bytes to Python
is via the pybind11::bytes
class.
"""
127 b = s
if env.PY2
else s.encode(
"utf8")
131 assert m.strlen(to_bytes(
"hi")) == 2
132 assert m.string_length(to_bytes(
"world")) == 5
133 assert m.string_length(to_bytes(
"a\x00b")) == 3
134 assert m.strlen(to_bytes(
"a\x00b")) == 1
137 assert m.string_length(
u"π©".encode(
"utf8")) == 4
140@pytest.mark.skipif(not hasattr(m, "has_string_view"), reason=
"no <string_view>")
142 """Tests support for C++17 string_view arguments and return values"""
143 assert m.string_view_chars(
"Hi") == [72, 105]
144 assert m.string_view_chars(
"Hi π") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82]
145 assert m.string_view16_chars(
u"Hi π") == [72, 105, 32, 0xD83C, 0xDF82]
146 assert m.string_view32_chars(
u"Hi π") == [72, 105, 32, 127874]
148 assert m.string_view8_chars(
"Hi") == [72, 105]
149 assert m.string_view8_chars(
u"Hi π") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82]
151 assert m.string_view_return() ==
u"utf8 secret π"
152 assert m.string_view16_return() ==
u"utf16 secret π"
153 assert m.string_view32_return() ==
u"utf32 secret π"
155 assert m.string_view8_return() ==
u"utf8 secret π"
158 m.string_view_print(
"Hi")
159 m.string_view_print(
"utf8 π")
160 m.string_view16_print(
u"utf16 π")
161 m.string_view32_print(
u"utf32 π")
173 m.string_view8_print(
"Hi")
174 m.string_view8_print(
u"utf8 π")
184 m.string_view_print(
"Hi, ascii")
185 m.string_view_print(
"Hi, utf8 π")
186 m.string_view16_print(
u"Hi, utf16 π")
187 m.string_view32_print(
u"Hi, utf32 π")
199 m.string_view8_print(
"Hi, ascii")
200 m.string_view8_print(
u"Hi, utf8 π")
209 assert m.string_view_bytes() == b
"abc \x80\x80 def"
210 assert m.string_view_str() ==
u"abc β½ def"
211 assert m.string_view_from_bytes(
u"abc β½ def".encode(
"utf-8")) ==
u"abc β½ def"
213 assert m.string_view8_str() ==
u"abc β½ def"
215 assert m.string_view_memoryview() ==
"Have some π".encode()
217 assert m.bytes_from_type_with_both_operator_string_and_string_view() == b
"success"
218 assert m.str_from_type_with_both_operator_string_and_string_view() ==
"success"
222 """Issue #929 - out-of-range integer values shouldn't be accepted"""
223 assert m.i32_str(-1) ==
"-1"
224 assert m.i64_str(-1) ==
"-1"
225 assert m.i32_str(2000000000) ==
"2000000000"
226 assert m.u32_str(2000000000) ==
"2000000000"
228 assert m.i32_str(long(-1)) ==
"-1"
229 assert m.i64_str(long(-1)) ==
"-1"
231 m.i64_str(long(-999999999999))
235 m.u64_str(long(999999999999))
239 assert m.i64_str(-999999999999) ==
"-999999999999"
240 assert m.u64_str(999999999999) ==
"999999999999"
242 with pytest.raises(TypeError)
as excinfo:
244 assert "incompatible function arguments" in str(excinfo.value)
245 with pytest.raises(TypeError)
as excinfo:
247 assert "incompatible function arguments" in str(excinfo.value)
248 with pytest.raises(TypeError)
as excinfo:
249 m.i32_str(-3000000000)
250 assert "incompatible function arguments" in str(excinfo.value)
251 with pytest.raises(TypeError)
as excinfo:
252 m.i32_str(3000000000)
253 assert "incompatible function arguments" in str(excinfo.value)
256 with pytest.raises(TypeError)
as excinfo:
258 assert "incompatible function arguments" in str(excinfo.value)
259 with pytest.raises(TypeError)
as excinfo:
261 assert "incompatible function arguments" in str(excinfo.value)
280 class IntAndIndex(
object):
287 class RaisingTypeErrorOnIndex(
object):
294 class RaisingValueErrorOnIndex(
object):
301 convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert
303 def requires_conversion(v):
304 pytest.raises(TypeError, noconvert, v)
307 pytest.raises(TypeError, convert, v)
309 assert convert(7) == 7
310 assert noconvert(7) == 7
311 cant_convert(3.14159)
314 if (3, 8) <= env.PY < (3, 10)
and env.CPYTHON:
316 assert convert(Int()) == 42
318 assert convert(Int()) == 42
319 requires_conversion(Int())
320 cant_convert(NotInt())
321 cant_convert(Float())
325 assert convert(Index()) == 42
326 assert noconvert(Index()) == 42
327 assert convert(IntAndIndex()) == 0
328 assert noconvert(IntAndIndex()) == 0
329 assert convert(RaisingTypeErrorOnIndex()) == 42
330 requires_conversion(RaisingTypeErrorOnIndex())
331 assert convert(RaisingValueErrorOnIndex()) == 42
332 requires_conversion(RaisingValueErrorOnIndex())
336 np = pytest.importorskip(
"numpy")
338 convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert
340 def require_implicit(v):
341 pytest.raises(TypeError, noconvert, v)
344 assert convert(np.intc(42)) == 42
345 assert noconvert(np.intc(42)) == 42
351 if (3, 8) <= env.PY < (3, 10)
and env.CPYTHON:
353 assert convert(np.float32(3.14159)) == 3
355 assert convert(np.float32(3.14159)) == 3
356 require_implicit(np.float32(3.14159))
360 """std::pair <-> tuple & std::tuple <-> tuple"""
361 assert m.pair_passthrough((
True,
"test")) == (
"test",
True)
362 assert m.tuple_passthrough((
True,
"test", 5)) == (5,
"test",
True)
364 assert m.pair_passthrough([
True,
"test"]) == (
"test",
True)
365 assert m.tuple_passthrough([
True,
"test", 5]) == (5,
"test",
True)
366 assert m.empty_tuple() == ()
369 doc(m.pair_passthrough)
371 pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool]
373 Return a pair in reversed order
377 doc(m.tuple_passthrough)
379 tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool]
381 Return a triple in reversed order
385 assert m.rvalue_pair() == (
"rvalue",
"rvalue")
386 assert m.lvalue_pair() == (
"lvalue",
"lvalue")
387 assert m.rvalue_tuple() == (
"rvalue",
"rvalue",
"rvalue")
388 assert m.lvalue_tuple() == (
"lvalue",
"lvalue",
"lvalue")
389 assert m.rvalue_nested() == (
"rvalue", (
"rvalue", (
"rvalue",
"rvalue")))
390 assert m.lvalue_nested() == (
"lvalue", (
"lvalue", (
"lvalue",
"lvalue")))
392 assert m.int_string_pair() == (2,
"items")
396 """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
397 assert m.return_none_string()
is None
398 assert m.return_none_char()
is None
399 assert m.return_none_bool()
is None
400 assert m.return_none_int()
is None
401 assert m.return_none_float()
is None
402 assert m.return_none_pair()
is None
406 """None passed as various argument types should defer to other overloads"""
407 assert not m.defer_none_cstring(
"abc")
408 assert m.defer_none_cstring(
None)
409 assert not m.defer_none_custom(UserType())
410 assert m.defer_none_custom(
None)
411 assert m.nodefer_none_void(
None)
415 assert m.load_nullptr_t(
None)
is None
416 assert m.cast_nullptr_t()
is None
420 """std::reference_wrapper for builtin and user types"""
421 assert m.refwrap_builtin(42) == 420
422 assert m.refwrap_usertype(UserType(42)) == 42
423 assert m.refwrap_usertype_const(UserType(42)) == 42
425 with pytest.raises(TypeError)
as excinfo:
426 m.refwrap_builtin(
None)
427 assert "incompatible function arguments" in str(excinfo.value)
429 with pytest.raises(TypeError)
as excinfo:
430 m.refwrap_usertype(
None)
431 assert "incompatible function arguments" in str(excinfo.value)
433 assert m.refwrap_lvalue().value == 1
434 assert m.refwrap_lvalue_const().value == 1
436 a1 = m.refwrap_list(copy=
True)
437 a2 = m.refwrap_list(copy=
True)
438 assert [x.value
for x
in a1] == [2, 3]
439 assert [x.value
for x
in a2] == [2, 3]
440 assert not a1[0]
is a2[0]
and not a1[1]
is a2[1]
442 b1 = m.refwrap_list(copy=
False)
443 b2 = m.refwrap_list(copy=
False)
444 assert [x.value
for x
in b1] == [1, 2]
445 assert [x.value
for x
in b2] == [1, 2]
446 assert b1[0]
is b2[0]
and b1[1]
is b2[1]
448 assert m.refwrap_iiw(IncType(5)) == 5
449 assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
453 """std::complex casts"""
454 assert m.complex_cast(1) ==
"1.0"
455 assert m.complex_cast(2j) ==
"(0.0, 2.0)"
459 """Test bool caster implicit conversions."""
460 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
462 def require_implicit(v):
463 pytest.raises(TypeError, noconvert, v)
466 pytest.raises(TypeError, convert, v)
469 assert convert(
True)
is True
470 assert convert(
False)
is False
471 assert noconvert(
True)
is True
472 assert noconvert(
False)
is False
475 require_implicit(
None)
476 assert convert(
None)
is False
479 def __init__(self, x):
482 def __nonzero__(self):
496 require_implicit(
A(
True))
497 assert convert(
A(
True))
is True
498 assert convert(
A(
False))
is False
502 np = pytest.importorskip(
"numpy")
504 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert
507 pytest.raises(TypeError, convert, v)
510 assert convert(np.bool_(
True))
is True
511 assert convert(np.bool_(
False))
is False
512 assert noconvert(np.bool_(
True))
is True
513 assert noconvert(np.bool_(
False))
is False
514 cant_convert(np.zeros(2, dtype=
"int"))
518 """In Python 2, a C++ int should return a Python int rather than long
519 if possible: longs are
not always accepted where ints are used (such
520 as the argument to sys.exit()). A C++ long long
is always a Python
528 assert isinstance(m.longlong_cast(), must_be_long)
532 assert m.test_void_caster()
536 """Verifies that const-ref is propagated through type_caster cast_op.
537 The returned ConstRefCasted type is a minimal type that
is constructed to
538 reference the casting mode used.
541 assert m.takes(x) == 1
542 assert m.takes_move(x) == 1
544 assert m.takes_ptr(x) == 3
545 assert m.takes_ref(x) == 2
546 assert m.takes_ref_wrap(x) == 2
548 assert m.takes_const_ptr(x) == 5
549 assert m.takes_const_ref(x) == 4
550 assert m.takes_const_ref_wrap(x) == 4
\rst Holds a reference to a Python object (with reference counting)
object getattr(handle obj, handle name)
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_single_char_arguments()
def test_bytes_to_string()
def test_reference_wrapper()
def test_unicode_conversion()
Annotation for documentation.