Site Tools


import-unittest

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 == b
  • self.assertNotEqual(a, b): a != b
  • self.assertTrue(x): x is true
  • self.assertFalse(x): x is false
  • self.assertIn(a, b): a in b
  • self.assertRaises(Exception): code raises exception
  • setUp(): run before each test
  • tearDown(): run after each test
import-unittest.md · Last modified: by 127.0.0.1