Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing unit test for list iterator?

Hi I'm new to Python and I just started learning how to implement array based list in Python. I made my list iterable with an iterator. I raised an error to stop iteration when the index is greater than length of list. However, when I'm writing my unit test I got this error, but I clearly raised StopIteration in my list iterator?

Traceback (most recent call last):
  File "C:\Users\User\Desktop\task1unitTest.py", line 110, in testIter
    self.assertRaises(StopIteration, next(it1))
  File "C:\Users\User\Desktop\ListIterator.py", line 10, in __next__
   raise StopIteration
StopIteration

This is my list iterator:

class ListIterator:
    def __init__(self,array):
        self.current=array
        self.index=0

    def __iter__(self):
        return self
    def __next__(self):
        if self.current[self.index]==None:
            raise StopIteration
        else:
            item_required=self.current[self.index]
            self.index+=1
            return item_required

Any help will be appreciated!

EDIT: Okay this is how I tested it:

def testIter(self):
    a_list=List()
    a_list.append(1)
    a_list.append(2)
    a_list.append(3)
    it1=iter(a_list)
    self.assertEqual(next(it1),1)
    self.assertEqual(next(it1),2)
    self.assertEqual(next(it1),3)
    #self.assertRaises(StopIteration, next(it1))

The error occurs at self.assertRaises

like image 895
Sook Lim Avatar asked Nov 15 '25 14:11

Sook Lim


1 Answers

This isn't the correct usage of unittest.assertRaises.

self.assertRaises(StopIteration, next(it1))

Try this:

with self.assertRaises(StopIteration):
    next(it1)

Or this:

self.assertRaises(StopIteration, next, it1)
like image 171
Robᵩ Avatar answered Nov 18 '25 04:11

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!