Course › Week 5 · HTTP services with net/http › Day 7 · lesson 35 of 42 · 20 min reading + 2 h practice
Week 5 checkpoint
Integration tests against a fresh database, and the service’s exit check.
On this page
The service of the build day was tried by hand with curl. Before it goes to production it needs tests that try every answer it can give, against a real database, on every commit: the Go version of Laravel’s feature tests with RefreshDatabase.
Then two bugs that look harmless in a code review, and the test that catches each one.
Integration tests
1. A fresh database per test
testDB connects to TEST_DATABASE_URL, a database used for nothing else, and loads testdata/schema.sql into it. Go ignores folders named testdata when it builds, so they are the place for test files. Laravel can write that file for you: php artisan schema:dump saves the schema its migrations created, and the Go tests load exactly that.
t.Helper() marks a function as a test helper, so a failure inside it is reported at the line of the test that called it. t.Cleanup(f) runs f when the test ends, like a defer that belongs to the test. t.Skip ends the test as skipped: without the variable, the tests never touch a database that was not meant for them.
2. The real routes, a fake API, and no sleeping
Each test builds the service the way main does (the tests lesson), with the analysis API replaced by an httptest.NewServer that answers what the test needs, and sends requests through s.routes() with a recorder.
The batch runs in a goroutine. Instead of time.Sleep and hoping it was long enough, the test waits on the runner’s own WaitGroup: when run.running.Wait() returns, every batch has finished. The test is as fast as the work and never flaky.
package main
import (
"context"
"database/sql"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
const testKey = "test-key-0123456789abcdef"
// testDB returns a connection to TEST_DATABASE_URL with every table dropped and created again from
// testdata/schema.sql. Without TEST_DATABASE_URL the test is skipped: it never runs against a
// database that was not meant for it.
func testDB(t *testing.T) *sql.DB {
t.Helper()
url := os.Getenv("TEST_DATABASE_URL")
if url == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
db, err := sql.Open("pgx", url)
if err != nil {
t.Fatalf("opening the test database: %v", err)
}
t.Cleanup(func() { db.Close() })
schema, err := os.ReadFile("testdata/schema.sql")
if err != nil {
t.Fatalf("reading the schema: %v", err)
}
if _, err := db.ExecContext(context.Background(), string(schema)); err != nil {
t.Fatalf("loading the schema: %v", err)
}
return db
}
// fakeAnalysis is the analysis API: it answers every call with status and body.
func fakeAnalysis(t *testing.T, status int, body string) string {
t.Helper()
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
fmt.Fprint(w, body)
}))
t.Cleanup(api.Close)
return api.URL
}
// newTestServer builds the service as main does, with a logger that discards everything.
func newTestServer(t *testing.T, db *sql.DB, analysisURL string) (*server, *runner) {
t.Helper()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
run := &runner{db: db, analyser: newAnalyser(analysisURL, logger), logger: logger, concurrency: 4, ctx: context.Background()}
return &server{runner: run, logger: logger, apiKey: testKey}, run
}
// call sends one request through the real routes, with the API key unless auth is false.
func call(t *testing.T, s *server, method, path, body string, auth bool) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if auth {
req.Header.Set("Authorization", "Bearer "+testKey)
}
rec := httptest.NewRecorder()
s.routes().ServeHTTP(rec, req)
return rec
}
func count(t *testing.T, db *sql.DB, query string) int {
t.Helper()
var n int
if err := db.QueryRowContext(context.Background(), query).Scan(&n); err != nil {
t.Fatalf("%s: %v", query, err)
}
return n
}
const okAnalysis = `{"evaluation_id": 1, "positive": 2, "negative": 1, "neutral": 0}`
func TestABatchIsAnalysedAndSaved(t *testing.T) {
db := testDB(t)
s, run := newTestServer(t, db, fakeAnalysis(t, http.StatusOK, okAnalysis))
rec := call(t, s, "POST", "/api/batches", `{"reference": "r1", "evaluation_ids": [1043, 1042, 9999]}`, true)
if rec.Code != http.StatusAccepted || rec.Header().Get("Location") != "/api/batches/1" {
t.Fatalf("POST = %d, Location %q; want 202 and /api/batches/1: %s", rec.Code, rec.Header().Get("Location"), rec.Body)
}
run.running.Wait() // the batch runs in the background: wait for it, instead of sleeping
rec = call(t, s, "GET", "/api/batches/1", "", true)
if !strings.Contains(rec.Body.String(), `"status":"done","total":3,"analysed":2,"failed":1`) {
t.Errorf("GET = %s, want done with 2 analysed and 1 failed", rec.Body)
}
if n := count(t, db, "select count(*) from evaluations where status = 'analysed' and positive = 2"); n != 2 {
t.Errorf("%d evaluations saved, want 2", n)
}
}
func TestARetryDoesNotStartASecondBatch(t *testing.T) {
db := testDB(t)
s, run := newTestServer(t, db, fakeAnalysis(t, http.StatusOK, okAnalysis))
first := call(t, s, "POST", "/api/batches", `{"reference": "r1", "evaluation_ids": [1042, 1043]}`, true)
again := call(t, s, "POST", "/api/batches", `{"reference": "r1", "evaluation_ids": [1043, 1042, 1042]}`, true)
other := call(t, s, "POST", "/api/batches", `{"reference": "r1", "evaluation_ids": [1045]}`, true)
run.running.Wait()
if first.Code != 202 || again.Code != 200 || other.Code != 409 {
t.Errorf("codes = %d, %d, %d; want 202, 200, 409", first.Code, again.Code, other.Code)
}
if n := count(t, db, "select count(*) from analysis_batches"); n != 1 {
t.Errorf("%d batches stored, want 1", n)
}
}
func TestTheAPIBeingDownSavesNothing(t *testing.T) {
db := testDB(t)
s, run := newTestServer(t, db, fakeAnalysis(t, http.StatusServiceUnavailable, `{"message": "Service Unavailable"}`))
call(t, s, "POST", "/api/batches", `{"reference": "r1", "evaluation_ids": [1042, 1045]}`, true)
run.running.Wait()
rec := call(t, s, "GET", "/api/batches/1", "", true)
if !strings.Contains(rec.Body.String(), `"status":"failed"`) {
t.Errorf("GET = %s, want a failed batch", rec.Body)
}
if n := count(t, db, "select count(*) from evaluations where status <> 'pending'"); n != 0 {
t.Errorf("%d evaluations changed, want none", n)
}
}
func TestAnUnfinishedBatchIsResumed(t *testing.T) {
db := testDB(t)
_, run := newTestServer(t, db, fakeAnalysis(t, http.StatusOK, okAnalysis))
_, err := db.ExecContext(context.Background(),
"insert into analysis_batches (reference, evaluation_ids, status, total) values ('cut-off', '{1042,1045}', 'running', 2)")
if err != nil {
t.Fatal(err)
}
if err := run.resume(context.Background()); err != nil {
t.Fatalf("resume: %v", err)
}
run.running.Wait()
if n := count(t, db, "select count(*) from analysis_batches where status = 'done' and analysed = 2"); n != 1 {
t.Errorf("the cut-off batch was not finished")
}
}
func TestEveryBatchRouteNeedsTheKey(t *testing.T) {
db := testDB(t)
s, _ := newTestServer(t, db, fakeAnalysis(t, http.StatusOK, okAnalysis))
for _, route := range []struct{ method, path string }{{"POST", "/api/batches"}, {"GET", "/api/batches/1"}} {
if rec := call(t, s, route.method, route.path, "{}", false); rec.Code != http.StatusUnauthorized {
t.Errorf("%s %s without a key = %d, want 401", route.method, route.path, rec.Code)
}
}
}
=== RUN TestABatchIsAnalysedAndSaved
--- PASS: TestABatchIsAnalysedAndSaved (0.03s)
=== RUN TestARetryDoesNotStartASecondBatch
--- PASS: TestARetryDoesNotStartASecondBatch (0.04s)
=== RUN TestTheAPIBeingDownSavesNothing
--- PASS: TestTheAPIBeingDownSavesNothing (0.64s)
=== RUN TestAnUnfinishedBatchIsResumed
--- PASS: TestAnUnfinishedBatchIsResumed (0.04s)
=== RUN TestEveryBatchRouteNeedsTheKey
--- PASS: TestEveryBatchRouteNeedsTheKey (0.03s)
PASS
ok github.com/you/analysis-service 0.785sFive tests: a batch saved end to end, a retry and a conflict, the API down saving nothing, a cut-off batch resumed, and the key on every route. Each one starts from the same empty schema, so they can run in any order.
Run them with TEST_DATABASE_URL=postgres://…/nordic_test go test ./..., and in CI with a Postgres service container. go test alone, without the variable, skips them and still runs the unit tests.
Two bugs the tests catch
3. “The retry check is not needed”
A refactor drops the if !created block from storeBatch, because “createBatch already handles the duplicate”. It compiles, and every manual test of a single click still works:
--- FAIL: TestARetryDoesNotStartASecondBatch (0.05s)
integration_test.go:115: codes = 202, 202, 202; want 202, 200, 409
FAIL
exit status 1
FAIL github.com/you/analysis-service 0.054sThe retry and the conflict both got 202 and started the batch again, the second time with the old ids. Only one batch row exists, so a test that counted rows alone would pass; the status codes give it away. createBatch stores the batch once, but the decision about what a duplicate means lives in the handler.
4. “A batch with no results is still a result”
Someone removes the “API is down” check from the runner, so that every batch ends as done:
--- FAIL: TestTheAPIBeingDownSavesNothing (0.64s)
integration_test.go:131: GET = {"id":1,"reference":"r1","status":"done","total":2,"analysed":0,"failed":2,"error":null,"failures":[{"evaluation_id":1042,"reason":"analysis API answered 503 Service Unavailable","retryable":true},{"evaluation_id":1045,"reason":"analysis API answered 503 Service Unavailable","retryable":true}]}, want a failed batch
FAIL
exit status 1
FAIL github.com/you/analysis-service 0.648sThe batch is done with 0 analysed and 2 retryable failures. Laravel would retry the two evaluations once with -retry and give up, while the right answer was to fail the batch and let the user try again when the API is back. The test states the rule, so the next refactor cannot quietly remove it.
The service exit check
Before Week 6, your service from the build day must pass every line of this table.
| Check | How |
|---|---|
| The integration tests pass against a fresh database | TEST_DATABASE_URL=… go test -race ./... |
| No test sleeps | Search the tests for time.Sleep: wait on the work itself. |
| A retried POST never starts a second batch | The retry test, and the unique index in the migration. |
| Ctrl-C while a batch runs loses nothing | Start a batch against a slow fake API, stop the service, start it again: the batch finishes. |
Every 5xx is logged with its cause; the client sees only Server Error | Break the database URL after startup and request a batch. |
| The service refuses to start without a long enough key | Run it with SERVICE_API_KEY=short. |
gofmt -l ., go vet ./... and staticcheck ./... print nothing | Run all three. |
Coming from Laravel’s feature tests
<?php
use RefreshDatabase;
public function test_a_retry_does_not_start_a_second_batch(): void
{
Queue::fake();
$this->postJson('/api/batches', ['reference' => 'r1', 'evaluation_ids' => [1042]])->assertAccepted();
$this->postJson('/api/batches', ['reference' => 'r1', 'evaluation_ids' => [1042]])->assertOk();
$this->assertDatabaseCount('analysis_batches', 1);
}
RefreshDatabase is testDB, postJson is call with a recorder, Queue::fake() is the fake analysis API, and waiting for the queue is run.running.Wait(). The Go version has no framework magic to learn, and no global state between tests: each one builds its own service from its own parts.
Remember
- Integration tests run the real routes against a fresh database, and wait on the work, never on a timer.
Week 6 starts Laravel Go: Laravel’s own framework for Go, the CLI, and the shape of a new application.