如何在 python 单元测试脚本中抑制 ImportWarning

2024-03-22

我当前正在运行一个单元测试脚本,该脚本成功通过了各种指定的测试,并在控制台中显示了一条烦人的 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

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

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()

Source: https://stackoverflow.com/a/40994600/328469 https://stackoverflow.com/a/40994600/328469

Update:

@billjoie 肯定是正确的。如果OP选择使回复52463661 https://stackoverflow.com/a/52463661/328469已接受的答案,我对此表示同意。我可以确认以下内容可以有效地使用 python 版本 2.7.11、3.4.3、3.5.4、3.6.5 和 3.7.1 在运行时抑制此类警告消息:

#! /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()

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 python 单元测试脚本中抑制 ImportWarning 的相关文章

随机推荐