使用nosetests进行测试时,可以将warn.filterwarnings设置为本地操作

Posted

技术标签:

【中文标题】使用nosetests进行测试时,可以将warn.filterwarnings设置为本地操作【英文标题】:can warn.filterwarnings be set to act locally when testing with nosetests 【发布时间】:2014-06-25 17:10:14 【问题描述】:

在使用nosetests 时,我在 python 测试中过滤警告时遇到了一些麻烦。我希望我对warn.filterwarnings 的调用仅对单个文件是本地的,但是如果我使用nosetests 测试的任何文件调用warn.filterwarnings,则在所有测试中都会过滤警告。例如(来自scikit-bio code base),skbio/math/diversity/beta/tests/test_base.py 没有对warn.filterwarnings 的调用,因此如果在测试期间生成警告,则会按预期将其打印到屏幕上:

$ nosetests skbio/math/diversity/beta/tests/test_base.py
../Users/caporaso/Dropbox/code/skbio/skbio/math/diversity/beta/base.py:89: UserWarning: pw_distances_from_table is deprecated. In the future (tentatively scikit-bio 0.2.0), pw_distance will take a biom.table.Table object and this function will be removed. You will need to update your code to call pw_distances at that time.
  warn("pw_distances_from_table is deprecated. In the future (tentatively "
...
----------------------------------------------------------------------
Ran 5 tests in 0.017s

OK

但是,在skbio/core/alignment/tests/test_pairwise.py 中,有一个对warn.filterwarnings 的调用。如果我在skbio/math/diversity/beta/tests/test_base.py 之前运行这些测试,则不会打印上述警告:

$ nosetests skbio/core/alignment/tests/test_pairwise.py skbio/math/diversity/beta/tests/test_base.py
...................
----------------------------------------------------------------------
Ran 19 tests in 0.056s

OK

我希望打印来自skbio/math/diversity/beta/tests/test_base.py 的警告,即使从其他测试文件调用了其他warn.filterwarnings。在实践中,我最终也会对其进行过滤,但我想知道是否还有其他警告没有被我的测试套件中其他地方的测试捕获。

【问题讨论】:

【参考方案1】:

理想情况下,您希望使用conext manager 来temporarily suppress them。

【讨论】:

谢谢你,成功了。具体来说,我所做的是从我的测试套件中删除所有对warn.filterwarnings 的调用,然后按照您发送的链接中的建议包装引发警告的调用。

以上是关于使用nosetests进行测试时,可以将warn.filterwarnings设置为本地操作的主要内容,如果未能解决你的问题,请参考以下文章

使用补丁模拟两个函数以进行单元测试

当使用nosetest或print时,oserror python 3.5.4 on win 10 1709

ModuleNotFoundError:没有名为“numpy.testing.nosetester”的模块

ModuleNotFoundError: No module named 'numpy.testing.nosetester'----import sklearn.datasets.m

强制 Nosetests 使用 Python 2.7 而不是 3.4

[接口测试_B] 04 Pytest断言处理_告警断言