相关疑难解决方法(0)

用yield编写功能的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
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,则该测试顺利通过。如何编写生成器的测试?

python unit-testing generator

1
推荐指数
1
解决办法
3517
查看次数

标签 统计

generator ×1

python ×1

unit-testing ×1