You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

221 lines
7.8 KiB

  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(u'é') == 0xE9 # requires 2 bytes in utf-8, but can be stuffed in a char
  36. with pytest.raises(ValueError) as excinfo:
  37. assert m.ord_char(u'Ā') == 0x100 # requires 2 bytes, doesn't fit in a char
  38. assert str(excinfo.value) == toobig_message(0x100)
  39. with pytest.raises(ValueError) as excinfo:
  40. assert m.ord_char(u'ab')
  41. assert str(excinfo.value) == toolong_message
  42. assert m.ord_char16(u'a') == 0x61
  43. assert m.ord_char16(u'é') == 0xE9
  44. assert m.ord_char16(u'Ā') == 0x100
  45. assert m.ord_char16(u'') == 0x203d
  46. assert m.ord_char16(u'') == 0x2665
  47. with pytest.raises(ValueError) as excinfo:
  48. assert m.ord_char16(u'🎂') == 0x1F382 # requires surrogate pair
  49. assert str(excinfo.value) == toobig_message(0x10000)
  50. with pytest.raises(ValueError) as excinfo:
  51. assert m.ord_char16(u'aa')
  52. assert str(excinfo.value) == toolong_message
  53. assert m.ord_char32(u'a') == 0x61
  54. assert m.ord_char32(u'é') == 0xE9
  55. assert m.ord_char32(u'Ā') == 0x100
  56. assert m.ord_char32(u'') == 0x203d
  57. assert m.ord_char32(u'') == 0x2665
  58. assert m.ord_char32(u'🎂') == 0x1F382
  59. with pytest.raises(ValueError) as excinfo:
  60. assert m.ord_char32(u'aa')
  61. assert str(excinfo.value) == toolong_message
  62. assert m.ord_wchar(u'a') == 0x61
  63. assert m.ord_wchar(u'é') == 0xE9
  64. assert m.ord_wchar(u'Ā') == 0x100
  65. assert m.ord_wchar(u'') == 0x203d
  66. assert m.ord_wchar(u'') == 0x2665
  67. if m.wchar_size == 2:
  68. with pytest.raises(ValueError) as excinfo:
  69. assert m.ord_wchar(u'🎂') == 0x1F382 # requires surrogate pair
  70. assert str(excinfo.value) == toobig_message(0x10000)
  71. else:
  72. assert m.ord_wchar(u'🎂') == 0x1F382
  73. with pytest.raises(ValueError) as excinfo:
  74. assert m.ord_wchar(u'aa')
  75. assert str(excinfo.value) == toolong_message
  76. def test_bytes_to_string():
  77. """Tests the ability to pass bytes to C++ string-accepting functions. Note that this is
  78. one-way: the only way to return bytes to Python is via the pybind11::bytes class."""
  79. # Issue #816
  80. import sys
  81. byte = bytes if sys.version_info[0] < 3 else str
  82. assert m.strlen(byte("hi")) == 2
  83. assert m.string_length(byte("world")) == 5
  84. assert m.string_length(byte("a\x00b")) == 3
  85. assert m.strlen(byte("a\x00b")) == 1 # C-string limitation
  86. # passing in a utf8 encoded string should work
  87. assert m.string_length(u'💩'.encode("utf8")) == 4
  88. @pytest.mark.skipif(not hasattr(m, "has_string_view"), reason="no <string_view>")
  89. def test_string_view(capture):
  90. """Tests support for C++17 string_view arguments and return values"""
  91. assert m.string_view_chars("Hi") == [72, 105]
  92. assert m.string_view_chars("Hi 🎂") == [72, 105, 32, 0xf0, 0x9f, 0x8e, 0x82]
  93. assert m.string_view16_chars("Hi 🎂") == [72, 105, 32, 0xd83c, 0xdf82]
  94. assert m.string_view32_chars("Hi 🎂") == [72, 105, 32, 127874]
  95. assert m.string_view_return() == "utf8 secret 🎂"
  96. assert m.string_view16_return() == "utf16 secret 🎂"
  97. assert m.string_view32_return() == "utf32 secret 🎂"
  98. with capture:
  99. m.string_view_print("Hi")
  100. m.string_view_print("utf8 🎂")
  101. m.string_view16_print("utf16 🎂")
  102. m.string_view32_print("utf32 🎂")
  103. assert capture == """
  104. Hi 2
  105. utf8 🎂 9
  106. utf16 🎂 8
  107. utf32 🎂 7
  108. """
  109. with capture:
  110. m.string_view_print("Hi, ascii")
  111. m.string_view_print("Hi, utf8 🎂")
  112. m.string_view16_print("Hi, utf16 🎂")
  113. m.string_view32_print("Hi, utf32 🎂")
  114. assert capture == """
  115. Hi, ascii 9
  116. Hi, utf8 🎂 13
  117. Hi, utf16 🎂 12
  118. Hi, utf32 🎂 11
  119. """
  120. def test_tuple(doc):
  121. """std::pair <-> tuple & std::tuple <-> tuple"""
  122. assert m.pair_passthrough((True, "test")) == ("test", True)
  123. assert m.tuple_passthrough((True, "test", 5)) == (5, "test", True)
  124. # Any sequence can be cast to a std::pair or std::tuple
  125. assert m.pair_passthrough([True, "test"]) == ("test", True)
  126. assert m.tuple_passthrough([True, "test", 5]) == (5, "test", True)
  127. assert doc(m.pair_passthrough) == """
  128. pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool]
  129. Return a pair in reversed order
  130. """
  131. assert doc(m.tuple_passthrough) == """
  132. tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool]
  133. Return a triple in reversed order
  134. """
  135. def test_builtins_cast_return_none():
  136. """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
  137. assert m.return_none_string() is None
  138. assert m.return_none_char() is None
  139. assert m.return_none_bool() is None
  140. assert m.return_none_int() is None
  141. assert m.return_none_float() is None
  142. def test_none_deferred():
  143. """None passed as various argument types should defer to other overloads"""
  144. assert not m.defer_none_cstring("abc")
  145. assert m.defer_none_cstring(None)
  146. assert not m.defer_none_custom(UserType())
  147. assert m.defer_none_custom(None)
  148. assert m.nodefer_none_void(None)
  149. def test_void_caster():
  150. assert m.load_nullptr_t(None) is None
  151. assert m.cast_nullptr_t() is None
  152. def test_reference_wrapper():
  153. """std::reference_wrapper for builtin and user types"""
  154. assert m.refwrap_builtin(42) == 420
  155. assert m.refwrap_usertype(UserType(42)) == 42
  156. with pytest.raises(TypeError) as excinfo:
  157. m.refwrap_builtin(None)
  158. assert "incompatible function arguments" in str(excinfo.value)
  159. with pytest.raises(TypeError) as excinfo:
  160. m.refwrap_usertype(None)
  161. assert "incompatible function arguments" in str(excinfo.value)
  162. a1 = m.refwrap_list(copy=True)
  163. a2 = m.refwrap_list(copy=True)
  164. assert [x.value for x in a1] == [2, 3]
  165. assert [x.value for x in a2] == [2, 3]
  166. assert not a1[0] is a2[0] and not a1[1] is a2[1]
  167. b1 = m.refwrap_list(copy=False)
  168. b2 = m.refwrap_list(copy=False)
  169. assert [x.value for x in b1] == [1, 2]
  170. assert [x.value for x in b2] == [1, 2]
  171. assert b1[0] is b2[0] and b1[1] is b2[1]
  172. assert m.refwrap_iiw(IncType(5)) == 5
  173. assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
  174. def test_complex_cast():
  175. """std::complex casts"""
  176. assert m.complex_cast(1) == "1.0"
  177. assert m.complex_cast(2j) == "(0.0, 2.0)"