test_builtin_casters.py 11 KB

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