python Python的单元测试和动态创建测试用例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1193909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:41:26  来源:igfitidea点击:

Python's unittest and dynamic creation of test cases

pythonunit-testingdynamic

提问by dbr

Possible Duplicate:
How to generate dynamic (parametrized) unit tests in python?

可能的重复:
如何在 python 中生成动态(参数化)单元测试?

Is there a way to dynamically create unittesttest cases? I have tried the following..

有没有办法动态创建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)

..which creates all the methods correctly (they show up in dir()and are callable), but unittest's test detector, nor nosetestexecutes them ("Ran 0 tests in ...")

..它正确创建了所有方法(它们出现dir()并可以调用),但是 unittest 的测试检测器,也不nosetest执行它们(“Ran 0 tests in ...”)

Since I may be asking the wrong question - what I am trying to achieve:

因为我可能问错了问题 - 我想要实现的目标:

I have a file containing test data, a list of input filenames, and expected data (simplified to episodenumberin the above code), stored in a Python dictionary. The key is the category, the value is a list of test cases, for example..

我有一个包含测试数据、输入文件名列表和预期数据(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}
]

Currently I just loop over all the data, call self.assertEqualson each test. The problem is, if one fails, I don't see the rest of the failures as they are also grouped into one test, which aborts when an assertion fails.

目前我只是遍历所有数据,调用self.assertEquals每个测试。问题是,如果一个失败,我看不到其余的失败,因为它们也被分组到一个测试中,当断言失败时会中止。

The way around this, I thought, would be to (dynamically) create a function for each test case, perhaps there is a better way?

我认为解决这个问题的方法是(动态)为每个测试用例创建一个函数,也许有更好的方法?

采纳答案by David Raznick

For this you should use test generatorsin nose. All you need to do is yield a tuple, with the first being a function and the rest being the args. From the docs here is the example.

为此,您应该在鼻子中使用测试生成器。您需要做的就是产生一个元组,第一个是函数,其余的是参数。来自此处的文档是示例。

def test_evens():
    for i in range(0, 5):
        yield check_even, i, i*3

def check_even(n, nn):
    assert n % 2 == 0 or nn % 2 == 0

回答by Adrian Panasiuk

In the following solution, the class Testscontains the helper method checkand no test cases statically defined. Then, to dynamically add a test cases, I use setattrto define functions in the class. In the following example, I generate test cases test_<i>_<j>with i and j spanning [1,3] and [2,5] respectively, which use the helper method checkwith different values of i and j.

在以下解决方案中,该类Tests包含辅助方法check并且没有静态定义的测试用例。然后,为了动态添加测试用例,我使用setattr在类中定义函数。在下面的示例中,我生成test_<i>_<j>了 i 和 j 分别跨越 [1,3] 和 [2,5] 的测试用例,它们使用check具有不同 i 和 j 值的辅助方法。

class Tests(unittest.TestCase):
    def check(self, i, j):
        self.assertNotEquals(0, i-j)



for i in xrange(1, 4):
    for j in xrange(2, 6):
        def ch(i, j):
            return lambda self: self.check(i, j)
        setattr(Tests, "test_%r_%r" % (i, j), ch(i, j))

回答by Xavier Decoret

I have posted a solution to a similar question that should give you hints of how to do this. It is based on metaclass and decorators.

我已经发布了一个类似问题的解决方案,应该会给你一些关于如何做到这一点的提示。它基于元类和装饰器。

Python unittest: Generate multiple tests programmatically?

Python unittest:以编程方式生成多个测试?