Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Lib/test/string_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,14 @@ class subtype(self.__class__.type2test):
self.assertIsNot(obj, realresult)

# check that obj.method(*args) raises exc
def checkraises(self, exc, obj, methodname, *args):
def checkraises(self, exc, obj, methodname, *args, expected_msg=None):
obj = self.fixtype(obj)
args = self.fixtype(args)
with self.assertRaises(exc) as cm:
getattr(obj, methodname)(*args)
self.assertNotEqual(str(cm.exception), '')
if expected_msg is not None:
self.assertEqual(str(cm.exception), expected_msg)

# call obj.method(*args) without any checks
def checkcall(self, obj, methodname, *args):
Expand Down Expand Up @@ -1195,6 +1197,10 @@ def test_subscript(self):

self.checkraises(TypeError, 'abc', '__getitem__', 'def')

for idx_type in ('def', object()):
expected_msg = "string indices must be integers, not '{}'".format(type(idx_type).__name__)
self.checkraises(TypeError, 'abc', '__getitem__', idx_type, expected_msg=expected_msg)

def test_slice(self):
self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
Expand Down
4 changes: 3 additions & 1 deletion Lib/test/test_userstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ def checkequal(self, result, object, methodname, *args, **kwargs):
realresult
)

def checkraises(self, exc, obj, methodname, *args):
def checkraises(self, exc, obj, methodname, *args, expected_msg=None):
obj = self.fixtype(obj)
# we don't fix the arguments, because UserString can't cope with it
with self.assertRaises(exc) as cm:
getattr(obj, methodname)(*args)
self.assertNotEqual(str(cm.exception), '')
if expected_msg is not None:
self.assertEqual(str(cm.exception), expected_msg)

def checkcall(self, object, methodname, *args):
object = self.fixtype(object)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve :func:`str.__getitem__` error message
3 changes: 2 additions & 1 deletion Objects/unicodeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -14564,7 +14564,8 @@ unicode_subscript(PyObject* self, PyObject* item)
assert(_PyUnicode_CheckConsistency(result, 1));
return result;
} else {
PyErr_SetString(PyExc_TypeError, "string indices must be integers");
PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
Py_TYPE(item)->tp_name);
return NULL;
}
}
Expand Down