-
Notifications
You must be signed in to change notification settings - Fork 5
/
handle_test.go
121 lines (105 loc) · 2.62 KB
/
handle_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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package differer
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/jimen0/differer/scheduler"
"github.com/stretchr/testify/require"
)
func TestHandleInput(t *testing.T) {
tt := []struct {
name string
method string
input *input
runners []Runner
expStatus int
expResults *output
}{
{
name: "valid",
method: http.MethodPost,
input: &input{Addrs: []string{"https://example.com/"}},
runners: []Runner{stubRunner{expected: &scheduler.Result{Id: "bbac", Value: "test"}}},
expStatus: http.StatusOK,
expResults: &output{
Results: []addressResult{
{
Input: "https://example.com/",
Runner: "stub",
Output: &scheduler.Result{
Id: "bbac",
Value: "test",
},
},
},
},
},
{
name: "invalid method",
method: http.MethodGet,
runners: []Runner{stubRunner{expectedErr: errors.New("invalid method")}},
expStatus: http.StatusMethodNotAllowed,
},
{
name: "empty input",
method: http.MethodPost,
input: &input{Addrs: []string{}},
runners: []Runner{stubRunner{expectedErr: errors.New("empty input")}},
expStatus: http.StatusBadRequest,
},
{
name: "bad runner",
method: http.MethodPost,
input: &input{Addrs: []string{"https://example.com/"}},
runners: []Runner{stubRunner{expectedErr: errors.New("bad runner")}},
expStatus: http.StatusOK,
expResults: &output{
Results: []addressResult{
{
Input: "https://example.com/",
Runner: "stub",
Output: nil,
},
},
},
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
b, err := json.Marshal(tc.input)
require.Nil(t, err)
req := httptest.NewRequest(tc.method, "/differer", bytes.NewReader(b))
w := httptest.NewRecorder()
HandleInput(tc.runners).ServeHTTP(w, req)
res := w.Result()
defer res.Body.Close()
require.Equal(t, tc.expStatus, res.StatusCode)
// for error requests only status must be checked.
if tc.expStatus != http.StatusOK {
return
}
var got output
err = json.NewDecoder(res.Body).Decode(&got)
require.Nil(t, err)
require.Equal(t, tc.expResults, &got)
})
}
}
type stubRunner struct {
expected *scheduler.Result
expectedErr error
}
// Run returns the configured results for the stub.
func (sr stubRunner) Run(ctx context.Context, data []byte) (*scheduler.Result, error) {
return sr.expected, sr.expectedErr
}
// Name returns stub's name.
func (sr stubRunner) GetName() string {
return "stub"
}
// ensure stubRunner implements the Runner interface.
var _ Runner = (*stubRunner)(nil)