Skip to content

    Testing with unittest & pytest

    Python · Intermediate

    Definition

    Tests are code that checks other code automatically using assertions.

    Catches bugs early and makes refactoring safe.

    Diagram

    code→ test→ pass ✓ / fail ✗

    Flowchart

    Write a functionWrite test with assertRun pytestFix failures

    Example: Simple asserts

    def add(a, b): return a + b
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    print('all tests passed')

    Output: all tests passed

    Key points

    • Test edge cases: empty, zero, negative
    • pytest discovers test_*.py files

    Interview questions

    Unit vs integration test?

    Unit tests check one piece alone; integration tests check pieces together.

    More Python topics