QA and Test Automation ยท Lab 32 of 35

Generate Test Cases From a User Story With AI, Then Review Them

Ask a local model for boundary test cases from a ShopRung checkout story, then check every row with an oracle you write from the acceptance criteria. In a real run, llama3.2:3b got 5 of 34 rows right across three drafts. You build the oracle, a review script that finds wrong values, untraceable rows and missing boundaries, and a reviewed case list that passes.

โฑ 45 minIntermediate๐Ÿ’ธ Free6 steps

Python 3.12pytestOllama (optional)llama3.2:3b

Overview video

1 / 6

0 of 6 steps done

What you will build

A folder story-to-tests that turns an AI draft into test cases you can trust:

  • story.md: a user story with ShopRung's coupon and shipping rules as acceptance criteria.
  • pricing.py: the oracle, the rules as code, written by you from the story, with its own tests.
  • generate.py: asks a local model for test cases as CSV, with the same prompt our real run used.
  • review.py: checks every row: wrong amounts, rows that point at no rule, and boundaries nobody tested.
  • cases.csv: the reviewed list: 11 cases, all correct, every boundary covered.

Before you start

Setup

S1Make the project

Python 3.12 or newer (py on Windows). Create requirements.txt with the content below, then make the virtual environment and install. Run the activate line again in every new terminal.

Run
mkdir -p story-to-tests/tests story-to-tests/drafts
cd story-to-tests
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
You should seeyour text will differ: the model writes it
Successfully installed ... pytest-8.3.4

S2A local model (optional)

Step 3 asks a model for a draft. To run it yourself, install Ollama and pull the same small model we used (about 2 GB). Without it, you will use our three real drafts, which are given in full.

Run
ollama pull llama3.2:3b
ollama list
You should seeyour text will differ: the model writes it
NAME           ID              SIZE      MODIFIED
llama3.2:3b    ...             2.0 GB    ...
1

The story

Acceptance criteria are the only source of truth.

Save the story. Its acceptance criteria are copied from ShopRung's requirements, with their ids. Every test case you keep must point at one of these ids, and every expected amount must follow from them, not from what a model or a screen says.

story.md
# Story SHOP-142: Coupons and shipping at checkout

As a shopper, I want to use a coupon and see the shipping cost before I pay,
so that I know exactly what my order will cost.

## Acceptance criteria (from ShopRung's requirements)

- PRICE-2  Only one coupon can be used per order. Coupon codes are not case-sensitive.
- PRICE-3  SAVE10 takes 10% off the subtotal when the subtotal is $50.00 or more.
- PRICE-4  FLAT5 takes $5.00 off when the subtotal is $20.00 or more.
- PRICE-5  WELCOME15 expired on 31 December 2025 and must be refused with "This coupon has expired".
- PRICE-6  A percentage discount is rounded to the nearest cent (half a cent rounds up).
- PRICE-7  An unknown code is refused with "No coupon called <CODE>".
- PRICE-9  Shipping is free when the subtotal after the discount is $75.00 or more. Otherwise shipping is $4.99.
- PRICE-10 Total = subtotal - discount + shipping.
  1. A limit: test exactly $50.00 and one cent below.line 9
  2. After the discount: $80.00 with SAVE10 is $72.00, so shipping is charged.line 14
2

Write the oracle first

The rules as code, before you see any AI output.

An oracle tells you the expected result for any input. Write pricing.py from the story, in cents so there are no rounding surprises, then its tests. Writing it first matters: once you have read a model's confident table, it is hard not to copy its mistakes.

The tests pin the boundaries and two traps: SAVE10 at $80.00 still pays shipping, and 10% of $74.95 is 749.5 cents, which rounds up to $7.50.

pricing.py
"""The test oracle: ShopRung's coupon and shipping rules, written by the tester from the story (in cents)."""

COUPONS = {"SAVE10": ("percent", 10, 5000), "FLAT5": ("flat", 500, 2000)}
EXPIRED = {"WELCOME15"}
FREE_SHIPPING_FROM = 7500
SHIPPING = 499


def price(subtotal: int, code: str | None = None) -> dict:
    """Expected discount, shipping and total for a cart subtotal and an optional coupon code."""
    discount, refused = 0, None
    if code:
        code = code.strip().upper()                       # PRICE-2: not case-sensitive
        if code in EXPIRED:
            refused = "This coupon has expired"           # PRICE-5
        elif code not in COUPONS:
            refused = f"No coupon called {code}"          # PRICE-7
        else:
            kind, amount, minimum = COUPONS[code]
            if subtotal < minimum:
                refused = f"This coupon needs a subtotal of at least ${minimum / 100:.2f}"
            elif kind == "percent":
                discount = (subtotal * amount + 50) // 100   # PRICE-6: nearest cent, half up
            else:
                discount = amount
    shipping = 0 if subtotal - discount >= FREE_SHIPPING_FROM else SHIPPING   # PRICE-9
    return {"discount": discount, "shipping": shipping, "total": subtotal - discount + shipping, "refused": refused}
  1. $50.00 itself is allowed: the rule says "or more".line 20
  2. PRICE-6: half a cent rounds up, in whole cents.line 23
  3. PRICE-9 uses the subtotal after the discount.line 26
tests/test_pricing.py
import pytest

from pricing import price


@pytest.mark.parametrize("subtotal, code, discount, shipping, total", [
    (5000, "SAVE10", 500, 499, 4999),      # exactly $50.00
    (4999, "SAVE10", 0, 499, 5498),        # one cent below: refused
    (2000, "FLAT5", 500, 499, 1999),
    (1999, "flat5", 0, 499, 2498),         # lower case, below the minimum
    (7500, None, 0, 0, 7500),              # free shipping exactly at $75.00
    (7499, None, 0, 499, 7998),
    (8000, "SAVE10", 800, 499, 7699),      # $72.00 after the discount: shipping is charged
    (7495, "SAVE10", 750, 499, 7244),      # 749.5 cents rounds up to 750
])
def test_prices(subtotal, code, discount, shipping, total):
    p = price(subtotal, code)
    assert (p["discount"], p["shipping"], p["total"]) == (discount, shipping, total)


def test_refusal_messages():
    assert price(5000, "WELCOME15")["refused"] == "This coupon has expired"
    assert price(5000, "FREE100")["refused"] == "No coupon called FREE100"
    assert price(4999, "SAVE10")["refused"] == "This coupon needs a subtotal of at least $50.00"
Run
pytest -q tests/test_pricing.py
You should see
.........                                                                [100%]
9 passed in 0.01s
3

Ask the model for a draft

A prompt with the rules, the technique and the format.

Create generate.py. The prompt gives the model the story, asks for boundary value analysis (one case at each limit and one a cent below), demands exact amounts, tells it to put anything unclear under QUESTIONS instead of guessing, and fixes the CSV format with an example row. It saves each raw answer, so you review exactly what the model said.

With Ollama, run it three times. Each answer differs: the temperature is 0.7, as in most chat tools. Without Ollama, save the three real drafts below into drafts/ instead.

generate.py
"""Ask a local model (Ollama) for test cases for the story, and save each raw answer to drafts/.

    python generate.py --runs 3
"""
import argparse
import json
import os
import urllib.request
from pathlib import Path

OLLAMA = os.environ.get("OLLAMA_URL", "http://localhost:11434")
MODEL = os.environ.get("MODEL", "llama3.2:3b")

PROMPT = """You are a senior software tester. Write test cases for this user story.

{story}

Rules for your answer:
- Use boundary value analysis: for every limit, one case exactly at the limit and one a cent below it.
- Cover the expired coupon and an unknown code too.
- Every row has exact dollar amounts for discount, shipping and total. A refused coupon has discount $0.00.
- Use ONLY the acceptance criteria. Put anything unclear under QUESTIONS, never in a test case.
- Output a CSV with exactly this header, then a line QUESTIONS and one question per line:
id,rule,subtotal,coupon,discount,shipping,total

Example row:
TC-01,PRICE-4,$20.00,FLAT5,$5.00,$4.99,$19.99"""


def ask(prompt: str) -> str:
    body = {"model": MODEL, "messages": [{"role": "user", "content": prompt}], "stream": False,
            "options": {"temperature": 0.7, "num_predict": 1500}}
    req = urllib.request.Request(f"{OLLAMA}/api/chat", data=json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=300) as r:
        return json.load(r)["message"]["content"]


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--runs", type=int, default=1)
    args = parser.parse_args()
    prompt = PROMPT.format(story=Path("story.md").read_text())
    Path("drafts").mkdir(exist_ok=True)
    for run in range(1, args.runs + 1):
        out = Path(f"drafts/run-{run}.csv")
        out.write_text(ask(prompt))
        print(f"saved {out}")


if __name__ == "__main__":
    main()
  1. Name the technique, and say what it means.line 19
  2. Questions are useful output; guessed rules are not.line 22
  3. One example fixes the format better than a description.line 26
Run
python generate.py --runs 3
You should see
saved drafts/run-1.csv
saved drafts/run-2.csv
saved drafts/run-3.csv
4

Read a draft like a reviewer

Confident format, wrong numbers.

Here are the three drafts llama3.2:3b wrote in our run, unedited. They look professional: ids, rule numbers, dollar amounts, sensible questions. Now check a few rows against the story yourself before running any script.

Run 1, TC-02: SAVE10 at $49.99, below its limit, with a $9.50 discount and free shipping. Run 1, TC-08: the error message sits in the total column. Run 2's totals for carts with no discount are lower than their subtotals. Run 3 gives a $49.95 cart a $9.96 discount and a total above the subtotal. Save them as drafts/llama3.2-run-1.csv, -2 and -3.

drafts/llama3.2-run-1.csv
Here are the test cases for the user story:

```
id,rule,subtotal,coupon,discount,shipping,total
TC-01,PRICE-2,$0.00,,$0.00,$4.99,$4.99
TC-02,PRICE-3,$49.99,SAVE10,$9.50,$0.00,$39.49
TC-03,PRICE-3,$50.00,SAVE10,$9.50,$0.00,$40.50
TC-04,PRICE-4,$19.99,FLAT5,$5.00,$4.99,$14.98
TC-05,PRICE-4,$20.00,FLAT5,$5.00,$4.99,$15.00
TC-06,PRICE-5,$0.00,WELCOME15,$0.00,$0.00,$0.00
TC-07,PRICE-6,$49.99,SAVE10,$9.50,$0.01,$39.48
TC-08,PRICE-7,$0.00,UNKNOWN,,$0.00,$No coupon called XXXXX
TC-09,PRICE-9,$74.99,,$0.00,$0.00,$74.99
TC-10,PRICE-9,$75.00,,$0.00,$0.00,$75.00
```

QUESTIONS

1. How is the discount applied when the subtotal is exactly $50.00?
2. What happens if an unknown coupon code is entered?
3. Is the shipping cost calculated correctly for orders with a subtotal of $74.99?
4. Can the total be rounded to half a cent (e.g., $0.01 vs. $0.005)?
5. How does the system handle expired coupons when the order is processed?
drafts/llama3.2-run-2.csv
Here are the test cases based on the acceptance criteria:

id,rule,subtotal,coupon,discount,shipping,total
TC-01,PRICE-2,$50.00,,$0.00,$4.99,$45.97
TC-02,PRICE-2,$49.99,,$0.00,$4.99,$44.98
TC-03,PRICE-3,$50.00,SAVE10,$5.00,$4.99,$39.99
TC-04,PRICE-3,$40.00,SAVE10,$0.00,$4.99,$35.99
TC-05,PRICE-4,$20.00,FLAT5,$5.00,$4.99,$19.99
TC-06,PRICE-4,$21.01,FLAT5,$5.00,$4.99,$24.98
TC-07,PRICE-5,$0.00,WELCOME15,,$0.00,$0.00
TC-08,PRICE-5,$1.00,WELCOME15,,$0.00,$0.00
TC-09,PRICE-7,$100.01,UNKNOWN,,,$4.99,$103.98
TC-10,PRICE-7,$0.00,UNKNOWN,,,$4.99,$4.99
TC-11,PRICE-9,$75.00,,$0.00,$0.00,$75.00
TC-12,PRICE-9,$74.99,,$0.00,$4.99,$74.98
TC-13,PRICE-10,$50.00,SAVE10,$5.00,$4.99,$39.99
TC-14,PRICE-10,$20.00,FLAT5,$5.00,$4.99,$19.99

QUESTIONS:
1. Does the system allow a coupon to be used multiple times per order?
2. Is the discount for a valid coupon code rounded correctly to the nearest cent?
3. How is an expired coupon handled in terms of error message and outcome?
drafts/llama3.2-run-3.csv
Here are the test cases for the user story:

```
id,rule,subtotal,coupon,discount,shipping,total
TC-01,PRICE-3,$49.99,SAVE10,$0.00,$4.99,$50.00
TC-02,PRICE-3,$49.98,SAVE10,$0.00,$4.99,$50.00
TC-03,PRICE-6,$49.95,SAVE10,$9.96,$4.99,$59.90
TC-04,PRICE-2,$20.00,FLAT5,$0.00,$4.99,$24.99
TC-05,PRICE-4,$19.99,FLAT5,$0.00,$4.99,$23.98
TC-06,PRICE-9,$74.99,*,$0.00,$0.00,$74.99
TC-07,PRICE-9,$74.98,*,$0.00,$0.00,$74.98
TC-08,PRICE-7,*,NO_COUPON, $0.00,$4.99,$4.99
TC-09,PRICE-5,$20.01,SAVE10,$0.00,$4.99,$24.99
TC-10,PRICE-5,$75.00,SAVE10,$0.00,$0.00,$75.00
```

QUESTIONS

1. Is the discount for FLAT5 calculated as $4.99 when the subtotal is exactly $20.00?
2. Is the shipping cost free when the subtotal after the discount is exactly $75.00 or more?
3. Are unknown coupon codes correctly refused with "No coupon called <CODE>"?
4. Is the total calculation accurate for expired coupons (e.g., SAVE10 with a value of $0.00)?
5. Does rounding of percentage discounts to the nearest cent occur as expected?
5

Review every row with the oracle

Wrong values, untraceable rows, missing boundaries.

Create review.py and its tests. It finds the CSV inside the model's chatter, then for every row: does the rule id exist, and do discount, shipping and total match the oracle? Finally it lists the boundaries the story needs that no row covers. It exits 1 if anything is wrong, so it can gate a pull request.

Run it on the three drafts. Together: 34 rows, 5 correct, 28 wrong, 1 untraceable, and 6 required boundaries missing. Note that run 1 covered every boundary and was still 80% wrong: coverage of the right inputs says nothing about the expected results.

review.py
"""Check AI-drafted test cases against the oracle: wrong values, rows without a rule, and missing boundaries.

    python review.py drafts/run-1.csv
"""
import csv
import io
import re
import sys
from pathlib import Path

from pricing import price

RULES = {f"PRICE-{n}" for n in range(2, 11)}
# The boundaries the story needs, as (coupon, subtotal in cents). None = no coupon.
REQUIRED = {
    ("SAVE10", 5000): "SAVE10 exactly at $50.00", ("SAVE10", 4999): "SAVE10 one cent below $50.00",
    ("FLAT5", 2000): "FLAT5 exactly at $20.00", ("FLAT5", 1999): "FLAT5 one cent below $20.00",
    (None, 7500): "no coupon at $75.00 (free shipping)", (None, 7499): "no coupon at $74.99 (shipping $4.99)",
    ("WELCOME15", None): "the expired WELCOME15", ("UNKNOWN", None): "an unknown code",
}


def cents(text: str) -> int | None:
    m = re.search(r"-?\$?\s*(\d+(?:\.\d{1,2})?)", text or "")
    return round(float(m.group(1)) * 100) if m else None


def rows_from(draft: str) -> list[dict]:
    """The CSV part of a model's answer: from the header line to the first blank line or QUESTIONS."""
    lines = draft.replace("```csv", "").replace("```", "").splitlines()
    start = next((i for i, l in enumerate(lines) if l.strip().lower().startswith("id,")), None)
    if start is None:
        return []
    body = []
    for line in lines[start:]:
        if not line.strip() or line.strip().upper().startswith("QUESTIONS"):
            break
        body.append(line)
    return list(csv.DictReader(io.StringIO("\n".join(body))))


def review(draft: str) -> dict:
    report = {"ok": [], "wrong": [], "untraceable": [], "covered": set()}
    for row in rows_from(draft):
        rid, rule = (row.get("id") or "?").strip(), (row.get("rule") or "").strip().upper()
        sub, coupon = cents(row.get("subtotal")), (row.get("coupon") or "").strip().upper() or None
        if rule not in RULES or sub is None:
            report["untraceable"].append(f"{rid}: rule {rule or '-'}, subtotal {row.get('subtotal')!r}")
            continue
        p = price(sub, coupon)
        key = coupon if coupon in (None, "SAVE10", "FLAT5", "WELCOME15") else "UNKNOWN"
        report["covered"] |= {(key, sub), (key, None)}
        problems = []
        for field in ("discount", "shipping", "total"):
            got = cents(row.get(field))
            if got is None or got != p[field]:
                problems.append(f"{field} {row.get(field)!r}, expected ${p[field] / 100:.2f}")
        (report["wrong"] if problems else report["ok"]).append(f"{rid} {rule} ${sub / 100:.2f} {coupon or '-'}: " + ("; ".join(problems) or "ok"))
    report["missing"] = [name for key, name in REQUIRED.items() if key not in report["covered"]]
    return report


def main() -> None:
    r = review(Path(sys.argv[1]).read_text())
    total = len(r["ok"]) + len(r["wrong"]) + len(r["untraceable"])
    print(f"{total} rows: {len(r['ok'])} correct, {len(r['wrong'])} wrong, {len(r['untraceable'])} untraceable")
    for line in r["wrong"]:
        print("WRONG      ", line)
    for line in r["untraceable"]:
        print("UNTRACEABLE", line)
    for name in r["missing"]:
        print("MISSING    ", name)
    sys.exit(1 if r["wrong"] or r["untraceable"] or r["missing"] else 0)


if __name__ == "__main__":
    main()
  1. The boundaries from the story, decided by you, not the model.line 15
  2. Models wrap CSV in prose and code fences; take only the table.line 28
  3. Every amount is checked against the oracle.line 50
  4. Non-zero exit: usable as a CI gate.line 73
tests/test_review.py
from review import review

HEADER = "id,rule,subtotal,coupon,discount,shipping,total"


def test_a_correct_row_passes():
    r = review(f"{HEADER}\nTC-1,PRICE-3,$50.00,SAVE10,$5.00,$4.99,$49.99")
    assert r["ok"] and not r["wrong"]


def test_a_wrong_discount_is_reported():
    r = review(f"{HEADER}\nTC-1,PRICE-3,$50.00,SAVE10,$2.50,$4.99,$52.49")
    assert r["wrong"] == ["TC-1 PRICE-3 $50.00 SAVE10: discount '$2.50', expected $5.00; total '$52.49', expected $49.99"]


def test_a_row_without_a_known_rule_is_untraceable():
    r = review(f"{HEADER}\nTC-1,PRICE-99,$50.00,SAVE10,$5.00,$4.99,$49.99")
    assert r["untraceable"] == ["TC-1: rule PRICE-99, subtotal '$50.00'"]


def test_missing_boundaries_are_listed():
    r = review(f"{HEADER}\nTC-1,PRICE-3,$50.00,SAVE10,$5.00,$4.99,$49.99")
    assert "SAVE10 one cent below $50.00" in r["missing"]
    assert "SAVE10 exactly at $50.00" not in r["missing"]


def test_text_around_the_csv_is_ignored():
    draft = f"Here are the cases:\n```csv\n{HEADER}\nTC-1,PRICE-4,$20.00,FLAT5,$5.00,$4.99,$19.99\n```\nQUESTIONS\nNone"
    assert len(review(draft)["ok"]) == 1
Run
pytest -q tests
for n in 1 2 3; do python review.py drafts/llama3.2-run-$n.csv; done
You should seeyour text will differ: the model writes it
14 passed in 0.01s
10 rows: 2 correct, 8 wrong, 0 untraceable
WRONG       TC-02 PRICE-3 $49.99 SAVE10: discount '$9.50', expected $0.00; shipping '$0.00', expected $4.99; total '$39.49', expected $54.98
...
14 rows: 3 correct, 11 wrong, 0 untraceable
...
MISSING     SAVE10 one cent below $50.00
MISSING     FLAT5 one cent below $20.00
10 rows: 0 correct, 9 wrong, 1 untraceable
...
UNTRACEABLE TC-08: rule PRICE-7, subtotal '*'
MISSING     SAVE10 exactly at $50.00
...
6

Keep the good parts, write the rest

A reviewed case list that passes.

What was worth keeping from the drafts? The inputs (run 1 chose every required boundary) and some questions (all three asked about rounding or the expired coupon). The expected results had to be recomputed. Write cases.csv from the oracle, add the traps the model missed (SAVE10 at $80.00, the $74.95 rounding case, a lower-case code) and answer the questions from the story where it can.

Review it: 11 rows, all correct, nothing missing, exit 0. This file, not the model's draft, is what goes into your test management tool or drives an API suite.

cases.csv
id,rule,subtotal,coupon,discount,shipping,total
TC-01,PRICE-3,$50.00,SAVE10,$5.00,$4.99,$49.99
TC-02,PRICE-3,$49.99,SAVE10,$0.00,$4.99,$54.98
TC-03,PRICE-4,$20.00,FLAT5,$5.00,$4.99,$19.99
TC-04,PRICE-4,$19.99,FLAT5,$0.00,$4.99,$24.98
TC-05,PRICE-9,$75.00,,$0.00,$0.00,$75.00
TC-06,PRICE-9,$74.99,,$0.00,$4.99,$79.98
TC-07,PRICE-9,$80.00,SAVE10,$8.00,$4.99,$76.99
TC-08,PRICE-6,$74.95,SAVE10,$7.50,$4.99,$72.44
TC-09,PRICE-5,$60.00,WELCOME15,$0.00,$4.99,$64.99
TC-10,PRICE-7,$60.00,FREE100,$0.00,$4.99,$64.99
TC-11,PRICE-2,$50.00,save10,$5.00,$4.99,$49.99
QUESTIONS
Does free shipping use the subtotal before or after the discount? (PRICE-9 says after: TC-07)
Can a second coupon replace the first, or is it refused? (PRICE-2 says only one per order)
  1. The model never produced this trap: $72.00 after the discount pays shipping.line 8
  2. PRICE-2: codes are not case-sensitive.line 12
Run
python review.py cases.csv
You should see
11 rows: 11 correct, 0 wrong, 0 untraceable

Check it works

pytest -q tests passes: the oracle and the reviewer are tested.

python review.py cases.csv reports 11 correct and exits 0; every llama3.2 draft exits 1.

Test
pytest -q tests
python review.py cases.csv
You should see
14 passed in 0.01s
11 rows: 11 correct, 0 wrong, 0 untraceable

Troubleshooting

urllib.error.URLError: Connection refused from generate.py.

Ollama is not running. Start the Ollama app, or ollama serve, and check ollama list shows llama3.2:3b.

review.py says "0 rows".

The draft has no line starting with id,. The model ignored the format; ask again, or fix the header by hand and review the rows.

Your own drafts score differently from ours.

Expected: the temperature is 0.7, so every run differs. Review each draft; never trust one because a previous one was good.

A row you believe is right is reported WRONG.

Check the oracle against the story first, then against ShopRung by hand. If the oracle is wrong, fix it and add a test for that case.

What changes in production

  • Teams use AI to draft test ideas and inputs, and keep expected results tied to requirements or an oracle.
  • Review scripts like this run in CI on test-data files, so a pasted AI table cannot merge with wrong amounts.
  • Every kept case carries a requirement id, which makes coverage and impact analysis possible.
  • Private stories and data go to a local model, as here, not to a cloud service, unless policy allows it.

Interview angle

โ€œWould you use AI to write test cases from a user story?โ€

For drafts, yes; never as the source of expected results. In a real run, a small local model produced three tidy drafts: 34 rows, only 5 with correct amounts, and one draft missed four required boundaries. I write an oracle from the acceptance criteria first, review every row with a script that checks amounts, rule ids and boundaries, keep the useful inputs and questions, and recompute the rest. The reviewed list, with requirement ids, is what we keep.

Clean up

Practice

These run in your browser and check your answer.

Expected shipping

Write shipping(subtotal, discount) in cents: free (0) when the subtotal after the discount is 7500 or more, otherwise 499.

Exercise
def shipping(subtotal, discount):
    return 0 if subtotal >= 7500 else 499
Hint

PRICE-9 compares the subtotal after the discount.

The full project

Every file from this lab, as it is after the last step.

Download Python project (.zip)