Possible Duplicate:
How to generate dynamic (parametrized) unit tests in python?
有没有动态创建unittest
测试用例的方法?我已经试过了。。
class test_filenames(unittest.TestCase):
def setUp(self):
for category, testcases in files.items():
for testindex, curtest in enumerate(testcases):
def thetest():
parser = FileParser(curtest['input'])
theep = parser.parse()
self.assertEquals(theep.episodenumber, curtest['episodenumber'])
setattr(self, 'test_%s_%02d' % (category, testindex), thetest)
…它正确地创建了所有方法(它们显示在dir()
中并且是可调用的),但是unittest的测试检测器,或者nosetest
执行它们(“在中运行0个测试…”)
因为我可能问错了问题-我想达到的目标是:
我有一个包含测试数据、输入文件名列表和预期数据(在上面的代码中简化为episodenumber
)的文件,存储在Python字典中。关键是类别,值是测试用例列表,例如。。
test_cases = {}
test_cases['example_1'] = [
{'input': 'test.01',
'episodenumber': 1},
{'input': 'test.02',
'episodenumber': 2}
]
test_cases['example_2'] = [
{'input': 'another.123',
'episodenumber': 123},
{'input': 'test.e42',
'episodenumber': 32}
]
目前,我只是循环遍历所有数据,对每个测试调用self.assertEquals
。问题是,如果其中一个失败,我看不到其余的失败,因为它们也被分组到一个测试中,当断言失败时,测试将中止。
我想,解决这个问题的方法是(动态地)为每个测试用例创建一个函数,也许有更好的方法?
我已经发布了一个类似问题的解决方案,应该会给你一些如何做到这一点的提示。它基于元类和decorators。
Python unittest: Generate multiple tests programmatically?
在下面的解决方案中,类
Tests
包含helper方法check
,并且没有静态定义测试用例。然后,为了动态地添加测试用例,我使用setattr
来定义类中的函数。在下面的示例中,我生成了测试用例test_<i>_<j>
,其中I和j分别跨越[1,3]和[2,5],它们使用具有不同I和j值的助手方法check
为此,您应该在nose中使用testgenerators。您只需要生成一个元组,第一个元组是一个函数,其余的元组是参数。这里是文档中的例子。
相关问题 更多 >
编程相关推荐