Test oracles for LLM features

Study time
≈ 3 h (estimate)
Needs
L1-M02-L02, L1-M03-L05
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M04 · Duration: ~165 min (estimate, including the independent exercise) · Previous: L1-M03-L05 · Next: L02 - Negative and boundary inputs (empty, very long, mixed language, malformed)

1. Introduction

Every test has to answer one question: is this output right or wrong? Whatever gives that answer is called the test oracle. For ordinary software, the oracle is often very simple: assert total == 150000. For an LLM feature, the same question can have dozens of correct answers worded differently, so assert answer == "..." is usually the wrong approach.

This lesson teaches you to choose the right kind of oracle for each requirement: an exact match where the output is decided by code, a property check where the wording may change, a comparison against reference facts where the content must be correct, and a hand-off to a person where a machine cannot decide. It also teaches something that is often skipped: testing the oracle itself, because a wrong oracle gives a wrong pass or a wrong fail, and nobody notices.

The whole module tests ShopEasy Assistant (fictional, simulated). It is the customer-care assistant of ShopEasy, the shop you met in L1-M01.

2. Learning objectives

  1. Explain what a test oracle is and why the "oracle problem" is harder for LLM features.
  2. Distinguish four kinds of oracle: exact, rule, reference, human, with the strengths and weaknesses of each.
  3. Choose a suitable oracle for each clause of a product contract.
  4. Implement a test that uses several oracles for one answer and read the PASS/FAIL/REVIEW verdict.
  5. Verify an oracle with samples known to be good and samples known to be bad.

3. Prerequisites and tools

  • L1-M02-L02: deterministic checks (must_not_contain, sentence counting). This lesson generalises those checks.
  • L1-M03: pytest, fixtures, parametrize.
  • The code lab code-labs/l1-m04, installed as described in the lab's README. No API key is needed.

4. Concepts

4.1 Test oracles and the oracle problem

A test oracle is the mechanism that decides whether the output of a system for a given input is acceptable or not. The survey by Barr and colleagues calls this challenge the test oracle problem: "Given an input for a system, the challenge of distinguishing the corresponding desired, correct behaviour from potentially incorrect behavior is called the 'test oracle problem'" [R1].

For LLM features, the problem is harder in three ways:

  • Many correct answers. "You can return items within 30 days" and "The return period is 30 days" are both correct.
  • Output changes between runs (L1-M01-L03). An oracle that matches the whole sentence fails at random.
  • Some properties need a human judge: is the tone empathetic, is the answer helpful.

Everyday example. Marking a multiple-choice test only means comparing each question with one correct letter (A, B, C or D). Marking an essay is different: there is no single "right" essay, so the teacher uses a marking scheme (points that must appear, mistakes that must not) and sometimes has to read for style. Testing an LLM feature is closer to marking an essay: the oracle is your marking scheme.

4.2 The four kinds of oracle in this module

Kind The question it answers ShopEasy example Strengths Weaknesses
Exact Is the value exactly the expected value? intent == "handoff"; the order status taken from the system Clear, unambiguous Usable only where the output is decided by code or data
Rule (property) Does every acceptable answer have this property? No links outside shopeasy.example; the answer is in Vietnamese Independent of wording Catches only what it checks; can reach the wrong verdict (false pass/false fail, §4.4)
Reference (reference facts) Are the key facts of the model answer present? Contains "30 ngày" and "kể từ ngày nhận hàng" ("ngày" = days; "kể từ ngày nhận hàng" = from the date of receipt) Checks content while still allowing different wording The list of facts may be incomplete; string matching does not understand meaning
Human Would a person accept this answer? The tone with an upset customer Can judge quality Slow, costly, graders may be inconsistent

In the lab, the human oracle returns the verdict REVIEW: the test does not decide on its own but passes the case to a person. Level 2 adds oracles based on semantic similarity and LLM-as-judge. This module uses only oracles that you control and can explain.

Everyday example. A café manager checks an iced milk coffee before it goes out: the price on the receipt must be right to the last đồng (exact); every glass must have ice and no hair in it (rule); the glass must contain coffee and milk, even if the ratio varies a little each time (reference); and "does it taste good" needs someone to taste it (human). Nobody uses one check for all four.

4.3 Choosing an oracle per clause

A practical rule: use the strictest oracle the clause allows.

  1. Which part of the output is decided by code or data (intent, order number, status, a fixed sentence in the contract)? Use exact.
  2. Which part is a property that every correct answer has (language, links, length, no leaked secrets)? Use rule.
  3. Which part is content that must be correct but may be worded differently (policies, figures)? Use reference.
  4. The rest (tone, helpfulness, appropriateness)? Use human, and write down the question for the grader.

A clause often needs several oracles. Clause C3 (the returns policy) needs: exact for the intent, reference for the two facts, and rule for "states no other time limit".

Worked example: a false fail caused by the wrong oracle. A tester writes a test for an English question about returns by copying the oracles of the Vietnamese question and only translating the fact. Save the code below as vd_l01.py in the lab folder and run python vd_l01.py:

from lab import oracles as O
from lab.shopeasy import make_assistant

reply = make_assistant("v1").reply("What is the refund policy?")
print(reply)
verdict, results = O.evaluate(reply, [O.exact("intent", "refund_policy"),
                                      O.facts("30 days"), O.language("vi")])
print(verdict)
for r in results:
    print(" ", r.verdict, r.oracle, r.message)

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions give identical output):

{'intent': 'refund_policy', 'answer': 'You can return items within 30 days of delivery. Details: https://help.shopeasy.example/returns'}
FAIL
  PASS exact(intent='refund_policy') 
  PASS facts('30 days',) 
  FAIL language(vi) answer looks en
  1. exact(intent=...) PASS: the part decided by code is right.
  2. facts('30 days',) PASS: the key fact is present.
  3. language(vi) FAIL with the message answer looks en. But C5 says a question written entirely in English gets an English answer. The product is right and the oracle is wrong: this is a false fail (§4.4). Fix it to O.language("en").

Lesson: when a case FAILs, read the oracle's message and check the clause again before you report a bug.

4.4 Oracles can be wrong too

An oracle is code, so it has bugs. There are two kinds of error:

  • False pass: the oracle lets a wrong answer through. Example: checking that the answer contains "30" lets "300 days" through.
  • False fail: the oracle rejects a correct answer. Example: matching the whole sentence exactly rejects a sentence that is worded differently but still correct.

So before you trust an oracle, run it on samples known to be good (must PASS) and samples known to be bad (must FAIL). This is the "test the test" you already met in L1-M02.

Worked example: good and bad samples. Compare a weak oracle (contains_all("30")) with the C3 oracle on three hand-written answers, run from the lab folder as in the example in §4.3:

from lab import oracles as O
weak = O.contains_all("30")
strong = O.facts("30 ngày", "kể từ ngày nhận hàng")
for answer in ("Đổi trả trong 30 ngày kể từ ngày nhận hàng.",
               "Đổi trả trong 300 ngày kể từ ngày nhận hàng.",
               "Đổi trả trong 130 ngày kể từ ngày nhận hàng."):
    r = {"answer": answer}
    print(f"weak={weak(r).verdict:4}  strong={strong(r).verdict:4}  {answer}")

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions give identical output):

weak=PASS  strong=PASS  Đổi trả trong 30 ngày kể từ ngày nhận hàng.
weak=PASS  strong=FAIL  Đổi trả trong 300 ngày kể từ ngày nhận hàng.
weak=PASS  strong=PASS  Đổi trả trong 130 ngày kể từ ngày nhận hàng.
  • Line 1: a good sample, both oracles PASS. As expected.
  • Line 2: the weak oracle lets "300 ngày" (three hundred days) through (false pass). The facts oracle catches it.
  • Line 3: both let "130 ngày" through, because the string "130 ngày" contains "30 ngày". Even the better oracle still has a false pass. Only a bad sample chosen on purpose exposes this gap. The extra exercise in §9.2 closes it.

Good vs bad.

Weak way to verify an oracle Good way
Run the oracle on the product's real output and trust it if it is green Run the oracle on a table of known samples: at least one good sample must PASS, and each kind of error you worry about (missing fact, wrong number, look-alike number) has a sample that must FAIL

Why: real output only shows how the oracle behaves on today's answer. The sample table shows how it behaves on wrong answers you have not met yet.

Common misconception: "The looser the oracle, the fewer tests fail, the better." Fewer failures does not mean fewer defects: a loose oracle only hides them.

5. Technical deep dive

5.1 The product contract

Every oracle in the module is based on the contract C1-C12 at the top of the file lab/shopeasy.py. For example:

  • C1: reply(message, docs=None) returns {"intent": str, "answer": str}.
  • C2: the order status comes from the order system: "Đơn SE1001: đang giao."; order numbers are case-insensitive.
  • C3: a Vietnamese answer must contain "30 ngày" and "kể từ ngày nhận hàng", and must not state another time limit.

The contract covers a structured answer (intent) and free text (answer). Many real chatbots do the same. The structured part gives you a place to use an exact oracle.

Everyday example. A contract is like the priced menu of a phở shop: "rare beef phở 50,000 dong, with spring onion, no MSG on request". When the bowl arrives, you can complain about what the menu promised (wrong price, no spring onion). "The broth is a bit bland" is not on the menu, so it is feedback, not a breach. Testers work with C1-C12 the same way: every expectation must point to the clause it comes from.

5.2 The oracles in lab/oracles.py

Each oracle is a function that takes reply and returns Result(verdict, oracle, message):

Function Kind Notes
exact(field, expected) exact Compares one field
contains_all(*phrases), contains_none(*phrases) rule Compares after bringing both to the same Unicode form (NFC) and lower case
language("vi" | "en") rule A heuristic based on Vietnamese diacritics. Cannot tell Vietnamese written without diacritics from English
only_links_to(*domains) rule Every link and email must belong to an allowed domain, subdomains included
not_leaking(*secrets) rule Ignores spaces, hyphens and upper case, so it still catches a secret that has been rewritten (used in L04)
facts(*required) reference Each fact is a string or a tuple of accepted spellings
human(question) human Always returns REVIEW with the question for the grader

evaluate(reply, oracles) combines the results: any FAIL makes the case FAIL; no FAIL but a REVIEW makes it REVIEW; otherwise PASS. An empty list of oracles raises an error, because a case without oracles checks nothing at all (fail closed, as in L1-M02).

Good vs bad. The same check for C3, written two ways:

Weak Good
assert "30 ngày" in reply["answer"] O.evaluate(reply, [O.exact("intent", "refund_policy"), O.facts("30 ngày", "kể từ ngày nhận hàng"), O.contains_none("60 ngày", "90 ngày")])
A failure only says AssertionError; you cannot tell what is missing; NFD text makes it fail wrongly Every oracle has a name and a message (missing facts [...]); comparison after NFC and lower case

Why: a failing test must say which oracle failed and why (§6).

5.3 The Python you need for this lesson

  • Functions that return functions. exact("intent", "handoff") does not check anything right away. It returns a function check, and that function does the check when it is called with reply. This lets you declare the list of oracles first and apply them later.
  • *phrases accepts any number of arguments and collects them into a tuple: contains_all("a", "b") gives phrases == ("a", "b").

Everyday example. A function that returns a function is like a printed checklist at a cashier's desk. The manager prints the "check the change given back to the customer" sheet once (creating the oracle). The cashier uses that sheet for every receipt of the day (calling the oracle with each reply). Printing the sheet checks nothing yet: the check happens only when there is a receipt.

6. The QA perspective

  • What to test: every clause of the contract has at least one oracle; every oracle has at least one good sample and one bad sample.
  • What can go wrong: an oracle that is too loose (false pass), too strict (false fail), or checks the wrong thing (for example, checking a keyword when the clause is about meaning).
  • The biggest risk: a green test suite built on oracles that have never been verified.
  • How to report: when a case FAILs, state which oracle failed and its message. "Test failed" without naming the oracle leaves whoever fixes it guessing.
  • REVIEW is not PASS. Count the REVIEW cases separately in the report, and assign someone responsible for grading them.

7. Real-world scenarios

Scenario 1 (fictional): a number that is almost right. A team testing a banking chatbot checks the interest rate with "5" in answer. The model answers "the interest rate is 0.5%" and the test still passes. A reference oracle with the fact "5%" together with the rule contains_none("0,5%") would catch it. The lesson: for numbers, check the unit as well as the values that are easy to confuse.

Scenario 2 (fictional): a fixed sentence gets reworded. The contract of a health app requires a fixed disclaimer sentence. The team uses contains_all for the whole sentence. After a model change, the sentence is paraphrased and 300 tests fail at once. This is correct: the sentence is legal text, so an exact oracle is the right choice, and the defect is in the product, not in the test. The lesson: a strict oracle is right when the requirement is strict.

8. Hands-on tutorial

8.1 Running the demo

cd academy-content/code-labs/l1-m04
python -m lab.demo l01

Output (copied from a real run, 2026-10-31):

PASS   Đơn SE1001 sao rồi?
       PASS   exact(intent='order_status') 
       PASS   contains_all('Đơn SE1001: đang giao',) 
PASS   Chính sách hoàn tiền thế nào?
       PASS   exact(intent='refund_policy') 
       PASS   facts('30 ngày', 'kể từ ngày nhận hàng') 
       PASS   language(vi) 
       PASS   only_links_to('shopeasy.example',) 
REVIEW Cho tôi gặp nhân viên, tôi đang rất bực
       PASS   exact(intent='handoff') 
       REVIEW human Câu trả lời có thể hiện sự đồng cảm phù hợp không?

Test the oracle itself (known-good and known-bad answers):
  PASS   Đổi trả trong 30 ngày kể từ ngày nhận hàng.
  FAIL   Đổi trả trong 30 ngày.
  FAIL   Đổi trả trong 3 ngày kể từ ngày nhận hàng.

In English: the first message asks for the status of the order shown, the second reads "What is the refund policy?" and the third "Let me talk to a staff member, I am very annoyed"; the human question reads "Does the answer show appropriate empathy?"; the last three lines are a complete returns answer, the same answer without "kể từ ngày nhận hàng", and an answer with the wrong number of days.

Reading the output:

  • The third case has the right intent but is still REVIEW: a machine cannot decide whether the answer is empathetic.
  • The last three lines verify the facts oracle: the good sample PASSes, the sample missing a fact FAILs, and the "3 ngày" sample FAILs. The "3 ngày" sample matters: it proves the oracle does not let a near-identical number through.

8.2 Running the tests

python -m pytest tests/test_l01_oracles.py -v

Expected result: every test PASSes. Read test_contains_none_known_limit_substring: it records a limitation of the string oracle ("90 ngày" is found inside "190 ngày"). Recording a limitation as a test is how you stop the next person from "fixing" it by mistake, and how you know when a better oracle is needed.

8.3 Troubleshooting

Symptom Common cause Fix
ModuleNotFoundError: No module named 'lab' Running outside the lab folder cd academy-content/code-labs/l1-m04
ValueError: a case with no oracles verifies nothing Calling evaluate with an empty list Add at least one oracle
contains_all fails even though you can see the phrase Different punctuation or whitespace Print repr(reply["answer"]) to see the actual characters

9. Independent exercise

9.1 Main exercise

Problem: You have been asked to write oracles for three requirements.

Requirements: complete exercises/test_l01_oracle_choice.py:

  1. TODO 1 (C2): an order number that does not exist. Choose the strictest oracle that C2 allows.
  2. TODO 2 (C3 + C5): an English question about returns. Check the language and the facts in English.
  3. TODO 3: test the oracle only_links_to("shopeasy.example") itself with one valid link (must PASS) and two spoofed links you invent yourself (must FAIL), different from the two kinds already in tests/test_l01_oracles.py.
  4. Write a short table: for each clause C2, C3, C5, C8, which oracle you choose and why.

Test data: v1; "Đơn SE9999 đâu?"; "What is the refund policy?".

Deliverable: the completed test file and the oracle-choice table.

Acceptance criteria: python -m pytest exercises/test_l01_oracle_choice.py passes; TODO 3 has two different kinds of spoofing; the table gives a reason for each choice.

Hint: C2 gives you the answer word for word. For TODO 3, think about how an attacker makes a domain look like shopeasy.example.

9.2 Extra exercise: a "30 days only" oracle (15-30 minutes)

Problem: In §4.4, facts("30 ngày") still lets "130 ngày" through. C3 also forbids stating any other period, but a fixed list such as contains_none("60 ngày", "90 ngày") only catches the numbers you thought of.

Requirements: in exercises/test_l01_extra_period_oracle.py, write the function only_30_days(reply). It returns PASS when the answer states "30 ngày" and no other number of days; it returns FAIL, with a message saying what it found, in every other case. Compare on O.norm(reply["answer"]) so that capitals and NFD do not matter.

Run: python -m pytest exercises/test_l01_extra_period_oracle.py. Until you do the work, every test fails with TODO: implement only_30_days().

Acceptance criteria: 11 tests pass: the 7 known samples in the KNOWN table, the NFD form of a good answer, a FAIL message that contains the number found, v1's real answer PASSes, and v1's answer with the help article carrying an injected instruction (case INJ-03 from L04) FAILs.

Hint: re.findall(r"(\d+)\s*ngày", text) returns every number right before the word "ngày". Ask yourself: does an answer with no number of days PASS or FAIL? Read C3 again.

9.3 Real-world scenario: oracles for a food-delivery assistant

Context (fictional): The food-delivery app NhanhNhanh adds a chat assistant. The product owner sends you five requirements:

  1. When a customer asks about the delivery fee, the assistant states the exact amount computed by the system (for example 15,000 dong).
  2. The estimated delivery time is given as a range of minutes, never as an exact clock time.
  3. The assistant sends no link outside nhanhnhanh.example.
  4. When a dish is sold out, the assistant suggests at least one alternative from the same restaurant.
  5. When a customer complains that the food arrived cold, the assistant apologises sincerely.

Your task: write a five-row table with: the requirement, the kind of oracle (exact, rule, reference, human), the concrete check, and one bad sample the oracle must FAIL. Add one question for the product owner about something still ambiguous.

A good answer has:

  • Every requirement has at least one oracle, following "the strictest oracle the requirement allows" (§4.3).
  • Requirement 1 uses exact against the amount from the system (not a number copied by hand), with a bad sample such as "1,500 dong" or "150,000 dong".
  • Requirement 5 uses a human oracle with a clear question for the grader, not shrunk into a rule such as "contains the word sorry".
  • Every oracle has a concrete bad sample (§4.4).
  • At least one question for the product owner, for example: how wide may the range of minutes be?

10. Knowledge check

0/18 done · Results are kept in this browser only.

P02 · True or false

A test suite with no FAIL cases proves that the oracles are correct.

P03 · Short answer

How do an oracle's false pass and false fail differ? Give one example of each.

P04 · Short answer

Why must REVIEW be counted separately and not added to PASS?

P05 · Short answer

(Scenario) A colleague proposes checking C3 with "30" in answer. Give two wrong answers that this oracle lets through, and propose a replacement oracle.

P06 · Match

Following the table in §4.2, match each kind of oracle with its ShopEasy example.

P08 · Multiple choice

In the demo in §8.1, why does the sample "Đổi trả trong 3 ngày kể từ ngày nhận hàng." matter when verifying the facts oracle?

P09 · True or false

contains_none("90 ngày") gives PASS for the answer "Hạn 190 ngày".

P10 · Spot the bug

The allowed function below is copied from only_links_to in lab/oracles.py but has one defect. Find it.

def allowed(host):
    host = host.lower().rstrip(".")
    return any(host == d or host.endswith(d) for d in domains)

P11 · Recall

Lesson: L1-M03-L05

L1-M03-L05: when a request is not in the cassette, what does ReplayClient do?

P12 · Put in order

Following §4.3, put the questions for choosing an oracle for a clause in order, from strictest to loosest.

  1. Which part is a property that every correct answer has? Use rule
  2. Which part is decided by code or data? Use exact
  3. Which part is content that must be correct but may be worded differently? Use reference
  4. The rest? Use human, and write down the question for the grader

P13 · Select all that apply

According to "What to test" in §6, what does the set of oracles for a contract need? Select every correct option.

P15 · Multiple choice

In the worked example in §4.4, why does facts("30 ngày", "kể từ ngày nhận hàng") PASS "Đổi trả trong 130 ngày kể từ ngày nhận hàng."?

P16 · True or false

In the example in §4.3, the case FAILs because the tester chose the wrong oracle language("vi"), not because v1 violates C5.

P17 · Select all that apply

According to §9.2, which answers must FAIL with the oracle only_30_days? Select every correct option.

P18 · Apply now

In code-labs/l1-m04, do the extra exercise §9.2 in exercises/test_l01_extra_period_oracle.py, then run python -m pytest exercises/test_l01_extra_period_oracle.py.

Checklist

11. Summary

  • Concepts: test oracle, the oracle problem; the four kinds of oracle; choosing the strictest oracle the requirement allows; false pass/false fail; testing the oracle itself.
  • Skills: assigning an oracle to each clause; using several oracles for one case; reading the PASS/FAIL/REVIEW verdict.
  • Pitfalls: matching whole sentences of free text; checking a number without checking its unit; trusting an oracle that has not been verified; treating REVIEW as PASS.
  • You can now: write oracles for the product contract of an LLM feature and prove that those oracles work.

12. References

ID Title Publisher URL Accessed Relevance
R1 The Oracle Problem in Software Testing: A Survey (Barr, Harman, McMinn, Shahbaz, Yoo), IEEE TSE 41(5):507-525, 2015, DOI 10.1109/TSE.2014.2372785 IEEE https://doi.org/10.1109/TSE.2014.2372785 2026-10-31 Definition of the test oracle problem (quoted from the PDF hosted on a University of Michigan course page)

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Test oracle Cơ chế quyết định output đúng hay sai
Exact / rule / reference / human oracle Oracle so khớp chính xác / tính chất / dữ kiện tham chiếu / người chấm
False pass / false fail Cho qua nhầm / đánh rớt nhầm
Product contract Hợp đồng hành vi của sản phẩm
Verdict Kết luận của test (PASS/FAIL/REVIEW)