Asserts that the operation is causing a halt

I have a generator that I want to confirm has ended (at some point in the program. I am using unittest in python 2.7

# it is a generator whould have only one item
item = it.next()
# any further next() calls should raise StopIteration
self.assertRaises(StopIteration, it.next())

      

But it fails with the message

======================================================================
ERROR: test_productspider_parse_method (__main__.TestMyMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/myName/tests/__main__.py", line 94, in test_my_method
    self.assertRaises(StopIteration, it.next())
StopIteration

----------------------------------------------------------------------

      

+3


source to share


1 answer


You need to pass the method itself instead of calling the method. In other words, drop the parentheses.

self.assertRaises(StopIteration, it.next)

      



Or you can use it as a context manager:

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

      

+6


source







All Articles