gpt4 book ai didi

python - 断言一个操作引发了一个 Stopiteration

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:41 25 4
gpt4 key购买 nike

我有一个生成器,我想确认它已经结束(在程序的某个点。我在 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

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

最佳答案

您需要传递方法本身而不是调用方法。换句话说,去掉括号。

self.assertRaises(StopIteration, it.next)

或者您可以将其用作上下文管理器:

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

关于python - 断言一个操作引发了一个 Stopiteration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27496115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com