Testing and debugging in Laravel Rust
Keep working in the project from the lesson on ticket CRUD. Keep the Cargo.lock for the data lessons. You'll test input rules in isolation, then send requests through the actual local HTTP server backed by PostgreSQL.
Test the input rules directly
Create src/routes/api/tests.rs. These tests distinguish an omitted field from null and a title suitable for preview from one PostgreSQL can store. Append the module declaration to src/routes/api.rs and keep the previous tests.
use super::{patch_input, persistent_title, validated_title};
use serde_json::json;
#[test]
fn patch_distinguishes_omission_from_null_and_rejects_an_id() {
let patch = patch_input(json!({"status": "closed"})).ok().expect("valid patch");
assert_eq!(patch.title, None);
assert_eq!(patch.status.as_deref(), Some("closed"));
for input in [json!({"title": null}), json!({"status": "closed", "id": 9})] {
assert_eq!(patch_input(input).err().expect("rejected").status(), 422);
}
}
#[test]
fn only_persistent_titles_reject_nul() {
// Check the storage rule separately to preserve the preview contract.
let title = validated_title(" a\0b ").expect("valid for preview");
assert_eq!(title, "a\0b");
assert_eq!(persistent_title(&title).expect_err("not PG text").status(), 422);
}
#[cfg(test)]
#[path = "api/tests.rs"]
mod persistence_tests;
From the project root, check formatting and types, run the library tests, and build the executable. The integration scenario uses this same binary.
export CARGO_TARGET_DIR="$PWD/target"
export CARGO_BUILD_BUILD_DIR="$CARGO_TARGET_DIR/build"
export CARGO_INCREMENTAL=0
cargo fmt --check &&
cargo check --locked --offline --all-targets &&
cargo test --locked --offline --lib &&
cargo build --locked --offline
Run HTTP checks against dedicated PostgreSQL
In the skeleton's src/testing.rs, for_testing selects the testing environment. with_env and with_envs set explicit Laravel configuration overrides. With refresh_database, the harness uses the configured connection's driver. For PostgreSQL it creates numbered copies, applies migrations, and rolls back each test's transaction. That needs permission to create databases. A test transaction also keeps its uncommitted changes invisible to other connections.
This exercise needs a real HTTP listener, multiple connections that can see commits, and a separate session for a controlled lock. The ordinary server uses the same configure, connection pool, and role without database creation privileges. The script starts the server on a free loopback port and sends requests only there. Create scripts/check-tickets.sh. You need curl, jq, and the existing PostgreSQL tools.
The script first verifies the test database and starts the server. It then checks HTTP responses and row snapshots, including slot. Finally, it exercises rollback, timeout, and the race for the last slot. In http, -q is the first curl argument so .curlrc cannot alter the local requests.
#!/usr/bin/env bash
set -euo pipefail
source scripts/ticket-db.sh
database=ticket_test
role=ticket_api
# The test needs a separate database in a known starting state.
verify "$role" "$database" ticket_data
[[ $(sql "$role" "$database" -c 'SELECT count(*) FROM tickets') == 2 ]]
run=$(mktemp -d "$lab/http.XXXXXXXX")
app_pid=
lock_pid=
# Wait for the lock session and stop only the server started by this script.
cleanup() {
if [[ -n $lock_pid ]]; then wait "$lock_pid" || true; fi
if [[ -n $app_pid ]]; then
kill "$app_pid" 2>/dev/null || true
wait "$app_pid" || true
fi
}
trap cleanup EXIT
bash scripts/ticket-db.sh serve "$database" 0 >"$run/server.log" 2>&1 &
app_pid=$!
base=
for _ in {1..50}; do
kill -0 "$app_pid"
base=$(sed -n 's/^Server running at `\(http:\/\/127\.0\.0\.1:[0-9]*\)`.*/\1/p' "$run/server.log")
if [[ -n $base ]]; then break; fi
sleep .1
done
[[ $base =~ ^http://127\.0\.0\.1:[0-9]+$ ]]
tickets=/api/tickets
body=$run/body
checks=0
# Save the body to a file so the response status can be checked separately.
http() {
local path=$1 output=$2
shift 2
curl -q -sS --noproxy '*' --max-time 8 -H 'Accept: application/json' \
-o "$output" -w '%{http_code}' "$@" "$base$path"
}
expect() {
local expected=$1 path=$2 status
shift 2
status=$(http "$path" "$body" "$@")
if [[ $status != "$expected" ]]; then
printf 'Expected %s for %s, received %s\n' "$expected" "$path" "$status" >&2
exit 1
fi
checks=$((checks + 1))
}
json=(-H 'Content-Type: application/json')
snapshot() {
sql "$role" "$database" -c 'SELECT id, title, status, slot FROM tickets ORDER BY id'
}
# Compare snapshots of all columns to catch unintended writes.
baseline=$(snapshot)
expect 200 "$tickets/1" -X OPTIONS -D "$run/preflight" \
-H 'Origin: https://example.invalid' -H 'Access-Control-Request-Method: PATCH'
if grep -qi '^access-control-allow-origin:' "$run/preflight"; then exit 1; fi
expect 200 "$tickets" -D "$run/headers" -H 'Origin: https://example.invalid'
if grep -qi '^access-control-allow-origin:' "$run/headers"; then exit 1; fi
jq -e 'map(.status) == ["open","closed"] and (map(.id) == (map(.id) | sort))' "$body" >/dev/null
other=$(jq -er '.[1].id' "$body")
expect 200 "$tickets/preview" "${json[@]}" --data '{"title":" Preview ","id":7,"status":"closed"}'
jq -e '. == {"title":"Preview"}' "$body" >/dev/null
expect 200 "$tickets/preview" "${json[@]}" --data '{"title":"x\u0000y"}'
jq -e '.title == "x\u0000y"' "$body" >/dev/null
expect 400 "$tickets" "${json[@]}" --data '{"title":'
expect 415 "$tickets" --data 'title=form'
expect 400 "$tickets?status=pending"
expect 400 "$tickets/0"
expect 404 "$tickets/-1"
jq -e '.message == "Not Found"' "$body" >/dev/null
expect 404 "$tickets/4294967296"
expect 404 "$tickets/4294967295"
jq -e '.message == "Ticket not found."' "$body" >/dev/null
for payload in '{"title":null}' '{"title":7}' '{"title":""}' '{"title":" \t "}' '{"title":"a\u0000b"}'; do
expect 422 "$tickets" "${json[@]}" --data "$payload"
jq -e '.errors.title | length > 0' "$body" >/dev/null
done
long=$(jq -nc '{title:("🦀"*121)}')
expect 422 "$tickets" "${json[@]}" --data "$long"
printf '%-4096s' '{"title":"Edge"}' >"$run/padded.json"
expect 200 "$tickets/preview" "${json[@]}" --data-binary "@$run/padded.json"
printf ' ' >>"$run/padded.json"
expect 413 "$tickets" "${json[@]}" --data-binary "@$run/padded.json"
[[ $(snapshot) == "$baseline" ]]
title=$(jq -nr '"🦀"*120')
payload=$(jq -nc --arg title "$title" '{title:("\u00a0"+$title+"\u2009"),id:900,status:"closed",role:"owner"}')
expect 201 "$tickets" "${json[@]}" --data "$payload"
id=$(jq -er '.id | select(type=="number" and .>0 and .!=900)' "$body")
jq -e --arg title "$title" '.title == $title and .status == "open"' "$body" >/dev/null
expect 200 "$tickets/$id"
jq -e --arg title "$title" '.title == $title' "$body" >/dev/null
# Even a valid title must stay unchanged when another field fails validation.
before=$(snapshot)
for payload in '{}' '{"title":null}' '{"status":null}' '{"title":7}' '{"status":"pending"}' \
'{"title":"Valid replacement","status":"pending"}' \
'{"title":" "}' '{"title":"a\u0000b"}' '{"title":"Ignored","id":9}' '{"status":"closed","role":"owner"}'; do
expect 422 "$tickets/$id" -X PATCH "${json[@]}" --data "$payload"
jq -e '.errors | length > 0' "$body" >/dev/null
done
[[ $(snapshot) == "$before" ]]
# Update different fields concurrently to catch a lost change.
literal="O'Reilly -- fixture"
payload=$(jq -nc --arg title " $literal " '{title:$title}')
http "$tickets/$id" "$run/title.json" -X PATCH "${json[@]}" --data "$payload" >"$run/title.status" &
title_pid=$!
http "$tickets/$id" "$run/status.json" -X PATCH "${json[@]}" \
--data '{"status":"closed"}' >"$run/status.status" &
status_pid=$!
wait "$title_pid"
wait "$status_pid"
[[ $(cat "$run/title.status") == 200 && $(cat "$run/status.status") == 200 ]]
expect 200 "$tickets/$id"
jq -e --arg title "$literal" '.title == $title and .status == "closed"' "$body" >/dev/null
expect 200 "$tickets?status=closed"
jq -e --argjson id "$id" --argjson other "$other" 'map(.id) == [$other,$id]' "$body" >/dev/null
expect 200 "$tickets/$id" -X PATCH "${json[@]}" --data '{"title":"Reopened fixture","status":"open"}'
jq -e --argjson id "$id" '. == {id:$id,title:"Reopened fixture",status:"open"}' "$body" >/dev/null
expect 200 "$tickets/$id"
jq -e --argjson id "$id" '. == {id:$id,title:"Reopened fixture",status:"open"}' "$body" >/dev/null
expect 204 "$tickets/$id" -X DELETE
[[ ! -s $body ]]
expect 404 "$tickets/$id" -X DELETE
expect 404 "$tickets/$id" -X PATCH "${json[@]}" --data '{"status":"open"}'
expect 404 "$tickets/$id"
[[ $(snapshot) == "$baseline" ]]
# The second insert must violate the constraint and roll back the first.
verify "$role" "$database" ticket_data
if sql "$role" "$database" -v VERBOSITY=verbose >"$run/constraint.log" 2>&1 <<'SQL'
BEGIN;
INSERT INTO tickets (slot,title) VALUES (3,'Rolled back');
INSERT INTO tickets (slot,title) VALUES (4,U&'\00a0Untrimmed\2009');
COMMIT;
SQL
then
exit 1
fi
grep -q '23514:.*tickets_title' "$run/constraint.log"
[[ $(snapshot) == "$baseline" ]]
# A separate session holds the lock past the API timeout to reproduce the failure.
verify ticket_owner "$database" ticket_data
sql ticket_owner "$database" >"$run/lock.log" 2>&1 <<'SQL' &
BEGIN;
SET LOCAL statement_timeout = '9s';
LOCK TABLE tickets IN ACCESS EXCLUSIVE MODE;
SELECT pg_sleep(7);
ROLLBACK;
SQL
lock_pid=$!
locked=f
for _ in {1..40}; do
locked=$(sql "$role" "$database" -c "
SELECT EXISTS (SELECT FROM pg_locks WHERE relation='tickets'::regclass
AND mode='AccessExclusiveLock' AND granted)")
if [[ $locked == t ]]; then break; fi
sleep .05
done
[[ $locked == t ]]
expect 500 "$tickets/$other"
jq -e '. == {"message":"Server Error"}' "$body" >/dev/null
expect 500 "$tickets" "${json[@]}" --data '{"title":"Blocked by test lock"}'
jq -e '. == {"message":"Server Error"}' "$body" >/dev/null
wait "$lock_pid"
lock_pid=
[[ $(snapshot) == "$baseline" ]]
for n in {3..31}; do
payload=$(jq -nc --arg title "Capacity $n" '{title:$title}')
expect 201 "$tickets" "${json[@]}" --data "$payload"
done
# Three requests compete for one slot, so only one may succeed.
pids=()
for n in {1..3}; do
payload=$(jq -nc --arg title "Last slot $n" '{title:$title}')
http "$tickets" "$run/race$n.json" "${json[@]}" --data "$payload" >"$run/race$n.status" &
pids+=("$!")
done
for pid in "${pids[@]}"; do wait "$pid"; done
statuses=$(for n in {1..3}; do cat "$run/race$n.status"; printf '\n'; done | sort)
[[ $statuses == $'201\n409\n409' ]]
for n in {1..3}; do
if [[ $(cat "$run/race$n.status") == 409 ]]; then
jq -e '.message == "Ticket store is full."' "$run/race$n.json" >/dev/null
fi
done
before=$(snapshot)
expect 409 "$tickets" "${json[@]}" --data '{"title":"No more room"}'
[[ $(snapshot) == "$before" ]]
expect 200 "$tickets"
jq -e 'length == 32 and (map(.id) | unique | length) == 32
and map(.id) == (map(.id) | sort)' "$body" >/dev/null
[[ $(sql "$role" "$database" -c 'SELECT count(*), count(DISTINCT id) FROM tickets') == '32|32' ]]
printf '%s HTTP status assertions; rollback, timeout and row checks passed\n' "$checks"
Run the commands from the project root in a separate terminal. They create a fresh cluster and a fresh ticket_test with the migration's two starting records. The script runs one scenario in order, with two independent updates and three competing inserts inside it. Each replay starts in a new directory, independent of rows from the previous run. The demo database is outside this scenario.
export PG_BIN=/usr/lib/postgresql/18/bin
TICKET_LAB=$(mktemp -d /tmp/ticket-lab.XXXXXXXX)
export TICKET_LAB
bash scripts/ticket-db.sh init &&
bash scripts/ticket-db.sh provision ticket_test &&
bash scripts/ticket-db.sh migrate ticket_test &&
bash scripts/check-tickets.sh
72 HTTP status assertions; rollback, timeout and row checks passed
Diagnose the step that failed
A 422 response means the input failed validation. Compare errors and snapshots of the rows before and after the request. A 404 with Ticket not found. means the parser accepted the ID and the lookup returned no row. A separate SQL transaction demonstrates constraint error 23514. When the second statement fails, the first insert is also absent after rollback.
An invalid status rejects the entire PATCH even if the new title is valid. A successful two-field PATCH is confirmed by a subsequent GET. On creation, the script checks that the leading nonbreaking space and trailing thin space are removed from the 120-scalar title. A direct insert with those same edge spaces violates tickets_title.
For a controlled failure, the test holds an ACCESS EXCLUSIVE lock on the table from another session. PostgreSQL cancels the blocked query when lock_timeout expires. Both reading an existing ticket and trying to write get the same generic 500 response. After the lock is released, the row snapshot is unchanged. The status, reproducible scenario, and connection check are enough to isolate the failure. There is no need to enable APP_DEBUG or print payloads and connection strings.
Local logs sit in the http.* directory under TICKET_LAB. server.log shows startup, routes, and response statuses. Look in constraint.log for the constraint name and SQLSTATE, and in lock.log for the separate session holding the lock. These are local logs from synthetic tests. The client receives only the safe HTTP response.
Even if a check fails, run the command below from the same terminal with the test-cluster variables still set. The HTTP script stops the server it started when it exits. Directories and logs stay on disk. The demo database from lessons 09–10 stays in its own cluster.
bash scripts/ticket-db.sh stop
Summary
Unit tests cover rules independent of the database. The integration scenario checks HTTP, privileges, commits, and failure effects in a separate cluster. Diagnose rejected input, a missing record, and a database operation that could not finish as distinct cases.
References
- Laravel Rust 0.1.4 source —
docs/testing.md,src/db/provider.rs. - Test database provisioning source —
src/db/migrations/refresh.rs. - Explicit locking in PostgreSQL.