对于BOOST\u AUTO\u TEST\u CASE\u模板,python的unittest等价于什么

2024-04-23 14:43:34 发布

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

我正在使用unittest框架,却错过了一个我在Boost.Test中学会喜欢的功能。它是BOOST_AUTO_TEST_CASE_TEMPLATE,在它的帮助下,可以对不同的类型运行基本相同的测试,例如

typedef boost::mpl::vector<TypeA, TypeB> types_for_test;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_something, T, types_for_test){
    T obj;
    BOOST_CHECK_EQUAL(obj.empty(), true);
}

将导致两个不同的单元测试:一个用于类型TypeA,另一个用于类型TypeB。你知道吗

但是,我在^{}-documentation中没有发现这种情况。你知道吗

因此,我的问题是:模拟BOOST_AUTO_TEST_CASE_TEMPLATE功能的标准方法是什么?你知道吗


Tags: test功能框架obj类型forautotemplate
3条回答

有两种方法可以到达那里。你知道吗

选项1

使用unittest实现您想要的最简单的方法可能是从包含您的测试方法的超类继承。你知道吗

class templateMethodsForTesting:
    def test_foo(self):
        item = self.testclass("some args")
        assertEqual(item.foo, 1)

    def test_bar(self):
        item = self.testclass("other args")
        assertEqual(item.bar, 2)

那么继承自unittest.Testcase测试用例以及模板:

class testClass1(unittest.Testcase, templateMethodsForTesting):
    def __init__(self):
        self.testclass = Class1

class testClass2(unittest.Testcase, templateMethodsForTesting):
    def __init__(self):
        self.testclass = Class2

此时,两个类将具有相同的方法名,但将是不同的类,这些类被测试发现识别为从Testcase派生。你知道吗

自动发现过程应该实例化两者,并调用两者上的所有test*方法。你知道吗

选项2

相反,您可以用一个对象或一个类参数将单个测试类参数化为构造函数(__init__)。然后您必须自己创建测试用例,并将它们组合成一个套件。你知道吗

比如:

class testSeveralClasses(unittest.Testcase):
    def __init__(self, cls):
        self.obj = cls()
    def test_method1(self):
        assertEqual(self.obj.foo, 1)

但是,测试生成器不知道如何提供cls参数,因此需要构建一个套件。所有这些请参考文档。你知道吗

@Austin的答案很好(非常感谢!)。然而,在我看来,这只是太多的样板代码。你知道吗

另一种可能性是为unittest.TestCase类编写一个类修饰符(我们称之为from_templates)。decorator将检查类,找到模板方法,并为所有需要的类型创建真正的测试用例。例如:

import unittest

@from_templates([list, set, dict])
class TestBasics(unittest.TestCase):

    def template_is_empty(self, type4test):
        self.assertEquals(len(type4test()), 0)

大致与

import unittest

class TestBasics(unittest.TestCase):

    def test_list_is_empty(self):
        self.assertEquals(len(list()), 0)

    def test_set_is_empty(self):
        self.assertEquals(len(set()), 0)

    def test_dict_is_empty(self):
        self.assertEquals(len(dict()), 0)

我对这个想法的实现可以在这里找到:https://github.com/realead/uttemplate

Unittest没有此功能。您需要使用第三方pytest模块,它有extensive support用于参数化测试。你知道吗

相关问题 更多 >