Configuration, secrets and provider abstraction

Study time
≈ 3 h (estimate)
Needs
L1-M07-L01
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-M07 · Duration: ~165 min (estimate, including the independent exercise) · Previous: L01 · Next: L03 - End-to-end tests for chat UIs with Playwright

1. Introduction

An LLM test framework must run in two modes: mock (offline, free, on every commit) and live (the real API, costs money, run on purpose). Two questions decide its quality:

  1. How do the configuration and the API key get into the framework, so that the API key never leaks into a log or a report?
  2. How can one test suite run against both the mock and the real API without the mock quietly drifting away from the real API?

This lesson teaches how to answer both: a configuration object checked at startup, a Secret type that does not print its own value, and one interface with two implementations, verified by the same set of contract tests.

2. Learning objectives

  1. Design configuration read from environment variables, with safe defaults and error checks at startup.
  2. Verify that a secret does not appear in repr, str, logs or tracebacks.
  3. Separate the provider-calling layer behind an interface and choose the implementation by mode.
  4. Write contract tests that run against both the mock and the real client.
  5. Apply test-first to a new configuration rule.

3. Prerequisites and tools

  • L01; L1-M03-L01 (API keys, environment variables, budgets); L1-M03-L05 (test doubles).

4. Concepts

4.1 Configuration: one place, early checks, safe defaults

load_settings() reads every AIQA_* variable and ANTHROPIC_API_KEY in one place and checks them at once:

Variable Default Check
AIQA_MODE mock Only mock or live; case-insensitive, whitespace stripped
ANTHROPIC_API_KEY (empty) Required in live mode
AIQA_MODEL claude-opus-5-5 (exercise: must not be empty)
AIQA_MAX_USD 0.50 A positive number
AIQA_TIMEOUT_S 30 A positive number

A configuration error is reported before the first test runs, with a message that says exactly what to fix. That is much better than 200 tests failing with the same obscure error.

Everyday example. At the airport, your passport is checked at the check-in desk, not after the plane has taken off. Finding an expired passport at the desk costs a few minutes; finding it abroad costs the whole trip. load_settings() is the check-in desk of the test suite.

Worked example: checking the configuration early. Save as vd_l02.py in the lab folder and run python vd_l02.py:

import sys

sys.path.insert(0, "src")                    # like demo.py: run from the lab folder on any OS
from aiqa.config import ConfigError, load_settings  # noqa: E402

for env in ({"AIQA_MODE": " LIVE ", "ANTHROPIC_API_KEY": "sk-test-fake"},
            {"AIQA_MAX_USD": "0,5"},
            {"AIQA_MAX_USD": "0.5"}):
    try:
        s = load_settings(env)
        print(env, "->", s.mode, s.max_usd)
    except ConfigError as exc:
        print(env, "-> ConfigError:", exc)

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

{'AIQA_MODE': ' LIVE ', 'ANTHROPIC_API_KEY': 'sk-test-fake'} -> live 0.5
{'AIQA_MAX_USD': '0,5'} -> ConfigError: AIQA_MAX_USD and AIQA_TIMEOUT_S must be numbers: could not convert string to float: '0,5'
{'AIQA_MAX_USD': '0.5'} -> mock 0.5
  1. " LIVE " is trimmed and lower-cased, so it becomes the valid live mode (with a fake key next to it).
  2. "0,5" is the usual way to write a decimal number in Vietnam, but Python's float() accepts only a dot. The error appears as soon as the configuration is read, with the name of the variable to fix, not in the middle of a run.
  3. "0.5" is valid. The variable that is not set (AIQA_MODE) gets the safe default, mock.

4.2 A secret does not print itself

An API key usually leaks not because someone tries to print it, but through places nobody watches: print(settings), a debug log, a traceback when a test fails, a report. The lab's Secret always has Secret('***') as its repr and str (Secret('') when the value is empty). To get the real value you must call .reveal(), and only the client calls it, right when it sends the request.

A limit to know: Secret protects only the framework's objects. It cannot protect a test that writes assert settings.api_key.reveal() == ... (when it fails, pytest prints both sides), nor the inside of the SDK once the API key has been handed to it. The rule: never assert on the real value of the API key; tests use only a fake API key.

The test for this must check every printing path: repr(settings), str(settings), an f-string, repr(secret).

Worked example: a key leaking through an assert. Save as exercises/vd_l02_leak.py and run python -m pytest -q exercises/vd_l02_leak.py:

from aiqa.config import load_settings


def test_key_is_loaded():
    s = load_settings({"AIQA_MODE": "live", "ANTHROPIC_API_KEY": "sk-test-fake-value-123"})
    assert s.api_key.reveal() == "sk-test-other"          # bad: compares the real value

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

E       AssertionError: assert 'sk-test-fake-value-123' == 'sk-test-other'
1 failed

Secret did its job, but the test called .reveal() itself and compared the value, so when it fails pytest prints both sides, the key included. On CI, this line ends up in the log and in the report. Delete the file when you are done.

Good vs bad.

Weak test Good test
assert s.api_key.reveal() == "sk-..." assert "sk-test-fake-value-123" not in repr(s) with a fake key, and also check str(s), repr(s.api_key)

Why: the good test asserts what must be protected (the key does not appear when printed), and even when it fails it prints only a fake key.

4.3 One interface, two implementations

class ChatClient(Protocol):
    def reply(self, messages: list, system: str = "", max_tokens: int = 300) -> ChatResult: ...
  • ScriptedClient: the mock. It answers by predefined rules, records every call, and can be slow or fail on request.
  • AnthropicClient: calls the real API with the SDK (L1-M03) and checks the budget before every call.
  • make_client(settings) chooses the implementation according to AIQA_MODE.

The rest of the framework code (the trial app, the tests) knows only ChatClient. This is the technique you met in L1-M03-L05 (test doubles), now placed at the framework level.

Everyday example. Power sockets in a house follow one standard. To try a new lamp, an electrician can plug it into a test power unit on the bench (mock) or into a real wall socket (live). The lamp does not need to know where it is plugged in, as long as the plug fits the standard. ChatClient is that plug standard.

4.4 Contract tests: keeping the mock honest

A mock is dangerous when it differs from what it imitates: tests are green with the mock and red with the real system. The defence is contract tests: tests that describe what every implementation must do, run against each implementation.

@pytest.fixture(params=["scripted", LIVE])     # LIVE: marker live + skipif không có key
def any_client(request): ...

def test_contract_returns_a_chat_result(any_client): ...

In English, the code comment says: LIVE is the live marker plus a skip condition when no API key is set.

On your machine and on ordinary CI, only the scripted parameter runs. In a live run (L04), the same tests run against the real API. If the mock and the real API differ in something the contract checks, the live run reports it.

Good vs bad.

Weak contract test Good contract test
assert r.text == "ShopEasy: mình đã nhận câu hỏi của bạn." isinstance(r, ChatResult) and r.text.strip() and r.stop_reason in ("end_turn", "max_tokens")

Why: the weak test copies the mock's answer, so it is bound to fail against the real API and says nothing about the contract. The good test checks the shape that every implementation must have, including max_tokens, a value the lab's mock never returns (scenario 2 in §7).

5. Technical deep dive

5.1 The budget in the live client

AnthropicClient.reply() estimates the worst-case cost before calling (using up all of max_tokens), like the budget guard in L1-M03-L01, then refuses if the total would exceed AIQA_MAX_USD. The number of characters is used instead of the number of input tokens: this is a rough estimate, usually higher than reality for Vietnamese and English text, but it can be lower for emoji or Chinese characters (one character, several tokens), as the comment in clients.py says. Prices come from the price table of 2026-10-31 (L1-M03-L01).

Worked example: the budget stops the call before it is made. Save as vd_l02b.py in the lab folder and run python vd_l02b.py:

import sys

sys.path.insert(0, "src")
from aiqa.clients import AnthropicClient, BudgetExceeded  # noqa: E402
from aiqa.config import load_settings  # noqa: E402

s = load_settings({"AIQA_MODE": "live", "ANTHROPIC_API_KEY": "sk-test-fake",
                   "AIQA_BASE_URL": "http://127.0.0.1:9", "AIQA_MAX_USD": "0.001"})
try:
    AnthropicClient(s).reply([{"role": "user", "content": "x"}], max_tokens=1000)
except BudgetExceeded as exc:
    print("BudgetExceeded:", exc)

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

BudgetExceeded: next call could cost $0.0200; spent $0.0000 of $0.001
  1. The input is 1 character, counted as 1 token at $4 per million input tokens for claude-opus-5-5: $0.000004.
  2. The worst-case output is 1000 tokens at $20 per million output tokens: $0.02.
  3. The total is $0.020004, printed as $0.0200, which is more than the $0.001 budget, so the client raises BudgetExceeded before it sends the request. Nothing listens on 127.0.0.1:9, and the connection error never happens.

test_live_client_checks_the_budget_before_calling checks this without any network call: the client points to an address where nothing listens (127.0.0.1:9), and the test asserts that BudgetExceeded is raised before the request is sent.

5.2 The Python you need for this lesson

  • typing.Protocol describes "something that has a reply method" without forcing classes to inherit from it.
  • @dataclass(frozen=True) creates an object that cannot be modified after creation: the configuration cannot change midway.
  • pytest.param("live", marks=[...]) attaches a marker to one value of params.

6. The QA perspective

  • What to test: the defaults; every configuration error; the secret through every printing path; the choice of implementation; the contract with each implementation; the budget blocking before the call.
  • What can go wrong: an API key in the code or in a committed file; print(settings) in a debugging test; a default of live; a mock that returns a different structure from the real API; contract tests that run only with the mock and never live.
  • Reporting: a configuration error is a bug in the framework, not in the product.

7. Real-world scenarios

Scenario 1 (fictional): an API key in a traceback. CI runs pytest with --showlocals, so when a test fails, pytest prints the values of local variables, including the configuration object that holds the API key as a plain string. The HTML report of that run is attached to a public ticket. A Secret type that does not print itself would have prevented this.

Scenario 2 (fictional): a mock "better" than the real API. The team's mock always returns stop_reason: "end_turn". The product code does not handle max_tokens, and every test is green. The first live run with the contract tests immediately exposes a truncated reply.

8. Hands-on tutorial

8.1 Running the demo

python demo.py l02

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

settings: Settings(mode='live', model='claude-opus-5-5', api_key=Secret('***'), base_url=None, max_usd=0.5, timeout_s=30.0)
{'AIQA_MODE': 'live'} -> ConfigError: AIQA_MODE=live needs ANTHROPIC_API_KEY (use a separate key with a low spend limit)
{'AIQA_MODE': 'prod'} -> ConfigError: AIQA_MODE must be one of ('mock', 'live'), got 'prod'
{'AIQA_MAX_USD': '0'} -> ConfigError: AIQA_MAX_USD and AIQA_TIMEOUT_S must be positive
mock mode client: ScriptedClient | ShopEasy: mình đã nhận câu hỏi của bạn.
scripted rule: 30 ngày kể từ ngày nhận hàng

In English: the mock client answers "ShopEasy: we have received your question."; the scripted rule answers with the return window counted from the day the goods are received.

The first line prints the whole configuration, including the API key, and the API key appears only as Secret('***'). The next three lines are three configuration errors, each saying exactly what to fix.

8.2 Running the tests

python -m pytest tests/unit/test_config.py tests/unit/test_clients.py -v -rs

The two [live] tests are skipped, with a reason. That is correct: they run only when you deliberately turn on live mode.

8.3 Troubleshooting

Symptom Cause Fix
ConfigError: AIQA_MODE=live needs ANTHROPIC_API_KEY Live mode turned on without an API key As designed; see L1-M03-L01 on a separate API key and a spend limit
Live tests run although you do not want them to AIQA_MODE=live is still set in the shell unset AIQA_MODE (PowerShell: Remove-Item Env:AIQA_MODE)

9. Independent exercise

9.1 Main exercise

Problem: AIQA_MODEL=" " is currently accepted, and the error appears only when the first request reaches the API.

Requirements (test first):

  1. Run python -m pytest exercises/test_l02_model_setting.py. Record which test fails and why.
  2. Fix src/aiqa/config.py so that load_settings() raises ConfigError with a message containing AIQA_MODEL when the value is empty or only whitespace.
  3. Run the exercise file again and python -m pytest tests/unit to make sure nothing is broken.
  4. Run python mutate.py tests/unit/test_config.py (L05 explains the result) to make sure the existing tests still catch every seeded defect.

Deliverable: the diff of config.py, the output of step 1 and step 3.

Acceptance criteria: both commands in step 3 pass; the error message says exactly what to fix.

Hint: check after .strip().

9.2 Extra exercise: clean a log before it leaves the machine (15-25 minutes)

Problem: The example in §4.2 shows that the key still reaches the log when a test calls .reveal() itself. Secret cannot protect text that already contains the real value. Before a log or a report is attached to a ticket, the framework must replace every secret value with ***.

Requirements: in exercises/test_l02_extra_redact.py:

  1. TODO 1: write redact(text, secrets): replace every occurrence of the value of each Secret (read it with .reveal()) in text with MASK.
  2. Run the file and read the name of each failing test carefully: each one is a way that cleaning a log can go wrong.

Run: python -m pytest exercises/test_l02_extra_redact.py. Until you do the work, the tests fail with TODO 1.

Acceptance criteria: 6 tests pass, including the test that cleans the exact output line of §4.2.

Hint: str.replace replaces a string character for character, while re.sub reads +, . and * as special symbols. What about an empty Secret? If one key is the beginning of another, which one should be replaced first?

9.3 Real-world scenario: reviewing the configuration of an exam-results chatbot

Context (fictional): The DiemSo team builds a chatbot that looks up exam results by calling an external grading API. A pull request adds configuration and a mock for that API:

  • At startup, the app prints f"config: {cfg.__dict__}" "to make debugging easier"; cfg.score_api_key is a plain string.
  • SCORE_ENV defaults to prod, "so that demos are quicker".
  • SCORE_TIMEOUT is read with int(...) just before the first request; the value "30s" breaks the run at minute 12.
  • The mock always returns {"status": "ok", "score": 8.5}. The real API's documentation says it can return {"status": "pending"}, without a score field, while an exam is still being graded.
  • A .env.example file is committed, with a key value that looks real.

Your task: write (a) review comments for the pull request, each with a severity and a fix; (b) a configuration table in the format of §4.1 (variable, default, check) for the SCORE_* variables; (c) three contract tests that can run against both the mock and the real API, each with one sentence describing what it asserts.

A good answer has:

  • Every comment is tied to a rule of the lesson (§4.1, §4.2, §4.4, §6) and has a concrete fix, not just "unsafe".
  • The severity is explained by its consequence: who is affected, what it costs.
  • The configuration table has a safe default and a check for every variable, enough for errors to show up before the first test.
  • The contract tests check the shape that every implementation must have, without copying the mock's values.
  • There is at least one thing to ask the team or the API vendor, instead of a guess.

10. Knowledge check

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

P02 · True or false

If every contract test passes with the mock, they will certainly pass with the real API.

P03 · Short answer

Why must the default mode be mock?

P04 · Short answer

How does a contract test differ from an ordinary test?

P05 · Short answer

(Scenario) A colleague adds print(settings) to a fixture for debugging, then commits it. What happens with the lab's framework, and with a framework that stores the API key as a plain string?

P07 · Multiple choice

Call the lab's load_settings(env) with each env below. Which env is accepted?

P08 · Spot the bug

The method below is copied from AnthropicClient in src/aiqa/clients.py (two comment lines removed), with one line moved. Find the bug.

    def reply(self, messages, system="", max_tokens=300):
        estimate = self._cost(sum(len(m["content"]) for m in messages) + len(system), max_tokens)
        kwargs = {"system": system} if system else {}
        r = self._sdk.messages.create(model=self.model, max_tokens=max_tokens, messages=messages, **kwargs)
        self.budget.check(estimate)
        self.budget.record(self._cost(r.usage.input_tokens, r.usage.output_tokens))
        text = "".join(b.text for b in r.content if b.type == "text")
        return ChatResult(text, r.stop_reason, r.model, r.usage.input_tokens, r.usage.output_tokens)

P09 · Recall

Lesson: L1-M07-L01

L01 §4.4: the autouse fixture named ___ forces mock mode and a fake API key for every test, except tests with the ___ marker.

P10 · Select all that apply

According to §4.2, which expressions must a "the secret does not print itself" test include in its check? Select every correct option.

P11 · True or false

In the lab, print(Secret("")) prints Secret('***').

P13 · True or false

In the worked example of §4.1, load_settings({"AIQA_MAX_USD": "0,5"}) raises ConfigError as soon as the configuration is read, before any test runs.

P14 · Fill in the blank

Worked example of §5.1: at $20 per million output tokens, a worst case of 1000 output tokens costs $___. With the input added, the client prints next call could cost $___ and raises BudgetExceeded because the budget is only $0.001.

P15 · Apply now

In code-labs/l1-m07, do the extra exercise of §9.2: write redact(text, secrets) in exercises/test_l02_extra_redact.py, then run python -m pytest exercises/test_l02_extra_redact.py.

Checklist

P16 · Multiple choice

Worked example of §4.2: the test assert s.api_key.reveal() == "sk-test-other" fails, with the fake key sk-test-fake-value-123. What is the first E line that pytest prints?

P17 · True or false

ScriptedClient records every call, so a test can assert the system prompt that the code sent to the client.

11. Summary

  • Concepts: configuration in one place, checked early, with safe defaults; the Secret type; an interface and two implementations; contract tests run against each implementation; the budget blocking before the call.
  • Skills: testing configuration and secrets; writing contract tests with a live parameter; test-first for a new rule.
  • Pitfalls: an API key printed through an unexpected path; a mock that differs from the real API; a contract that never runs live.
  • You can now: build the configuration and client layer of an LLM test framework that runs both offline and live.

12. References

ID Title Publisher URL Accessed Relevance
R1 How to use fixtures (parametrized fixtures) pytest https://docs.pytest.org/en/stable/how-to/fixtures.html 2026-10-31 Parametrized fixtures for contract tests

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Configuration / settings Cấu hình
Secret Bí mật (key, mật khẩu)
Interface / implementation Giao diện / cài đặt
Contract test Test hợp đồng: điều mọi cài đặt phải làm
Test-first Viết test trước khi sửa code