Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/05-testing-with-ai/05-testing-with-ai.ipynb

View source on GitHub

Module 05: Testing with AI#

AI-assisted test generation for comprehensive coverage.

Learning Objectives#

  1. Understand why testing is crucial with AI-generated code

  2. Write tests with pytest

  3. Use AI to generate test cases

  4. Measure and improve code coverage

  5. Practice test-driven development

Why Testing Matters More with AI#

AI generates code faster → more code to verify → more potential bugs.

Tests are your safety net for AI-generated code:

  • Catch AI mistakes before they reach production

  • Verify AI understood your requirements

  • Enable confident refactoring

  • Document expected behavior

Tests as a Pacing Mechanism#

Remember from Module 00: never develop faster than you can comprehend and test. Your test suite is your speedometer. If you are adding features but your tests are not keeping up, you are outpacing yourself. A practical rule:

  • Do not move to the next function until the current one has tests.

  • Do not move to the next milestone until coverage is where you want it.

  • If coverage is dropping, stop adding features and write tests.

AI makes it dangerously easy to generate 10 functions in five minutes. But if none of them are tested, you have 10 potential bugs and no way to catch them. Write the tests alongside the code — or even before it (TDD). Your future self will thank you.

pytest Basics#

# test_example.py

def add(a, b):
    return a + b

def test_add_positive():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, 1) == 0

def test_add_zero():
    assert add(0, 0) == 0

Run tests:

pytest                    # All tests
pytest test_example.py    # Specific file
pytest -v                 # Verbose
pytest -x                 # Stop on first failure

Context Engineering Reminder (from Module 00)

Before starting this exercise, think about what context the agent needs. For testing, that means:

  • Have the agent read the source file before writing tests — it needs to see the function signatures, edge cases, and existing patterns

  • Show it any existing tests so new tests follow the same style (fixtures, naming conventions)

  • If a test fails, paste the full pytest output so the agent can see the traceback and assertion details

Load the context first, then ask for the action.

Exercise 1: Write Your First Test (10 min)#

Create a file called test_basics.py with the following content and then add your own tests:

# test_basics.py

def add(a, b):
    return a + b

def test_add_positive():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, -2) == -3

def test_add_zero():
    assert add(0, 5) == 5

Step 1: Run the tests:

pytest test_basics.py -v

All three should pass.

Step 2: Now add a test that you expect to fail:

def test_add_floats():
    assert add(0.1, 0.2) == 0.3

Run pytest test_basics.py -v again. Why does this test fail? (Hint: floating point arithmetic.)

Step 3: Fix the failing test using pytest.approx:

import pytest

def test_add_floats():
    assert add(0.1, 0.2) == pytest.approx(0.3)

Run again — it should now pass. Understanding when exact equality fails is critical for scientific code.

AI-Generated Tests#

This is where AI really shines:

> Write pytest tests for this function:

def calculate_h_index(citations: list[int]) -> int:
    """Calculate the h-index from a list of citation counts."""
    citations_sorted = sorted(citations, reverse=True)
    h = 0
    for i, c in enumerate(citations_sorted, 1):
        if c >= i:
            h = i
        else:
            break
    return h

AI generates:

import pytest
from mypackage import calculate_h_index

def test_h_index_typical():
    assert calculate_h_index([6, 5, 3, 1, 0]) == 3

def test_h_index_empty():
    assert calculate_h_index([]) == 0

def test_h_index_all_zeros():
    assert calculate_h_index([0, 0, 0]) == 0

def test_h_index_all_high():
    assert calculate_h_index([100, 100, 100]) == 3

def test_h_index_single_paper():
    assert calculate_h_index([5]) == 1
    assert calculate_h_index([0]) == 0

Exercise 2: AI Test Generation (10 min)#

Let’s see how AI generates tests — and whether you should trust them blindly.

Step 1: Copy this function into a file called doi_utils.py:

def is_valid_doi(doi):
    """Check if a string looks like a valid DOI."""
    return doi.startswith("10.") and "/" in doi

Step 2: Ask your AI agent:

“Write pytest tests for this function: def is_valid_doi(doi): return doi.startswith("10.") and "/" in doi”

Step 3: Save the AI-generated tests to test_doi_utils.py and run them:

pytest test_doi_utils.py -v

Step 4: Review critically:

  • Did AI think of edge cases you wouldn’t have? (e.g., empty string, None, DOI with spaces)

  • Are any tests wrong? AI sometimes generates tests with incorrect expected values.

  • Did AI test the boundary: a string that starts with “10.” but has no “/”?

  • Did AI test a string with “/” but not starting with “10.”?

Fix any issues in the AI-generated tests and re-run until all pass.

Test Fixtures#

Fixtures provide reusable test data:

import pytest

@pytest.fixture
def sample_author():
    return {
        'name': 'Jane Doe',
        'works_count': 50,
        'citations': [100, 80, 60, 40, 20]
    }

def test_author_h_index(sample_author):
    h = calculate_h_index(sample_author['citations'])
    assert h == 5

Parametrized Tests#

Test many cases with one function:

@pytest.mark.parametrize("citations,expected", [
    ([6, 5, 3, 1, 0], 3),
    ([], 0),
    ([100], 1),
    ([1, 1, 1, 1, 1], 1),
    ([5, 5, 5, 5, 5], 5),
])
def test_h_index_parametrized(citations, expected):
    assert calculate_h_index(citations) == expected

Exercise 3: Parametrize Practice (10 min)#

Convert individual tests into a single parametrized test.

Step 1: Create a file test_h_index.py with this function and these individual tests:

def calculate_h_index(citations):
    citations_sorted = sorted(citations, reverse=True)
    h = 0
    for i, c in enumerate(citations_sorted, 1):
        if c >= i:
            h = i
        else:
            break
    return h

def test_h_index_1():
    assert calculate_h_index([6, 5, 3, 1, 0]) == 3

def test_h_index_2():
    assert calculate_h_index([]) == 0

def test_h_index_3():
    assert calculate_h_index([100]) == 1

def test_h_index_4():
    assert calculate_h_index([0]) == 0

Run pytest test_h_index.py -v to confirm they all pass.

Step 2: Now replace the four individual test functions with a single parametrized test:

import pytest

@pytest.mark.parametrize("citations,expected", [
    ([6, 5, 3, 1, 0], 3),
    ([], 0),
    ([100], 1),
    ([0], 0),
])
def test_h_index(citations, expected):
    assert calculate_h_index(citations) == expected

Step 3: Run pytest test_h_index.py -v again. Notice how each parametrized case is listed separately in the output with its parameters shown.

Step 4: Add two more test cases to the parametrize list (e.g., all citations equal, very large lists). Run again to verify.

Code Coverage#

Measure how much code is tested:

# Install
pip install pytest-cov

# Run with coverage
pytest --cov=mypackage

# HTML report
pytest --cov=mypackage --cov-report=html

AI for Coverage Gaps#

> My coverage report shows these lines are untested:
  [shows uncovered lines]
  Write tests to cover them.

Test-Driven Development with AI#

  1. Write the test first (with AI help)

  2. Run the test - it should fail

  3. Have AI write the implementation

  4. Run the test - it should pass

  5. Refactor with confidence

Example workflow:

> Write a test for a function that calculates the i10-index
  (number of papers with at least 10 citations)

[AI generates test]
[Test fails - function doesn't exist]

> Now write the function to make this test pass

[AI generates implementation]
[Test passes]

Testing API Code#

Use mocking to test API calls without hitting real servers:

from unittest.mock import patch, Mock

@patch('mypackage.openalex.requests.get')
def test_search_works(mock_get):
    # Setup mock response
    mock_get.return_value = Mock(
        status_code=200,
        json=lambda: {
            'results': [{'title': 'Test Paper'}],
            'meta': {'count': 1}
        }
    )
    
    # Call function
    results = search_works('test query')
    
    # Verify
    assert len(results) == 1
    assert results[0]['title'] == 'Test Paper'
    mock_get.assert_called_once()

Exercise 4: Mock an API Call (10 min)#

Write a test that uses mocking so you never hit a real network.

Step 1: Create a file paper_fetcher.py:

import requests

def get_paper_title(doi):
    """Fetch a paper title from OpenAlex by DOI."""
    url = f"https://api.openalex.org/works/doi:{doi}"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json().get("title", "Unknown")
    return None

Step 2: Create test_paper_fetcher.py with a mocked test:

from unittest.mock import patch, Mock
from paper_fetcher import get_paper_title

@patch("paper_fetcher.requests.get")
def test_get_paper_title(mock_get):
    # Set up the mock to return a fake response
    mock_get.return_value = Mock(
        status_code=200,
        json=lambda: {"title": "Test Paper"}
    )

    # Call the function — no real HTTP request is made
    title = get_paper_title("10.1234/fake")

    # Verify the result
    assert title == "Test Paper"
    mock_get.assert_called_once()

Step 3: Run the test:

pytest test_paper_fetcher.py -v

It should pass instantly (no network delay) because requests.get was replaced by the mock.

Step 4: Add a second test for the error case (status code 404). What should get_paper_title return? Write the test and verify.

Bonus: If mocking syntax feels unfamiliar, ask your AI agent: “Explain what @patch does in this test and how Mock works.” Compare the AI explanation to your understanding.

Exercise: Achieve 95% Coverage#

  1. Run coverage on your package

  2. Identify untested code

  3. Ask AI to generate tests for uncovered code

  4. Review AI-generated tests for correctness

  5. Iterate until you reach 95%

AI Prompt#

Here's my module and current tests:
[paste code]

Coverage shows these lines are untested:
[paste uncovered lines]

Write additional tests to cover:
1. Edge cases
2. Error conditions
3. The uncovered lines

Summary#

Concept

Key Point

pytest

Simple, powerful testing

AI generation

Great for comprehensive tests

Coverage

Aim for 90%+

Mocking

Test APIs without network

TDD

Test first, implement second

Tips and Tricks#

  • Prompt: “Write pytest tests for [function] including edge cases”: Always specify edge cases or the AI will only test the happy path.

  • Run tests after every AI change: Make pytest your reflex — it catches regressions immediately.

  • Prompt: “Write a parametrized test for [function] with these inputs: [list]”: Parametrized tests are verbose to write by hand; AI generates them quickly.

  • Use --tb=short for faster feedback: pytest --tb=short gives you compact tracebacks that are easier to paste into the agent.

  • Ask the agent to explain failing tests: “This test is failing with [error]. Explain why and fix it.” — often faster than debugging yourself.

  • Coverage is a guide, not a goal: 90% coverage with meaningful tests beats 100% coverage with trivial assertions.

  • Prompt: “What cases am I not testing for [function]?”: AI is good at finding blind spots in test suites.

  • Commit passing tests before adding features: Green tests give you a safe rollback point.

Foundational Concepts to Commit to Memory#

  • assert is the core of pytest – every test boils down to asserting that something is true, and pytest gives you detailed failure messages when it is not

  • Test naming convention: files start with test_, functions start with test_ – pytest discovers tests automatically based on these names

  • Fixtures (@pytest.fixture) provide reusable setup data or resources to your tests, keeping test code DRY and readable

  • Parametrize (@pytest.mark.parametrize) lets you run one test function with many different inputs, which is far cleaner than writing separate test functions for each case

  • Mocking (unittest.mock.patch) replaces real objects (like network calls) with fake ones so your tests run fast, offline, and deterministically

  • Code coverage measures which lines of your code are actually exercised by tests – aim for 90%+, but remember that 100% coverage does not mean zero bugs

  • Test-Driven Development (TDD) means writing the test before the implementation – this forces you to think about the interface and edge cases up front

  • pytest.approx is essential for floating-point comparisons in scientific code – never use == to compare floats directly

Knowing vs. Doing: Reflection#

Testing is the place where the tension between learning and doing shows up most sharply. You can read about pytest fixtures, parametrize decorators, mocking strategies, and property-based testing for weeks. There is a whole discipline of software testing with deep theory behind it. But the reality is that an untested function you shipped last week is more dangerous than a perfectly tested function you never wrote. The goal is not to become a testing theorist – it is to build the habit of writing tests alongside your code, and to know enough about the tools that you can write meaningful tests quickly.

AI is remarkably good at generating tests. Give it a function, and it will produce a solid set of test cases – often including edge cases you would not have thought of. This is one of the highest-value uses of AI in your workflow. But here is the catch: if you do not understand what a good test looks like, you will not notice when AI generates a test with the wrong expected value, or when it tests the implementation rather than the behavior. You need to know what assertions mean, what mocking does, and why parametrize exists – not so you can write every test by hand, but so you can review AI-generated tests with a critical eye.

The practical balance looks like this: learn the pytest fundamentals well enough that you could write a basic test suite from scratch. Then use AI to accelerate the tedious parts – generating edge cases, writing mock setups, hitting coverage targets. The more you know about testing patterns, the better your prompts will be and the faster you will spot AI mistakes. You are not trying to become a QA engineer. You are trying to ship code that works, and testing is how you prove it does.

Additional Resources#

Next Steps#

In the next module, we’ll add code quality tools to maintain standards.