当使用Python的unittest模块作为testrunner时,如何在测试之前运行初始化代码?

2024-09-28 22:19:08 发布

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

在运行库提供的测试之前,库的用户如何运行自己的初始化代码(例如设置记录器的调试级别)?Python的unittest模块用作测试运行程序。在


Tags: 模块代码用户程序unittest级别运行库记录器
3条回答

类似问题的答案在这里更有帮助:

How to a run a specific code before & after each unit test in python

我使用了python setUpClass方法 https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUpClass

setUpClass()
A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():

@classmethod
def setUpClass(cls):
    ...

我这样做我的测试:

^{pr2}$

您可以在调用unittest.main之前完成设置工作。在

或者您可以将测试套件子类化并运行class-level setup method。在

或者可以让测试设置将回调合并到用户定义的设置方法中。在

您可以尝试使用pytest来运行unittests。如果这是可行的(许多基于unittest的测试套件都可以工作),那么您可以创建一个小模块,例如“mymod.py公司,定义pytest配置挂钩:

# content of mymod.py
def pytest_configure():
    import logging
    logging.getLogger().setLevel(logging.WARN)

如果你现在执行py.测试像这样:

^{pr2}$

然后将搜索“mylib”包中的测试,并在运行它们之前修改日志级别。“-p”选项指定要加载的插件,“pyargs”告诉pytest先尝试导入参数,而不是将它们当作目录或文件名(默认设置)。在

有关详细信息:http://pytest.orghttp://pytest.org/latest/unittest.html

嗯, 霍尔格

相关问题 更多 >