-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmux_var_test.go
86 lines (76 loc) · 2.19 KB
/
mux_var_test.go
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 jsonapi_test
import (
"bytes"
"context"
"fmt"
"github.com/mnavarrocarter/jsonapi"
"io"
"net/http"
"net/http/httptest"
"testing"
)
func Test_WithVar(t *testing.T) {
tt := []struct {
caseName string
handler http.Handler
req *http.Request
expectedResponse []byte
expectedStatus int
}{
{
caseName: "resolves a mux var",
handler: jsonapi.Wrap(func(_ context.Context, id string) map[string]string {
return map[string]string{
"msg": fmt.Sprintf("user id is %s", id),
}
}, jsonapi.WithVar("id", 1)),
req: httptest.NewRequest("GET", "/user/1234", http.NoBody),
expectedResponse: []byte(`{"msg":"user id is 1234"}` + "\n"),
expectedStatus: http.StatusOK,
},
{
caseName: "not found",
handler: jsonapi.NotFoundHandler,
req: httptest.NewRequest("GET", "/user", http.NoBody),
expectedResponse: []byte(`{"status":404,"details":"No handler found for GET /user"}` + "\n"),
expectedStatus: http.StatusNotFound,
},
{
caseName: "method not allowed",
handler: jsonapi.MethodNotAllowedHandler,
req: httptest.NewRequest("POST", "/user/1234", http.NoBody),
expectedResponse: []byte(`{"status":405,"details":"Method not allowed for POST /user/1234"}` + "\n"),
expectedStatus: http.StatusMethodNotAllowed,
},
}
// Configure the global var function
jsonapi.VarFunc = func(r *http.Request) map[string]string {
return map[string]string{
"id": "1234",
}
}
for _, test := range tt {
t.Run(test.caseName, func(t *testing.T) {
rec := httptest.NewRecorder()
test.handler.ServeHTTP(rec, test.req)
res := rec.Result()
b, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal("could not read response body")
}
defer func(c io.Closer) {
_ = c.Close()
}(res.Body)
if res.StatusCode != test.expectedStatus {
t.Errorf("expected status %d does not match received %d", test.expectedStatus, res.StatusCode)
}
if !bytes.Equal(test.expectedResponse, b) {
t.Errorf(
"response body does not match\nexpected: %s\nreceived: %s\n",
string(test.expectedResponse),
string(b),
)
}
})
}
}