Skip to content

Commit 58cae28

Browse files
bbanniertimwoj
authored andcommitted
Do not assume that binary addresses are valid unicode
On lookup failure we would previously assume that binary addresses are valid unicode when constructing exception messages. With python/cpython#105375 which appeared e.g., in python-3.11.9 this starts to cause failures as invalid unicode is now more consistently rejected; e.g., in the test `pysubnettree.lookup` we construct a binary address `1.3.3.255` which corresponds to `b'\x01\x03\x03\xff'` which is not valid unicode. With this patch we set messages for `KeyError` from a `bytes` object instead of a `str`, so that user's see e.g., KeyError: b'1:3:3::3' instead of the previous KeyError: '1:3:3::3' This should still provide all the information necessary while working with our interface which allows both `str` and `bytes` inputs. The changes to `SubnetTree_wrap.cc` are generated automatically with swig-3.0.12. (cherry picked from commit d61edb0)
1 parent 21f52a4 commit 58cae28

File tree

3 files changed

+7
-4
lines changed

3 files changed

+7
-4
lines changed

SubnetTree_wrap.cc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3457,7 +3457,7 @@ SWIGINTERN PyObject *SubnetTree___getitem__(SubnetTree *self,char *cidr,int size
34573457

34583458
PyObject* data = self->lookup(cidr, size);
34593459
if ( ! data ) {
3460-
PyErr_SetString(PyExc_KeyError, cidr);
3460+
PyErr_SetObject(PyExc_KeyError, PyBytes_FromStringAndSize(cidr, size));
34613461
return 0;
34623462
}
34633463

include/SubnetTree.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ class SubnetTree
147147

148148
PyObject* data = self->lookup(cidr, size);
149149
if ( ! data ) {
150-
PyErr_SetString(PyExc_KeyError, cidr);
150+
PyErr_SetObject(PyExc_KeyError, PyBytes_FromStringAndSize(cidr, size));
151151
return 0;
152152
}
153153

testing/pysubnettree/lookup.test

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,11 @@ def do_tests(binarymode):
4040
try:
4141
if t[v4("1.3.3.255")]: pass
4242
testcase(False, "lookup should throw exception")
43-
except KeyError:
44-
pass
43+
except KeyError as e:
44+
# We expect a `KeyError` which reports the key. Since above address
45+
# encodes to invalid unicode we'd expect to see the raw bytes as error
46+
# message in binary mode.
47+
assert str(e) == r"b'\x01\x03\x03\xff'" if binarymode else r"b'1.3.3.255'"
4548

4649
try:
4750
if t[v6("1:3:3::3")]: pass

0 commit comments

Comments
 (0)