使用Python的unittest模块作为testrunner时,如何在测试前运行初始化代码? [英] How to run initialization code before tests when using Python's unittest module as a testrunner?

查看:283
本文介绍了使用Python的unittest模块作为testrunner时,如何在测试前运行初始化代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can a user of a library run his own initialization code (setting debug levels of loggers for example) before running tests supplied with the library? Python's unittest module is used as a testrunner.

推荐答案

您可以尝试使用pytest运行单元测试.如果可行(许多基于单元测试的测试套件都可以使用),则可以创建一个小模块,例如"mymod.py",定义一个pytest配置钩子:

You can try using pytest to run the unittests. If that works (many unittest based test suites work), then you can create a little module, for example "mymod.py", defining a pytest configuration hook:

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

如果您现在这样执行py.test:

If you now execute py.test like this:

$ py.test -p mymmod --pyargs mylib

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

Then the "mylib" package will be searched for tests and ahead of running them the logging level is modified. The "-p" option specifies a plugin to load and the "--pyargs" tells pytest to try importing the arguments first, instead of treating them as directory or file names (the default).

有关更多信息: http://pytest.org HTH, 霍尔格

这篇关于使用Python的unittest模块作为testrunner时,如何在测试前运行初始化代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆