Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress ImportWarning in a python unittest script

I am currently running a unittest script which successfully passes the various specified test with a nagging ImportWarning message in the console:

...../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

The script is run with this main function:

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

I have read that warnings can be surpressed when the script is called like this:

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

However, is there a way of specifying this ignore warning in the script itself so that I don't have to call -W ignore:ImportWarning every time that the testscript is run?

Thanks in advance.

like image 251
Mysterio Avatar asked Jun 26 '18 14:06

Mysterio


1 Answers

Solutions with def setUp suppress warnings for all methods within class. If you don't want to suppress it for all of them, you can use decorator.

From Neural Dump:

def ignore_warnings(test_func):
def do_test(self, *args, **kwargs):
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        test_func(self, *args, **kwargs)
return do_test

Then you can use it to decorate single test method in your test class:

class TestClass(unittest.TestCase):
    @ignore_warnings
    def test_do_something_without_warning()
        self.assertEqual(whatever)

    def test_something_else_with_warning()
        self.assertEqual(whatever)
like image 134
M.wol Avatar answered Sep 21 '22 19:09

M.wol