aboutsummaryrefslogtreecommitdiffhomepage
path: root/cmd/mbf/internal/pkgserver/api_test.go
blob: 3a9945da43e7edd8cabc81dd97f7d8f7edaf9588 (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package pkgserver

import (
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"

	"hakurei.app/internal/info"
	"hakurei.app/internal/rosa"
)

// prefix is prepended to every API path.
const prefix = "/api/" + apiVersion + "/"

func TestAPIInfo(t *testing.T) {
	t.Parallel()

	w := httptest.NewRecorder()
	handleInfo(w, httptest.NewRequestWithContext(
		t.Context(),
		http.MethodGet,
		prefix+"info",
		nil,
	))

	resp := w.Result()
	checkStatus(t, resp, http.StatusOK)
	checkAPIHeader(t, w.Header())

	checkPayload(t, resp, struct {
		Count          int    `json:"count"`
		HakureiVersion string `json:"hakurei_version"`
	}{len(rosa.Native().Collect()), info.Version()})
}

func TestAPIGet(t *testing.T) {
	t.Parallel()
	const target = prefix + "get"

	index := newIndex(t)
	newRequest := func(suffix string) *httptest.ResponseRecorder {
		w := httptest.NewRecorder()
		index.handleGet(w, httptest.NewRequestWithContext(
			t.Context(),
			http.MethodGet,
			target+suffix,
			nil,
		))
		return w
	}

	checkValidate := func(t *testing.T, suffix string, vmin, vmax int, wantErr string) {
		t.Run("invalid", func(t *testing.T) {
			t.Parallel()

			w := newRequest("?" + suffix + "=invalid")
			resp := w.Result()
			checkError(t, resp, wantErr, http.StatusBadRequest)
		})

		t.Run("min", func(t *testing.T) {
			t.Parallel()

			w := newRequest("?" + suffix + "=" + strconv.Itoa(vmin-1))
			resp := w.Result()
			checkError(t, resp, wantErr, http.StatusBadRequest)

			w = newRequest("?" + suffix + "=" + strconv.Itoa(vmin))
			resp = w.Result()
			checkStatus(t, resp, http.StatusOK)
		})

		t.Run("max", func(t *testing.T) {
			t.Parallel()

			w := newRequest("?" + suffix + "=" + strconv.Itoa(vmax+1))
			resp := w.Result()
			checkError(t, resp, wantErr, http.StatusBadRequest)

			w = newRequest("?" + suffix + "=" + strconv.Itoa(vmax))
			resp = w.Result()
			checkStatus(t, resp, http.StatusOK)
		})
	}

	t.Run("limit", func(t *testing.T) {
		t.Parallel()
		checkValidate(
			t, "index=0&sort=0&limit", 1, 100,
			"limit must be an integer between 1 and 100",
		)
	})

	count := len(rosa.Native().Collect())
	t.Run("index", func(t *testing.T) {
		t.Parallel()
		checkValidate(
			t, "limit=1&sort=0&index", 0, count-1,
			"index must be an integer between 0 and "+strconv.Itoa(count-1),
		)
	})

	t.Run("sort", func(t *testing.T) {
		t.Parallel()
		checkValidate(
			t, "index=0&limit=1&sort", 0, int(sortOrderEnd),
			"sort must be an integer between 0 and "+strconv.Itoa(int(sortOrderEnd)),
		)
	})
}