获取nosetests配置选项

2 投票
3 回答
1507 浏览
提问于 2025-04-17 08:19

我想从nose的配置文件中获取一些选项。

不过我不想自己去解析这个文件,所以我试着使用nose的API

我不太确定如何理解这个页面上提到的信息:

import nose

def setup()
  noseParser = nose.config.Config().getParser()
  value = noseParser.get_option("debug-log")

我觉得应该是这样工作的。但是value一直是None,而且没有抛出任何异常。

我的使用场景是:每次运行nose的时候删除调试日志文件。

3 个回答

0

我觉得你最好的办法是写一个自定义插件。这样一来,就可以让nose来帮你完成工作。听起来你想做的事情是,在所有测试运行完后删除debug-log。为了实现这个,你需要一个插件,它要实现finalize()这个方法。在这个例子中,我还实现了options(),这样就可以开启或关闭这个插件,并且实现了configure(),用于找到debug-log的位置。这里可以查看所有方法的完整列表

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里,并在执行时启用它。这里有相关的说明。你可能还想调整一下score属性,以确保你的插件最后运行。

0

从nose的代码来看,我没有看到一个明确的接口可以从配置文件中获取选项。我看到的是:

  • 你可以通过 nose.config.all_config_files()nose.config.user_config_files() 来获取配置文件。
  • nose并没有使用任何自定义的解析类,而只是用了 ConfigParser.RawConfigParser

所以,直接解析配置文件也许并不是个坏主意。

1

根据你提供的链接,getParser() 返回的是一个命令行选项解析器。我不太确定,但你可以查看一下 nose.config.Config().debugLog 的设置是什么。

撰写回答