我试图为使用生成器的函数编写一个unittest。以下是我的代码:
def extract_data(body):
for i in body:
a = re.sub('<[^<]+?>', '', str(i))
b = re.sub('view\xc2\xa0book\xc2\xa0info', '', str(a))
c = re.sub('key', '', str(b))
d = re.sub('\xc2', ' ', str(c))
e = re.sub('\xa0', '', str(d))
yield e
我的单元测试代码:
^{pr2}$如果extract_data函数使用return而不是yield,则此测试可以顺利通过。如何编写生成器的测试?在
我知道我需要做什么。我需要把res列成一个列表。就这样。比我想象的简单多了。这就是现在的样子:
您的代码,稍作修改,不需要unittest:
这将打印
False
问题是,当您执行
^{pr2}$
return
时,在您的例子中,函数返回一个str
。然而,{cd4{cd6>返回这将打印
True
。在为了说明,在Python command prompt:
您的另一个选择(可能更好,取决于您的用例)是通过将}来测试
generator
对象的结果转换为list
或{generator
的所有结果是否正确,然后比较是否相等:相关问题 更多 >
编程相关推荐