如何在python单元测试脚本中抑制ImportWarning [英] How to suppress ImportWarning in a python unittest script

查看:15
本文介绍了如何在python单元测试脚本中抑制ImportWarning的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在运行一个unittest脚本,该脚本成功通过了各种指定的测试,并在控制台中显示了喋喋不休的ImportWarning消息:

...../lib/python3.6/importlib/_bootstrap.py:219: ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__
  return f(*args, **kwds)
....
----------------------------------------------------------------------
Ran 7 tests in 1.950s

OK

该脚本使用以下主函数运行:

if __name__ == '__main__':
    unittest.main()

我读到过这样调用脚本时可以抑制警告:

python  -W ignore:ImportWarning -m unittest testscript.py

但是,有没有办法在脚本本身中指定此忽略警告,这样我就不必在每次运行测试脚本时都调用-W ignore:ImportWarning

提前谢谢。

推荐答案

若要以编程方式防止显示此类警告,请调整您的代码,以便:

import warnings
if __name__ == '__main__':
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', category=ImportWarning)
        unittest.main()

来源:https://stackoverflow.com/a/40994600/328469

更新:

@billjoie当然是正确的。如果操作员选择将answer 52463661作为可接受的答案,我可以接受。我可以确认,在使用2.7.11、3.4.3、3.5.4、3.6.5和3.7.1版的Python运行时,以下内容可以有效地抑制此类警告消息:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
import warnings


class TestPandasImport(unittest.TestCase):
    def setUp(self):
        warnings.simplefilter('ignore', category=ImportWarning)

    def test_01(self):
        import pandas  # noqa: E402
        self.assertTrue(True)

    def test_02(self):
        import pandas  # noqa: E402
        self.assertFalse(False)


if __name__ == '__main__':
    unittest.main()
然而,我认为OP应该考虑对单元测试的应用程序代码目标进行更深入的调查,并尝试识别导致实际警告的特定包导入或操作,然后在代码中尽可能靠近发生违规的位置隐藏警告。这将避免在整个单元测试类中隐藏警告,这可能会无意中掩盖来自程序其他部分的警告。

在单元测试之外,应用程序代码中的某个地方:

with warnings.catch_warnings():
    warnings.simplefilter('ignore', category=ImportWarning)
    # import pandas
    # or_ideally_the_application_code_unit_that_imports_pandas()

隔离代码中导致警告的特定位置或利用导致警告的第三方软件可能需要一些工作,但开发人员将更清楚地了解警告的原因,这只会提高程序的整体可维护性。

这篇关于如何在python单元测试脚本中抑制ImportWarning的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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