使用pytes从一个函数报告多个测试

2024-06-16 08:36:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有一个简单的测试,它实例化一堆相似的对象并执行一个方法,以确保该方法不会引发任何异常:

class TestTemplates(object):

    def test_generate_all(self):
        '''Generate all the templates and ensure none of them throw validation errors'''
        for entry_point in pkg_resources.iter_entry_points('cloudformation.template'):
            object = entry_point.load()
            object().build().to_json()

这在pytest的文本输出中报告为单个测试:

^{pr2}$

同样在junitXML中:

<testcase classname="test.test_templates.TestTemplates" file="test/test_templates.py" line="31" name="test_generate_all" time="0.0983951091766"></testcase>

是否可以将每个被测对象作为单独的测试报告,而无需为每个对象手动定义测试函数?在


Tags: 对象实例方法testselfobjectdefall
1条回答
网友
1楼 · 发布于 2024-06-16 08:36:58

我会将你的对象列表定义为一个fixture,然后将该列表传递给参数化测试:

@pytest.fixture
def entry_point_objects()
    eps = pkg_resources.iter_entry_points('cloudformation.template')
    return [ep.load() for ep in eps]

@pytest.mark.parametrize('obj', entry_point_objects())
def test_generate_all(obj):
    obj().build().to_json()  

相关问题 更多 >