3

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

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
Sook Lim
  • 541
  • 6
  • 28
  • 1
    An initial glance at this suggests that you stop iterating if your list contains `None`, which isn't...exactly desirable in my mind. Could you show us how you're testing it? That is, what list do you feed it initially and what your expectation is? – Makoto May 03 '18 at 20:51
  • His [previous question](https://stackoverflow.com/q/50162089/1126841) implies he is initializing the array with something like `self.array = [None] * 50`, and that only non-`None` values are stored. – chepner May 03 '18 at 21:16

1 Answers1

3

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)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308