-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.go
64 lines (54 loc) · 1.28 KB
/
mock.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
package telegram
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path"
)
func WithClientMock(ok bool, result interface{}) ConfiguratorFunc {
return WithHTTPClient(&http.Client{
Transport: &MethodMock{
ok: ok,
result: result,
},
})
}
func WithMethodMock(name string, ok bool, result interface{}) ConfiguratorFunc {
return WithHTTPClient(&http.Client{
Transport: &MethodMock{
name: &name,
ok: ok,
result: result,
},
})
}
type MethodMock struct {
ok bool
result interface{}
name *string
}
func (mock *MethodMock) RoundTrip(r *http.Request) (*http.Response, error) {
if mock.name != nil {
if name := path.Base(r.URL.Path); name != *mock.name {
return nil, fmt.Errorf("invalid method call: called %s when expected %s", name, *mock.name)
}
}
resultData, err := json.Marshal(mock.result)
if err != nil {
return nil, fmt.Errorf("failed to mock telegram request: %w", err)
}
responseData, err := json.Marshal(Response{
OK: mock.ok,
Result: resultData,
})
if err != nil {
return nil, fmt.Errorf("failed to mock telegram request: %w", err)
}
return &http.Response{
Status: http.StatusText(http.StatusOK),
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader(responseData)),
}, nil
}