Commit 6ef4d699 by Ralf W. Grosse-Kunstleve Committed by Copybara-Service

Make pybind11_abseil `StatusNotOk.__str__` compatible with long-established…

Make pybind11_abseil `StatusNotOk.__str__` compatible with long-established Google-internal behavior.

For example:

* Old: `INTERNAL: GetMemoryInfo error`
* New: `GetMemoryInfo error [INTERNAL]`

This behavior change is likely to only affect asserts in test code.

PiperOrigin-RevId: 478905904
parent c18f6323
...@@ -231,6 +231,18 @@ void RegisterStatusBindings(module m) { ...@@ -231,6 +231,18 @@ void RegisterStatusBindings(module m) {
[](const absl::Status& s) { [](const absl::Status& s) {
return decode_utf8_replace(s.ToString()); return decode_utf8_replace(s.ToString());
}) })
.def("status_not_ok_str",
[](const absl::Status& s) {
std::string code_str = absl::StatusCodeToString(s.code());
if (code_str.empty()) {
// This code is meant to be unreachable, but we want to produce
// as much of the original error as possible even if this
// assumption is violated.
code_str = std::to_string(static_cast<int>(s.code()));
}
return decode_utf8_replace(
absl::StrCat(s.message(), " [", code_str, "]"));
})
.def_static("OkStatus", DoNotThrowStatus(&absl::OkStatus)) .def_static("OkStatus", DoNotThrowStatus(&absl::OkStatus))
.def("raw_code", &absl::Status::raw_code) .def("raw_code", &absl::Status::raw_code)
.def("CanonicalCode", .def("CanonicalCode",
...@@ -360,7 +372,7 @@ void RegisterStatusBindings(module m) { ...@@ -360,7 +372,7 @@ void RegisterStatusBindings(module m) {
return self._status.message() return self._status.message()
def __str__(self): def __str__(self):
return self._status.to_string() return self._status.status_not_ok_str()
def __eq__(self, other): def __eq__(self, other):
if not isinstance(other, StatusNotOk): if not isinstance(other, StatusNotOk):
......
...@@ -200,7 +200,7 @@ class StatusTest(parameterized.TestCase): ...@@ -200,7 +200,7 @@ class StatusTest(parameterized.TestCase):
self.assertEqual(stx80.to_string(), 'INVALID_ARGUMENT: �') self.assertEqual(stx80.to_string(), 'INVALID_ARGUMENT: �')
self.assertEqual(str(stx80), 'INVALID_ARGUMENT: �') self.assertEqual(str(stx80), 'INVALID_ARGUMENT: �')
e = status.StatusNotOk(stx80) e = status.StatusNotOk(stx80)
self.assertEqual(str(e), 'INVALID_ARGUMENT: �') self.assertEqual(str(e), '� [INVALID_ARGUMENT]')
def test_raw_code_ne_code(self): def test_raw_code_ne_code(self):
st500 = status_example.status_from_int_code(500, 'Not a canonical code.') st500 = status_example.status_from_int_code(500, 'Not a canonical code.')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment