test_builtin_casters.py revision 12391:ceeca8b41e4b
1# Python < 3 needs this: coding=utf-8 2import 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" 18 19 with pytest.raises(UnicodeDecodeError): 20 m.bad_utf8_string() 21 22 with pytest.raises(UnicodeDecodeError): 23 m.bad_utf16_string() 24 25 # These are provided only if they actually fail (they don't when 32-bit and under Python 2.7) 26 if hasattr(m, "bad_utf32_string"): 27 with pytest.raises(UnicodeDecodeError): 28 m.bad_utf32_string() 29 if hasattr(m, "bad_wchar_string"): 30 with pytest.raises(UnicodeDecodeError): 31 m.bad_wchar_string() 32 33 assert m.u8_Z() == 'Z' 34 assert m.u8_eacute() == u'é' 35 assert m.u16_ibang() == u'‽' 36 assert m.u32_mathbfA() == u'' 37 assert m.wchar_heart() == u'♥' 38 39 40def test_single_char_arguments(): 41 """Tests failures for passing invalid inputs to char-accepting functions""" 42 def toobig_message(r): 43 return "Character code point not in range({0:#x})".format(r) 44 toolong_message = "Expected a character, but multi-character string found" 45 46 assert m.ord_char(u'a') == 0x61 # simple ASCII 47 assert m.ord_char(u'é') == 0xE9 # requires 2 bytes in utf-8, but can be stuffed in a char 48 with pytest.raises(ValueError) as excinfo: 49 assert m.ord_char(u'Ā') == 0x100 # requires 2 bytes, doesn't fit in a char 50 assert str(excinfo.value) == toobig_message(0x100) 51 with pytest.raises(ValueError) as excinfo: 52 assert m.ord_char(u'ab') 53 assert str(excinfo.value) == toolong_message 54 55 assert m.ord_char16(u'a') == 0x61 56 assert m.ord_char16(u'é') == 0xE9 57 assert m.ord_char16(u'Ā') == 0x100 58 assert m.ord_char16(u'‽') == 0x203d 59 assert m.ord_char16(u'♥') == 0x2665 60 with pytest.raises(ValueError) as excinfo: 61 assert m.ord_char16(u'') == 0x1F382 # requires surrogate pair 62 assert str(excinfo.value) == toobig_message(0x10000) 63 with pytest.raises(ValueError) as excinfo: 64 assert m.ord_char16(u'aa') 65 assert str(excinfo.value) == toolong_message 66 67 assert m.ord_char32(u'a') == 0x61 68 assert m.ord_char32(u'é') == 0xE9 69 assert m.ord_char32(u'Ā') == 0x100 70 assert m.ord_char32(u'‽') == 0x203d 71 assert m.ord_char32(u'♥') == 0x2665 72 assert m.ord_char32(u'') == 0x1F382 73 with pytest.raises(ValueError) as excinfo: 74 assert m.ord_char32(u'aa') 75 assert str(excinfo.value) == toolong_message 76 77 assert m.ord_wchar(u'a') == 0x61 78 assert m.ord_wchar(u'é') == 0xE9 79 assert m.ord_wchar(u'Ā') == 0x100 80 assert m.ord_wchar(u'‽') == 0x203d 81 assert m.ord_wchar(u'♥') == 0x2665 82 if m.wchar_size == 2: 83 with pytest.raises(ValueError) as excinfo: 84 assert m.ord_wchar(u'') == 0x1F382 # requires surrogate pair 85 assert str(excinfo.value) == toobig_message(0x10000) 86 else: 87 assert m.ord_wchar(u'') == 0x1F382 88 with pytest.raises(ValueError) as excinfo: 89 assert m.ord_wchar(u'aa') 90 assert str(excinfo.value) == toolong_message 91 92 93def test_bytes_to_string(): 94 """Tests the ability to pass bytes to C++ string-accepting functions. Note that this is 95 one-way: the only way to return bytes to Python is via the pybind11::bytes class.""" 96 # Issue #816 97 import sys 98 byte = bytes if sys.version_info[0] < 3 else str 99 100 assert m.strlen(byte("hi")) == 2 101 assert m.string_length(byte("world")) == 5 102 assert m.string_length(byte("a\x00b")) == 3 103 assert m.strlen(byte("a\x00b")) == 1 # C-string limitation 104 105 # passing in a utf8 encoded string should work 106 assert m.string_length(u''.encode("utf8")) == 4 107 108 109@pytest.mark.skipif(not hasattr(m, "has_string_view"), reason="no <string_view>") 110def test_string_view(capture): 111 """Tests support for C++17 string_view arguments and return values""" 112 assert m.string_view_chars("Hi") == [72, 105] 113 assert m.string_view_chars("Hi ") == [72, 105, 32, 0xf0, 0x9f, 0x8e, 0x82] 114 assert m.string_view16_chars("Hi ") == [72, 105, 32, 0xd83c, 0xdf82] 115 assert m.string_view32_chars("Hi ") == [72, 105, 32, 127874] 116 117 assert m.string_view_return() == "utf8 secret " 118 assert m.string_view16_return() == "utf16 secret " 119 assert m.string_view32_return() == "utf32 secret " 120 121 with capture: 122 m.string_view_print("Hi") 123 m.string_view_print("utf8 ") 124 m.string_view16_print("utf16 ") 125 m.string_view32_print("utf32 ") 126 assert capture == """ 127 Hi 2 128 utf8 9 129 utf16 8 130 utf32 7 131 """ 132 133 with capture: 134 m.string_view_print("Hi, ascii") 135 m.string_view_print("Hi, utf8 ") 136 m.string_view16_print("Hi, utf16 ") 137 m.string_view32_print("Hi, utf32 ") 138 assert capture == """ 139 Hi, ascii 9 140 Hi, utf8 13 141 Hi, utf16 12 142 Hi, utf32 11 143 """ 144 145 146def test_integer_casting(): 147 """Issue #929 - out-of-range integer values shouldn't be accepted""" 148 import sys 149 assert m.i32_str(-1) == "-1" 150 assert m.i64_str(-1) == "-1" 151 assert m.i32_str(2000000000) == "2000000000" 152 assert m.u32_str(2000000000) == "2000000000" 153 if sys.version_info < (3,): 154 assert m.i32_str(long(-1)) == "-1" # noqa: F821 undefined name 'long' 155 assert m.i64_str(long(-1)) == "-1" # noqa: F821 undefined name 'long' 156 assert m.i64_str(long(-999999999999)) == "-999999999999" # noqa: F821 undefined name 157 assert m.u64_str(long(999999999999)) == "999999999999" # noqa: F821 undefined name 'long' 158 else: 159 assert m.i64_str(-999999999999) == "-999999999999" 160 assert m.u64_str(999999999999) == "999999999999" 161 162 with pytest.raises(TypeError) as excinfo: 163 m.u32_str(-1) 164 assert "incompatible function arguments" in str(excinfo.value) 165 with pytest.raises(TypeError) as excinfo: 166 m.u64_str(-1) 167 assert "incompatible function arguments" in str(excinfo.value) 168 with pytest.raises(TypeError) as excinfo: 169 m.i32_str(-3000000000) 170 assert "incompatible function arguments" in str(excinfo.value) 171 with pytest.raises(TypeError) as excinfo: 172 m.i32_str(3000000000) 173 assert "incompatible function arguments" in str(excinfo.value) 174 175 if sys.version_info < (3,): 176 with pytest.raises(TypeError) as excinfo: 177 m.u32_str(long(-1)) # noqa: F821 undefined name 'long' 178 assert "incompatible function arguments" in str(excinfo.value) 179 with pytest.raises(TypeError) as excinfo: 180 m.u64_str(long(-1)) # noqa: F821 undefined name 'long' 181 assert "incompatible function arguments" in str(excinfo.value) 182 183 184def test_tuple(doc): 185 """std::pair <-> tuple & std::tuple <-> tuple""" 186 assert m.pair_passthrough((True, "test")) == ("test", True) 187 assert m.tuple_passthrough((True, "test", 5)) == (5, "test", True) 188 # Any sequence can be cast to a std::pair or std::tuple 189 assert m.pair_passthrough([True, "test"]) == ("test", True) 190 assert m.tuple_passthrough([True, "test", 5]) == (5, "test", True) 191 assert m.empty_tuple() == () 192 193 assert doc(m.pair_passthrough) == """ 194 pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool] 195 196 Return a pair in reversed order 197 """ 198 assert doc(m.tuple_passthrough) == """ 199 tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool] 200 201 Return a triple in reversed order 202 """ 203 204 assert m.rvalue_pair() == ("rvalue", "rvalue") 205 assert m.lvalue_pair() == ("lvalue", "lvalue") 206 assert m.rvalue_tuple() == ("rvalue", "rvalue", "rvalue") 207 assert m.lvalue_tuple() == ("lvalue", "lvalue", "lvalue") 208 assert m.rvalue_nested() == ("rvalue", ("rvalue", ("rvalue", "rvalue"))) 209 assert m.lvalue_nested() == ("lvalue", ("lvalue", ("lvalue", "lvalue"))) 210 211 212def test_builtins_cast_return_none(): 213 """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None""" 214 assert m.return_none_string() is None 215 assert m.return_none_char() is None 216 assert m.return_none_bool() is None 217 assert m.return_none_int() is None 218 assert m.return_none_float() is None 219 220 221def test_none_deferred(): 222 """None passed as various argument types should defer to other overloads""" 223 assert not m.defer_none_cstring("abc") 224 assert m.defer_none_cstring(None) 225 assert not m.defer_none_custom(UserType()) 226 assert m.defer_none_custom(None) 227 assert m.nodefer_none_void(None) 228 229 230def test_void_caster(): 231 assert m.load_nullptr_t(None) is None 232 assert m.cast_nullptr_t() is None 233 234 235def test_reference_wrapper(): 236 """std::reference_wrapper for builtin and user types""" 237 assert m.refwrap_builtin(42) == 420 238 assert m.refwrap_usertype(UserType(42)) == 42 239 240 with pytest.raises(TypeError) as excinfo: 241 m.refwrap_builtin(None) 242 assert "incompatible function arguments" in str(excinfo.value) 243 244 with pytest.raises(TypeError) as excinfo: 245 m.refwrap_usertype(None) 246 assert "incompatible function arguments" in str(excinfo.value) 247 248 a1 = m.refwrap_list(copy=True) 249 a2 = m.refwrap_list(copy=True) 250 assert [x.value for x in a1] == [2, 3] 251 assert [x.value for x in a2] == [2, 3] 252 assert not a1[0] is a2[0] and not a1[1] is a2[1] 253 254 b1 = m.refwrap_list(copy=False) 255 b2 = m.refwrap_list(copy=False) 256 assert [x.value for x in b1] == [1, 2] 257 assert [x.value for x in b2] == [1, 2] 258 assert b1[0] is b2[0] and b1[1] is b2[1] 259 260 assert m.refwrap_iiw(IncType(5)) == 5 261 assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10] 262 263 264def test_complex_cast(): 265 """std::complex casts""" 266 assert m.complex_cast(1) == "1.0" 267 assert m.complex_cast(2j) == "(0.0, 2.0)" 268 269 270def test_bool_caster(): 271 """Test bool caster implicit conversions.""" 272 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert 273 274 def require_implicit(v): 275 pytest.raises(TypeError, noconvert, v) 276 277 def cant_convert(v): 278 pytest.raises(TypeError, convert, v) 279 280 # straight up bool 281 assert convert(True) is True 282 assert convert(False) is False 283 assert noconvert(True) is True 284 assert noconvert(False) is False 285 286 # None requires implicit conversion 287 require_implicit(None) 288 assert convert(None) is False 289 290 class A(object): 291 def __init__(self, x): 292 self.x = x 293 294 def __nonzero__(self): 295 return self.x 296 297 def __bool__(self): 298 return self.x 299 300 class B(object): 301 pass 302 303 # Arbitrary objects are not accepted 304 cant_convert(object()) 305 cant_convert(B()) 306 307 # Objects with __nonzero__ / __bool__ defined can be converted 308 require_implicit(A(True)) 309 assert convert(A(True)) is True 310 assert convert(A(False)) is False 311 312 313@pytest.requires_numpy 314def test_numpy_bool(): 315 import numpy as np 316 convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert 317 318 # np.bool_ is not considered implicit 319 assert convert(np.bool_(True)) is True 320 assert convert(np.bool_(False)) is False 321 assert noconvert(np.bool_(True)) is True 322 assert noconvert(np.bool_(False)) is False 323