~bigbes/huntsman

ref: 783841b91eafd678cb3895cfcc8dfd89f290ece7 huntsman/internal/server/router_test.go -rw-r--r-- 2.3 KiB
783841b9 — Eugene Blikh Initial commit: multi-provider search router 6 days ago
                                                                                
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
87
package server

import (
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"sourcecraft.dev/bigbes/huntsman/internal/domain/search"
	"sourcecraft.dev/bigbes/huntsman/internal/platform/health"
)

func newTestRouter(t *testing.T) http.Handler {
	t.Helper()
	logger := slog.New(slog.NewTextHandler(io.Discard, nil))
	svc, err := search.NewService("gh", "https://example.com")
	if err != nil {
		t.Fatalf("NewService: %v", err)
	}
	return Routes(logger, health.New(), search.NewHandler(svc))
}

func TestIndexHandler(t *testing.T) {
	h := newTestRouter(t)
	rr := httptest.NewRecorder()
	h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/", http.NoBody))

	if rr.Code != http.StatusOK {
		t.Fatalf("status = %d", rr.Code)
	}
	if got := rr.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/html") {
		t.Errorf("content-type = %q", got)
	}
	body := rr.Body.String()
	if !strings.Contains(body, `<link rel="search"`) {
		t.Errorf("body missing OSD link tag: %q", body)
	}
	if !strings.Contains(body, "huntsman") {
		t.Errorf("body missing service name")
	}
}

func TestRoutesMountAllExpectedPaths(t *testing.T) {
	h := newTestRouter(t)

	cases := []struct {
		path       string
		wantStatus int
	}{
		{"/healthz", 200},
		{"/readyz", 200},
		{"/", 200},
		{"/providers", 200},
		{"/opensearch.xml", 200},
		{"/opensearch/gh.xml", 200},
		{"/search?q=foo", 302},
	}
	for _, tc := range cases {
		t.Run(tc.path, func(t *testing.T) {
			rr := httptest.NewRecorder()
			h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", tc.path, http.NoBody))
			if rr.Code != tc.wantStatus {
				t.Errorf("%s: status = %d, want %d", tc.path, rr.Code, tc.wantStatus)
			}
		})
	}
}

func TestRoutesAttachRequestIDMiddleware(t *testing.T) {
	h := newTestRouter(t)
	rr := httptest.NewRecorder()
	h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/", http.NoBody))
	if rr.Header().Get("X-Request-ID") == "" {
		t.Error("expected X-Request-ID header from middleware")
	}
}

func TestRoutesUnknownPath404(t *testing.T) {
	h := newTestRouter(t)
	rr := httptest.NewRecorder()
	h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/no-such-thing", http.NoBody))
	if rr.Code != http.StatusNotFound {
		t.Errorf("status = %d, want 404", rr.Code)
	}
}