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
122
123
124
125
| package hello
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"testing"
"time"
)
type APIMock struct{}
func (a *APIMock) FetchPostByID(ctx context.Context, id int) (*APIPost, error) {
return nil, fmt.Errorf(http.StatusText(http.StatusNotFound))
}
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
type HTTPClientMock struct {
DoFunc func(*http.Request) (*http.Response, error)
}
func (h HTTPClientMock) Do(r *http.Request) (*http.Response, error) {
return h.DoFunc(r)
}
func New(client HTTPClient, baseURL string, timeout time.Duration) API {
return &v1{
c: client,
baseURL: baseURL,
timeout: timeout,
}
}
type v1 struct {
c HTTPClient
baseURL string
timeout time.Duration
}
func (v v1) FetchPostByID(ctx context.Context, id int) (*APIPost, error) {
u := fmt.Sprintf("%s/posts/%d", v.baseURL, id)
ctx, cancel := context.WithTimeout(ctx, v.timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
}
res, err := v.c.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf(http.StatusText(res.StatusCode))
}
var result *APIPost
return result, json.NewDecoder(res.Body).Decode(&result)
}
var (
client = &HTTPClientMock{}
api = New(client, "", 0)
)
func TestV1FetchPostByID(t *testing.T) {
postTests := []struct {
Body string
StatusCode int
Result *APIPost
Error error
}{
{
Body: `{"id":1,"user_id":1001,"title":"title 1","body":"body 1"}`,
StatusCode: 200,
Result: &APIPost{1, 1001, "title 1", "body 1"},
Error: nil,
},
{
Body: `{"id":2,"user_id":1002,"title":"title 2","body":"body 2"}`,
StatusCode: 200,
Result: &APIPost{2, 1002, "title 2", "body 2"},
Error: nil,
},
{
Body: ``,
StatusCode: http.StatusBadRequest,
Result: nil,
Error: fmt.Errorf(http.StatusText(http.StatusBadRequest)),
},
{
Body: ``,
StatusCode: http.StatusBadRequest,
Result: nil,
Error: fmt.Errorf(http.StatusText(http.StatusBadRequest)),
},
}
for _, tt := range postTests {
client.DoFunc = func(r *http.Request) (*http.Response, error) {
return &http.Response{
Body: io.NopCloser(strings.NewReader(tt.Body)),
StatusCode: tt.StatusCode,
}, nil
}
post, err := api.FetchPostByID(context.Background(), 0)
if err != nil && err.Error() != tt.Error.Error() {
t.Fatalf("want %v, got %v", tt.Error, err)
}
if !reflect.DeepEqual(post, tt.Result) {
t.Fatalf("want %v, got %v", tt.Result, post)
}
}
}
|