[英]testing over an iterator, how to do it?
I have made a simple generator in Python, it is under a file called program.py 我在Python中制作了一个简单的生成器,它位于名为program.py的文件下
class Loop():
def __init__(self):
self.i=1
def __iter__(self):
return self
def next(self):
if self.i>10:
raise StopIteration
self.i=self.i+1
return self.i
I have made a unittest module so that it tests the iterator and when there is a number 5 on the list then it prints that the test has failed in that part. 我制作了一个unittest模块,以便它测试迭代器,并且当列表中有数字5时,它会打印出该部分测试失败。 I have do something like this: 我做了这样的事情:
class TestA(unittest.TestCase):
def test(self):
for x in Loop():
if not self.assertRaises(AssertionError,self.assertEqual(x,5)):
print x
but I see that this breaks up after the first iteration, what am I doing wrong? 但是我看到这在第一次迭代后就破裂了,我在做什么错呢?
any help? 有什么帮助吗? Thanks 谢谢
You're approaching the test incorrectly. 您的测试方法有误。
Your iterator is basically the equivalent of xrange
hardcoded to start from 2 and goes to infinity. 您的迭代器基本上相当于从2开始硬编码到无穷大的xrange
。
The reason it starts from 2
is because you're initialising i
to 1 and incrementing i
inside the next before returning the first value. 从开始的原因2
是因为你初始化i
1和递增i
返回的第一个值先下一内。
I would write the test as follows 我将测试编写如下
class TestA(unittest.TestCase):
def test_loop_is_sliceable(self):
slc = itertools.islice(Loop(), 5)
self.assertEqual(range(2, 7), list(slc))
Also note that asserts are not predicates so they don't give you back a bool to use in conditional statements. 还要注意,断言不是谓词,因此它们不会给您带来条件语句中的麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.