简体   繁体   English

在python中对paramaterize单元测试进行测试

[英]Paramaterize unit tests in python

I work on a set of python unit tests that are currently built using pythons built in testing framework. 我正在研究一组python单元测试,这些测试目前是使用内置测试框架的pythons构建的。 I would like to write paramaterized tests that will execute multiple times based on the set of data I give it. 我想编写参数化测试,根据我给出的数据集执行多次。

ie. 即。 if my data set is [1,2,3,4] my test function would run four times using the input in my data set. 如果我的数据集是[1,2,3,4],我的测试函数将使用我的数据集中的输入运行四次。

def test(data):
    if data > 0:
       #Pass the test

From my understanding this isn't possible currently in the built in framework, unless I put a loop in my test function. 根据我的理解,目前在内置框架中这是不可能的,除非我在我的测试函数中放置一个循环。 I don't want to do this because I need the test to continue executing even if one input fails. 我不想这样做,因为即使一个输入失败,我也需要测试继续执行。

I've seen that it's possible to do using nose, or pyTest. 我已经看到可以使用nose或pyTest。 Which is the best framework to use? 哪个是最好的框架? Is there another framework I could use that would be better than either of these? 是否有另一个我可以使用的框架比其中任何一个更好?

Thanks in advance! 提前致谢!

Note that this is precisely one of the most common uses of the recent addition of funcargs in py.test . 请注意,这恰恰是最近加入的最常见的用途之一funcargspy.test。

In your case you'd get: 在你的情况下,你会得到:

def pytest_generate_tests(metafunc):
    if 'data' in metafunc.funcargnames:
        metafunc.parametrize('data', [1,2,3,4])

def test_data(data):
    assert data > 0

[EDIT] I should probably add that you can also do that as simply as [编辑]我应该补充一点,你也可以这样做

@pytest.mark.parametrize('data', [1,2,3,4])
def test_data(data):
    assert data > 0

So I'd say that py.test is a great framework for parameterized unit testing... 所以我会说py.test是参数化单元测试的一个很好的框架......

You can create tests dynamically based on your data set in the following way: 您可以通过以下方式根据数据集动态创建测试:

import unittest

data_set = [1,2,3,4]

class TestFunctions(unittest.TestCase):
    pass  # all your non-dynamic tests here as normal

for i in data_set:
    test_name = "test_number_%s" % i # a valid unittest test name starting with "test_"
    def dynamic_test(self, i=i):
        self.assertTrue(i % 2)
    setattr(TestFunctions, test_name, dynamic_test)

if __name__ == '__main__':
    unittest.main()

The question Python unittest: Generate multiple tests programmatically? Python unittest的问题:以编程方式生成多个测试? has more discussion of this, including another approach that achieves the same thing by dynamically creating multiple instances of the test case into a test suite. 对此进行了更多的讨论,包括通过动态地将测试用例的多个实例动态创建到测试套件中来实现相同目的的另一种方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM