我有一个我想确认的生成器已经结束(在程序中的某一点。我在python 2.7中使用unittest
# it is a generator whould have only one item
item = it.next()
# any further next() calls should raise StopIteration
self.assertRaises(StopIteration, it.next())
但它失败并显示消息
======================================================================
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
----------------------------------------------------------------------
答案 0 :(得分:6)
您需要传递方法本身而不是调用方法。换句话说,放下括号。
self.assertRaises(StopIteration, it.next)
或者您可以将其用作上下文管理器:
with self.assertRaises(StopIteration):
it.next()