-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonhandler_test.go
More file actions
47 lines (36 loc) · 1.21 KB
/
jsonhandler_test.go
File metadata and controls
47 lines (36 loc) · 1.21 KB
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
package prefab
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/dpup/prefab/errors"
"github.com/dpup/prefab/logging"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
)
func TestJSONHandler(t *testing.T) {
customHandler := func(req *http.Request) (any, error) {
return map[string]string{
"method": req.Method,
"url": req.URL.String(),
}, nil
}
httpHandler := wrapJSONHandler(customHandler)
req := httptest.NewRequest(http.MethodGet, "/test", nil)
rr := httptest.NewRecorder()
httpHandler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
assert.JSONEq(t, `{"method":"GET","url":"/test"}`, rr.Body.String())
}
func TestJSONHandlerError(t *testing.T) {
customHandler := func(req *http.Request) (any, error) {
return nil, errors.NewC("test error", codes.Internal)
}
httpHandler := wrapJSONHandler(customHandler)
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req = req.WithContext(logging.EnsureLogger(t.Context()))
rr := httptest.NewRecorder()
httpHandler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusInternalServerError, rr.Code)
assert.JSONEq(t, `{"code":13,"codeName":"INTERNAL","message":"test error", "details": []}`, rr.Body.String())
}