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

时间:2011-12-22 17:37:55

标签: python unit-testing logging

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

3 个答案:

答案 0 :(得分:2)

您可以尝试使用pytest来运行单元测试。如果可行(许多基于单元测试的测试套件工作),那么你可以创建一个小模块,例如“mymod.py”,定义一个pytest配置钩子:

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

如果您现在执行py.test,请执行以下操作:

$ py.test -p mymmod --pyargs mylib

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

了解详情:http://pytest.orghttp://pytest.org/latest/unittest.html

HTH, 霍尔格

答案 1 :(得分:1)

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

或者您可以继承测试套件并运行class-level setup method

或者您可以让测试设置包含对用户定义的设置方法的回调。

答案 2 :(得分:0)

类似问题的解答在这里更有用:

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):
    ...

我这样运行测试:

python -m unittest discover -v