Answer a question

I would like my Python unittest module to tell the test runner to skip it entirety under some situations (such as being unable to import a module or locate a critical resource).

I can use @unittest.skipIf(...) to skip a unittest.TestCase class, but how do I skip the entire module? Applying skips to every class is not sufficient because the class definitions themselves could cause exceptions if a module fails to import.

Answers

If you look at the definition of unittest.skipIf and unittest.skip, you can see that the key is doing raise unittest.SkipTest(reason) when the test is executed. If you're okay with having it show up as one skipped test instead of several in the testrunner, you can simply raise unittest.SkipTest yourself on import:

import unittest
try:
    # do thing
except SomeException:
    raise unittest.SkipTest("Such-and-such failed. Skipping all tests in foo.py")

Running with nosetests -v gives:

Failure: SkipTest (Such-and-such failed. Skipping all tests in foo.py) ... SKIP:
Such-and-such failed. Skipping all tests in foo.py

----------------------------------------------------------------------
Ran 1 test in 0.002s

OK (SKIP=1)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐