File tree Expand file tree Collapse file tree 2 files changed +19
-10
lines changed Expand file tree Collapse file tree 2 files changed +19
-10
lines changed Original file line number Diff line number Diff line change @@ -928,12 +928,12 @@ class str : public object {
928
928
private:
929
929
// / Return string representation -- always returns a new reference, even if already a str
930
930
static PyObject *raw_str (PyObject *op) {
931
- #if PY_MAJOR_VERSION < 3
932
- PyObject *str_value = PyObject_Unicode (op);
933
- #else
934
931
PyObject *str_value = PyObject_Str (op);
935
- #endif
936
932
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
937
937
return str_value;
938
938
}
939
939
};
Original file line number Diff line number Diff line change @@ -251,15 +251,24 @@ def test_pybind11_str_raw_str():
251
251
assert cvt (set ()) == u"set([])" if str is bytes else "set()"
252
252
assert cvt ({3 , 3 }) == u"set([3])" if str is bytes else "{3}"
253
253
254
- valid_utf8 = u"DZ" .encode ("utf-8" )
254
+ valid_orig = u"DZ"
255
+ valid_utf8 = valid_orig .encode ("utf-8" )
255
256
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'"
258
262
259
263
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'"
263
272
264
273
265
274
def test_implicit_casting ():
You can’t perform that action at this time.
0 commit comments