blob: a6f9b57af186f72f610d3ff8f1e27a73050c9bd8 [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
Jason Rhinelander259b2fa2017-07-01 16:31:49 -0400146def 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"
155 assert m.i64_str(long(-1)) == "-1"
156 assert m.i64_str(long(-999999999999)) == "-999999999999"
157 assert m.u64_str(long(999999999999)) == "999999999999"
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))
178 assert "incompatible function arguments" in str(excinfo.value)
179 with pytest.raises(TypeError) as excinfo:
180 m.u64_str(long(-1))
181 assert "incompatible function arguments" in str(excinfo.value)
182
183
Dean Moldovan83e328f2017-06-09 00:44:49 +0200184def 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
192 assert doc(m.pair_passthrough) == """
193 pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool]
194
195 Return a pair in reversed order
196 """
197 assert doc(m.tuple_passthrough) == """
198 tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool]
199
200 Return a triple in reversed order
201 """
202
203
204def test_builtins_cast_return_none():
205 """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
206 assert m.return_none_string() is None
207 assert m.return_none_char() is None
208 assert m.return_none_bool() is None
209 assert m.return_none_int() is None
210 assert m.return_none_float() is None
211
212
213def test_none_deferred():
214 """None passed as various argument types should defer to other overloads"""
215 assert not m.defer_none_cstring("abc")
216 assert m.defer_none_cstring(None)
217 assert not m.defer_none_custom(UserType())
218 assert m.defer_none_custom(None)
219 assert m.nodefer_none_void(None)
220
221
222def test_void_caster():
223 assert m.load_nullptr_t(None) is None
224 assert m.cast_nullptr_t() is None
225
226
227def test_reference_wrapper():
228 """std::reference_wrapper for builtin and user types"""
229 assert m.refwrap_builtin(42) == 420
230 assert m.refwrap_usertype(UserType(42)) == 42
231
232 with pytest.raises(TypeError) as excinfo:
233 m.refwrap_builtin(None)
234 assert "incompatible function arguments" in str(excinfo.value)
235
236 with pytest.raises(TypeError) as excinfo:
237 m.refwrap_usertype(None)
238 assert "incompatible function arguments" in str(excinfo.value)
239
240 a1 = m.refwrap_list(copy=True)
241 a2 = m.refwrap_list(copy=True)
242 assert [x.value for x in a1] == [2, 3]
243 assert [x.value for x in a2] == [2, 3]
244 assert not a1[0] is a2[0] and not a1[1] is a2[1]
245
246 b1 = m.refwrap_list(copy=False)
247 b2 = m.refwrap_list(copy=False)
248 assert [x.value for x in b1] == [1, 2]
249 assert [x.value for x in b2] == [1, 2]
250 assert b1[0] is b2[0] and b1[1] is b2[1]
251
252 assert m.refwrap_iiw(IncType(5)) == 5
253 assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]
254
255
256def test_complex_cast():
257 """std::complex casts"""
258 assert m.complex_cast(1) == "1.0"
259 assert m.complex_cast(2j) == "(0.0, 2.0)"