-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathendpoint_test.go
107 lines (98 loc) · 2.61 KB
/
endpoint_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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package service
import (
"bytes"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
)
type MockEndpoint struct {
CallFunc func(interface{}) (interface{}, error)
}
func (m *MockEndpoint) Call(req interface{}) (interface{}, error) {
return m.CallFunc(req)
}
func TestHandlerFunc(t *testing.T) {
tests := []struct {
name string
reqBody io.Reader
mockCallFunc func(interface{}) (interface{}, error)
expectedStatus int
expectedResp string
method string
}{
{
name: "Malformed JSON",
method: http.MethodPost,
reqBody: bytes.NewBufferString(`{"key": "value",}`),
expectedStatus: http.StatusBadRequest,
},
{
name: "Invalid HTTP method",
method: http.MethodGet,
reqBody: bytes.NewBufferString(`{
"key": "value"
}`),
mockCallFunc: func(interface{}) (interface{}, error) {
return map[string]string{"result": "success"}, nil
},
expectedStatus: http.StatusMethodNotAllowed,
},
{
name: "Endpoint returns error",
method: http.MethodPost,
reqBody: bytes.NewBufferString(`{
"key": "value"
}`),
mockCallFunc: func(interface{}) (interface{}, error) {
return nil, errors.New("test error")
},
expectedStatus: http.StatusInternalServerError,
},
{
name: "Valid request and response",
method: http.MethodPost,
reqBody: bytes.NewBufferString(`{
"key": "value"
}`),
mockCallFunc: func(interface{}) (interface{}, error) {
return map[string]string{"result": "success"}, nil
},
expectedStatus: http.StatusOK,
expectedResp: "{\"result\":\"success\"}\n",
},
{
name: "Response not encodable",
method: http.MethodPost,
reqBody: bytes.NewBufferString(`{
"key": "value"
}`),
mockCallFunc: func(interface{}) (interface{}, error) {
return func() {}, nil // A function is not JSON encodable
},
expectedStatus: http.StatusInternalServerError,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
mockEndpoint := &MockEndpoint{CallFunc: tc.mockCallFunc}
handler := HandlerFunc[interface{}, interface{}](mockEndpoint)
req := httptest.NewRequest(tc.method, "/", tc.reqBody)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != tc.expectedStatus {
t.Errorf("Expected status %d, got %d", tc.expectedStatus, rec.Code)
}
if tc.expectedResp != "" {
resp, err := io.ReadAll(rec.Body)
if err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
if string(resp) != tc.expectedResp {
t.Errorf("Expected response %v, got %v", tc.expectedResp, string(resp))
}
}
})
}
}