blob: 59af0ee9a92ca57ebaf6c2e99020b18231ad2eea [file] [log] [blame]
Dean Moldovan83e328f2017-06-09 00:44:49 +02001# 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_tuple(doc):
147 """std::pair <-> tuple & std::tuple <-> tuple"""
148 assert m.pair_passthrough((True, "test")) == ("test", True)
149 assert m.tuple_passthrough((True, "test", 5)) == (5, "test", True)
150 # Any sequence can be cast to a std::pair or std::tuple
151 assert m.pair_passthrough([True, "test"]) == ("test", True)
152 assert m.tuple_passthrough([True, "test", 5]) == (5, "test", True)
153
154 assert doc(m.pair_passthrough) == """
155 pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool]
156
157 Return a pair in reversed order
158 """
159 assert doc(m.tuple_passthrough) == """
160 tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool]
161
162 Return a triple in reversed order
163 """
164
165
166def test_builtins_cast_return_none():
167 """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
168 assert m.return_none_string() is None
169 assert m.return_none_char() is None
170 assert m.return_none_bool() is None
171 assert m.return_none_int() is None
172 assert m.return_none_float() is None
173
174
175def test_none_deferred():
176 """None passed as various argument types should defer to other overloads"""
177 assert not m.defer_none_cstring("abc")
178 assert m.defer_none_cstring(None)
179 assert not m.defer_none_custom(UserType())
180 assert m.defer_none_custom(None)
181 assert m.nodefer_none_void(None)
182
183
184def test_void_caster():
185 assert m.load_nullptr_t(None) is None
186 assert m.cast_nullptr_t() is None
187
188
189def test_reference_wrapper():
190 """std::reference_wrapper for builtin and user types"""
191 assert m.refwrap_builtin(42) == 420
192 assert m.refwrap_usertype(UserType(42)) == 42
193
194 with pytest.raises(TypeError) as excinfo:
195 m.refwrap_builtin(None)
196 assert "incompatible function arguments" in str(excinfo.value)
197
198 with pytest.raises(TypeError) as excinfo:
199 m.refwrap_usertype(None)
200 assert "incompatible function arguments" in str(excinfo.value)
201
202 a1 = m.refwrap_list(copy=True)
203 a2 = m.refwrap_list(copy=True)
204 assert [x.value for x in a1] == [2, 3]
205 assert [x.value for x in a2] == [2, 3]
206 assert not a1[0] is a2[0] and not a1[1] is a2[1]
207
208 b1 = m.refwrap_list(copy=False)
209 b2 = m.refwrap_list(copy=False)
210 assert [x.value for x in b1] == [1, 2]
211 assert [x.value for x in b2] == [1, 2]
212 assert b1[0] is b2[0] and b1[1] is b2[1]
213
214 assert m.refwrap_iiw(IncType(5)) == 5
215 assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
216
217
218def 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)"