Files
scrabble-game/gateway/internal/admin/admin_test.go
T
developer 3a640a17a4
Tests · Go / test (push) Successful in 7s
Tests · Integration / integration (push) Successful in 13s
Stage 10: admin console & dictionary ops (complaint review, hot-reload, broadcasts) (#11)
2026-06-04 07:27:49 +00:00

81 lines
2.2 KiB
Go

package admin_test
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"scrabble/gateway/internal/admin"
)
// newAdmin fronts a fake backend with the admin proxy. The fake backend records the
// path it receives so a test can assert the proxy forwards /_gm verbatim.
func newAdmin(t *testing.T) (front *httptest.Server, gotPath *string, cleanup func()) {
t.Helper()
var path string
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_, _ = w.Write([]byte("console"))
}))
proxy, err := admin.NewProxy(backend.URL, "ops", "secret", nil)
if err != nil {
t.Fatalf("new proxy: %v", err)
}
front = httptest.NewServer(proxy)
return front, &path, func() { front.Close(); backend.Close() }
}
func TestAdminRejectsMissingCredentials(t *testing.T) {
front, _, cleanup := newAdmin(t)
defer cleanup()
resp, err := http.Get(front.URL + "/_gm/")
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", resp.StatusCode)
}
if resp.Header.Get("WWW-Authenticate") == "" {
t.Error("missing WWW-Authenticate challenge")
}
}
func TestAdminProxiesVerbatimWithCredentials(t *testing.T) {
front, gotPath, cleanup := newAdmin(t)
defer cleanup()
req, _ := http.NewRequest(http.MethodGet, front.URL+"/_gm/complaints", nil)
req.SetBasicAuth("ops", "secret")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK || string(body) != "console" {
t.Fatalf("status = %d body = %q, want 200 console", resp.StatusCode, body)
}
if *gotPath != "/_gm/complaints" {
t.Errorf("backend path = %q, want /_gm/complaints (verbatim)", *gotPath)
}
}
func TestAdminRejectsWrongPassword(t *testing.T) {
front, _, cleanup := newAdmin(t)
defer cleanup()
req, _ := http.NewRequest(http.MethodGet, front.URL+"/_gm/", nil)
req.SetBasicAuth("ops", "wrong")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", resp.StatusCode)
}
}