TExcelTAD
Home › DevOps Capstone: Ship a Production Service › Unit & Integration Tests

Unit & Integration Tests

CI can only protect what tests check. linkly has two layers of tests with different jobs:

Layer Talks to Speed Proves
Unit tests (app_test.go) an in-memory Store fake and miniredis, an in-process Redis server milliseconds, no setup handler logic: status codes, validation, cache hit/miss/error paths, readiness rules, metric labels
Integration test (integration_test.go, build tag integration) real PostgreSQL and Redis seconds, needs both servers the SQL, the unique-constraint mapping, real TTLs, the pgx and go-redis wiring

Both run in CI on every pull request (The CI Workflow); only unit tests run on every save.

The idea, runnable

The trick that makes handlers testable is the Store interface: tests swap PostgreSQL for a map. Here is that idea on its own, small enough to run in the browser: a fake store, a handler, and httptest calling it without opening a port. (It skips Redis, which the real tests replace with miniredis.)

go · try it yourself
package main

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
)

var ErrNotFound = errors.New("not found")

type Store interface{ Get(code string) (string, error) }

type memStore map[string]string

func (m memStore) Get(code string) (string, error) {
	if url, ok := m[code]; ok {
		return url, nil
	}
	return "", ErrNotFound
}

func redirect(s Store) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		url, err := s.Get(r.PathValue("code"))
		switch {
		case errors.Is(err, ErrNotFound):
			http.NotFound(w, r)
		case err != nil:
			http.Error(w, "internal error", http.StatusInternalServerError)
		default:
			http.Redirect(w, r, url, http.StatusFound)
		}
	}
}

type brokenStore struct{}

func (brokenStore) Get(string) (string, error) { return "", errors.New("connection refused") }

func main() {
	for _, tc := range []struct {
		name  string
		store Store
		path  string
		want  int
	}{
		{"known code", memStore{"docs": "https://go.dev/doc/"}, "/docs", 302},
		{"unknown code", memStore{}, "/nope", 404},
		{"database down", brokenStore{}, "/docs", 500},
	} {
		mux := http.NewServeMux()
		mux.HandleFunc("GET /{code}", redirect(tc.store))
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, httptest.NewRequest("GET", tc.path, strings.NewReader("")))
		verdict := "PASS"
		if rec.Code != tc.want {
			verdict = "FAIL"
		}
		fmt.Printf("%s %-14s got %d want %d %s\n", verdict, tc.name, rec.Code, tc.want, rec.Header().Get("Location"))
	}
}
PASS known code     got 302 want 302 https://go.dev/doc/
PASS unknown code   got 404 want 404
PASS database down  got 500 want 500

The real tests

The session recreates linkly, adds the two test files, runs the unit tests verbosely, then starts PostgreSQL and Redis and runs the integration test against them. Finally it runs everything again with the race detector and prints coverage:

bash · try it yourself
initdb -D pgdata -U linkly --auth=trust >/dev/null
mkdir -p pgrun
pg_ctl -D pgdata -o "-k /home/learner/pgrun -c listen_addresses=" -l pg.log start >/dev/null
createdb linkly
redis-server --port 6379 --bind 127.0.0.1 --daemonize yes --dir /home/learner
mkdir linkly && cd linkly
cat > main.go <<'EOF'
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

// version is stamped at build time: go build -ldflags "-X main.version=1.4.0"
var version = "dev"

type config struct {
	Addr, DatabaseURL, RedisAddr, BaseURL, LogLevel, Traces string
	CacheTTL, ShutdownGrace                                 time.Duration
}

func env(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

// loadConfig reads the twelve-factor configuration from the environment.
func loadConfig() (config, error) {
	c := config{
		Addr:        env("LISTEN_ADDR", ":8080"),
		DatabaseURL: env("DATABASE_URL", ""),
		RedisAddr:   env("REDIS_ADDR", "localhost:6379"),
		BaseURL:     env("BASE_URL", "http://localhost:8080"),
		LogLevel:    env("LOG_LEVEL", "info"),
		Traces:      env("OTEL_TRACES_EXPORTER", "none"),
	}
	var err error
	if c.CacheTTL, err = time.ParseDuration(env("CACHE_TTL", "1h")); err != nil {
		return c, fmt.Errorf("CACHE_TTL: %w", err)
	}
	if c.ShutdownGrace, err = time.ParseDuration(env("SHUTDOWN_GRACE", "10s")); err != nil {
		return c, fmt.Errorf("SHUTDOWN_GRACE: %w", err)
	}
	if c.DatabaseURL == "" {
		return c, errors.New("DATABASE_URL is required")
	}
	return c, nil
}

func main() {
	cfg, err := loadConfig()
	var level slog.Level
	if err == nil {
		err = level.UnmarshalText([]byte(cfg.LogLevel))
	}
	log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
	if err == nil {
		err = run(cfg, log)
	}
	if err != nil {
		log.Error("linkly stopped", "err", err)
		os.Exit(1)
	}
}

func run(cfg config, log *slog.Logger) error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	shutdownTracing, err := setupTracing(cfg.Traces, os.Stderr)
	if err != nil {
		return err
	}
	defer shutdownTracing(context.Background())

	db, err := pgxpool.New(ctx, cfg.DatabaseURL)
	if err != nil {
		return fmt.Errorf("database: %w", err)
	}
	defer db.Close()
	if err := migrate(ctx, db); err != nil {
		return fmt.Errorf("migrate: %w", err)
	}
	redis.SetLogger(redisLogger{log})
	rdb := newRedis(cfg.RedisAddr)
	defer rdb.Close()

	app := newApp(pgStore{db}, rdb, cfg, log, prometheus.DefaultRegisterer, prometheus.DefaultGatherer)
	srv := &http.Server{Addr: cfg.Addr, Handler: app.Handler(), ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
	errc := make(chan error, 1)
	go func() {
		log.Info("listening", "addr", cfg.Addr, "version", version)
		errc <- srv.ListenAndServe()
	}()
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	log.Info("shutting down", "grace", cfg.ShutdownGrace.String())
	app.draining.Store(true) // /readyz now answers 503
	sctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil {
		return err
	}
	log.Info("stopped")
	return nil
}

// newRedis takes host:port or a redis:// or rediss:// (TLS) URL. The short timeouts keep
// the cache from slowing requests down when Redis is unwell.
func newRedis(addr string) *redis.Client {
	opt, err := redis.ParseURL(addr)
	if err != nil {
		opt = &redis.Options{Addr: addr}
	}
	opt.DialTimeout, opt.DialerRetries, opt.MaxRetries = time.Second, 1, 1
	opt.ReadTimeout, opt.WriteTimeout = 300*time.Millisecond, 300*time.Millisecond
	return redis.NewClient(opt)
}

// redisLogger sends go-redis's own messages to the JSON log instead of plain stderr.
type redisLogger struct{ log *slog.Logger }

func (r redisLogger) Printf(ctx context.Context, format string, v ...any) {
	r.log.WarnContext(ctx, fmt.Sprintf(format, v...), "component", "go-redis")
}

// setupTracing installs the OpenTelemetry SDK; "console" writes spans as JSON to w.
func setupTracing(exporter string, w io.Writer) (func(context.Context) error, error) {
	res := resource.NewSchemaless(semconv.ServiceName("linkly"), semconv.ServiceVersion(version))
	opts := []sdktrace.TracerProviderOption{sdktrace.WithResource(res)}
	switch exporter {
	case "none":
	case "console":
		exp, err := stdouttrace.New(stdouttrace.WithWriter(w))
		if err != nil {
			return nil, err
		}
		opts = append(opts, sdktrace.WithSyncer(exp))
	default:
		return nil, fmt.Errorf("OTEL_TRACES_EXPORTER=%q: this build supports none and console", exporter)
	}
	tp := sdktrace.NewTracerProvider(opts...)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.TraceContext{})
	return tp.Shutdown, nil
}
EOF
cat > app.go <<'EOF'
package main

import (
	"context"
	"crypto/rand"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"net/url"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/attribute"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
	"go.opentelemetry.io/otel/trace"
)

type App struct {
	store    Store
	cache    *redis.Client
	ttl      time.Duration
	baseURL  string
	log      *slog.Logger
	newCode  func() string
	draining atomic.Bool
	metrics  http.Handler

	requests  *prometheus.CounterVec
	duration  *prometheus.HistogramVec
	cacheReqs *prometheus.CounterVec
	created   prometheus.Counter
}

func newApp(store Store, cache *redis.Client, cfg config, log *slog.Logger,
	reg prometheus.Registerer, g prometheus.Gatherer) *App {
	f := promauto.With(reg)
	a := &App{store: store, cache: cache, ttl: cfg.CacheTTL, baseURL: cfg.BaseURL, log: log,
		newCode: randomCode, metrics: promhttp.HandlerFor(g, promhttp.HandlerOpts{}),
		requests: f.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total",
			Help: "HTTP requests by route and status code."}, []string{"route", "code"}),
		duration: f.NewHistogramVec(prometheus.HistogramOpts{Name: "http_request_duration_seconds",
			Help:    "Time to handle a request, by route.",
			Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5}}, []string{"route"}),
		cacheReqs: f.NewCounterVec(prometheus.CounterOpts{Name: "linkly_cache_requests_total",
			Help: "Redis lookups for redirects, by result (hit, miss, error)."}, []string{"result"}),
		created: f.NewCounter(prometheus.CounterOpts{Name: "linkly_links_created_total",
			Help: "Short links created."}),
	}
	f.NewGaugeVec(prometheus.GaugeOpts{Name: "linkly_build_info", Help: "Always 1; labels describe the build."},
		[]string{"version", "goversion"}).WithLabelValues(version, runtime.Version()).Set(1)
	return a
}

func (a *App) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /links", a.createLink)
	mux.HandleFunc("GET /{code}", a.redirect)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok\n")) })
	mux.HandleFunc("GET /readyz", a.readyz)
	mux.Handle("GET /metrics", a.metrics)
	notProbe := func(r *http.Request) bool { return !quiet(r.URL.Path) }
	return otelhttp.NewHandler(a.observe(mux), "linkly", otelhttp.WithFilter(notProbe))
}

func quiet(route string) bool {
	return route == "/healthz" || route == "/readyz" || route == "/metrics"
}

// observe records metrics, names the trace span and logs every request, all by route template.
func (a *App) observe(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		route := "unmatched" // r.Pattern is "GET /{code}" once the mux has matched, "" otherwise
		if _, p, ok := strings.Cut(r.Pattern, " "); ok {
			route = p
		}
		a.requests.WithLabelValues(route, strconv.Itoa(rec.status)).Inc()
		a.duration.WithLabelValues(route).Observe(time.Since(start).Seconds())
		span := trace.SpanFromContext(r.Context())
		span.SetName(r.Method + " " + route)
		span.SetAttributes(semconv.HTTPRoute(route))
		level := slog.LevelInfo
		if quiet(route) {
			level = slog.LevelDebug
		} else if rec.status >= 500 {
			level = slog.LevelError
		}
		a.log.LogAttrs(r.Context(), level, "request", slog.String("method", r.Method),
			slog.String("route", route), slog.Int("status", rec.status),
			slog.String("trace_id", span.SpanContext().TraceID().String()))
	})
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }

var codeRE = regexp.MustCompile(`^[A-Za-z0-9_-]{3,32}

  
    
    
    Unit & Integration Tests - DevOps Capstone: Ship a Production Service · ExcelTAD
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
    )

const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

// randomCode returns 7 random characters from a 64-letter alphabet (b&63 has no modulo bias).
// They come from crypto/rand, so codes can't be predicted.
func randomCode() string {
	b := make([]byte, 7)
	if _, err := rand.Read(b); err != nil {
		panic(err) // the OS random source failed: nothing sensible is left to do
	}
	for i := range b {
		b[i] = alphabet[b[i]&63]
	}
	return string(b)
}

func validateURL(raw string) error {
	if len(raw) > 2048 {
		return errors.New("url is longer than 2048 bytes")
	}
	u, err := url.Parse(raw)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return errors.New("url must be an absolute http or https URL")
	}
	return nil
}

func (a *App) createLink(w http.ResponseWriter, r *http.Request) {
	var req struct{ URL, Code string }
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": `body must be JSON like {"url": "https://..."}`})
		return
	}
	if err := validateURL(req.URL); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
		return
	}
	if req.Code != "" && !codeRE.MatchString(req.Code) {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "code must be 3-32 of A-Z a-z 0-9 _ -"})
		return
	}
	code := req.Code
	for attempt := 1; ; attempt++ {
		if req.Code == "" {
			code = a.newCode()
		}
		err := a.store.Create(r.Context(), code, req.URL)
		if err == nil {
			break
		}
		if errors.Is(err, ErrExists) && req.Code == "" && attempt < 3 {
			continue // a random code collided: draw again
		}
		if errors.Is(err, ErrExists) {
			writeJSON(w, http.StatusConflict, map[string]string{"error": "code already taken"})
			return
		}
		a.fail(w, r, err)
		return
	}
	a.created.Inc()
	writeJSON(w, http.StatusCreated, map[string]string{"code": code, "short_url": a.baseURL + "/" + code, "url": req.URL})
}

// redirect reads through the cache: Redis first, PostgreSQL on a miss (or when Redis is down).
func (a *App) redirect(w http.ResponseWriter, r *http.Request) {
	code, ctx := r.PathValue("code"), r.Context()
	if !codeRE.MatchString(code) {
		http.NotFound(w, r)
		return
	}
	key := "link:" + code
	target, err := a.cache.Get(ctx, key).Result()
	result := "hit"
	if errors.Is(err, redis.Nil) {
		result = "miss"
	} else if err != nil {
		result = "error"
		a.log.WarnContext(ctx, "cache read failed", "err", err)
	}
	a.cacheReqs.WithLabelValues(result).Inc()
	trace.SpanFromContext(ctx).SetAttributes(attribute.String("linkly.cache", result))
	if result != "hit" {
		if target, err = a.store.Get(ctx, code); errors.Is(err, ErrNotFound) {
			http.NotFound(w, r)
			return
		} else if err != nil {
			a.fail(w, r, err)
			return
		}
		if err := a.cache.Set(ctx, key, target, a.ttl).Err(); err != nil {
			a.log.WarnContext(ctx, "cache write failed", "err", err)
		}
	}
	http.Redirect(w, r, target, http.StatusFound)
}

// readyz fails only on the database: without Redis, linkly is slower but still correct.
func (a *App) readyz(w http.ResponseWriter, r *http.Request) {
	if a.draining.Load() {
		writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "draining"})
		return
	}
	ctx, cancel := context.WithTimeout(r.Context(), time.Second)
	defer cancel()
	res, code := map[string]string{"status": "ready", "database": "up", "cache": "up"}, http.StatusOK
	if err := a.store.Ping(ctx); err != nil {
		a.log.WarnContext(ctx, "readiness: database", "err", err)
		res["status"], res["database"], code = "unavailable", "down", http.StatusServiceUnavailable
	}
	if err := a.cache.Ping(ctx).Err(); err != nil {
		a.log.WarnContext(ctx, "readiness: cache", "err", err)
		res["cache"] = "down"
	}
	writeJSON(w, code, res)
}

func (a *App) fail(w http.ResponseWriter, r *http.Request, err error) {
	a.log.ErrorContext(r.Context(), "request failed", "err", err)
	writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
}

func writeJSON(w http.ResponseWriter, code int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(v)
}
EOF
cat > store.go <<'EOF'
package main

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
)

var (
	ErrNotFound = errors.New("link not found")
	ErrExists   = errors.New("code already exists")
)

// Store is where links live; pgStore in production, an in-memory fake in unit tests.
type Store interface {
	Create(ctx context.Context, code, url string) error
	Get(ctx context.Context, code string) (string, error)
	Ping(ctx context.Context) error
}

const schema = `CREATE TABLE IF NOT EXISTS links (
  code       text PRIMARY KEY,
  url        text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now())`

func migrate(ctx context.Context, db *pgxpool.Pool) error {
	_, err := db.Exec(ctx, schema)
	return err
}

type pgStore struct{ db *pgxpool.Pool }

func (s pgStore) Create(ctx context.Context, code, url string) error {
	_, err := s.db.Exec(ctx, `INSERT INTO links (code, url) VALUES ($1, $2)`, code, url)
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation
		return ErrExists
	}
	return err
}

func (s pgStore) Get(ctx context.Context, code string) (string, error) {
	var url string
	err := s.db.QueryRow(ctx, `SELECT url FROM links WHERE code = $1`, code).Scan(&url)
	if errors.Is(err, pgx.ErrNoRows) {
		return "", ErrNotFound
	}
	return url, err
}

func (s pgStore) Ping(ctx context.Context) error { return s.db.Ping(ctx) }
EOF
cat > app_test.go <<'EOF'
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/testutil"
	"github.com/redis/go-redis/v9"
)

// memStore is the in-memory fake Store for unit tests.
type memStore struct {
	mu    sync.Mutex
	links map[string]string
	down  bool
}

func (m *memStore) Create(_ context.Context, code, url string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if _, ok := m.links[code]; ok {
		return ErrExists
	}
	m.links[code] = url
	return nil
}

func (m *memStore) Get(_ context.Context, code string) (string, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if url, ok := m.links[code]; ok {
		return url, nil
	}
	return "", ErrNotFound
}

func (m *memStore) Ping(context.Context) error {
	if m.down {
		return errors.New("connection refused")
	}
	return nil
}

func newTestApp(t *testing.T) (*App, *memStore, *miniredis.Miniredis, *prometheus.Registry) {
	mr := miniredis.RunT(t)
	store := &memStore{links: map[string]string{}}
	reg := prometheus.NewRegistry()
	log := slog.New(slog.NewJSONHandler(io.Discard, nil))
	redis.SetLogger(redisLogger{log})
	cfg := config{BaseURL: "https://lnk.test", CacheTTL: time.Hour}
	a := newApp(store, newRedis(mr.Addr()), cfg, log, reg, reg)
	n := 0
	a.newCode = func() string { n++; return fmt.Sprintf("code%03d", n) }
	return a, store, mr, reg
}

func do(h http.Handler, method, path, body string) *httptest.ResponseRecorder {
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))
	return rec
}

func TestCreateAndRedirect(t *testing.T) {
	a, _, mr, _ := newTestApp(t)
	h := a.Handler()
	rec := do(h, "POST", "/links", `{"url": "https://go.dev/doc/"}`)
	want := `{"code":"code001","short_url":"https://lnk.test/code001","url":"https://go.dev/doc/"}` + "\n"
	if rec.Code != http.StatusCreated || rec.Body.String() != want {
		t.Fatalf("POST /links = %d %s", rec.Code, rec.Body)
	}
	for i := 0; i < 2; i++ { // the first redirect misses the cache, the second hits it
		rec = do(h, "GET", "/code001", "")
		if rec.Code != http.StatusFound || rec.Header().Get("Location") != "https://go.dev/doc/" {
			t.Fatalf("GET /code001 = %d %q", rec.Code, rec.Header().Get("Location"))
		}
	}
	for result, want := range map[string]float64{"miss": 1, "hit": 1} {
		if got := testutil.ToFloat64(a.cacheReqs.WithLabelValues(result)); got != want {
			t.Errorf("cache %s = %v, want %v", result, got, want)
		}
	}
	if ttl := mr.TTL("link:code001"); ttl != time.Hour {
		t.Errorf("cache TTL = %v, want 1h", ttl)
	}
}

func TestBadRequests(t *testing.T) {
	a, _, _, _ := newTestApp(t)
	h := a.Handler()
	do(h, "POST", "/links", `{"url": "https://example.com", "code": "docs"}`)
	for _, tc := range []struct {
		method, path, body string
		want               int
	}{
		{"POST", "/links", `not json`, 400},
		{"POST", "/links", `{"url": "ftp://example.com/file"}`, 400},
		{"POST", "/links", `{"url": "/relative/path"}`, 400},
		{"POST", "/links", `{"url": "https://example.com", "code": "a b"}`, 400},
		{"POST", "/links", `{"url": "https://example.org", "code": "docs"}`, 409},
		{"GET", "/nope", "", 404},
		{"GET", "/x", "", 404}, // too short to be a code: rejected before any lookup
		{"DELETE", "/links", "", 405},
	} {
		if rec := do(h, tc.method, tc.path, tc.body); rec.Code != tc.want {
			t.Errorf("%s %s %s = %d, want %d", tc.method, tc.path, tc.body, rec.Code, tc.want)
		}
	}
}

func TestRedisDownFallsBackToDatabase(t *testing.T) {
	a, store, mr, _ := newTestApp(t)
	h := a.Handler()
	store.links["docs"] = "https://go.dev/doc/"
	mr.Close()
	if rec := do(h, "GET", "/docs", ""); rec.Code != http.StatusFound {
		t.Fatalf("redirect without Redis = %d, want 302", rec.Code)
	}
	if got := testutil.ToFloat64(a.cacheReqs.WithLabelValues("error")); got != 1 {
		t.Errorf("cache errors = %v, want 1", got)
	}
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusOK {
		t.Errorf("readyz without Redis = %d, want 200 (the cache is optional)", rec.Code)
	}
}

func TestReadiness(t *testing.T) {
	a, store, _, _ := newTestApp(t)
	h := a.Handler()
	store.down = true
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusServiceUnavailable {
		t.Errorf("readyz without the database = %d, want 503", rec.Code)
	}
	store.down = false
	a.draining.Store(true)
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusServiceUnavailable {
		t.Errorf("readyz while draining = %d, want 503", rec.Code)
	}
}

func TestMetricsUseRouteTemplates(t *testing.T) {
	a, store, _, reg := newTestApp(t)
	h := a.Handler()
	store.links["abc"] = "https://example.com"
	do(h, "GET", "/abc", "")
	do(h, "GET", "/zzz", "")
	do(h, "GET", "/a/b/c", "")
	want := `
# HELP http_requests_total HTTP requests by route and status code.
# TYPE http_requests_total counter
http_requests_total{code="302",route="/{code}"} 1
http_requests_total{code="404",route="/{code}"} 1
http_requests_total{code="404",route="unmatched"} 1
`
	if err := testutil.GatherAndCompare(reg, strings.NewReader(want), "http_requests_total"); err != nil {
		t.Error(err)
	}
}
EOF
cat > integration_test.go <<'EOF'
//go:build integration

package main

import (
	"context"
	"io"
	"log/slog"
	"os"
	"testing"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
)

// Run with real servers: DATABASE_URL=... REDIS_ADDR=... go test -tags integration ./...
func TestWithPostgresAndRedis(t *testing.T) {
	dsn, addr := os.Getenv("DATABASE_URL"), os.Getenv("REDIS_ADDR")
	if dsn == "" || addr == "" {
		t.Skip("DATABASE_URL and REDIS_ADDR are not set")
	}
	ctx := context.Background()
	db, err := pgxpool.New(ctx, dsn)
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	if err := migrate(ctx, db); err != nil {
		t.Fatal(err)
	}
	db.Exec(ctx, `DELETE FROM links WHERE code LIKE 'it-%'`)
	rdb := newRedis(addr)
	defer rdb.Close()
	rdb.Del(ctx, "link:it-docs")

	reg := prometheus.NewRegistry()
	cfg := config{BaseURL: "https://lnk.test", CacheTTL: time.Minute}
	h := newApp(pgStore{db}, rdb, cfg, slog.New(slog.NewJSONHandler(io.Discard, nil)), reg, reg).Handler()

	if rec := do(h, "POST", "/links", `{"url": "https://go.dev/doc/", "code": "it-docs"}`); rec.Code != 201 {
		t.Fatalf("create = %d %s", rec.Code, rec.Body)
	}
	if rec := do(h, "POST", "/links", `{"url": "https://example.com", "code": "it-docs"}`); rec.Code != 409 {
		t.Errorf("duplicate = %d, want 409 from the primary key", rec.Code)
	}
	if rec := do(h, "GET", "/it-docs", ""); rec.Code != 302 {
		t.Fatalf("redirect = %d", rec.Code)
	}
	if ttl := rdb.TTL(ctx, "link:it-docs").Val(); ttl <= 0 || ttl > time.Minute {
		t.Errorf("cached TTL = %v", ttl)
	}
	if rec := do(h, "GET", "/readyz", ""); rec.Code != 200 {
		t.Errorf("readyz = %d %s", rec.Code, rec.Body)
	}
}
EOF
go mod init github.com/acme/linkly >/dev/null 2>&1 && go mod tidy 2>/dev/null
echo "== unit tests"
go test -v ./... 2>&1 | grep -E '^(=== RUN|--- |PASS|FAIL|ok)' | sed 's/ (.*)$//'
echo "== integration test (real PostgreSQL and Redis)"
export DATABASE_URL="postgres:///linkly?host=/home/learner/pgrun" REDIS_ADDR=127.0.0.1:6379
go test -tags integration -run WithPostgres -v ./... 2>&1 | grep -E '^(--- |ok|FAIL)' | sed 's/ (.*)$//'
psql -tAc "SELECT code, url FROM links"
echo "== everything, with the race detector"
go test -race -tags integration -cover ./... | sed -E 's/\t[0-9.]+s\t/\t/'
== unit tests
=== RUN   TestCreateAndRedirect
--- PASS: TestCreateAndRedirect
=== RUN   TestBadRequests
--- PASS: TestBadRequests
=== RUN   TestRedisDownFallsBackToDatabase
--- PASS: TestRedisDownFallsBackToDatabase
=== RUN   TestReadiness
--- PASS: TestReadiness
=== RUN   TestMetricsUseRouteTemplates
--- PASS: TestMetricsUseRouteTemplates
PASS
ok  	github.com/acme/linkly	0.077s
== integration test (real PostgreSQL and Redis)
--- PASS: TestWithPostgresAndRedis
ok  	github.com/acme/linkly	0.029s
it-docs|https://go.dev/doc/
== everything, with the race detector
ok  	github.com/acme/linkly	coverage: 59.0% of statements

Walkthrough

newTestApp builds a real App with three substitutions: the memStore fake, a go-redis client pointed at miniredis (miniredis.RunT starts it and stops it when the test ends), and a fresh prometheus.NewRegistry(). The private registry is why newApp takes a Registerer: with the global default registry, the second test to call newApp would panic on duplicate metric registration, and counters would leak between tests. newCode is replaced with a counter, so random codes become code001, code002: tests must be deterministic.

TestCreateAndRedirect checks the whole read-through path in one go: 201 with the exact JSON body, two 302s, one miss and one hit read straight from the counters with testutil.ToFloat64, and the one-hour TTL read from miniredis with mr.TTL. Asserting on metrics is cheap and catches the bug where a refactor silently stops counting.

TestBadRequests is a table of inputs and expected codes: invalid JSON, a non-HTTP scheme, a relative URL, a code with a space, a duplicate (409), unknown and too-short codes (404), and a wrong method (405, produced by the mux pattern alone).

TestRedisDownFallsBackToDatabase closes miniredis during the test, then demands a 302, one error cache count, and a ready /readyz. This is the test that keeps the "cache is optional" decision from being undone by accident.

TestMetricsUseRouteTemplates uses testutil.GatherAndCompare with the expected exposition text: /abc, /zzz and /a/b/c must collapse into route="/{code}" and route="unmatched". If someone changes the label to r.URL.Path, this test fails before Prometheus does.

The integration test has //go:build integration on its first line, so a plain go test ./... doesn't even compile it. It skips (rather than fails) when DATABASE_URL or REDIS_ADDR is missing, cleans up only the rows it owns (it-%), and checks what the fakes can't: that a duplicate insert really produces SQLSTATE 23505 and becomes a 409, and that the TTL in a real Redis is within bounds.

-race instruments memory accesses and fails a test when two goroutines touch the same data without synchronisation. net/http serves each request on its own goroutine, so handler state (like draining, an atomic.Bool) is exactly where races hide. It needs cgo, which the CI runner has.

Tip: Coverage is a map, not a target. The integration tag raises it because pgStore and the wiring in newRedis only run there; main/run stay uncovered, and that's fine: the Running linkly session and the deployed readiness probe exercise them.

Test yourself

Why does each unit test create its own prometheus.NewRegistry()?

  1. The default registry is slower
  2. Registering the same metric twice in the default registry panics, and counts would leak between tests
  3. Prometheus requires one registry per handler
  4. To export metrics over HTTP

How does go test ./... without flags treat integration_test.go?

  1. Runs it and fails without a database
  2. Runs it and skips
  3. Doesn't compile it: the //go:build integration constraint excludes it
  4. Runs it against miniredis

What can only the integration test prove?

  1. That invalid JSON returns 400
  2. That a duplicate insert really raises SQLSTATE 23505 and becomes a 409
  3. That metrics use route templates
  4. That /healthz returns 200