Skip to content

Unit Testing Basics

Write and run tests with unittest and pytest: assertions, fixtures, mocking, and coverage.

What you'll learn

  • Write test cases with unittest.TestCase
  • Use pytest for simpler, more powerful tests
  • Apply assertions and test discovery
  • Use fixtures and parametrized tests
  • Measure and improve test coverage

Concept

Why Test?

Tests verify that your code works correctly and catch regressions when you make changes. Without tests, every modification is a gamble — you might break something without knowing. Testing is a fundamental professional skill.

Benefits:

  • Catch bugs early — before they reach production
  • Refactor with confidence — tests verify behavior is preserved
  • Documentation — tests show how the code is supposed to work
  • Design aid — writing tests first (TDD) leads to better APIs

unittest — The Standard Library Framework

Python's built-in unittest module provides a testing framework:

import unittest

# The code we want to test
def add(a, b):
    return a + b

def is_even(n):
    return n % 2 == 0

# The test class
class TestMathFunctions(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)
        self.assertEqual(add(0, 0), 0)

    def test_is_even(self):
        self.assertTrue(is_even(4))
        self.assertFalse(is_even(3))

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

Test methods must start with test_. The unittest.main() call discovers and runs all tests. Run with python test_file.py.

Common Assertions

class TestExample(unittest.TestCase):
    def test_assertions(self):
        # Equality
        self.assertEqual(2 + 2, 4)
        self.assertNotEqual(2 + 2, 5)

        # Truthiness
        self.assertTrue(True)
        self.assertFalse(False)

        # None checks
        self.assertIsNone(None)
        self.assertIsNotNone(42)

        # Containment
        self.assertIn(3, [1, 2, 3])
        self.assertNotIn(4, [1, 2, 3])

        # Type checks
        self.assertIsInstance("hello", str)

        # Exceptions — assert code raises an error
        with self.assertRaises(ZeroDivisionError):
            result = 10 / 0

        # Approximate equality for floats
        self.assertAlmostEqual(0.1 + 0.2, 0.3, places=7)

setUp and tearDown

class TestDatabase(unittest.TestCase):
    def setUp(self):
        """Runs before EACH test method."""
        self.db = create_test_database()
        self.db.connect()

    def tearDown(self):
        """Runs after EACH test method."""
        self.db.close()

    def test_insert(self):
        self.db.insert("users", {"name": "Ada"})
        self.assertEqual(self.db.count("users"), 1)

    def test_delete(self):
        self.db.insert("users", {"name": "Bob"})
        self.db.delete("users", "Bob")
        self.assertEqual(self.db.count("users"), 0)

setUp creates a fresh test environment before each test, and tearDown cleans up after. This ensures tests are isolated — they do not affect each other.

pytest — The Simpler, More Powerful Framework

pytest is the most popular third-party testing framework. It requires less boilerplate and has more features:

pip install pytest
# test_math.py — no classes needed!
def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

def test_is_even():
    assert is_even(4) == True
    assert is_even(3) == False

def test_divide_by_zero():
    import pytest
    with pytest.raises(ZeroDivisionError):
        10 / 0

Run with pytest — it automatically discovers files named test_*.py and functions named test_*. The plain assert statement is the biggest advantage — no self.assertEqual boilerplate.

pytest Fixtures

Fixtures provide reusable setup logic:

import pytest

@pytest.fixture
def sample_list():
    """Provide a fresh list for each test."""
    return [1, 2, 3, 4, 5]

def test_sum(sample_list):
    assert sum(sample_list) == 15

def test_length(sample_list):
    assert len(sample_list) == 5

@pytest.fixture
def db_connection():
    """Setup and teardown with yield."""
    conn = create_connection()
    yield conn  # test runs here
    conn.close()  # cleanup

def test_query(db_connection):
    assert db_connection.query("SELECT 1") == 1

Fixtures are injected by name — pytest sees sample_list in the function signature and calls the fixture. The yield form handles both setup (before yield) and teardown (after yield).

Parametrized Tests

Run the same test with multiple inputs:

import pytest

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),
    (-1, 1, 0),
    (0, 0, 0),
    (100, 200, 300),
])
def test_add(a, b, expected):
    assert add(a, b) == expected

@pytest.mark.parametrize("n, expected", [
    (2, True),
    (3, False),
    (4, True),
    (0, True),
])
def test_is_even(n, expected):
    assert is_even(n) == expected

Parametrized tests eliminate duplication — one test function covers many cases, and each case appears separately in the test report.

Running Tests

# Run all tests
pytest

# Run a specific file
pytest test_math.py

# Run a specific test
pytest test_math.py::test_add

# Verbose output
pytest -v

# Stop on first failure
pytest -x

# Show print output
pytest -s

# Run only tests matching a pattern
pytest -k "add"

Coverage

Measure how much of your code is tested:

pip install pytest-cov
pytest --cov=myapp --cov-report=term-missing

Coverage shows which lines are not tested. Aim for high coverage on critical paths, but remember: 100% coverage does not mean 100% correctness — you still need meaningful assertions.

Test Organization

project/
├── src/
│   └── myapp/
│       ├── calculator.py
│       └── parser.py
└── tests/
    ├── test_calculator.py
    ├── test_parser.py
    └── conftest.py    # shared fixtures

conftest.py contains shared fixtures available to all tests in the directory. Keep tests in a separate tests/ directory, mirroring your source structure.

Example

              import unittest
import pytest

# --- Code to test ---
def add(a, b):
    return a + b

def is_even(n):
    return n % 2 == 0

def factorial(n):
    if n < 0:
        raise ValueError("n must be non-negative")
    if n <= 1:
        return 1
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

# --- unittest style ---
class TestMath(unittest.TestCase):
    def setUp(self):
        self.test_data = [1, 2, 3, 4, 5]

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

    def test_is_even(self):
        self.assertTrue(is_even(4))
        self.assertFalse(is_even(3))
        self.assertTrue(is_even(0))

    def test_factorial(self):
        self.assertEqual(factorial(0), 1)
        self.assertEqual(factorial(1), 1)
        self.assertEqual(factorial(5), 120)
        with self.assertRaises(ValueError):
            factorial(-1)

# --- pytest style (simpler!) ---
def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

def test_is_even():
    assert is_even(4) is True
    assert is_even(3) is False

@pytest.mark.parametrize("n, expected", [
    (0, 1), (1, 1), (2, 2), (3, 6), (4, 24), (5, 120),
])
def test_factorial(n, expected):
    assert factorial(n) == expected

def test_factorial_negative():
    with pytest.raises(ValueError):
        factorial(-1)

# --- pytest fixture ---
@pytest.fixture
def numbers():
    return [1, 2, 3, 4, 5]

def test_sum(numbers):
    assert sum(numbers) == 15

def test_max(numbers):
    assert max(numbers) == 5

# Run: pytest test_file.py -v
# Run unittest: python -m unittest test_file.py
            

Shows both unittest (TestCase, setUp, assertions) and pytest (plain assert, fixtures, parametrize) styles for testing add, is_even, and factorial functions. pytest is simpler and more powerful.

Try it

  • JSON Formatter

    Testing JSON serialization/deserialization is a common unit test scenario.

  • Regex Tester

    Regex patterns should be tested with various inputs — parametrize is ideal.

Common mistakes

The mistake

Writing tests that depend on order or shared mutable state

The fix

Each test should be independent — it should not rely on other tests running first or modifying shared state. Use setUp/tearDown or pytest fixtures to create a fresh environment for each test. Tests that depend on order are fragile and hard to debug.

The mistake

Testing implementation details instead of behavior

The fix

Test what the function does (its observable behavior), not how it does it (internal implementation). Tests that check private methods or internal state break when you refactor. Focus on inputs and outputs — if the function returns the right result for various inputs, it works correctly.

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors