import-unittest
Table of Contents
import unittest
import unittest is a Python import that provides a framework for writing and running unit tests. Use it to test code systematically and catch regressions.
Example
# Python # description: write and run unit tests import unittest def add(a, b): return a + b class TestMath(unittest.TestCase): def setUp(self): """Called before each test.""" self.result = 0 def test_add_positive(self): self.assertEqual(add(2, 3), 5) def test_add_negative(self): self.assertEqual(add(-1, -2), -3) def test_add_zero(self): self.assertEqual(add(0, 5), 5) if __name__ == "__main__": unittest.main() # Run: Python test.py # Output: ... (3 tests passed)
Common assertions
self.assertEqual(a, b): a == bself.assertNotEqual(a, b): a != bself.assertTrue(x): x is trueself.assertFalse(x): x is falseself.assertIn(a, b): a in bself.assertRaises(Exception): code raises exceptionsetUp(): run before each testtearDown(): run after each test
import-unittest.md · Last modified: by 127.0.0.1
