forked from trussworks/go-sample-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdogs_test.go
94 lines (81 loc) · 2.06 KB
/
dogs_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
package handlers
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"github.com/google/uuid"
"bin/bork/pkg/appcontext"
"bin/bork/pkg/models"
)
func (s HandlerTestSuite) TestDogsHandler_Handle() {
dog := models.Dog{
ID: uuid.New(),
Name: "Chihua",
Breed: models.Chihuahua,
BirthDate: s.base.clock.Now(),
}
fakeFetchDogs := func(ctx context.Context) (*models.Dogs, error) {
return &models.Dogs{dog}, nil
}
requestContext := context.Background()
requestContext = appcontext.WithUser(requestContext, models.User{ID: "McName"})
s.Run("golden path GET returns 200", func() {
rr := httptest.NewRecorder()
req, err := http.NewRequestWithContext(
requestContext,
"GET",
"/dogs",
bytes.NewBufferString(""),
)
s.NoError(err)
req = req.WithContext(appcontext.WithEmptyRequestLog(req.Context()))
DogsHandler{
s.base,
fakeFetchDogs,
}.Handle()(rr, req)
s.Equal(http.StatusOK, rr.Code)
responseDogs := &models.Dogs{}
err = json.Unmarshal(rr.Body.Bytes(), responseDogs)
s.NoError(err)
s.Len(*responseDogs, 1)
s.Equal(dog.ID, (*responseDogs)[0].ID)
})
s.Run("GET with fetch failing returns 500", func() {
failFetchDogs := func(ctx context.Context) (*models.Dogs, error) {
return nil, errors.New("failed to fetch dog")
}
rr := httptest.NewRecorder()
req, err := http.NewRequestWithContext(
requestContext,
"GET",
"/dogs",
bytes.NewBufferString(""),
)
s.NoError(err)
req = req.WithContext(appcontext.WithEmptyRequestLog(req.Context()))
DogsHandler{
s.base,
failFetchDogs,
}.Handle()(rr, req)
s.Equal(http.StatusInternalServerError, rr.Code)
})
s.Run("unsupported method returns 405", func() {
rr := httptest.NewRecorder()
req, err := http.NewRequestWithContext(
requestContext,
"OPTIONS",
"/dogs",
bytes.NewBufferString(""),
)
s.NoError(err)
req = req.WithContext(appcontext.WithEmptyRequestLog(req.Context()))
DogsHandler{
s.base,
fakeFetchDogs,
}.Handle()(rr, req)
s.Equal(http.StatusMethodNotAllowed, rr.Code)
})
}