Lef*_*fty 1 python unit-testing generator
我正在尝试为使用生成器的函数编写单元测试。下面是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
我的单元测试代码:
def test_extract_data(self):
sample_input = ['<tr><h1>keyThis</h1><h2>\xc2</h2><h3>\xa0</h3><h4>view\xc2\xa0book\xc2\xa0info</h4><h5>Test Passes</h5></tr>']
expected_res = 'This Test Passes'
res = extract_data(sample_input)
self.assertEqual(expected_res, res)
Run Code Online (Sandbox Code Playgroud)
如果extract_data函数使用return而不是yield,则该测试顺利通过。如何编写生成器的测试?
我想出了我需要做的。我需要将res放入列表中。就是这样。比我预期的要简单得多。所以这是现在的样子:
class TestScrapePage(unittest.TestCase):
def test_extract_data(self):
sample_input = ['<tr><h1>keyThis</h1><h2>\xc2</h2><h3>\xa0</h3><h4>view\xc2\xa0book\xc2\xa0info</h4><h5>Test Passes</h5></tr>']
expected_res = ['This Test Passes']
res = list(extract_data(sample_input))
self.assertEqual(expected_res, res)
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)