AI Test Case Generator with Claude and Pytest (Project)

๐Ÿ“š Exam guide v1.1 (exams from 7 Dec 2026)๐Ÿ”„ Checked against official sources: 24 Nov 2026โฑ๏ธ 8 min read๐ŸŽฏ Project ยท D6 Structured Output and Defensive Parsing ยท D4 Evaluation Design

๐Ÿ‘‹ In plain words: Writing test cases from requirements is slow and repetitive. In this project you build a command-line tool that reads a requirement, asks Claude for a structured test suite, checks the suite for gaps, and writes pytest skeletons plus a CSV your test management tool can import. Every step is small and testable.

Advertisement

AI test generation is useful only if the output is trustworthy and fits your process. In this project you will define the suite format as Pydantic models, generate it with structured output, apply coverage rules in code (every rule has a negative case, IDs are unique), render pytest skeletons and a CSV, collect the generated tests with pytest to prove they are valid, and cover the tool with offline tests.

๐Ÿ“– What You’ll Learn: You will be able to build a test-case generator that produces validated, traceable suites with Claude, enforce coverage rules in code, render them into pytest and CSV, and test the generator itself.

๐Ÿ”‘ Key terms

  • Traceability: each test case links to the requirement rule it checks.
  • Coverage rule: a check that the suite covers what it must, such as one negative case per rule.
  • Skeleton test: a generated pytest function with steps and expected result, marked to be automated later.

๐Ÿชœ Step 1: Lay out the project

๐Ÿ“„ LAYOUT.txt

testgen/
  requirements/coupon.md      input requirement
  testgen/models.py           suite format (Pydantic)
  testgen/generate.py         Claude call + coverage rules
  testgen/render.py           pytest skeletons + CSV
  cli.py                      command-line entry point
  tests/test_rules.py         offline tests of the rules and rendering
  pytest.ini

๐Ÿ“„ pytest.ini

[pytest]
pythonpath = .
testpaths = tests

๐Ÿ“„ requirements/coupon.md

# Coupon codes at checkout
R1: A valid coupon gives 10% off orders over $50.
R2: Orders of $50 or less cannot use a coupon.
R3: Each coupon works once per customer.
R4: Expired coupons are rejected with the message "Coupon expired".

๐Ÿชœ Step 2: Define the suite format

๐Ÿ“„ testgen/__init__.py

๐Ÿ“„ testgen/models.py

from typing import Literal

from pydantic import BaseModel, Field


class TestCase(BaseModel):
    __test__ = False  # stop pytest treating this model as a test class
    id: str = Field(description="TC-01, TC-02, ...")
    rule: str = Field(description="The requirement rule ID this case checks, e.g. R1")
    kind: Literal["positive", "negative", "boundary"]
    title: str
    steps: list[str]
    expected: str


class TestSuite(BaseModel):
    __test__ = False
    feature: str
    cases: list[TestCase]
    open_questions: list[str] = Field(description="Gaps or ambiguities in the requirement")

__test__ = False stops pytest from trying to collect these models as test classes because their names start with Test (a classic QA-project warning). open_questions gives Claude a sanctioned place to report gaps instead of inventing behaviour.

Advertisement

๐Ÿชœ Step 3: Generate and enforce coverage rules

๐Ÿ“„ testgen/generate.py

import re

import anthropic

from testgen.models import TestSuite

SYSTEM = """You are a senior QA engineer. Write test cases for the requirement.
For every rule (R1, R2, ...) write at least one positive and one negative case, plus boundary cases where a number is involved.
Do not invent behaviour that the requirement does not state; list it under open_questions instead."""


class CoverageError(Exception):
    pass


def check_coverage(suite: TestSuite, requirement: str) -> list[str]:
    problems = []
    rules = sorted(set(re.findall(r"\bR\d+\b", requirement)))
    ids = [c.id for c in suite.cases]
    if len(ids) != len(set(ids)):
        problems.append("duplicate test IDs")
    for rule in rules:
        kinds = {c.kind for c in suite.cases if c.rule == rule}
        if "negative" not in kinds:
            problems.append(f"{rule} has no negative case")
    for c in suite.cases:
        if c.rule not in rules:
            problems.append(f"{c.id} points to unknown rule {c.rule}")
    return problems


def generate_suite(client: anthropic.Anthropic, requirement: str) -> TestSuite:
    r = client.messages.parse(model="claude-opus-5-5", max_tokens=8000, output_format=TestSuite, system=SYSTEM,
                              messages=[{"role": "user", "content": f"<requirement>\n{requirement}\n</requirement>"}])
    if r.stop_reason != "end_turn" or r.parsed_output is None:
        raise CoverageError(f"incomplete generation ({r.stop_reason})")
    return r.parsed_output

Claude is asked for coverage; your code checks it. The model’s promise is not the proof.

๐Ÿชœ Step 4: Render pytest skeletons and a CSV

๐Ÿ“„ testgen/render.py

import csv
import re
from pathlib import Path

from testgen.models import TestSuite


def to_pytest(suite: TestSuite) -> str:
    lines = ["import pytest", ""]
    for c in suite.cases:
        name = "test_" + re.sub(r"\W+", "_", c.id.lower() + "_" + c.title.lower()).strip("_")[:60]
        lines += ["", f'@pytest.mark.skip(reason="{c.id} ({c.rule}, {c.kind}): not automated yet")',
                  f"def {name}():", f'    """{c.title}', ""]
        lines += [f"    {n}. {s}" for n, s in enumerate(c.steps, 1)]
        lines += ["", f"    Expected: {c.expected}", '    """', ""]
    return "\n".join(lines).rstrip() + "\n"


def to_csv(suite: TestSuite, path: Path) -> None:
    with path.open("w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["ID", "Rule", "Type", "Title", "Steps", "Expected"])
        for c in suite.cases:
            w.writerow([c.id, c.rule, c.kind, c.title, " | ".join(c.steps), c.expected])

๐Ÿชœ Step 5: Wire up the CLI

๐Ÿ“„ cli.py

import sys
from pathlib import Path

import anthropic

from testgen.generate import check_coverage, generate_suite
from testgen.render import to_csv, to_pytest


def main(req_path: str, out_dir: str = "out") -> int:
    requirement = Path(req_path).read_text()
    suite = generate_suite(anthropic.Anthropic(), requirement)
    problems = check_coverage(suite, requirement)
    out = Path(out_dir)
    out.mkdir(exist_ok=True)
    (out / "test_generated.py").write_text(to_pytest(suite))
    to_csv(suite, out / "cases.csv")
    print(f"{suite.feature}: {len(suite.cases)} cases written to {out}/")
    for q in suite.open_questions:
        print("  open question:", q)
    for p in problems:
        print("  COVERAGE PROBLEM:", p)
    return 1 if problems else 0


if __name__ == "__main__":
    sys.exit(main(*sys.argv[1:]))

โŒจ๏ธ Terminal

python cli.py requirements/coupon.md out

๐Ÿ–ฅ๏ธ Output (sample run)

Coupon codes at checkout: 7 cases written to out/
  open question: Does the 10% apply before or after shipping?
  open question: Is $50 measured before or after tax?
  COVERAGE PROBLEM: R4 has no negative case

Read the output: Claude listed two genuine open questions, and the coverage check found a real gap: R4 has no negative case (for example, a valid coupon must not show “Coupon expired”). The CLI exits with code 1, so a pipeline would stop until someone adds the case or regenerates.

Advertisement

๐Ÿชœ Step 6: Prove the generated tests are valid pytest

โŒจ๏ธ Terminal

pytest --collect-only -q -p no:cacheprovider out/test_generated.py

๐Ÿ–ฅ๏ธ Output

out/test_generated.py::test_tc_01_10_off_a_60_order
out/test_generated.py::test_tc_02_invalid_code_is_rejected
out/test_generated.py::test_tc_03_exactly_50_cannot_use_a_coupon
out/test_generated.py::test_tc_04__20_order_cannot_use_a_coupon
out/test_generated.py::test_tc_05_first_use_works
out/test_generated.py::test_tc_06_second_use_by_same_customer_fails
out/test_generated.py::test_tc_07_expired_coupon_message

7 tests collected in 0.42s

๐Ÿ“„ show_generated.py

from pathlib import Path

print("\n".join(Path("out/test_generated.py").read_text().splitlines()[:14]))

โŒจ๏ธ Terminal

python show_generated.py

๐Ÿ–ฅ๏ธ Output

import pytest


@pytest.mark.skip(reason="TC-01 (R1, positive): not automated yet")
def test_tc_01_10_off_a_60_order():
    """10% off a $60 order

    1. Add items worth $60
    2. Apply coupon SAVE10

    Expected: Total is $54.00
    """
Advertisement

๐Ÿชœ Step 7: Test the generator offline

๐Ÿ“„ tests/test_rules.py

from testgen.generate import check_coverage
from testgen.models import TestCase, TestSuite
from testgen.render import to_pytest

REQ = "R1: rule one.\nR2: rule two."


def case(id, rule, kind):
    return TestCase(id=id, rule=rule, kind=kind, title="t", steps=["s"], expected="e")


def test_full_coverage_passes():
    suite = TestSuite(feature="f", open_questions=[], cases=[case("TC-1", "R1", "negative"), case("TC-2", "R2", "negative")])
    assert check_coverage(suite, REQ) == []


def test_missing_negative_and_unknown_rule_are_reported():
    suite = TestSuite(feature="f", open_questions=[], cases=[case("TC-1", "R1", "positive"), case("TC-2", "R9", "negative")])
    problems = check_coverage(suite, REQ)
    assert "R1 has no negative case" in problems and "TC-2 points to unknown rule R9" in problems


def test_duplicate_ids_are_reported():
    suite = TestSuite(feature="f", open_questions=[], cases=[case("TC-1", "R1", "negative"), case("TC-1", "R2", "negative")])
    assert "duplicate test IDs" in check_coverage(suite, REQ)


def test_rendered_code_compiles():
    suite = TestSuite(feature="f", open_questions=[], cases=[case("TC-1", "R1", "negative")])
    compile(to_pytest(suite), "generated.py", "exec")

โŒจ๏ธ Terminal

pytest -q -p no:cacheprovider

๐Ÿ–ฅ๏ธ Output

....                                                                     [100%]
4 passed in 0.42s

๐Ÿชœ Step 8: Evaluate the generator

Criterion Check
Traceability Every case has a rule ID that exists in the requirement
Coverage Positive, negative and boundary cases per rule, enforced in code
No invention Gaps go to open_questions; reviewers check new facts against the requirement
Validity Generated code compiles and pytest collects it
Usefulness Reviewers accept most cases with small edits; track acceptance rate per run
Regression A golden set of requirements with expected coverage, run on prompt or model changes (Lesson 45)
๐ŸŽฏ Exam focus: The project exercises “Structured Output and Defensive Parsing” (Pydantic schema, stop_reason check, rules in code) and “Evaluation Design” (coverage criteria and a golden set). The design choice to remember: let Claude generate, let code verify.

๐Ÿงช Practice Questions

Question 1. The generator’s prompt says “write a negative case for every rule”, yet some suites lack them. What is the most reliable safeguard?

  • A. Repeat the instruction three times
  • B. Check coverage in code after generation and fail or regenerate when a rule lacks a negative case
  • C. Use a larger max_tokens
  • D. Ask Claude to confirm it followed the rule
Show answer

Answer: B. Instructions are not proof. A deterministic coverage check verifies every suite.

Question 2. Why does the schema include open_questions?

  • A. To give Claude a sanctioned place to report gaps instead of inventing behaviour
  • B. To make the output longer
  • C. Because Pydantic requires a list field
  • D. To store reviewer comments
Show answer

Answer: A. When missing information has a home, the model is less likely to fill gaps with invented requirements.

Question 3. Which two checks prove generated pytest files are usable? (Choose 2.)

  • A. The code compiles
  • B. The file is longer than 100 lines
  • C. pytest collects the tests without errors
  • D. Claude says the tests are correct
Show answer

Answer: A and C. Compilation and collection are objective, fast validity checks.

Question 4. A requirement contains R1โ€“R4, and a generated case points to R7. What should the tool do?

  • A. Accept it; Claude knows best
  • B. Report it as a traceability problem
  • C. Rename R7 to R4
  • D. Delete the requirement
Show answer

Answer: B. Each case must trace to an existing rule; unknown rules signal invented requirements.

๐Ÿ“ Assignment

  1. Task 1: Run the CLI with your key on one of your own requirements.
    โœ… Done when: the coverage check passes or you have added the missing cases.
  2. Task 2: Add a rule: every requirement number (like “$50”) must have at least one boundary case.
    โœ… Done when: a test shows a suite without boundary cases fails.
  3. Stretch: When coverage fails, send the problems back to Claude once and ask for only the missing cases, then merge them.
    โœ… Done when: the CLI ends with zero coverage problems after one repair round.
Advertisement

โ“ Frequently Asked Questions

๐Ÿค” Can Claude generate test cases from requirements?

Yes. With a structured schema, explicit coverage expectations and code-level checks, Claude can draft traceable suites that reviewers then refine.

๐Ÿค” How do I make AI-generated tests trustworthy?

Require traceability to requirement rules, enforce coverage in code, keep gaps as open questions, validate generated code, and measure reviewer acceptance.

๐Ÿค” Should generated tests run automatically?

Generate skeletons marked as not automated, let a person review and implement them, then remove the skip marker.

๐Ÿค” How do I import generated cases into a test management tool?

Write a CSV (or the tool’s import format) with ID, rule, type, title, steps and expected result, as this project does.

๐Ÿ Summary

  • Define the suite as Pydantic models with traceability and open questions.
  • Generate with structured output; check stop_reason.
  • Enforce coverage and traceability in code; exit non-zero on gaps.
  • Render pytest skeletons and CSV; prove validity with compile and collection.
  • Test the generator offline and evaluate it with a golden set.
๐Ÿ“ Test yourself: CCDV-F Mock Exam 1 (70 questions, 120 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with AI Test Failure and Log Analysis with Claude (Project).

๐ŸŽฌ Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.