Skip to content

Commit 4f28229

Browse files
committed
Adding tests specifically to exercise pybind11::str::raw_str.
These tests will also alert us to any behavior changes across Python and PyPy versions. Hardening tests in preparation for changing `pybind11::str` to only hold `PyUnicodeObject` (NOT also `bytes`). Note that this test exposes that `pybind11::str` can also hold `bytes`.
1 parent 6f3470f commit 4f28229

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

tests/test_pytypes.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,8 @@ TEST_SUBMODULE(pytypes, m) {
237237
);
238238
});
239239

240+
m.def("convert_to_pybind11_str", [](py::object o) { return py::str(o); });
241+
240242
m.def("get_implicit_casting", []() {
241243
py::dict d;
242244
d["char*_i1"] = "abc";

tests/test_pytypes.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,38 @@ def test_constructors():
220220
assert noconv2[k] is expected[k]
221221

222222

223+
def test_pybind11_str_raw_str():
224+
# specifically to exercise pybind11::str::raw_str
225+
cvt = m.convert_to_pybind11_str
226+
assert cvt(u"Str") == u"Str"
227+
assert cvt(b'Bytes') == u"Bytes" if str is bytes else "b'Bytes'"
228+
assert cvt(None) == u"None"
229+
assert cvt(False) == u"False"
230+
assert cvt(True) == u"True"
231+
assert cvt(42) == u"42"
232+
assert cvt(2**65) == u"36893488147419103232"
233+
assert cvt(-1.50) == u"-1.5"
234+
assert cvt(()) == u"()"
235+
assert cvt((18,)) == u"(18,)"
236+
assert cvt([]) == u"[]"
237+
assert cvt([28]) == u"[28]"
238+
assert cvt({}) == u"{}"
239+
assert cvt({3: 4}) == u"{3: 4}"
240+
assert cvt(set()) == u"set([])" if str is bytes else "set()"
241+
assert cvt({3, 3}) == u"set([3])" if str is bytes else "{3}"
242+
243+
valid_orig = u"DZ"
244+
valid_utf8 = valid_orig.encode("utf-8")
245+
valid_cvt = cvt(valid_utf8)
246+
assert type(valid_cvt) == bytes # Probably surprising.
247+
assert valid_cvt == b'\xc7\xb1'
248+
249+
malformed_utf8 = b'\x80'
250+
malformed_cvt = cvt(malformed_utf8)
251+
assert type(malformed_cvt) == bytes # Probably surprising.
252+
assert malformed_cvt == b'\x80'
253+
254+
223255
def test_implicit_casting():
224256
"""Tests implicit casting when assigning or appending to dicts and lists."""
225257
z = m.get_implicit_casting()

0 commit comments

Comments
 (0)