1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
package httpserver_test
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"testing/fstest"
"github.com/bots-garden/ori/internal/httpserver"
)
// builtUI mimics a Vite production build.
var builtUI = fstest.MapFS{
"index.html": {Data: []byte("<html>ori</html>")},
"assets/app.js": {Data: []byte("console.log('ori')")},
"assets/app.css": {Data: []byte("body{}")},
"vite.svg": {Data: []byte("<svg/>")},
}
func get(t *testing.T, handler http.Handler, path string) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
return rec
}
func TestHealthz(t *testing.T) {
rec := get(t, httpserver.Handler(builtUI, nil), "/healthz")
if rec.Code != http.StatusOK {
t.Fatalf("GET /healthz status = %d, want 200", rec.Code)
}
if body := rec.Body.String(); body != `{"status":"ok"}` {
t.Errorf("GET /healthz body = %q", body)
}
}
func TestServesIndex(t *testing.T) {
rec := get(t, httpserver.Handler(builtUI, nil), "/")
if rec.Code != http.StatusOK {
t.Fatalf("GET / status = %d, want 200", rec.Code)
}
if body := rec.Body.String(); body != "<html>ori</html>" {
t.Errorf("GET / body = %q, want index.html content", body)
}
}
func TestServesStaticAsset(t *testing.T) {
rec := get(t, httpserver.Handler(builtUI, nil), "/assets/app.js")
if rec.Code != http.StatusOK {
t.Fatalf("GET /assets/app.js status = %d, want 200", rec.Code)
}
if body := rec.Body.String(); body != "console.log('ori')" {
t.Errorf("GET /assets/app.js body = %q", body)
}
}
func TestUnknownPathFallsBackToIndex(t *testing.T) {
rec := get(t, httpserver.Handler(builtUI, nil), "/some/client/route")
if rec.Code != http.StatusOK {
t.Fatalf("GET /some/client/route status = %d, want 200 (SPA fallback)", rec.Code)
}
if body := rec.Body.String(); body != "<html>ori</html>" {
t.Errorf("SPA fallback body = %q, want index.html content", body)
}
}
func TestMissingBuildAnswers503(t *testing.T) {
empty := fstest.MapFS{".gitkeep": {Data: nil}}
rec := get(t, httpserver.Handler(empty, nil), "/")
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("GET / without a UI build status = %d, want 503", rec.Code)
}
}
func TestExtraRouteIsMounted(t *testing.T) {
extra := map[string]http.Handler{
"GET /ws": http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, "ws-here")
}),
}
rec := get(t, httpserver.Handler(builtUI, extra), "/ws")
if rec.Code != http.StatusOK || rec.Body.String() != "ws-here" {
t.Fatalf("GET /ws = %d %q, want 200 \"ws-here\"", rec.Code, rec.Body.String())
}
}
|