Skip to content

Commit c58c7b7

Browse files
committed
undoing change to pybind11::str::raw_str, adjusting test_pybind11_str_raw_str to match behavior after changing detail::PyUnicode_Check_Permissive to PyUnicode_Check'
1 parent a7e2458 commit c58c7b7

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

include/pybind11/pytypes.h

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -928,12 +928,12 @@ class str : public object {
928928
private:
929929
/// Return string representation -- always returns a new reference, even if already a str
930930
static PyObject *raw_str(PyObject *op) {
931-
#if PY_MAJOR_VERSION < 3
932-
PyObject *str_value = PyObject_Unicode(op);
933-
#else
934931
PyObject *str_value = PyObject_Str(op);
935-
#endif
936932
if (!str_value) throw error_already_set();
933+
#if PY_MAJOR_VERSION < 3
934+
PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
935+
Py_XDECREF(str_value); str_value = unicode;
936+
#endif
937937
return str_value;
938938
}
939939
};

tests/test_pytypes.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -251,15 +251,24 @@ def test_pybind11_str_raw_str():
251251
assert cvt(set()) == u"set([])" if str is bytes else "set()"
252252
assert cvt({3, 3}) == u"set([3])" if str is bytes else "{3}"
253253

254-
valid_utf8 = u"DZ".encode("utf-8")
254+
valid_orig = u"DZ"
255+
valid_utf8 = valid_orig.encode("utf-8")
255256
valid_cvt = cvt(valid_utf8)
256-
assert type(valid_cvt) == bytes # Probably surprising.
257-
assert valid_cvt == b'\xc7\xb1'
257+
assert type(valid_cvt) == type(u"") # Py2 unicode, Py3 str, flake8 compatible
258+
if str is bytes:
259+
assert valid_cvt == valid_orig
260+
else:
261+
assert valid_cvt == u"b'\\xc7\\xb1'"
258262

259263
malformed_utf8 = b'\x80'
260-
malformed_cvt = cvt(malformed_utf8)
261-
assert type(malformed_cvt) == bytes # Probably surprising.
262-
assert malformed_cvt == b'\x80'
264+
if str is bytes:
265+
with pytest.raises(UnicodeDecodeError) as excinfo:
266+
cvt(malformed_utf8)
267+
assert "invalid start byte" in str(excinfo)
268+
else:
269+
malformed_cvt = cvt(malformed_utf8)
270+
assert type(valid_cvt) == type(u"")
271+
assert malformed_cvt == u"b'\\x80'"
263272

264273

265274
def test_implicit_casting():

0 commit comments

Comments
 (0)