17

When running nosetests from the command line, how do you specify that 'non-ignored' warnings should be treated as errors?

By default, warnings are printed, but not counted as failures:

[snip]/service/accounts/database.py:151: SADeprecationWarning: Use session.add()
  self.session.save(state)
[snip]/service/accounts/database.py:97: SADeprecationWarning: Use session.add()
  self.session.save(user)
............
----------------------------------------------------------------------
Ran 12 tests in 0.085s

OK

As we don't want our code to generate warnings, I don't want this situation to be OK.

Thanks!

Edit: Ideally what I'd like is a nosetests command line option that issues a warnings.simplefilter('error') prior to each test (and cleans it out afterwards).

Any solution that involves using the warnings module in the test code seems to defeat the point. I don't want to manually edit each test module to transform warnings into errors. Plus I don't want the author of each test module to be able to forget to 'turn on' warning errors.

4

3 回答 3

12

nosetests是一个小的 Python 脚本。用编辑器打开它,并-W error在第一行的末尾添加。这告诉 Python 解释器将警告转换为异常。

更简单的是使用 Python 环境变量来注入“将警告视为错误”标志:

PYTHONWARNINGS=error nosetests test/test_*.py --pdb
于 2014-01-08T14:25:54.337 回答
5

@khinsen 的回答有很大帮助,但如果它在测试发现期间发出以下警告(否则用户不可见)发出以下警告,则会停止执行鼻子测试:“ImportWarning: Not importing directory 'XXX': missing__init__.py

此外,在导入模块期间引发的警告(与在测试期间引发的警告相反)不应被视为错误。

我按照@dbw 的建议编写了一个插件,可以在 github 上找到:https ://github.com/Bernhard10/WarnAsError

一个鼻子插件WarnAsError

configure在and函数旁边options,插件实现了prepareTestRunner,它用具有不同运行方法的类替换默认的 TestRunner :

def prepareTestRunner(self, runner):
    return WaETestRunner(runner)

此类存储原始 TestRunner 及其run-Method 调用原始 TestRunner 的 run 方法与不同的warnings.simplefilter.

class WaETestRunner(object):
    def __init__(self, runner):
        self.runner=runner
    def run(self, test):
        with warnings.catch_warnings():
            warnings.simplefilter("error")
            return self.runner.run(test)
于 2015-10-20T13:04:23.837 回答
0

I don't think nose can directly control this: the warnings module doesn't raise an exception when the warning is issued. The warnings module gives you control over which warnings should be raised as exceptions.

于 2009-11-10T16:51:55.227 回答