Python Glossary Русский

all Python 3unittestfunction

unittest.main()

running tests

The command-line entry point: it finds the tests in a module, runs them with TextTestRunner and by default exits the program through sys.exit.

Syntax

unittest.main(module='__main__', defaultTest=None, argv=None, exit=True, verbosity=1, failfast=None)

By default exit=True: sys.exit is called after the tests, so code after unittest.main() never runs, and in Jupyter or IDLE you get SystemExit. Arguments come from sys.argv, and in a notebook the kernel flags cause a parsing error, so pass argv=['x'] and exit=False. It returns a TestProgram object with the outcome in .result. Call it under if __name__ == '__main__', or the tests run whenever the module is imported.

Examples

import sys
import unittest
class Tests(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('py'.upper(), 'PY')
if __name__ == '__main__':
    runner = unittest.TextTestRunner(stream=sys.stdout, verbosity=0)
    program = unittest.main(argv=['x'], exit=False, testRunner=runner)
    print(program.result.testsRun, program.result.wasSuccessful())  # → 1 True
    print('code after main() runs')  # → code after main() runs

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy