Skip to content

9. Testing & Docker Deployment ​

In the final chapter, we write unit + full-stack integration tests for TaskForge and build/run the hardened production Docker container.


9.1 Unit Test: DI Graph & Custom Validation (internal/tests/unit/task_module_test.go) ​

Verify that auth.Module() and task.Module() resolve cleanly without missing or circular dependencies, and that our custom task_priority rule works:

go
package unit

import (
	"testing"

	"github.com/acme/taskforge/boot/server"
	"github.com/acme/taskforge/core/config"
	"github.com/acme/taskforge/core/database"
	_ "github.com/acme/taskforge/core/database/drivers"
	"github.com/acme/taskforge/core/di"
	"github.com/acme/taskforge/core/events"
	corevalidator "github.com/acme/taskforge/core/validator"
	"github.com/acme/taskforge/internal/services/auth"
	"github.com/acme/taskforge/internal/services/task"
)

func TestTaskForgeDIGraph(t *testing.T) {
	cfg := &config.AllConfig{
		App: config.AppConfig{Key: "test-secret-key-for-di"},
		DB:  config.DBConfig{Connection: "sqlite", Name: t.TempDir() + "/di.db"},
	}

	c := di.New(
		di.AutoCollect[server.Router](),
		di.AutoCollect[server.GRPCRegistry](),
		di.WithProviders(
			func() *config.AllConfig { return cfg },
			func() (*database.Database, error) { return database.Connect(cfg.DB) },
			func() *events.EventBus { return events.New() },
		),
		di.WithModules(auth.Module(), task.Module()),
	)

	if err := c.Validate(); err != nil {
		t.Fatalf("DI graph validation failed: %v", err)
	}
}

func TestTaskPriorityValidation(t *testing.T) {
	req := task.CreateTaskRequest{
		Title:    "Ship v1",
		Priority: "urgent", // invalid: only low, medium, high allowed
	}
	if appErr := corevalidator.Validate(req); appErr == nil {
		t.Fatal("expected validation error for invalid priority")
	}
}

9.2 Full-Stack Integration Test (internal/tests/integration/taskforge_test.go) ​

Boot the real DI container (boot.NewWithConfig) against an isolated t.TempDir() SQLite database and test Limen registration/login, cookie-protected CRUD, cross-user isolation, and async audit log persistence:

go
package integration

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"testing"
	"time"

	"github.com/acme/taskforge/boot"
	"github.com/acme/taskforge/boot/server"
	"github.com/acme/taskforge/core/config"
	"github.com/acme/taskforge/core/database"
	"github.com/acme/taskforge/core/di"
	"github.com/acme/taskforge/internal/services/auth"
	"github.com/acme/taskforge/internal/services/task"
)

func TestTaskForgeEndToEnd(t *testing.T) {
	const appKey = "integration-app-key-123456"
	cfg := &config.AllConfig{
		App: config.AppConfig{
			Name:    "taskforge-test",
			Version: "1.0.0",
			Debug:   true,
			Key:     appKey,
			Host:    "127.0.0.1",
			Port:    0,
		},
		DB: config.DBConfig{
			Connection:      "sqlite",
			Name:            filepath.Join(t.TempDir(), "test.db"),
			MaxOpenConns:    5,
			MaxIdleConns:    2,
			ConnMaxLifetime: time.Minute,
		},
		HTTP: config.HTTPConfig{RateLimitPerMinute: 0},
		Task: config.TaskConfig{MaxPerUser: 10},
	}

	app, err := boot.NewWithConfig(cfg, auth.Module(), task.Module())
	if err != nil {
		t.Fatalf("boot.NewWithConfig: %v", err)
	}
	defer func() { _ = app.Stop(context.Background()) }()

	db, err := di.Resolve[*database.Database](app.Container)
	if err != nil {
		t.Fatalf("resolve db: %v", err)
	}
	gormDB, _ := db.GetGorm()
	if err := gormDB.AutoMigrate(app.Container.Models()...); err != nil {
		t.Fatalf("automigrate: %v", err)
	}

	engine := app.Servers[0].(*server.HTTPServer).Engine()

	// 1. Readiness probe
	w := httptest.NewRecorder()
	engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/ready", nil))
	if w.Code != http.StatusOK {
		t.Fatalf("expected 200 on /ready, got %d", w.Code)
	}

	// 2. Missing X-App-Key -> 401
	w = httptest.NewRecorder()
	engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/tasks", nil))
	if w.Code != http.StatusUnauthorized {
		t.Fatalf("expected 401 without X-App-Key, got %d", w.Code)
	}

	// 3. Register + Login via Limen
	regBody, _ := json.Marshal(map[string]string{
		"email": "alice@test.dev", "password": "Password123!", "first_name": "Alice", "last_name": "Test",
	})
	req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader(regBody))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-App-Key", appKey)
	w = httptest.NewRecorder()
	engine.ServeHTTP(w, req)
	if w.Code != http.StatusCreated && w.Code != http.StatusOK {
		t.Fatalf("register failed: %d %s", w.Code, w.Body.String())
	}

	loginBody, _ := json.Marshal(map[string]string{"email": "alice@test.dev", "password": "Password123!"})
	req = httptest.NewRequest(http.MethodPost, "/api/auth/login", bytes.NewReader(loginBody))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-App-Key", appKey)
	w = httptest.NewRecorder()
	engine.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Fatalf("login failed: %d %s", w.Code, w.Body.String())
	}
	cookies := w.Result().Cookies()

	// 4. Create Task with session cookie
	taskBody, _ := json.Marshal(map[string]string{"title": "Write docs", "priority": "high"})
	req = httptest.NewRequest(http.MethodPost, "/api/tasks", bytes.NewReader(taskBody))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-App-Key", appKey)
	for _, c := range cookies {
		req.AddCookie(c)
	}
	w = httptest.NewRecorder()
	engine.ServeHTTP(w, req)
	if w.Code != http.StatusCreated {
		t.Fatalf("create task failed: %d %s", w.Code, w.Body.String())
	}

	// 5. Verify async TaskAuditLog persisted after graceful stop drains EventBus
	if err := app.Stop(context.Background()); err != nil {
		t.Fatalf("app.Stop: %v", err)
	}
	var auditCount int64
	gormDB.Model(&task.TaskAuditLog{}).Where("action = ?", task.EventTaskCreated).Count(&auditCount)
	if auditCount != 1 {
		t.Fatalf("expected 1 audit log, got %d", auditCount)
	}
}

Run the full test suite with the race detector:

bash
go test -race ./...

9.3 Build & Run the Hardened Docker Container ​

GoForge's Dockerfile builds with -tags prod -ldflags="-s -w" (stripping the dev-only loader command), runs as non-root appuser on alpine:3.21, exposes ports 3000 and 50051, defines a /health HEALTHCHECK, and defaults to serve --no-tui:

bash
docker build -t taskforge:1.0.0 .

docker run --rm -p 3000:3000 -p 50051:50051 \
  -e APP_KEY="$(grep '^APP_KEY=' .env | cut -d= -f2-)" \
  -e APP_DEBUG=false \
  -e APP_HOST=0.0.0.0 \
  -e GRPC_HOST=0.0.0.0 \
  -e LOG_FORMAT=json \
  -e LOG_COLOR=never \
  taskforge:1.0.0

Verify the running container:

bash
curl http://127.0.0.1:3000/health
curl http://127.0.0.1:3000/ready

Congratulations! You have built a complete GoForge backend with Limen authentication, protected CRUD, Atlas + SQLC + Seeders, async events, OpenAPI 3.1 docs, gRPC + typed clients, custom CLI commands, tests, and a hardened production Docker image.

Explore Next: Framework Architecture Reference →

Released under the Apache-2.0 License.