用yield编写功能的unittest [英] Write unittest for function with yield

查看:154
本文介绍了用yield编写功能的unittest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为使用生成器的函数编写单元测试.下面是我的代码:

I am trying to write a unittest for a function that utilizes a generator. Below is my code:

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

我的单元测试代码:

    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)

如果extract_data函数使用return而不是yield,则此测试顺利通过.我该如何为生成器编写测试?

This test passes without issue if the extract_data function uses a return instead of yield. How do I write the test for the generator?

推荐答案

我想出了我需要做的事情.我需要将资源整理成一个列表.就是这样.比我预期的要简单得多.所以这是现在的样子:

I figured out what I needed to do. I needed to make the res into a list. and that was it. A lot simpler than I expected. so this is what it looks like now:

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()

这篇关于用yield编写功能的unittest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆