FunctionTestCase方法可以接受参数吗?

2024-06-08 04:30:27 发布

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

我使用unittest在Python中进行一些测试。我对FunctionTestCase感兴趣。从文档中,这是示例用法:

testcase = unittest.FunctionTestCase(testSomething,
                                     setUp=makeSomethingDB,
                                     tearDown=deleteSomethingDB)

testSomething定义为

def testSomething():
    something = makeSomething()
    assert something.name is not None
    # ...

但是,我有兴趣将一个参数传递给testSomething(),如下所示。你知道吗

  def testSomething(input):
        something = makeSomething(input)
        assert something.name is not None
        # ...

当我运行它时,已经构建了它,如上所述:

runner= unittest.TextTestRunner()
runner.run(testcase)

我明白了

    ERROR: unittest.case.FunctionTestCase (test_meth4)
----------------------------------------------------------------------
TypeError: testSomething() missing 1 required positional argument: 'input'

----------------------------------------------------------------------
Ran 1 tests in 0.007s

有没有方法传入参数,或者需要使用闭包/外部函数之类的函数?谢谢


Tags: 函数namenoneinputisdefnotassert
1条回答
网友
1楼 · 发布于 2024-06-08 04:30:27

看起来您不能将参数传递给正在测试的函数。在python2和python3中,FunctionTestCase.runTest()只包含一行:self._testFunc(),没有传递参数的规定。您可以将FunctionTestCase子类化并向其__init__()添加参数,然后让runTest()将参数传递给正在测试的函数:

import unittest

def my_func(arg1, arg2=None):
    print('arg1 is', arg1)
    print('arg2 is', arg2)

class MyFunctionTestCase(unittest.FunctionTestCase):
    def __init__(self, testFunc, setUp=None, tearDown=None,
                 description=None, args=(), kwargs={}):
        super(MyFunctionTestCase, self).__init__(testFunc, setUp=setUp,
                                                 tearDown=tearDown,
                                                 description=description)
        self.args = args
        self.kwargs = kwargs

    def runTest(self):
        self._testFunc(*self.args, **self.kwargs)

my_test = unittest.FunctionTestCase(my_func)
my_subclassed_test = MyFunctionTestCase(my_func, args=(42,), kwargs={'arg2': 24})

runner = unittest.TextTestRunner()
runner.run(my_test)
runner.run(my_subclassed_test)

我鼓励您在https://bugs.python.org请求此功能和/或更多关于此功能的文档。这似乎是一个很大的差距,而且几乎没有任何官方文档。你知道吗

相关问题 更多 >

    热门问题