ArcanaFutura is an AI-powered Tarot reading web application built as my final project for Harvard University's CS50 course. It features a multi-step user flow, interactive DOM manipulation, and real-time streaming of LLM-generated readings.
This portfolio details the comprehensive security and infrastructure QA audit conducted on the application. The audit identified and remediated critical vulnerabilities in API quota protection, state management, and protocol boundaries, ultimately backed by an automated Pytest regression suite.
TL;DR
Architectural Threat Map: Out of nearly 40 defects identified during the 301-point QA audit, these five represent the most critical and structurally diverse vulnerabilities. They span across five distinct architectural layers: two inside Flask's runtime (memory mutation, template injection), one at the proxy boundary (IP spoofing), and two on the WebSocket channel, one inbound (hijacking), one outbound (dead SID).
I structured the QA process using a professional Scrum hierarchy: 9 Epics and 54 User Stories, decomposed into a rigorous matrix of 301 executable subtasks tracked in Jira. I deliberately prioritized manual testing for this phase because automation only verifies what it is scripted to check. Manual exploratory testing brings the intuition and flexibility needed to uncover hidden bugs, unpredictable edge cases, and usability issues that fall outside of rigid automated paths.
When transitioning to automation, I applied a strict triage filter based on a single guiding question: "If this breaks, will the app crash, get hacked, or cost me money?." Visual and animation validations remained manual, while critical security gates, API quota protections and core routing logic were translated into a Pytest suite. This created a permanent regression safety net, ensuring that applying complex fixes during the QA phase never broke previously verified behavior.
Result: A test plan of 301 subtasks in Jira, backed by over 100 automated tests integrated into GitHub Actions for continuous CI/CD validation.
Selected from nearly 40 identified defects, these findings showcase the intersection of security auditing and systems engineering. Each entry follows a rigorous documentation standard: defining the observable failure, analyzing the real-world impact on API resources or user data, and verifying the fix through targeted regression testing to ensure long-term stability.
What broke: The shuffle function mutated
TAROT_CARDS dicts in-place — writing
card["value"] = "invertido" directly onto objects in the
global list. Under gevent's concurrent model, this list lives in process
memory for the entire server lifetime.
Real-world impact: Request A starts writing orientations to the global list while Request B is halfway through reading them. The global deck becomes a shared mutable scratchpad — the last concurrent write wins. After the first request, the deck is never truly random again; every subsequent reading inherits leftover orientation state from whoever hit the server last. The app logs zero errors, returns HTTP 200, and appears completely healthy while producing subtly incorrect results on every request under load.
The fix:
deck_copy = [card.copy() for card in TAROT_CARDS] — shuffle and
mutate the copy, never the global variable.
def test_global_deck_not_mutated(client): """The global TAROT_CARDS list must remain pristine across requests.""" with client.session_transaction() as sess: sess["selected_cards"] = "3" client.get("/cartas") # Triggers shuffle and orientation assignment # Hard assertion: no card in the global list should carry a value after the request from app import TAROT_CARDS for card in TAROT_CARDS: assert "value" not in card, ( f"Global card '{card['name']}' was mutated! Concurrency risk detected." )
What broke: Two separate failure modes appeared while tuning
ProxyFix behind Render's load balancers. With x_for=1
(the original setting), Flask-Limiter read Render's internal proxy IP — a
10.x.x.x address that changed on almost every request — instead of the user's
IP, so the per-IP limit never triggered. Raising it to x_for=2
extracted the real client IP, but trusted a hop the client can influence: an
attacker could prepend a fake IP to X-Forwarded-For and bypass the
limiter entirely.
Real-world impact: In the first state the rate limit was
effectively useless (a 105-request loop was never blocked until the fix). In
the over-trusted state, a single forged header
(X-Forwarded-For: 1.2.3.4) let 10 rapid requests through with no
429, giving unlimited free AI readings and draining Gemini API quota.
The fix: ProxyFix(app.wsgi_app, x_for=1, x_proto=1,
x_host=1, x_prefix=1). x_for=1 trusts only the last hop,
which closes the spoofing bypass (verified: the 8th request with a forged
header returns 429). Known limitation, documented and accepted:
behind Render's load balancers the limiter keys on the proxy's internal IP
rather than the user's public IP, so limits are effectively shared. For a
high-traffic deployment the recommendation is a proxy trust list or the
CF-Connecting-IP header.
from flask_limiter.util import get_remote_address def test_rate_limiter_keys_to_client_ip_not_load_balancer(client): """Flask-Limiter must resolve the real client IP, not the proxy IP.""" with client.application.test_request_context( headers={"X-Forwarded-For": "203.0.113.42, 10.0.0.1"} ): resolved = get_remote_address() assert resolved == "203.0.113.42", ( f"Expected real client IP, got '{resolved}' — ProxyFix x_for misconfigured" ) def test_spoofed_forwarded_for_is_not_trusted(client): """With x_for > 1, an attacker header bypasses rate limiting.""" with client.application.test_request_context( headers={"X-Forwarded-For": "127.0.0.1, 203.0.113.42, 10.0.0.1"} ): resolved = get_remote_address() assert resolved != "127.0.0.1", ( "Spoofed localhost IP was trusted — x_for set too high" )
What broke: The @socketio.on('send_message')
handler called no validate_csrf(), and the server was configured
with cors_allowed_origins="*". Flask-Limiter is blind to WebSocket
events entirely — HTTP rate limits do not apply to socket handlers.
Real-world impact: Any attacker page could get a logged-in user
to visit it, establish a WebSocket connection using the victim's valid session
cookie, and loop 200+ send_message events unimpeded. Every event
triggers a Gemini API call at real cost. Testing confirmed that a 200-event loop
completed without a single rejection.
The fix: validate_csrf() added to the handler,
plus a custom in-memory sliding-window limiter (is_rate_limited(),
backed by a defaultdict) allowing 10 messages per 60 seconds per
session, because Flask-Limiter cannot be applied to socket events.
def test_send_message_rejected_without_valid_csrf(socketio_client): """send_message must validate the CSRF token on every emit. Without this, any cross-origin page can drain Gemini quota.""" received = [] socketio_client.on("generation_error", lambda data: received.append(data)) # Emit with a tampered CSRF token socketio_client.emit("send_message", { "message": "test", "tarot_reading": "", "csrf_token": "invalid-token-xyz", }) assert len(received) > 0, "No error emitted — CSRF not validated on socket handler" assert "csrf" in received[0].get("message", "").lower()
What broke: The intention field was interpolated raw into a
socket.emit() call inside a <script> block:
intencao: "{{ intencao }}". The server
ran bleach.clean() on input, which appeared to sanitize it.
Real-world impact: bleach sanitizes HTML
context — it strips <script> tags and encodes angle
brackets. It deliberately leaves quotes and backslashes untouched because
those are valid in text content. A user typing
", csrf_token: "anything" passes bleach cleanly, gets stored
in the session, and Jinja2 injects it raw into a JavaScript string — breaking
out and overwriting the CSRF token in the socket payload. With a more
crafted payload ("}); maliciousFunction(); //), arbitrary code
executes inside the CSP nonce boundary. The vulnerability is not in the
HTML output pipeline at all — no amount of HTML sanitization ever catches it.
The fix:
intencao: {{ intencao | tojson }} —
| tojson JSON-encodes the string including all quotes,
closing the injection point entirely.
@pytest.mark.parametrize("payload", [ '\", csrf_token: \"injected', '"}); maliciousFunction(); //', ]) def test_intencao_is_json_encoded_in_script_context(client, payload): """| tojson must be applied in results.html — bleach.clean() does NOT protect against JS context breakout.""" with client.session_transaction() as sess: sess["intencao"] = payload html = client.get("/results").data.decode() # Raw payload must never appear verbatim inside a script block assert payload not in html, ( f"Raw payload in rendered HTML — | tojson not applied: {payload}" ) # JSON-encoded form must be present instead import json assert json.dumps(payload) in html
What broke: In a Flask-SocketIO + Flask-Session stack there
are two completely different things called "session". The code targeted
socketio.emit() using session.sid as the room name
— but session.sid is the Redis key from the HTTP session, not
the socket's ephemeral per-connection room ID (request.sid).
The emit fired at a room that doesn't exist.
Real-world impact: The Gemini API call completed successfully — consuming a real paid token. The result was emitted to a dead room. The client's loading spinner ran for 120 seconds, then the reconnection system retried up to 5 times, burning 5 more API tokens per stuck user. Zero errors in the logs, zero 500s, no indication anything was wrong. In a traffic spike this is silent, compounding quota burn: every concurrent stuck user costs 5 Gemini calls and receives nothing.
The fix: Replace session.sid with
request.sid inside all @socketio.on() handlers —
request.sid is the actual socket connection room ID. To survive
network drops, the reading is now cached in Redis using the persistent Flask
Session ID, allowing reconnected clients to retrieve it instantly.
def test_generation_emit_targets_socket_room_not_redis_key(socketio_client, mocker): """socketio.emit() must target request.sid (the socket room), not session.sid (the Redis session key). Emitting to the Redis key sends the response to a room that does not exist.""" emitted_rooms = [] original_emit = socketio_client.application.extensions["socketio"].emit def capture_emit(*args, **kwargs): emitted_rooms.append(kwargs.get("to") or kwargs.get("room")) return original_emit(*args, **kwargs) mocker.patch.object(socketio_client.application.extensions["socketio"], "emit", side_effect=capture_emit) socket_room_id = socketio_client.sid # the real ephemeral room ID socketio_client.emit("start_generation", {"intencao": "test"}) assert socket_room_id in emitted_rooms, ( f"Emit targeted '{emitted_rooms}' — expected socket room '{socket_room_id}'. " "session.sid (Redis key) was used instead of request.sid." )
The 301 manual test cases were organized into 9 Epics and 54 User Stories, mapped directly to the application's architecture. Each Epic targeted a distinct layer of the stack — from HTTP form handling to Redis session storage, WebSocket events, AI prompt integrity, and browser accessibility. A consistent triage filter was applied to automation decisions throughout: "If this breaks, will the app crash, get hacked, or cost money?"
Focus: Every interaction before the user reaches the card board — form submission, backend validation, session initialization, and CSRF protection.
bleach.clean()
against script tags, img onerror handlers, malformed HTML, link
injection, and the JavaScript quote-breakout vector. One subtask confirmed a
vulnerability where Jinja2's standard rendering (without the
| tojson filter) allowed double quotes to break out of the
inline JS string literal in results.html.
& expand to & after bleach
processing, causing a 400-character input to exceed the limit.session['selected_cards']
is stored as a Python string (required for the
not in ['1','3','5'] validation), while Jinja2 injects it into
the JS template as a bare integer (required for the === strict
equality counter logic). A type mismatch in either direction silently breaks
the entire card selection flow.
Focus: The card board's JavaScript state machine — from initial render to selection locking, animation timing, DOM reparenting, and final data serialization.
random.sample produces
a different card order across sessions and that every card receives exactly
one data-value attribute ("normal" or
"invertido"). A key regression guard targets the
deck_copy = [card.copy() for card in TAROT_CARDS] line — if
removed, the global deck dictionary accumulates stale orientation values
across concurrent users.
const selectedCardsCount = {{ selected_cards }};. If this
renders as 0 or None, the condition
clickedCards >= 0 is true on page load and no card can ever be
clicked — with no visible error.
card.dataset.processing = "true" lock against rapid
double-clicks during the 333ms mid-flip window, and verifying the
card.classList.contains('clicked') guard prevents re-selection
after animation completes.
stage.appendChild(card)
physically moves the correct elements to #selection-stage, that
the correct layout class (stage-1, stage-3, or
stage-5) is applied, and that card orientations survive the
transition unchanged.
leituraButton.click, including CSRF token inclusion and backend
handling of malformed, structurally invalid, and empty JSON payloads — each
a separate crash or cost vector.
Focus: The AI generation pipeline — from WebSocket event to Gemini API call to rendered HTML — and its failure modes.
model.generate_content calls to intercept and
inspect the exact prompt string sent to Gemini, verifying that card names,
orientations ("invertido"), and the user's intention all appear
before the API is called. A missing card name means a wasted API call and a
hallucinated reading.markdown_to_html()
revealed that Markup() marks output as Jinja2-safe but performs
no sanitization. The Python markdown library passes raw HTML
through unchanged. If Gemini returns a <script> tag (via
prompt injection), it survives the pipeline and executes via
.innerHTML in the browser. This was documented as a confirmed
finding with a recommended fix: pipe through bleach.clean()
before wrapping in Markup().
generate_tarot_reading()
propagates exceptions — rather than swallowing them — so the
background_generate task can emit generation_error
to the client. A function that catches and returns None on
failure causes a TypeError in the browser when it tries to
inject None into the DOM.
if not response.text: raise ValueError() catches safety-filter
rejections, where the API returns a response object but with no text
content.
Focus: The chat interface as a separate runtime layer — its initialization, real-time feedback loop, security surface, and known architectural bugs.
initializeSocket() — the function registering all chat UI event
listeners — was defined but never called. Only initSocket() was
wired to DOMContentLoaded. If deployed, the chat button, close
button, scroll shadow, and receive_message handler would all be
silently inert. Documented as a critical dead-code bug.
handle_message used data['message']
(direct key access) instead of data.get('message', ''), meaning
a missing key raises an unhandled KeyError in the gevent
greenlet; and no message length limit existed before
model.generate_content(), allowing unlimited-length chat
prompts to reach the AI.
removeLoadingIndicator() targeted
.chat-message:last-child. If the user sent a second message
before the first reply arrived, their second message bubble became
last-child, and the first loading bubble was permanently
orphaned in the chat history. Documented with a specific fix: use a unique
class on the loading element and target it directly.
background_chat exception
handler via mocked API failures to verify a receive_message
event is emitted on failure. If the except block silently fails, the
client's loading indicator spins indefinitely with no recovery path.Focus: The application's operational security layer — rate limiting, session hygiene, CSP enforcement, WebSocket authentication, and concurrent user isolation.
@limiter.limit
decorator on /results returns a 429 after the
configured threshold. The development limit is 200/min;
production is 5/min, dynamically selected via the
is_production flag.
Set-Cookie header: HttpOnly (blocks
document.cookie access), SameSite=Lax (restricts
cross-site POST), and Secure (HTTPS-only in production,
HTTP-accessible in dev). The Secure flag is dynamically tied to
is_production — hardcoding either value in either direction is
a bug.
start_generation with a missing token, a forged token, and
confirming the server emits generation_error in each case.
Tested on production via browser console injection.
/process_form simultaneously to verify session data
(intencao, selected_cards) is keyed per-session-ID
in Redis and cannot leak between users. Also testing the same-browser
concurrent-tab race condition on session['selected_cards']
writes.
SESSION_PERMANENT=False setting produces a
cookie with no Expires or Max-Age attribute —
making it a true browser-session cookie that disappears on close, critical
for shared-device privacy./clear_session route, introduced to support the
sessionStorage-based tab detection in cartas.html
and results.html, was specifically security-audited: verifying
it is @csrf.exempt (required because the JS fires before any
token is available), accepts only POST, fully clears all
session keys, and returns JSON — each a distinct crash or data-breach vector
if broken.
Focus: Mobile-specific rendering behavior, touch event semantics and responsive layout across viewport sizes.
#rotate-message overlay controlled by a CSS
@media (orientation: landscape) rule, verifying it blocks
interaction in landscape and disappears instantly on rotation.
isTouchDevice() detection
via window.matchMedia("(hover: none) and (pointer: coarse)"),
the keyboard-active class applied to <body>
on input focus, and the scrollIntoView behavior that prevents
the keyboard from covering the textarea. Also verifying the
localhost exclusion so the behavior doesn't trigger during
local development.
click event
listeners fire immediately on mobile tap without legacy 300ms delay
(suppressed by the width=device-width viewport meta tag), and
that CSS :hover states don't persist after tap-and-release
("sticky hover").
Focus: Out-of-order navigation, infrastructure outages, and the application's behavior when users don't follow the intended linear flow.
/cartas route
used int(session.get('selected_cards', 0)), which defaulted to
0 on missing sessions. The page rendered with HTTP 200, but
selectedCardsCount = 0 made clickedCards >= 0
immediately true — no card could be clicked, with no visible error. The fix
(if raw_val not in ['1','3','5']: redirect) was
regression-guarded with parametrized tests covering eight distinct invalid
session values.
/,
/cartas, /results) with no session, partial
sessions, and expired sessions to verify correct redirect chains without any
route serving a 500 or a broken 200.
/results to /cartas via the browser's Back
button — the DOM retains flipped cards but the JS clickedCards
counter resets to 0, potentially allowing the user to exceed their original
card limit.@app.errorhandler(404) redirects all app routes to home
(leaking nothing) but passes static file requests through as real
404s. Both code paths were tested separately, and Talisman
security header presence was verified on both response types.
Focus: Attack surfaces not covered by Epic 5 — Talisman's default security headers, WebSocket CORS policy, CSP nonce configuration, and development tooling leaks.
X-Frame-Options: SAMEORIGIN
(clickjacking), X-Content-Type-Options: nosniff (MIME
sniffing), and Referrer-Policy across all routes and both
error-response code paths (the redirect-based 404 and the
pass-through static-file 404).cors_allowed_origins="*" was
hardcoded unconditionally in the original code, allowing any external
website to establish a WebSocket connection. Combined with the missing CSRF
on send_message, this created a confirmed Cross-Site WebSocket
Hijacking (CSWSH) exploit path where an attacker's page could silently
consume Gemini API quota for free. Documented with a specific fix: restrict
to the production domain conditionally via is_production.g.nonce was generated
on every request and applied to script tags, but Talisman was not
initialized with
content_security_policy_nonce_in=['script-src'], and
'unsafe-inline' remained in script-src. The nonce
was cosmetic — the browser ignored it entirely because
unsafe-inline unconditionally allows all inline scripts. Any
XSS injection point would execute without restriction.
handle_generation
called validate_csrf(); handle_message did not. An
authenticated WebSocket connection could send unlimited chat prompts
directly to the Gemini API without any token. Documented with exact code
changes required for both backend and frontend.if not is_production: guard
wrapping localhost and LAN IP entries in the CSP dict was verified via
source inspection — an inverted or missing condition would whitelist
http://localhost:3000 in the production CSP, creating a
potential SSRF-based CSP bypass surface.
send_message events produced no 429, because
Flask-Limiter only covers HTTP routes. Fixed with a custom in-memory
sliding-window limiter (is_rate_limited(), 10 messages per 60s per
session), verified by sending 12 messages and receiving exactly 10 responses.
Focus: Scenarios that require a live browser, real devices, or human judgment — WebSocket network resilience, cross-browser rendering parity, keyboard accessibility, screen reader compatibility, and performance benchmarking. Not automated; executed manually on production via BrowserStack and Chrome DevTools.
generation_complete events because
SocketIO SIDs are per-connection, not per-session.rotateX/rotateY transforms without vendor
prefixes, Web Animations API (element.animate) support,
WebSocket wss:// connection establishment, and
marked.js rendering parity. All browsers passed without
requiring polyfills.
keydown listener. Found that
keyboard focus could escape the chat modal — fixed by implementing a focus
trap that intercepts Tab and Shift+Tab and cycles
within the modal boundaries.<button> with no text content), announced by screen
readers as "button" with no context — fixed by adding dynamic
aria-label attributes via Jinja2. The
#loading-message lacked an ARIA live region, so screen readers
received no notification when the AI finished generating — fixed by adding
role="status" and aria-live="polite". Color
contrast measured at 3.31:1 for inactive card buttons, meeting the WCAG AA
UI component standard.
/ at 968ms (within
the 1000ms target). A 46% asset reduction (262KB PNG → 140KB WebP) brought
/cartas to a TTI of 4.1s on a Lighthouse mobile audit — above the
3s target, accepted as the production baseline. AI reading generation averaged
6.78s (P95 8.10s) across 10 runs; chat responses averaged 4.45s (P95 6.88s).
A stress test with 5 concurrent users showed an ~8.4% latency increase
(7.35s vs 6.78s), within the 10–20% graceful-degradation target, with no
errors or Redis connection exhaustion.
What Pytest automated
Backend route behavior, session state integrity across requests, input sanitization reaching the AI prompt, CSRF token enforcement on all mutation endpoints, and WebSocket handler security via the Flask-SocketIO test client. Every test hits the actual application code—no mocks were used for the security assertions.
What was explicitly not automated
CSS transitions, animation timing, mobile viewport breakpoints, and orientation-based layout changes. These require a browser rendering engine and belong in Playwright or Cypress, not a unit test runner. Documenting this boundary is part of the strategy—pretending those cases don't exist would be a worse signal than the gap itself.
The xfail pattern (Test-Driven Bug Fixing)
Two known vulnerabilities—a KeyError crash in the WebSocket
handler when a session key is missing, and an unbounded chat input with no
API cost guard—were written as @pytest.mark.xfail tests before
the fix was applied. This documented each vulnerability with a reproducible
case that automatically converted to a passing test when the code was fixed.
A test that starts red and goes green on the fix is a much stronger signal
than a test written after the fact.
Transparency Note: The automated test code was written in collaboration with AI pair-programming tools. I designed the test strategy, identified the edge cases through manual exploratory testing, and reviewed all generated code against the application source. Utilizing AI assistance for test generation is a standard multiplier in modern professional QA workflows.
Brasil 2040 is a purpose-built RAG application — not a chatbot wrapper. The AI assistant answers exclusively from Brazilian government climate research: 42 PDFs I extracted, chunked, and embedded myself using multilingual-e5-large on a Kaggle GPU notebook. Every response must trace back to vectors stored in my own Supabase pgvector database, retrieved by a FastAPI backend I wrote. Gemini handles generation, but the documents are the ceiling. Testing that constraint is the whole point.
This audit ran two completely different testing layers on the same product: a Pytest eval suite with an LLM-as-judge pipeline in GitHub Actions CI/CD, measuring whether the AI stays faithful to its documents; and a ScoutQA AI agent that explored the live browser UI for 30 minutes without a script. Neither could see what the other found.
TL;DR
What makes this different from a chatbot test: The knowledge base was built from scratch. Numbers like "16,7×" and "167%" have to survive PDF extraction, chunking, embedding, vector retrieval, and LLM generation before reaching the user. A failure at any layer produces a confident wrong answer — with HTTP 200.
The QA problem this creates
A number like
"16,7×" has to survive PDF extraction, sentence-aware chunking, cosine
retrieval, and Gemini generation before it reaches the user. An old regex pattern in the
chunker destroyed numbers with commas — "16," and "7×" split
across chunk boundaries. I ran a diagnostic before embedding to verify numbers survived
cleaning. That's the real reason the retrieval eval runs first: if the
chunks are wrong, every downstream judge verdict is meaningless.
Before any test could run, the knowledge base had to be built correctly. This wasn't configuration — it was engineering. Three specific problems required QA thinking before a single question was evaluated.
Problem 1 — Numbers in tables
PyMuPDF's
standard get_text("text") misses numbers that live inside table cells. I
added explicit find_tables() extraction per page, appending table content
as structured text before chunking. Without this, numbers that live only in tables never
entered the vector store. A limit remains: numbers that exist only inside figures
(images) are still invisible to the pipeline. An audit of the evals found one such case,
the 74%–99% deficit risk for the SE/CO subsystem.
Problem 2 — Regex destroying decimals
A standard
\b\w{1,2}\b cleaning pattern — common in preprocessing tutorials —
destroyed Brazilian decimal notation. "16,7" became "16," and
"7" as separate tokens. I ran a diagnostic cell against all 42 PDFs before
embedding to verify every critical number survived the cleaning step.
Problem 3 — Sentence-aware chunking
A naive word-window chunker splits sentences at arbitrary positions. "O custo operacional aumentará em 16,7" followed by "× no cenário HadGEM 8.5" across chunk boundaries means no single chunk contains the complete fact. The chunker splits on sentence-ending punctuation before falling back to word windows — keeping numerical facts and their units in the same chunk. This directly affects whether the faithfulness judge can verify a claim, or whether it simply doesn't appear in retrieved context.
# Run before encoding — a QA step inside the build pipeline for pdf_path in pathlib.Path(PDF_DIR).glob("*.pdf"): for page_num, page in enumerate(doc, 1): raw = page.get_text("text") after_clean = OLD_CLEAN_PATTERN.sub('', raw) for term in TERMS_TO_CHECK: # ["16,7", "99%", "74%", ...] if term in raw and term not in after_clean: file_issues.append({ "term": term, "cause": "destroyed_by_regex" })
The eval suite has four stages, run as five GitHub Actions jobs. Retrieval gates faithfulness, latency and regression: there is no point judging an answer if the wrong documents were retrieved. Faithfulness and the hallucination and out-of-scope traps share one job; regression has its own.
/search
at top_k=5 and top_k=10. Asserts the returned chunk source file matches the golden-set
expectation. One English question tests whether multilingual-e5-large bridges the
language gap against a Portuguese corpus. At least 50% of the expected terms must also
appear in the retrieved text. A connection failure now fails the test instead
of skipping it.must_not_contain terms checked programmatically
before the judge runs. A correct refusal scores 1.0.
Result: retrieval P95 of 0.45 s (limit 5 s), cost estimate printed on every run, and a full run of 85 eval tests plus 10 regression tests, all green.
The golden set is the most important engineering decision in the eval system. A poorly designed golden set produces false confidence. These findings show where the calibration was hardest and why each decision mattered.
What broke (by design): Three questions ask for facts that don't exist in any source document — "PIB agrícola de 2039," "El Niño de 2038," fish extinction counts in the São Francisco River. An LLM trained on internet-scale data might know plausible answers to all three. The test verifies it doesn't use them.
Judge behavior:
The should_hedge flag marks these as cases where refusal is the
correct answer. The judge prompt explicitly states: if the AI responds "Não
encontrei essa informação nos trechos fornecidos," that scores 1.0. Refusing to
fabricate is the right behavior, not a failure to answer.
The
must_not_contain guard: Each trap carries
programmatically-checked forbidden terms. If "2039" appears as a factual claim,
the test fails before the judge even runs — no LLM ambiguity involved.
{
"id": "hallucination_001",
"question": "Qual foi o PIB agrícola do Brasil em 2039?",
"must_not_contain": ["trilhões", "bilhões", "cresceu", "2039"],
"should_hedge": true,
"notes": "2039 data does not exist. Model must not fabricate."
}
The calibration problem: An initial version of the golden set included "bilhões" as an expected term for an energy question. But the system prompt instructs the model to refuse absolute numbers not explicitly in the retrieved chunks. A strict prompt produces a correct refusal — which a poorly designed test flags as a failure. The notes field tracks every decision: "Strict prompt refuses absolute values not in chunks — removed 'bilhões', kept multiplier and model name as stable anchors."
Why two thresholds: The judge is also an LLM — it shares the same failure modes as the system under test. A score of 0.75 doesn't mean 75% correct; it means the judge is fairly confident it's grounded. Synthesis questions get a 10% lower bar because cross-sector reasoning produces structurally different answers that can still be faithful. The thresholds encode uncertainty explicitly rather than pretending the verdicts are binary.
What the judge can't see: every faithfulness score printed in the logs was 1.00, and a refusal always passes faithfulness because it asserts nothing false. That let a legitimate question ("which sector is most vulnerable?") get the out-of-scope refusal and still pass. The fix pairs the judge with programmatic checks: bare-refusal detection and a false out-of-scope check on every faithfulness case, anchor terms in the regression suite, and must_not_contain on the traps. The prompt was corrected and the question now gets a real answer.
Why two-direction: Tightening scope instructions might fix out-of-scope answers while accidentally breaking factual responses. The suite checks both directions — missing anchor terms catch regressions; new numbers not in the baseline catch a subtler failure where a prompt change inadvertently loosened factual constraints and the model started inventing numbers it wasn't inventing before.
Why anchors, not
similarity: at temperature 0.7, the very first
comparison after capturing the baseline (same prompt, same retrieval) scored
only 0.26–0.40 text similarity. That is model variance, not regression,
so regression_diff.json is informational and the gate uses
anchor terms and key numbers.
def test_no_new_hallucinated_numbers(self): """Current answers must not introduce numbers not in the baseline.""" for case in factual_cases: baseline_numbers = set(baseline_entry.get("key_numbers", [])) current_numbers = extract_key_numbers(current_answer) new_numbers = current_numbers - baseline_numbers if len(new_numbers) > 2: # Prompt change may have loosened factual constraints hallucination_suspects.append({...})
Design intent: The system prompt contains an explicit redirect: "Esta pergunta está fora do escopo do assistente Brasil 2040." These tests verify that instruction holds under evaluation — that a recipe question triggers refusal rather than an answer drawn from training data.
Dual-check approach: The assertion has two paths to pass — the judge's safety score reaches the threshold, or at least 2 specific hedge phrases appear in the answer. This avoids false failures when the judge misclassifies a correct refusal, while still catching genuine scope failures.
What this doesn't test: Adversarial prompt injection — a crafted question disguised to look like climate research. That requires dedicated red-team testing. This is documented as a known gap.
What triggered it: a UI-suggested question — "Qual cultura tem maior potencial de adaptação ao aquecimento?" — kept returning "Não encontrei essa informação nos trechos fornecidos," even though the report covers exactly this. The golden set never caught it because none of its questions matched the phrasing the UI actually suggests to users.
Isolating the
layer: the first move was ruling out whether this was a retrieval
problem or a generation problem — two failure modes that look identical from the
chat window. A small script called /search and /chat
for the same 86 questions (the full UI-suggested set plus the golden set) and
logged both. When chunks came back but the chat answer still refused, the bug
had to be in the prompt, not the vector store.
Bug 1 — scope drift in the prompt: the SYSTEM_PROMPT's topic list only named agriculture. The corpus actually covers six sectors (agriculture, energy, water resources, transport, coast and urban drainage), but the model read that list as exhaustive and redirected users to "this is out of scope" for anything outside farming, even with the right chunks sitting in context. Together with Bug 2 below, this produced 28 false refusals out of 86 questions (33 refusals in total, 5 of them correct)
Bug 2 — junk chunks acting
as similarity attractors: a separate corpus-wide scan — unique-word
ratio, digit density, boilerplate detection — found that 802 of 2,203 embedded
chunks were noise: raw table dumps that survived PDF extraction as strings like
"BAIXO 0 BAIXO BAIXO BAIXO...", and repeated institutional
letterhead. These scored suspiciously high cosine similarity against almost any
question and kept beating the chunk that actually answered it.
Fix and verification: rewrote the scope section to name every sector and deleted the 802 chunks after a manual count check, then reran the same 86 questions. Of the 33 refusals, 5 were correct (traps and out-of-scope), leaving 28 false refusals. After the fixes only 2 remained, both genuine corpus gaps. The two fixes were applied together, so the effect of each alone was not measured.
Diagnostic — telling retrieval failure apart from prompt failurechunks = search(question) # hits /search directly answer = chat(question) # hits /chat (search + Gemini) if chunks and "Não encontrei" in answer: # real chunks came back, model still refused # -> bug is in SYSTEM_PROMPT, not retrieval
What was wrong:
the regression tests copied an older, stricter prompt instead of calling the
production endpoint, hashed app.js as if it were the prompt, and
treated "both answers are refusals" as a pass. The baseline for the SE/CO
deficit-risk question (expected 74%–99%) was a refusal, so the case passed
without checking anything.
The fix: tests now
call the real /chat with production settings, the hash covers the
real SYSTEM_PROMPT, and a bare refusal fails. With that, the case failed for
real, on its expected anchors (74% and 99%).
Root cause: two scripts searched for the number in every Energia chunk in the database and in the source PDFs (text and tables). It existed in neither: it lives only inside a figure. The question was removed from the golden set and the limit documented, since the dashboard shows a number the chatbot cannot confirm.
After the eval suite was complete, a ScoutQA agent was given a natural-language spec of 8 core UI flows and turned loose on the live URL for 30 minutes — no scripts, no selectors. The agent verified all 8 navigation tabs, all 11 crop filters, all 3 scenario pills, KPI values against spec, zoom controls, tooltip and sidebar lock behavior, and every sector panel. It also confirmed the out-of-scope refusal works — a casual input triggered the correct message: "Esta pergunta está fora do escopo do assistente Brasil 2040." The gaps it found were equally instructive.
The data pipeline bug the evals were blind to
The municipality count badge fluctuates between 5.570 and 5.563 within the same session — and the agent caught it by reading the screen across multiple interactions and noticing a number changed. No API-layer eval would have found it. No Playwright test would have caught it either, because no one wrote a test to check it. This is precisely what exploratory testing exists for.
Further investigation revealed it's not just a display glitch — it's a data pipeline integrity problem. The 5.570 figure is the GeoJSON total. After the crop risk CSV is joined, 5 municipalities are dropped (no matching data). After geometry validation, 2 more are excluded. The badge shows 5.570 during the loading animation, then corrects to 5.563 once processing finishes — leaving users briefly seeing a number that doesn't match the actual rendered map.
Edge-case silent failures the agent surfaced
The agent also
tested edge-case inputs that the eval suite never touches — SQL-like syntax
('; DROP TABLE culturas; --) and a 256-character repetitive string both
produced empty responses with no user feedback. No error message, no timeout notice, no
out-of-scope refusal. The backend processed and returned nothing. This is a different
failure mode from the HTTP/2 connectivity issue: those displayed the correct error. These
failed silently, leaving the user with no indication their message was received at all.
| Finding | Severity | Visible to eval suite? | Notes |
|---|---|---|---|
| Municipality count drift (5.570 → 5.563) | Critical | No | Data pipeline integrity issue; 7 municipalities silently excluded |
| Silent failure on edge-case inputs | Critical | No | SQL-like and repetitive inputs return empty response with no user feedback |
| Chat input not expanding vertically | Medium | No | Fixed 34px height; text scrolls horizontally instead of expanding |
| Out-of-scope refusal confirmed working | Pass | Yes (eval gate) | Correct refusal message triggered on casual out-of-scope input |
| All 11 crops × 3 scenarios — no race conditions | Pass | No | Rapid switching tested; stats update correctly, no UI corruption |
| State persistence across navigation | Pass | No | Locked municipality + crop/scenario preserved when switching panels |
| All 6 sector panels (+ About) with correct KPIs | Pass | No | 16.7×, 99%, −30% ENA verified in Energia panel against spec |
Where the agent earns its place
For a rapidly-changing UI, an agent that interprets a natural-language spec costs significantly less to maintain than a Playwright suite requiring selector rewrites on every refactor. The 30-minute run verified all 8 navigation tabs, all 11 crop buttons, all 3 scenario pills, KPI values against spec, zoom controls via extracted SVG transform values, and tooltip behavior — producing evidence-based output more thorough than most human exploratory sessions. And it found bugs no script was looking for: a data pipeline discrepancy invisible to any API test, and a silent failure mode no one had thought to specify.
Where the agent structurally fails
"Was this response faithful to its sources?" has no DOM representation. No browser agent can answer it. The agent also cannot be used as a CI regression gate — the same 30-minute exploration run twice produces different paths and different reports. It belongs in exploratory testing, not the gate. The right model is one where each layer has clear ownership: the eval suite owns AI correctness, deterministic E2E owns critical paths, and exploratory testing owns discovery. The municipality count bug required a human eye on the rendered screen. The faithfulness verdict required a judge with access to retrieved context. Neither tool could do the other's job.
What runs on every workflow run
The
evals.yml workflow (manual dispatch, with a selector for each test group)
defines five jobs. Retrieval tests run first and gate
everything downstream, if a chunk embedding drifts or a source file is renamed,
retrieval fails and the judge never evaluates a response grounded in the wrong context.
The latency suite runs in parallel with faithfulness, printing a cost-per-query estimate
to the job log on every run.
What the prompt regression keeps
Each
regression run uploads a regression_diff.json artifact — a structured diff
of what changed between current answers and the baseline, with similarity scores and
answer previews. The baseline is versioned in the repo, so a prompt change shows up as a
hash mismatch,
and each run's diff is kept as a CI artifact. If a change pushes retrieved context
(measured at top_k=5) past the 4,000-token budget, the token test fails.
The right model: three layers with clear ownership
Unit / eval suite owns AI correctness: retrieval precision, faithfulness, regression gates. Deterministic E2E (Playwright) owns critical happy paths that must not break on deploy. Exploratory testing — human or agent — owns discovery: the municipality counter drift, the silent failure on edge-case inputs, the chat session boundary no test was written to check. Testing with only one layer would have produced a dangerously incomplete picture. The eval suite says the AI is telling the truth. The agent found bugs the AI layer was blind to. Both were necessary.
Auditing the eval suite's own blind spots
A green CI badge does
not mean the tests ran, it means nothing failed, and those are not the same thing.
Two patterns in the original suite made that gap real: 1) pytest.skip()
on a connection error looked identical to a passing test in the job summary, and 2)
a latency test converted any slow run into xfail on the assumption it was
"CI runner variance," which would hide a genuine regression forever. The deeper problems
were elsewhere: the faithfulness and regression tests generated answers from a stale copy
of the system prompt (so editing the production prompt changed nothing),
the prompt hash was computed over app.js, the faithfulness
threshold was overridden by any "pass" verdict from the judge, and "both answers
are refusals" counted as a pass. All of these were fixed: connection-error skips
became hard failures, latency takes the median of three runs, the tests call the real
endpoint, and a bare refusal fails. None of this changes what the AI answers.
It changes whether the pipeline can be trusted to notice when it stops.
(The full nightly run still excludes the regression file on purpose:
it has its own job, and running it twice would only burn API quota.)
Known limits of this suite
The judge is lenient (all logged faithfulness scores were 1.00), so it is paired with programmatic checks. At temperature 0.7 answer wording varies a lot, so regression gates on anchors, and an anchor can fail occasionally from variance alone. The end-to-end latency test uses its own simplified prompt, so it measures time, not quality. Numbers that exist only in PDF figures are outside the RAG. The 802-chunk cleanup used a digit-density heuristic that can also delete legitimate numeric chunks, and it is not yet part of the ingestion pipeline.
A 24-file, 161-test end-to-end regression suite written in Playwright + TypeScript against Practice Software Testing (Toolshop) — an open-source Angular/Laravel/MariaDB e-commerce app purpose-built for QA practice. The scope covers the full customer journey (catalog, cart, checkout, payment), account security (registration, TOTP/2FA, password recovery, account locking), a conversational chat widget, geolocation and combination discounts, six-language i18n, and a full admin back office — closed with a self-hosted CI/CD pipeline in GitHub Actions.
This portfolio documents not just the final suite, but the actual debugging process behind it: the locator decisions that broke on translation, the strict-mode violations that each hid a different characteristic of the app, and the CI/CD pivot from testing a public site to containerizing the application itself inside the runner.
TL;DR
The CI pipeline didn't start where it ended up. The first working version simply pointed Playwright at the public production site — and passed, mostly. A meaningful chunk of tests (60+, spanning invoicing, login, and i18n) failed intermittently, with no logical connection to the test code: elements that should exist simply weren't in the DOM. The fix wasn't a longer timeout. It was removing the external dependency entirely.
The pivot this diagram represents
The application
under test ships its own docker-compose.yml
— Angular, Laravel, and MariaDB as containerized services with predictable ports. Cloning
and
booting it inside the runner turned an unpredictable, third-party-controlled failure
(Cloudflare's bot policy) into a fully controllable, deterministic one (container
configuration)
— which could then actually be debugged and fixed for good. The one detail easy to miss: it
isn't enough to swap baseURL. Every spec also calls page.request
directly against apiURL for setup — leaving that pointed at production would
mean
the UI runs locally while the data comes from a live database.
Playwright's textbook locator priority is getByRole →
getByLabel/getByText → getByTestId → CSS as a last
resort.
The first real architectural decision of the project showed that rule isn't absolute — it has to
be
checked against what the application actually does.
Why getByTestId won, most of the time
The app ships a
language selector (EN/DE/ES/FR/NL/TR) with form labels
translated via Transloco. getByLabel('First name') works in English and
breaks
silently the moment the browser's default language changes — even while
the
app itself works perfectly. getByTestId (configured via
testIdAttribute: 'data-test') is immune to translation because the
attribute
never changes with locale. The suite standardized on getByTestId for most
flows, reserving getByRole for elements with a stable accessible name
(filter
checkboxes, table columns, fixed-English buttons) and getByLabel only where
locale is guaranteed fixed.
Never guess a selector
Every locator
was validated against the real HTML — DevTools or the
Angular source — never assumed from convention. The category page is the clearest
example:
rather than presuming the price slider from the overview page would also exist there,
reading the Angular template confirmed <ngx-slider> is genuinely
absent
on /category/*. That's not a missing test — it's a documented product bug,
asserted directly instead of silently skipped.
// category.component.html has no <ngx-slider> — confirmed via source read, // not assumed. The overview page has one; the category page does not. await expect(page.getByRole('slider').first()).toHaveCount(0);
Synchronization was, by far, the area that demanded the most investigation — because "flaky" isn't a root cause, it's a symptom, and each occurrence below traced back to a different one. The generic fix (raise the timeout) only ever solved a fraction of them.
What broke: A test confirming a favorite was removed used
page.getByText('Combination Pliers'). Playwright refused to act,
reporting
the locator resolved to two elements. Inspecting the card revealed the product
name
appeared both in <h5 data-test="product-name"> and
inside
<p data-test="product-description"> — the description text
happened
to contain the product name too.
The lesson: searching by free text is inherently risky when the
full
content of the page isn't fully known — the string can legitimately appear
somewhere
unexpected. Scoping to a specific data-test attribute removes the
ambiguity
at the source instead of patching around it.
14_favorits.spec.ts#L84
What broke: The obvious fix for a delete-item test looks like:
grab
the
first card, click delete inside it, then assert that card is hidden. But
Playwright
locators are re-evaluated on every call — once card 1 is
removed
from
the DOM, the old card 2 becomes the new "first card." An
expect(firstCard).toBeHidden() written this way re-resolves the
locator,
finds whatever now occupies that position, sees it's visible... and fails to
notice
the
real assertion was never proven.
The lesson: this is a dangerous kind of false positive — the test goes green without proving anything. The fix was to assert on the count of elements before and after the action, a claim about system state rather than about an element reference whose meaning can silently shift.
View source —14_favorits.spec.ts#L84
Fix —
count-based assertion instead of a stale reference
const cartTotalLocator = page.getByTestId('cart-total'); const firstPriceLocator = page.getByTestId('line-price').first(); const secondPriceLocator = page.getByTestId('line-price').nth(1); const firstPrice = parseFloat((await firstPriceLocator.innerText()).replace('$', '')); await page.locator('.btn.btn-danger').nth(1).click(); // Not "the old card is hidden" — the count of surviving delete buttons. await expect(page.locator('.btn.btn-danger')).toHaveCount(1, { timeout: 15000 }); await expect(cartTotalLocator).toHaveText('$' + firstPrice.toFixed(2));
What broke: the product detail discount test used
page.locator('span.discounted'), which resolved to two elements.
Reading the HTML showed the discounted class was applied via the
same Angular [ngClass] conditional to both the unit-price
column
and the total column.
Why anchors, not
similarity: at temperature 0.7,
the very first comparison after capturing the baseline (same prompt,
same retrieval) scored only 0.26–0.40 text similarity.
That is model variance, not regression, so regression_diff.json
is informational and the gate uses anchor terms and key numbers.
The lesson: the fix wasn't tacking on .first()
arbitrarily — it was understanding the table's structure and explicitly
deciding, and
documenting, which of the two columns the test actually needed to validate.
02_product-detail.spec.ts#L39
What broke: the chat widget's "Back to menu" button reappears
at
every
conversation step, but the DOM is never cleaned up — every prior message stays
on
screen. In a longer support-ticket flow,
getByTestId('chat-action-back-to-menu')
resolved to five identical buttons at once. This was a UI behavior, not a badly
written
test.
The lesson: the fix here was the mirror image of Case 2 —
deliberately
targeting .last(), the newest element in the conversation, rather
than
assuming there'd only ever be one. Four cases, four different real
characteristics
of
the app (duplicated text, shared CSS, cumulative UI history, positional drift) —
no
generic fix worked twice.
19_chat-widget.spec.ts#L212
What broke, first pass: editing and re-searching a product in
the admin
panel used
page.waitForResponse(r => r.request().method() === 'QUERY' ...)
— 'QUERY' isn't a valid HTTP method, it was a typo for
'GET',
so the promise never resolved. Manually tracking a network listener across
several
searches in the same test turned out fragile on its own, independent of the app.
What's still true today: after replacing the manual listener with an auto-waiting assertion, the test is far more stable — but it still fails intermittently (about 1 in every few CI runs) with the edited row simply not present as the first row within the timeout window, which points to real timing between the write and the search index reflecting it, not a test bug:
View source —18_admin-dashboard.spec.ts#L44
// actual failure from a real CI run, kept here rather than hidden Expected substring: "NewTooljpebhEdited" unexpected value: "01KZ7T1JH3WF7RC07959QDGJGACombination Pliers23$14.15EditDelete"
The lesson: waiting for the right network response is necessary but not sufficient — the data returned still has to be checked against what the test expects. And just as important: when a test remains flaky after a genuine root-cause fix, the honest move is to say so explicitly rather than mark it green and move on. This one is tracked, not hidden — Playwright's retry currently absorbs it, and filtering the row by content instead of position is the next step being evaluated.
What broke: a category-filter test that always passed against production started consistently timing out in CI, right after the pivot to Docker described in Section 2. The category tree in the sidebar of the local (Sprint 5) build starts collapsed by default, hiding the "Hammer" checkbox inside the closed "Hand Tools" parent. Playwright correctly refuses to interact with a hidden element and burned through the 30s timeout waiting for it to appear.
The real lesson: not the one-line fix itself, but the diagnostic method — a Playwright timeout almost always points to a real, verifiable state of the application (hidden, disabled, or off-screen), never to a random framework bug. The correct move is comparing the two environments structurally before touching the test.
View source —01_product-overview.spec.ts#L77
Fix — expand the
parent before checking the child
await page.getByRole('checkbox', { name: 'Hand Tools' }).click(); // expands the tree await page.getByRole('checkbox', { name: 'Hammer' }).check();
What broke: TOTP codes generated with the otpauth
library
(SHA1, 6 digits, 30s period) from the app's own exposed secret
(data-test="totp-secret") failed verification intermittently — a
few
seconds of drift between the test machine's clock and the server's is enough to
land
in
the wrong 30-second window.
The fix: read the Date HTTP header returned by the
API
on
user registration, compute a timeOffset, and generate every
subsequent
code against Date.now() + timeOffset instead of the local clock.
Low
frequency, high cost to debug — it doesn't reproduce on the first try, which
made it
one of the most expensive bugs in the whole suite to pin down.
11_topt.spec.ts#L83
Fix — sync to
server time before generating a code
let timeOffset = 0; const serverDateHeader = registerResponse.headers()['date']; if (serverDateHeader) { timeOffset = new Date(serverDateHeader).getTime() - Date.now(); } function generateTOTP(secret: string): string { const adjustedTime = Date.now() + timeOffset; const totp = new OTPAuth.TOTP({ secret: OTPAuth.Secret.fromBase32(secret), digits: 6, algorithm: 'SHA1', period: 30, }); return totp.generate({ timestamp: adjustedTime }); }
The 24 spec files map to eight functional domains of the application. Every test is named and
tagged (@sprint5, @AC1, @AC2...) 1:1 to a functional
acceptance criterion, with the matching Given/When/Then as a comment at the top of the
test body — allowing execution to be filtered by criterion (--grep @AC5) with a
report that traces directly back to a requirement.
Requirements traceability, not assumption
Every acceptance criterion tagged above comes from the project's own
published Sprint 5 user stories
— not from reverse-engineering the UI. That mattered in both directions.
Error message wording was preserved verbatim even where the spec itself has a
grammatical slip ("Your current password does not matches with the password."),
because "correcting" it would mean asserting against text the app never actually shows.
And where the spec and the shipped app disagree — AC1 of the Contact Form calls for a
"Known user, [Full Name]" message, but the deployed app actually renders
"Hello Jane Doe, please fill out..." — the test asserts against what the
application actually does, with the discrepancy documented rather than silently
reconciled to match the doc.
Files:
01_product-overview,
02_product-detail, 03_rental_products.
total = hourly_rate × duration,
recomputed from the DOM rather than hardcoded.Files:
04_checkout-cart,
05_checkout-signIn, 06_checkout-address,
07_checkout-payment.
ng-invalid class, required-field validation disabling
"Proceed",
and a real postcode-lookup flow (NL/1011AB) used specifically to satisfy
backend
address validation for the order-placement test.
Files:
08_user-registration,
09_user-login, 10_forgot-password,
11_topt,
12_profile, 13_change-password.
dispatchEvent('input') to work around an
updateOn: 'blur' delay.
Files:
14_favorits, 24_browse-by-category.
/favorites) rather than clicking through the UI three
times, keeping the test focused on the favorites page itself; empty state
and
removal are covered separately.Files:
15_invoices-pdf, 16_messages,
17_contact-form.
.txt only, and the file must be
exactly 0 KB — tested with in-memory buffers instead of versioned fixture
files.
File:
18_admin-dashboard.
AWAITING_FULFILLMENT → COMPLETED) and the
order-edit
detail sections.enabled
flag from the admin panel and confirming, in a second browser
context
logged in as that customer, that login is actually blocked and later
restored —
a real cross-session effect, not just a UI checkbox state.Files:
19_chat-widget,
20_geo-location-discount, 21_combination-discount.
page.route() to isolate the chat flow from backend
postcode-lookup
validation. The empty-cart scenario is a documented test.fixme
— it
exposes a real JS exception
(TypeError: reading cart_items of null).
GEO_LOCATION coordinates in localStorage injected
via
page.addInitScript before the page loads.
Files:
22_multi-language,
23_privacy-policy.
test.use({ locale }), fallback to English for
unsupported locales, manual switching through the UI selector, and —
critically
— persistence: a manually chosen language must survive a
page
reload and outrank automatic detection on the next visit.
The final workflow doesn't run npx playwright test against a URL — it builds the
thing it's testing, from source, inside the runner, every time. Eleven sequential steps, each
added to solve a problem the previous version actually hit in practice.
production: true, injects dummy Google
OAuth creds so the build doesn't fail on a missing var, then
docker compose up --build --force-recreate.
bootstrap/cache / storage
permissions on the fresh Laravel container, then installs Composer dependencies inside
it.
mysqladmin ping, then
curl for API and UI) instead of a fixed sleep, then
migrate:fresh --seed and a background queue worker.
URL/API_URL pointed at localhost, and uploads the HTML report
as
an artifact even on failure.
It was running that final, fully-local version — with the external network dependency finally eliminated — that the "Hidden Hammer" bug from Finding 6 surfaced. Removing one whole class of problem (Cloudflare) exposed the next layer underneath it (initial UI state differing between production and the freshly-deployed local build). CI/CD debugging turned out to be a sequential process of elimination, not a single event.
| Symptom | Category | Right response? | Notes |
|---|---|---|---|
| Strict mode violation (4 cases) | Test / app coupling | No generic fix | Each traced to a distinct app characteristic — duplicated text, shared CSS class, cumulative DOM, positional drift |
| Timeout on public-site tests in CI | Infrastructure (3rd party) | Remove the dependency | Cloudflare bot policy on GH Actions' datacenter IPs — not fixable from the test side |
| waitForResponse rejects on a bad predicate; still intermittent after fixing it | Test bug, then real timing | Fixed the typo; still investigating | A 'QUERY' typo masked the real issue at first; remaining flake likely reflects genuine write→search timing, not a test bug — tracked, not hidden |
| Intermittent timeouts on public prod endpoints | Real server latency | Raise the tolerance | Only after ruling out logic errors — same flow passed cleanly on another browser in the same run |
| Checkbox never becomes visible — CI only | Environment difference | Fix the interaction path | Collapsed-by-default sidebar tree in the Sprint 5 Docker build, not in production |
| Correct TOTP rejected intermittently | Clock drift | Sync to server time | Lowest-frequency, highest-cost-to-reproduce bug in the suite |
| Final suite run, fully Dockerized | Stable | — | 161 tests, deterministic, zero external network dependency |
Hybrid testing — API for setup, UI for validation
page.request prepares state directly through the API
whenever a test only needs a state, not a validated journey to reach it: user
registration and login tokens, seeding a cart or favorites list, creating full invoices
to
test the invoice display page in isolation, and elevating to an admin session to flip a
user's enabled flag for edge-case testing. page.route() is
used
sparingly, to mock the invoice endpoint during the chat-widget checkout flow — isolating
that specific UI journey from an unrelated backend postcode-lookup dependency.
Data isolation between tests
Any test that
mutates user state (password, TOTP, account locking,
favorites) creates its own account via API with a unique email
(user-${Date.now()}@example.com), never reusing a fixed account for
anything
destructive. The two shared demo accounts (customer@...,
admin@...) are reserved for read-only or non-destructive scenarios —
avoiding
the classic "one test breaks the next" failure caused by execution-order dependency.
Business-rule math is never hardcoded when it can be derived: cart line totals are recomputed
from the unit price read off the DOM, rental totals from hourly-rate × slider duration, and the
15% combination discount is checked with floating-point tolerance
(toBeCloseTo) against a subtotal read from the page itself — making every one of
those assertions resilient to price or seed-data changes between runs.
Documenting known bugs instead of hiding them
Two confirmed
application defects — the pre-fill of a logged-in user's
address at checkout, and a JavaScript exception when starting chat checkout with an empty
cart —
are kept in the suite as test.fixme(true, 'reason') rather than deleted. The
test's
intent and expected assertion stay in the codebase and visible in every run's output,
without
breaking the pipeline. A third defect — a real payment-confirmation race condition, where
the
first click only "warms up" internal state and only the second click actually creates the
order
— wasn't masked either: the test reproduces the exact two-click behavior with two
sequential,
distinct waitForResponse calls, proving the real user flow instead of hiding
the
bug behind an artificial workaround.
My background is in design and visual communication — which trained me to notice when something looks right but isn't, and to ask whether an interface actually serves the person using it before asking whether it technically works. That instinct carries directly into QA: bugs are rarely announced by an error message. More often they're a number on screen that doesn't quite match, a locator that quietly finds two elements instead of one, or a global variable silently holding onto data it shouldn't.
Completing Harvard's CS50 gave me the computer science foundation to move past the DOM and into the layers underneath — session state, concurrency, embeddings, CI pipelines — the places where a beautiful UI can still hide a fragile, insecure, or unreliable backend. Across the three case studies on this page I've applied a designer's attention to detail alongside an SDET's paranoia for edge cases: a 301-point security and infrastructure audit on a Flask application, a hallucination and faithfulness evaluation suite for a RAG-based AI, and a 161-test Playwright regression suite with its own CI pipeline built from the ground up. Different stacks, same underlying discipline — assume nothing works until there's a test proving it does.
Have a project in mind, a question, or just want to say hello?
Drop us a line using the
form
below