all Python 3unittestterm
unittest.TestCase
testing
The base class for test cases. Every method whose name starts with test_ is run as a separate test. It provides the assert* methods for checking results.
Syntax
class MyTests(unittest.TestCase):
def test_something(self): ...
unittest builds a fresh instance of the class for every test_ method, so you cannot hand state from one test to the next through self — anything shared belongs in setUp or setUpClass. Methods run in alphabetical order by name, not in the order they appear in the file, so no test may assume another already ran. Prefer self.assertEqual over a bare assert: it reports both values on failure and does not vanish when Python runs with -O.
Examples
import unittest
class MathTests(unittest.TestCase):
def test_sum(self):
self.assertEqual(1 + 1, 2)
def test_type(self):
self.assertIsInstance(42, int)
if __name__ == '__main__': # на уровне модуля, а не внутри класса
unittest.main() # → Ran 2 tests ... OK
See also
Open in the full glossarydocs.python.orgReport an inaccuracy