/
testcase.go
92 lines (77 loc) · 2.06 KB
/
testcase.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
package mockns1
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/stretchr/testify/assert"
)
type testCase struct {
status int
request struct {
headers http.Header
body []byte
json bool
}
response struct {
headers http.Header
body []byte
}
}
// AddTestCase adds a new test case to the mock service. Test cases are
// unique based on the method, uri, request headers, and request body.
func (s *Service) AddTestCase(
method, uri string, returnStatus int,
requestHeaders, responseHeaders http.Header,
requestBody, responseBody interface{},
) error {
s.stopTimer()
defer s.startTimer()
if !strings.HasPrefix(uri, "/v1/") {
uri = "/v1/" + uri
}
uri = strings.Replace(uri, "//", "/", -1)
tc := &testCase{
status: returnStatus,
}
tc.request.headers = requestHeaders
tc.response.headers = responseHeaders
var err error
if tc.request.body, tc.request.json, err = convertBody(requestBody); err != nil {
return fmt.Errorf("unable to convert request body to []byte: %s", err)
}
if tc.response.body, _, err = convertBody(responseBody); err != nil {
return fmt.Errorf("unable to convert response body to []byte: %s", err)
}
if _, exists := s.tests[method]; !exists {
s.tests[method] = map[string][]*testCase{}
}
if _, exists := s.tests[method][uri]; !exists {
s.tests[method][uri] = []*testCase{}
}
t := new(testifyT)
for _, test := range s.tests[method][uri] {
header := assert.Equal(t, tc.request.headers, test.request.headers)
body := assert.Equal(t, tc.request.body, test.request.body)
if header && body {
return errors.New("test case already registered")
}
}
s.tests[method][uri] = append(s.tests[method][uri], tc)
return nil
}
// ClearTestCases removes all previously added test cases
func (s *Service) ClearTestCases() {
s.tests = map[string]map[string][]*testCase{}
}
func convertBody(body interface{}) ([]byte, bool, error) {
switch b := body.(type) {
case []byte:
return b, false, nil
case string:
return []byte(b), false, nil
}
data, err := json.Marshal(body)
return data, true, err
}