在运行库提供的测试之前,库的用户如何运行自己的初始化代码(例如设置记录器的调试级别)? Python的unittest
模块用作测试人员。
答案 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.org和http://pytest.org/latest/unittest.html
HTH, 霍尔格
答案 1 :(得分:1)
答案 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