【问题标题】:Get nosetests configuration options获取鼻子测试配置选项
【发布时间】:2012-01-19 16:42:51
【问题描述】:
我想从鼻子配置文件中获得一些选项。
但是我不想自己解析文件,所以尝试用鼻子api
我不知道如何解释这边提到的信息:
import nose
def setup()
noseParser = nose.config.Config().getParser()
value = noseParser.get_option("debug-log")
这就是我认为它应该工作的方式。但是value 一直是None 并且没有引发异常。
我的用例:每次鼻子运行时删除调试日志文件。
【问题讨论】:
标签:
python
configuration
nosetests
【解决方案1】:
根据您提供的链接 getParser() 返回“命令行选项解析器”。我不确定,但您可以检查 nose.config.Config().debugLog 的设置。
【解决方案2】:
查看鼻子代码,我没有看到明确的 API 可以从配置文件中获取选项。我看到的是:
- 您可以从
nose.config.all_config_files()和nose.config.user_config_files()获取配置文件。
- 它没有使用任何自定义解析类,而只是
ConfigParser.RawConfigParser。
因此,毕竟直接解析配置文件也许不是一个坏主意。
【解决方案3】:
我认为你最好的方法是write a custom plugin。这样,您就可以让鼻子为您完成工作。听起来您想要做的是在运行所有测试后删除debug-log。为此,您需要一个实现 finalize() 方法的插件。在此示例中,我还实现了 options() 以便可以启用/禁用插件和 configure(),以查找调试日志的位置。 Check out the full list of methods here.
from nose.plugins import Plugin
import os
class AutoDeleteDebugLog(Plugin):
"""
Automatically deletes the error log after test execution. This may not be
wise, so think carefully.
"""
def options(self, parser, env):
"Register commandline options using Nose plugin API."
parser.add_option('--with-autodeletedebuglog', action='store_true',
help='Delete the debug log file after execution.')
self.debuglog = None
def configure(self, options, conf):
"Register commandline options using Nose plugin API."
self.enabled = options.autodeletedebuglog
self.debuglog = options.debugLog
def finalize(self, result):
"Delete debug log file after all results are printed."
if os.path.isfile(self.debuglog):
os.remove(self.debuglog)
编写插件后,您必须向nose 注册它,并在执行时启用它。有are instructions for that here。您可能还想使用score 属性来确保您的插件最后运行。