Skip to content

Improve PyBytes_FromStringAndSize test coverage #121842

Closed
@sobolevn

Description

@sobolevn

There's a fast-path in PyBytes_FromStringAndSize that is not covered:

if (size == 1 && str != NULL) {
op = CHARACTER(*str & 255);
assert(_Py_IsImmortal(op));
return (PyObject *)op;
}

Here:

PyObject *
PyBytes_FromStringAndSize(const char *str, Py_ssize_t size)
{
PyBytesObject *op;
if (size < 0) {
PyErr_SetString(PyExc_SystemError,
"Negative size passed to PyBytes_FromStringAndSize");
return NULL;
}
if (size == 1 && str != NULL) {
op = CHARACTER(*str & 255);
assert(_Py_IsImmortal(op));
return (PyObject *)op;
}

We don't have test cases for it:

def test_fromstringandsize(self):
# Test PyBytes_FromStringAndSize()
fromstringandsize = _testlimitedcapi.bytes_fromstringandsize
self.assertEqual(fromstringandsize(b'abc'), b'abc')
self.assertEqual(fromstringandsize(b'abc', 2), b'ab')
self.assertEqual(fromstringandsize(b'abc\0def'), b'abc\0def')
self.assertEqual(fromstringandsize(b'', 0), b'')
self.assertEqual(fromstringandsize(NULL, 0), b'')
self.assertEqual(len(fromstringandsize(NULL, 3)), 3)
self.assertRaises((MemoryError, OverflowError),
fromstringandsize, NULL, PY_SSIZE_T_MAX)
self.assertRaises(SystemError, fromstringandsize, b'abc', -1)
self.assertRaises(SystemError, fromstringandsize, b'abc', PY_SSIZE_T_MIN)
self.assertRaises(SystemError, fromstringandsize, NULL, -1)
self.assertRaises(SystemError, fromstringandsize, NULL, PY_SSIZE_T_MIN)

I propose adding:

self.assertEqual(fromstringandsize(b'a'), b'a')
self.assertEqual(fromstringandsize(b'a', 1), b'a')

So we would have better C coverage stats. It won't hurt in any case, even if this path is removed some day.

Linked PRs

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions