Python Glossary Русский

all Python 3unittestfunction

unittest.skipUnless()

skipping tests

A decorator that skips a test unless a condition is true: it runs the test only when, say, the needed module or OS is available.

Syntax

@unittest.skipUnless(condition, reason)

It mirrors skipIf: skipUnless(cond, r) is the same as skipIf(not cond, r), and mixing them up skips the test exactly where it should run. A handy pattern is an optional dependency: a try/except import at module level and @skipUnless(HAS_NUMPY, ...). Like skipIf, the condition is evaluated at import time.

Examples

import unittest
try:
    import no_such_module_xyz
    HAS_MODULE = True
except ImportError:
    HAS_MODULE = False
class Tests(unittest.TestCase):
    @unittest.skipUnless(HAS_MODULE, 'no_such_module_xyz не установлен')
    def test_feature(self):
        pass
result = unittest.TestResult()
unittest.TestLoader().loadTestsFromTestCase(Tests).run(result)
print(result.skipped[0][1])  # → no_such_module_xyz не установлен

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy