# Testing LLMs without an answer key, using nothing but pytest

> You may not know the right answer, but you can still know how two answers must relate, and that is enough to test on unlabeled client data.

Original: https://fdetimes.net/en/guides/metamorphic-testing-llms-pytest/

Thinking Machines Lab once sent the same prompt 1,000 times to Qwen3-235B-A22B-Instruct-2507 at temperature 0 and got back 80 different completions. The most common answer appeared only 78 times.

Anthropic's official glossary also states plainly that setting temperature to 0 does not make results deterministic, so the same input can produce different outputs across API calls.

That means a test of the form `assert output == expected` is almost guaranteed to be flaky. On a client site there is a second problem: there is usually no answer key at all. You inherit a ticket-classification pipeline, a few thousand tickets nobody has labeled, and a very specific question: "How do we know it works?"

The steps below give you an answer that runs. You will build a pytest suite based on metamorphic relations that works on unlabeled data, has a place to record known bugs, and uses a pass threshold set by the product side.

## No answers needed, only relations

The authors of LLMorph define a metamorphic relation (MR) as a relationship that the outputs of related inputs must satisfy. This lets metamorphic testing sidestep the "oracle problem": you do not need to know the correct answer.

Their tool implements 36 of the 191 MRs that have been catalogued, across four NLP tasks, and found faulty behavior with an average failure rate of 18%.

The two easiest kinds of relation come from CheckList (Ribeiro et al., ACL 2020). An invariance test (INV) applies a label-preserving change to the input and expects the prediction to stay the same. A directional test (DIR) does the same, but expects the label to move in a predetermined direction.

According to the CheckList authors, INV and DIR run on unlabeled data because they compare predictions with each other rather than with ground-truth labels. That is why the technique suits FDEs: a client's raw data is usable from week one.

**Key point:** Even without knowing the right answer, you know how two answers must relate to each other.

## What you will build, and what you need first

The running example is a hypothetical client that wants an LLM to rate the urgency of support tickets on three levels: `low`, `medium`, `high`.

You need Python, pytest and a function `classify(client, text)` that calls the model and returns one of the three labels. That function and the way you create a client depend on your provider, so the code below keeps them as stubs.

The minimal layout is `triage.py` (containing `classify`), `conftest.py` and `test_triage_mr.py`.

## Step 1: share the client with a fixture

Every test calls the model, so do not let each test create its own client. Per the pytest docs, a module-scoped fixture gives every test in the module a single shared instance, while session scope extends that sharing to the whole run.

```python
# conftest.py
import pytest
from triage import make_client  # stub: your client factory

@pytest.fixture(scope="session")
def llm():
    return make_client()
```

How to check: temporarily add a `print` line in the fixture and run `pytest -s`. If it prints exactly once, the client is being shared as intended.

## Step 2: write the input-pair table with parametrize

Each row in the table is a pair: the source input and the transformed input. For INV, the transformation is changing the sender's name or dropping punctuation, changes a support agent would consider insignificant. For DIR, the transformation adds a sentence reporting that the whole system is down, and urgency must not go down.

```python
# test_triage_mr.py
import pytest
from triage import classify

RANK = {"low": 0, "medium": 1, "high": 2}

INV_CASES = [
    ("Hi, I'm Anna. I can't log in since this morning.",
     "Hi, I'm Minh. I can't log in since this morning."),
    ("Invoice PDF shows the wrong date.",
     "Invoice PDF shows the wrong date"),
]

DIR_CASES = [
    ("Export to CSV is slow.",
     "Export to CSV is slow. Now the whole system is down for all users."),
]

@pytest.mark.parametrize("source, follow_up", INV_CASES)
def test_inv_same_label(llm, source, follow_up):
    assert classify(llm, source) == classify(llm, follow_up)

@pytest.mark.parametrize("source, follow_up", DIR_CASES)
def test_dir_not_less_urgent(llm, source, follow_up):
    assert RANK[classify(llm, follow_up)] >= RANK[classify(llm, source)]
```

Run `pytest -q`. Each pair shows up as its own test, so when one breaks you know immediately which.

## Step 3: compare free-text output by similarity

For discrete labels, `==` is enough. If the output is free text, such as a ticket summary, you need a semantic comparison. An empirical study of metamorphic testing for LLMs on NLP tasks used paraphrase-MiniLM-L6-v2 embeddings with cosine similarity, with thresholds of 0.8 for "similar" and 0.4 for "dissimilar", chosen through manual analysis.

```python
import math

def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

SIMILAR, DISSIMILAR = 0.8, 0.4  # thresholds from the study; calibrate your own

# stub: embed() calls the embedding model of your choice
# assert cosine(embed(sum_a), embed(sum_b)) >= SIMILAR
```

Those two numbers fit the researchers' data and may not fit yours. Take a few dozen pairs, judge by eye which ones are genuinely alike, then pick thresholds that separate the two groups.

## Step 4: record known bugs, do not delete the test

Say the client accepts that the model gets one case wrong and will fix it in the next prompt version. You should not remove that pair from the table. The pytest docs let you mark individual parameter sets in parametrize using `pytest.param` with `marks=pytest.mark.xfail`.

Put the case directly into the `INV_CASES` list from step 2, alongside the ordinary pairs, so the parametrize decorator picks it up like any other row:

```python
INV_CASES = [
    ("Hi, I'm Anna. I can't log in since this morning.",
     "Hi, I'm Minh. I can't log in since this morning."),
    ("Invoice PDF shows the wrong date.",
     "Invoice PDF shows the wrong date"),
    pytest.param(
        "Refund not received after 10 days.",
        "refund not received after 10 days",
        marks=pytest.mark.xfail(strict=True, reason="lowercase input lowers urgency"),
    ),
]
```

The `strict=True` argument matters here. By default, neither XFAIL nor XPASS fails the suite. With `strict=True`, when a fix makes the test pass unexpectedly, the suite goes red so you remove the xfail mark, instead of leaving the bug forgotten in a report.

## Why a red test is not always a bug

LLMorph recorded false positive rates from 0% to 70%, depending on the relation and the task. The empirical study mentioned above also found that the most common cause was the input transformation itself being faulty.

Apply that to the ticket example: if your automated "drop punctuation" step accidentally deletes the word "not", the sentence has changed meaning, and the model is right to change the label. So before running the model, reread every transformed input, especially auto-generated pairs. Whenever a test goes red, check the input pair first and only then suspect the model.

The second mistake is treating a single pass as proof. The model is nondeterministic even at temperature 0, so a pair that just passed may fail on the next run. When a test is flaky, running that pair several times is a simple way to see whether it fails consistently or only at random.

## Step 5: the pass rate is a product decision

Hamel Husain argues that assertion tests for LLMs need not pass 100% of the time like traditional unit tests. In his view, an acceptable pass rate is a product decision that depends on which failures you are willing to tolerate.

```python
def test_inv_pass_rate(llm):
    # skip cases wrapped in pytest.param (they have a marks attribute), i.e. known bugs
    pairs = [c for c in INV_CASES if not hasattr(c, "marks")]
    ok = sum(classify(llm, a) == classify(llm, b) for a, b in pairs)
    assert ok / len(pairs) >= 0.9  # example: the product owner sets this number
```

For tickets, a model that downgrades a "system down" ticket to `low` does far more damage than one that confuses `low` with `medium`. So DIR tests for critical cases should require a full pass, while INV tests for typos can have a lower bar. Discuss and agree the thresholds with the client rather than setting them alone.

## On the client site and on your CV

In the first week of a project you usually have no labels yet, but you do have logs of real inputs. One fast approach is to sit with the client's domain expert for 30 minutes and ask: "Which changes to a ticket would you consider insignificant? Which ones definitely make it more urgent?"

Each answer is an MR, and their expert is the person confirming it as a business requirement.

When writing your CV or talking in an interview, tell it through concrete results: which relations you used to test the model before labels existed, what kinds of bugs you caught, and how you weeded out false positives. If the job posting you are targeting mentions evals or testing LLM systems, put this example at the top of your experience section.

A good MR suite cannot prove the model is correct. What it gives you and the client is a clear, rerunnable record of what the model must not get wrong.

**Try this week:**

- Take 20 real inputs from an LLM project you are working on, hand-write one meaning-preserving transformation for each, and run INV tests with pytest.
- Reread every transformed input before running the model, and strike out any pair that changes the meaning.
- Propose a pass-rate threshold for the suite to your product owner, with the reasoning for why that error rate is acceptable.

## Sources

- [LLMORPH: Automated Metamorphic Testing of Large Language Models](https://arxiv.org/html/2603.23611v1)

- [Metamorphic Testing of Large Language Models for Natural Language Processing](https://arxiv.org/html/2511.02108v1)

- [Beyond Accuracy: Behavioral Testing of NLP Models with CheckList](https://ar5iv.labs.arxiv.org/html/2005.04118)

- [Glossary (Claude Platform Docs)](https://platform.claude.com/docs/en/about-claude/glossary)

- [Defeating Nondeterminism in LLM Inference](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/)

- [How to parametrize fixtures and test functions](https://docs.pytest.org/en/stable/how-to/parametrize.html)

- [How to use fixtures](https://docs.pytest.org/en/stable/how-to/fixtures.html)

- [How to use skip and xfail to deal with tests that cannot succeed](https://docs.pytest.org/en/stable/how-to/skipping.html)

- [Your AI Product Needs Evals](https://hamel.dev/blog/posts/evals/)
