diff --git a/internal/server/workers_internal_test.go b/internal/server/workers_internal_test.go new file mode 100644 index 0000000..003ec1d --- /dev/null +++ b/internal/server/workers_internal_test.go @@ -0,0 +1,69 @@ +package server + +import ( + "context" + "io" + "log/slog" + "net/http/httptest" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/erp" + "git.breakpilot.com/platform/tenant-registry/internal/mail" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// The background workers idle without their backend and stop with their +// context, after at least one round. +func TestWorkersStopWithTheirContext(t *testing.T) { + s := &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), Store: store.NewMemory()} + ctx := context.Background() + + // No mail sender, no ERP: the workers return at once. + s.RunMail(ctx, time.Millisecond) + s.RunOutbox(ctx, time.Millisecond) + + run := func(name string, f func(context.Context)) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, 30*time.Millisecond) + defer cancel() + done := make(chan struct{}) + go func() { f(ctx); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("%s did not stop with its context", name) + } + } + s.Mail = &mail.Recorder{} + run("mail", func(c context.Context) { s.RunMail(c, time.Millisecond) }) + s.ERP = erp.New(erp.Config{BaseURL: "http://127.0.0.1:1"}) + run("outbox", func(c context.Context) { s.RunOutbox(c, time.Millisecond) }) + s.ERP = nil + run("reconcile", func(c context.Context) { s.RunReconcile(c, time.Millisecond) }) + // A zero interval takes the default; the context ends the wait. + run("mail default", func(c context.Context) { s.RunMail(c, 0) }) + run("reconcile default", func(c context.Context) { s.RunReconcile(c, 0) }) +} + +// clientIP: the first X-Forwarded-For entry, else the remote address, +// IPv6 without brackets (Postgres inet rejects them). +func TestClientIP(t *testing.T) { + for _, c := range []struct{ fwd, remote, want string }{ + {"203.0.113.7, 10.0.0.1", "10.0.0.2:5000", "203.0.113.7"}, + {"[2001:db8::1]", "10.0.0.2:5000", "2001:db8::1"}, + {"", "10.0.0.2:5000", "10.0.0.2"}, + {"", "[::1]:443", "::1"}, + {"", "[::1]", "::1"}, + {"", "socket", "socket"}, + } { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = c.remote + if c.fwd != "" { + r.Header.Set("X-Forwarded-For", c.fwd) + } + if got := clientIP(r); got != c.want { + t.Errorf("fwd %q remote %q: %q, want %q", c.fwd, c.remote, got, c.want) + } + } +}