fix upb python: DO NOT create empty optional field after sorting empty repeated field

PiperOrigin-RevId: 618350866
pull/16282/head
Jie Luo 2024-03-22 19:54:49 -07:00 committed by Copybara-Service
parent 41aeb3c7ed
commit 7cf02389b3
2 changed files with 12 additions and 0 deletions

View File

@ -549,6 +549,15 @@ class MessageTest(unittest.TestCase):
self.assertEqual([4, 3, 2, 1],
[m.bb for m in msg.repeated_nested_message[::-1]])
def testSortEmptyRepeated(self, message_module):
message = message_module.NestedTestAllTypes()
self.assertFalse(message.HasField('child'))
self.assertFalse(message.HasField('payload'))
message.child.repeated_child.sort()
message.payload.repeated_int32.sort()
self.assertFalse(message.HasField('child'))
self.assertFalse(message.HasField('payload'))
def testSortingRepeatedScalarFieldsDefaultComparator(self, message_module):
"""Check some different types with the default comparator."""
message = message_module.TestAllTypes()

View File

@ -473,11 +473,14 @@ static PyObject* PyUpb_RepeatedContainer_Sort(PyObject* pself, PyObject* args,
}
}
if (PyUpb_RepeatedContainer_Length(pself) == 0) Py_RETURN_NONE;
PyObject* ret = NULL;
PyObject* full_slice = NULL;
PyObject* list = NULL;
PyObject* m = NULL;
PyObject* res = NULL;
if ((full_slice = PySlice_New(NULL, NULL, NULL)) &&
(list = PyUpb_RepeatedContainer_Subscript(pself, full_slice)) &&
(m = PyObject_GetAttrString(list, "sort")) &&