// Package wstest provides the small websocket echo server shared by the client // and CLI identity tests, so the request/reply harness is defined once. package wstest import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/coder/websocket" "github.com/coder/websocket/wsjson" "git.a-wan.net/alan/pipelines/internal/protocol" ) // Server starts a websocket endpoint that answers every request with // reply(request), echoing the request ID, and returns the client URL. func Server(t testing.TB, reply func(protocol.Message) protocol.Message) string { t.Helper() return serve(t, func(request protocol.Message) any { response := reply(request) response.ID = request.ID return response }) } // Raw starts a websocket endpoint that answers every request with a JSON object // from payload(request), with "id" set to the request ID, so tests can include // top-level keys the client does not model. func Raw(t testing.TB, payload func(protocol.Message) map[string]any) string { t.Helper() return serve(t, func(request protocol.Message) any { body := payload(request) body["id"] = request.ID return body }) } func serve(t testing.TB, reply func(protocol.Message) any) string { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := websocket.Accept(w, r, nil) if err != nil { return } defer conn.CloseNow() for { var request protocol.Message if err := wsjson.Read(r.Context(), conn, &request); err != nil { return } if err := wsjson.Write(r.Context(), conn, reply(request)); err != nil { return } } })) t.Cleanup(srv.Close) return "ws" + strings.TrimPrefix(srv.URL, "http") + "/connect" }