Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert that an operation raises a Stopiteration

I have a generator that I want to confirm has ended (at a certain 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

----------------------------------------------------------------------
like image 245
yayu Avatar asked Sep 05 '25 03:09

yayu


1 Answers

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

self.assertRaises(StopIteration, it.next)

Or you can use it as a context manager:

with self.assertRaises(StopIteration):
    it.next()
like image 50
falsetru Avatar answered Sep 07 '25 15:09

falsetru