Python – Writing unit tests for list iterators?

Writing unit tests for list iterators?… here is a solution to the problem.

Writing unit tests for list iterators?

Hi all, I’m new to Python and I’m just starting to learn how to implement array-based lists in Python. I use iterators to make my list iterable. When the index is larger than the list length, I throw a stop iteration error. However, I get this error when I write a unit test, but I apparently raised StopIteration in the 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

Here 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 would be appreciated!

Edit:
Ok, that’s 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

Solution

This is not unittest.assertRaises Correct usage

self.assertRaises(StopIteration, next(it1))

Try this :

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

Or this:

self.assertRaises(StopIteration, next, it1)

Related Problems and Solutions