Sub topic 15
Testing That Redaction Works and Keeps Working
Earlier chapters built a redactor and a logging wrapper. This chapter covers how to prove they behave as intended and how to keep them behaving that way as the code and the data change. It assumes you know pytest basics (functions named test_*, assert, parametrize, the caplog fixture) and can read simple regular expressions. The examples assume redact, call_logged, and stream_logged live in a module named llm_logging.py.
What can go wrong
A redactor fails in three ways, and each needs its own kind of test:
- A leak. A sensitive value passes through unchanged. This is the failure that matters most.
- Over-redaction. Ordinary text is replaced, so logs become useless for debugging.
- A bypass around the redactor. The redactor is correct, but some code path logs raw text without calling it. Unit tests of
redactnever see this.
Pattern-based redaction never catches everything. Tests do not prove that no leak exists. They prove that the leaks you know about stay fixed, and that the wrapper uses the redactor everywhere it should.
Unit tests for the redactor
Begin with the test from the plan, which checks that known sensitive strings do not survive:
def test_redact_removes_email_and_key():
out = redact("[email protected] sk-abcdefghijklmnop1234")
assert "[email protected]" not in out
assert "sk-abcdefghijklmnop1234" not in out
assert "[EMAIL]" in out and "[SECRET]" in outThis test checks one email and one key, so it covers very little. Parametrize it so each leak shape is a separate case with its own failure message:
import pytest
from llm_logging import redact
LEAKS = [
"[email protected]",
"[email protected]",
"[email protected]",
"sk-abcdefghijklmnop1234",
"token_ABCDEFGHIJKLMNOP_1234",
]
@pytest.mark.parametrize("secret", LEAKS)
def test_secret_never_survives(secret):
out = redact(f"before {secret} after")
assert secret not in out
assert out.startswith("before ") and out.endswith(" after")The assertion on secret not in out is the one that matters. It checks that the value is gone, not that a placeholder appeared. A test that only looks for [EMAIL] would still pass if the redactor left the address in place and added a placeholder next to it.
Include variants that real traffic produces: upper case, plus-addressing, subdomains, and a secret at the very start or end of the string. Each variant is a place where a regex can silently fail.
Testing for over-redaction and idempotence
Add tests that assert ordinary text comes back unchanged:
def test_plain_text_is_untouched():
text = "Use a key-value store for the task-force notes"
assert redact(text) == text
def test_redact_is_idempotent():
once = redact("[email protected] sk-abcdefghijklmnop1234")
assert redact(once) == onceThe first test guards against a pattern that grows too greedy. Words like task-force and key-value contain the same prefixes as secret formats, so they make good negative cases. The second test matters because log pipelines often redact twice, once in your app and once in a collector. Placeholders such as [EMAIL] must not match any pattern.
Recording known gaps with xfail
Some leaks you know about but have not fixed yet. The current patterns do not catch phone numbers, for example. Record the gap as an expected failure instead of leaving it out:
@pytest.mark.xfail(strict=True, reason="phone numbers are not covered yet")
def test_phone_numbers_are_redacted():
assert "555-0100" not in redact("Call me on 555-0100")With strict=True, the day you add a phone pattern this test starts passing and pytest reports it as a failure. That failure tells you to remove the marker, so the gap list stays accurate.
Testing the whole wrapper
A correct redact does not help if call_logged skips it. Test the wrapper through the logger, because the logger is what ends up in storage. The caplog fixture captures records emitted through the llm logger:
import json
import logging
import pytest
from llm_logging import call_logged
PROMPT = "Summarize for [email protected] using sk-abcdefghijklmnop1234"
def fake_call(model, prompt):
return "Sure, writing to [email protected]"
def test_default_log_has_metadata_only(caplog):
with caplog.at_level(logging.INFO, logger="llm"):
call_logged(fake_call, "test-model", PROMPT)
assert "[email protected]" not in caplog.text
assert "sk-abcdefghijklmnop1234" not in caplog.text
record = json.loads(caplog.records[0].getMessage())
assert record["status"] == "ok"
assert "prompt" not in record and "response" not in record
def test_gated_content_is_redacted(caplog):
with caplog.at_level(logging.INFO, logger="llm"):
call_logged(fake_call, "test-model", PROMPT, log_content=True)
assert "[email protected]" not in caplog.text
assert "sk-abcdefghijklmnop1234" not in caplog.text
record = json.loads(caplog.records[0].getMessage())
assert "[EMAIL]" in record["prompt"]
def test_error_path_logs_type_not_message(caplog):
def failing_call(model, prompt):
raise ValueError("bad input from [email protected]")
with caplog.at_level(logging.INFO, logger="llm"):
with pytest.raises(ValueError):
call_logged(failing_call, "test-model", PROMPT)
record = json.loads(caplog.records[0].getMessage())
assert record["status"] == "error"
assert record["error_type"] == "ValueError"
assert "[email protected]" not in caplog.textThe error-path test is easy to forget. Exception messages often echo the input that caused them, so they are a classic route for sensitive data into logs. The wrapper records only type(exc).__name__, and this test makes sure it stays that way.
Log injection
Model output is untrusted, so test that it cannot forge extra log lines:
def test_newlines_in_response_cannot_forge_records(caplog):
def sneaky(model, prompt):
return 'ok\n{"event": "forged", "status": "ok"}'
with caplog.at_level(logging.INFO, logger="llm"):
call_logged(sneaky, "test-model", "hi", log_content=True)
assert len(caplog.records) == 1
message = caplog.records[0].getMessage()
assert "\n" not in message
assert json.loads(message)["event"] == "llm_call"json.dumps escapes the newline as the two characters \n, so the record stays on one line. If someone later replaces JSON logging with an f-string, this test fails.
Testing streamed output
Streams add two risks. A sensitive value can be split across chunks, and the consumer can stop early. Test both:
from llm_logging import stream_logged
def test_stream_redacts_value_split_across_chunks():
events = []
chunks = ["Contact ana@exa", "mple.com now"]
out = list(stream_logged(iter(chunks), events.append))
assert out == chunks
assert len(events) == 1
assert "[email protected]" not in json.dumps(events[0])
def test_stream_logs_once_when_consumer_stops_early():
events = []
gen = stream_logged(iter(["Contact [email protected]", " now"]), events.append)
next(gen)
gen.close()
assert len(events) == 1
assert "[email protected]" not in json.dumps(events[0])The first test passes because the wrapper joins all chunks before redacting. Redacting each chunk on its own would miss the email. The test also checks that the caller still receives the original chunks unchanged.
Keeping the tests current
A redaction suite is useful only if it grows. Every time a leak is found, whether in a log review, a bug report, or an audit, follow the same loop before you touch the pattern:
Writing the failing test first proves the test can fail. A test you have never seen fail may be asserting nothing. Running the over-redaction tests in step E catches the common side effect of a new pattern, which is that it also matches harmless text.
Practical habits that keep the suite honest:
- Store leak shapes in one list, like
LEAKSabove, so adding a case is a one-line change. - Run the suite in CI on every pull request, and make it a required check.
- Add a test whenever a new field enters the log record, asserting that it holds no raw content.
- Review the
xfaillist on a schedule, because each entry is a leak you have accepted for now.
| Test type | Catches | Misses |
|---|---|---|
| Parametrized leak cases | Known sensitive formats | Formats you have not thought of |
| Over-redaction cases | Patterns that are too greedy | Subtle damage to meaning |
| `caplog` wrapper tests | Code paths that skip the redactor | Logs written outside the `llm` logger |
| Stream tests | Split values, double logging | Truncated partial values |
The last column is the point to remember. These tests lower the chance of a leak. They do not remove it, so they work alongside access control and retention limits, not in place of them.
Exercise
Your team adds a pattern for phone numbers, and the test test_phone_numbers_are_redacted (marked xfail(strict=True)) now reports a failure even though the redactor works. Why does it fail, and what should you do?
Show answer
With strict=True, an expected failure that passes is reported as a failure (XPASS). Here the phone pattern works, so the test passes unexpectedly. Remove the xfail marker so it becomes a normal test that guards the new behavior, and add some over-redaction cases to check that the new pattern does not match ordinary numbers in text.
Exercise
A developer changes call_logged to log f"error: {exc}" instead of the exception type name. Which test in this chapter should fail, and why?
Show answer
test_error_path_logs_type_not_message should fail. The fake call raises ValueError("bad input from [email protected]"), so logging str(exc) puts the email into the log. The test asserts that [email protected] is absent from caplog.text, and it also checks error_type, which would be missing.