Python unittest Module: Writing Automated Unit Tests ✅

Testing icon

Python unittest Module: Writing Automated Unit Tests ✅

The unittest module is Python's built-in unit testing framework, essential for verifying the correctness of your code automatically.

1. Writing Simple Function Tests

# calc.py
def add(a, b):
    return a + b

# test_calc.py
import unittest
from calc import add

class TestCalc(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

if __name__ == '__main__':
    unittest.main()

2. Using `setUp()` and `tearDown()` for Common Tasks

# test_list.py
import unittest

class TestList(unittest.TestCase):
    def setUp(self):
        self.lst = [1, 2, 3]

    def tearDown(self):
        self.lst.clear()

    def test_append(self):
        self.lst.append(4)
        self.assertIn(4, self.lst)

    def test_pop(self):
        value = self.lst.pop()
        self.assertEqual(value, 3)

if __name__ == '__main__':
    unittest.main()

3. Testing for Exceptions

# test_divide.py
import unittest

def divide(a, b):
    return a / b

class TestDivide(unittest.TestCase):
    def test_zero_division(self):
        with self.assertRaises(ZeroDivisionError):
            divide(1, 0)

if __name__ == '__main__':
    unittest.main()

4. Running Tests and Viewing Results

$ python -m unittest discover
...
----------------------------------------------------------------------
Ran 5 tests in 0.002s

OK

Summary

  • Create test cases with TestCase class
  • Utilize assertion methods like assertEqual, assertIn, and assertRaises
  • Handle setup and cleanup using setUp() and tearDown()
  • Automatically discover and run all tests using unittest discover

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“