gh-117557: Improve error messages when a string, bytes or bytearray of length 1 are expected (GH-117631)

This commit is contained in:
Serhiy Storchaka 2024-05-28 12:01:37 +03:00 committed by GitHub
parent bf08f0a5fe
commit b313cc68d5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 811 additions and 161 deletions

View file

@ -233,13 +233,20 @@ static int
PyCurses_ConvertToChtype(PyCursesWindowObject *win, PyObject *obj, chtype *ch)
{
long value;
if(PyBytes_Check(obj) && PyBytes_Size(obj) == 1) {
if (PyBytes_Check(obj)) {
if (PyBytes_GET_SIZE(obj) != 1) {
PyErr_Format(PyExc_TypeError,
"expect int or bytes or str of length 1, "
"got a bytes of length %zd",
PyBytes_GET_SIZE(obj));
return 0;
}
value = (unsigned char)PyBytes_AsString(obj)[0];
}
else if (PyUnicode_Check(obj)) {
if (PyUnicode_GetLength(obj) != 1) {
if (PyUnicode_GET_LENGTH(obj) != 1) {
PyErr_Format(PyExc_TypeError,
"expect bytes or str of length 1, or int, "
"expect int or bytes or str of length 1, "
"got a str of length %zi",
PyUnicode_GET_LENGTH(obj));
return 0;
@ -272,7 +279,7 @@ PyCurses_ConvertToChtype(PyCursesWindowObject *win, PyObject *obj, chtype *ch)
}
else {
PyErr_Format(PyExc_TypeError,
"expect bytes or str of length 1, or int, got %s",
"expect int or bytes or str of length 1, got %s",
Py_TYPE(obj)->tp_name);
return 0;
}
@ -315,7 +322,7 @@ PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
#ifdef HAVE_NCURSESW
if (PyUnicode_AsWideChar(obj, buffer, 2) != 1) {
PyErr_Format(PyExc_TypeError,
"expect bytes or str of length 1, or int, "
"expect int or bytes or str of length 1, "
"got a str of length %zi",
PyUnicode_GET_LENGTH(obj));
return 0;
@ -326,7 +333,14 @@ PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
return PyCurses_ConvertToChtype(win, obj, ch);
#endif
}
else if(PyBytes_Check(obj) && PyBytes_Size(obj) == 1) {
else if (PyBytes_Check(obj)) {
if (PyBytes_GET_SIZE(obj) != 1) {
PyErr_Format(PyExc_TypeError,
"expect int or bytes or str of length 1, "
"got a bytes of length %zd",
PyBytes_GET_SIZE(obj));
return 0;
}
value = (unsigned char)PyBytes_AsString(obj)[0];
}
else if (PyLong_CheckExact(obj)) {
@ -340,7 +354,7 @@ PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
}
else {
PyErr_Format(PyExc_TypeError,
"expect bytes or str of length 1, or int, got %s",
"expect int or bytes or str of length 1, got %s",
Py_TYPE(obj)->tp_name);
return 0;
}
@ -4443,7 +4457,7 @@ PyCurses_ConvertToWchar_t(PyObject *obj,
wchar_t buffer[2];
if (PyUnicode_AsWideChar(obj, buffer, 2) != 1) {
PyErr_Format(PyExc_TypeError,
"expect str of length 1 or int, "
"expect int or str of length 1, "
"got a str of length %zi",
PyUnicode_GET_LENGTH(obj));
return 0;
@ -4470,7 +4484,7 @@ PyCurses_ConvertToWchar_t(PyObject *obj,
}
else {
PyErr_Format(PyExc_TypeError,
"expect str of length 1 or int, got %s",
"expect int or str of length 1, got %s",
Py_TYPE(obj)->tp_name);
return 0;
}