Skip to content

Commit 8e71f89

Browse files
committed
Hardening tests in preparation for changing pybind11::str to only hold PyUnicodeObject (NOT also bytes).
NO change in behavior. These additional tests are designed to clearly bring out behavior changes related to planned `pybind11::str` changes.
1 parent aba08a4 commit 8e71f89

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

tests/test_pytypes.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,4 +372,11 @@ TEST_SUBMODULE(pytypes, m) {
372372
buf, static_cast<ssize_t>(strlen(buf)));
373373
});
374374
#endif
375+
376+
m.def("isinstance_pybind11_bytes", [](py::object o) { return py::isinstance<py::bytes>(o); });
377+
m.def("isinstance_pybind11_str", [](py::object o) { return py::isinstance<py::str>(o); });
378+
379+
m.def("pass_to_pybind11_bytes", [](py::bytes b) { return py::len(b); });
380+
m.def("pass_to_pybind11_str", [](py::str s) { return py::len(s); });
381+
m.def("pass_to_std_string", [](std::string s) { return s.size(); });
375382
}

tests/test_pytypes.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,3 +390,26 @@ def test_memoryview_from_memory():
390390
assert isinstance(view, memoryview)
391391
assert view.format == 'B'
392392
assert bytes(view) == b'\xff\xe1\xab\x37'
393+
394+
395+
def test_isinstance_string_types():
396+
assert m.isinstance_pybind11_bytes(b"")
397+
assert not m.isinstance_pybind11_bytes(u"")
398+
399+
assert m.isinstance_pybind11_str(u"")
400+
assert m.isinstance_pybind11_str(b"") # Probably surprising.
401+
402+
403+
def test_pass_bytes_or_unicode_to_string_types():
404+
assert m.pass_to_pybind11_bytes(b"Bytes") == 5
405+
with pytest.raises(TypeError):
406+
m.pass_to_pybind11_bytes(u"Str") # NO implicit encode
407+
408+
assert m.pass_to_pybind11_str(b"Bytes") == 5
409+
assert m.pass_to_pybind11_str(u"Str") == 3
410+
411+
assert m.pass_to_std_string(b"Bytes") == 5
412+
assert m.pass_to_std_string(u"Str") == 3
413+
414+
malformed_utf8 = b"\x80"
415+
assert m.pass_to_pybind11_str(malformed_utf8) == 1 # NO decoding error

0 commit comments

Comments
 (0)