6

Currently I'm writing a unittest for my class function.

def test_getitem(self):
    test1 = List(3)
    for i in range(3):
        test1.append(i)
    self.assertEqual(test1[2], 2)

    test1 = List(3)
    for i in range(3):
        test1.append(i)
    self.assertRaises(IndexError, test1[4])

the problem I'm having now is at the self.assertRaises part of my code. I'm not sure if that is how it's done but when I run the unittest, it produces an error Index out of range. By right, it should be "OK".

List is my class and List(3) creates an array based list. so when i test1.append(i), it is now [0,1,2].

test1[2] is a method of calling the getitem function in my class similar to self[index].

I'm wondering if I'm assert raising correctly? self.assertEqual is fine.

1
  • When you call assertRaises() like this you need to pass a callable as the second argument. So self.assertRaises(IndexError, lambda: test1[4]) would work, but @AK47's answer is the recommended way to do it. Commented Sep 13, 2017 at 13:03

2 Answers 2

7

You should use the with statement when you're asserting for exceptions being thrown

def test_getitem(self):
    test1 = List(3)
    for i in range(3):
        test1.append(i)
    self.assertEqual(test1[2], 2)

    test1 = List(3)
    for i in range(3):
        test1.append(i)
    with self.assertRaises(IndexError):
        test1[4]
Sign up to request clarification or add additional context in comments.

Comments

6

Arguments are evaluated before the function is called, so when you use test1[4] it's executed before the self.assertRaises is called. So it's not able to catch the exception.

That's also the reason why the 2-argument form has the signature assertRaises(exception, msg=None), the second argument here is the "msg" to match, not the function that is to be called. So it wouldn't have done the correct thing in any case.

You could use the context manager:

with self.assertRaises(IndexError):
    test1[4]

Or use the multiple argument form:

self.assertRaises(IndexError, test1.__getitem__, 4)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.