-
Notifications
You must be signed in to change notification settings - Fork 1
/
brewerydb_test.go
262 lines (223 loc) · 5.97 KB
/
brewerydb_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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package brewerydb
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"testing"
)
var (
mux *http.ServeMux
server *httptest.Server
client *Client
fakeKey = "abcdefghijklmnopqrstuvwxyz"
)
func loadTestData(filename string, t *testing.T) io.ReadCloser {
data, err := os.Open("test_data/" + filename)
if err != nil {
t.Fatal("Failed to open test data file")
}
return data
}
func setup() {
mux = http.NewServeMux()
server = httptest.NewServer(mux)
apiURL = server.URL
client = NewClient(fakeKey)
}
func teardown() {
server.Close()
}
// Checks that the HTTP Request's method matches the given method.
func checkMethod(t *testing.T, r *http.Request, method string) {
if method != r.Method {
t.Errorf("Request method = %v, want %v", r.Method, method)
}
}
// Checks that the HTTP Request contains a key "p" with a value matching the given page.
func checkPage(t *testing.T, r *http.Request, page int) {
if p := r.FormValue("p"); p != strconv.Itoa(page) {
t.Fatalf("Request.FormValue p = %v, want %v", p, page)
}
}
// Checks that the HTTP Request's URL path ends with suffix, ignoring any trailing slashes.
func checkURLSuffix(t *testing.T, r *http.Request, suffix string) {
if !strings.HasSuffix(strings.TrimSuffix(r.URL.Path, "/"), suffix) {
t.Fatalf("URL path = %s, expected suffix = %s", r.URL.Path, suffix)
}
}
// Checks that the Request's body contains name url-encoded with value=value
func checkPostFormValue(t *testing.T, r *http.Request, name, value string) {
if v := r.PostFormValue(name); v != value {
t.Fatalf("%s = %v, want %v", name, v, value)
}
}
// Checks that the Request's URL query string contains name url-encoded with value=value.
func checkFormValue(t *testing.T, r *http.Request, name, value string) {
if v := r.FormValue(name); v != value {
t.Fatalf("%s = %v, want %v", name, v, value)
}
}
// Checks that each key is NOT url-encoded in the Request's Body
func checkPostFormDNE(t *testing.T, r *http.Request, keys ...string) {
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
formMap := map[string][]string(r.PostForm)
for _, key := range keys {
if _, ok := formMap[key]; ok {
t.Fatalf("form value '%s' should not be encoded", key)
}
}
}
// Executes fn, expecting it to return an error
func testBadURL(t *testing.T, fn func() error) {
origURL := apiURL
apiURL = "http://%api.brewerydb.com/v2"
if err := fn(); err == nil {
t.Fatal("expected HTTP Request URL error")
}
apiURL = origURL
}
func TestNewRequest(t *testing.T) {
setup()
defer teardown()
// `data` parameter should be a struct, not a string
_, err := client.NewRequest("GET", "/heartbeat", "hello, world")
if err == nil {
t.Fatal("Expected query encoding error")
}
_, err = client.NewRequest("FOO", "/hearbeat", nil)
if err == nil {
t.Fatal("Expected HTTP method error")
}
}
// for testing client.Do error handling
type testTransport struct{}
func (t testTransport) RoundTrip(r *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("fake round-trip error")
}
func TestDo(t *testing.T) {
setup()
defer teardown()
client.JSONWriter = ioutil.Discard
const beerID = "o9TSOv"
mux.HandleFunc("/beer/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "{}")
})
_, err := client.Beer.Get(beerID)
if err != nil {
t.Fatal(err)
}
client.client.Transport = testTransport{}
_, err = client.Beer.Get(beerID)
if err == nil {
t.Fatal("Expected net/http Do error")
}
}
func TestYesNoUnmarshalJSON(t *testing.T) {
q := struct {
IsPrimary YesNo `url:"isPrimary"`
IsClosed YesNo `url:"isClosed,omitempty"`
}{}
js0 := []byte(`{"isPrimary":"Y"}`)
if err := json.Unmarshal(js0, &q); err != nil {
t.Error(err)
}
if v := YesNo(true); q.IsPrimary != v {
t.Errorf("q.IsPrimary = %v, want %v", q.IsPrimary, v)
}
if v := YesNo(false); q.IsClosed != v {
t.Errorf("q.IsClosed = %v, want %v", q.IsClosed, v)
}
js1 := []byte(`{"isPrimary":"N", "isClosed":"Y"}`)
if err := json.Unmarshal(js1, &q); err != nil {
t.Error(err)
}
if v := YesNo(false); q.IsPrimary != v {
t.Errorf("q.IsPrimary = %v, want %v", q.IsPrimary, v)
}
if v := YesNo(true); q.IsClosed != v {
t.Errorf("q.IsClosed = %v, want %v", q.IsClosed, v)
}
js2 := []byte(`{"isPrimary":"y", "isClosed":true}`)
if err := json.Unmarshal(js2, &q); err == nil {
t.Errorf(`Expected unmarshal error (only "Y" or "N" are valid YesNo JSON)`)
}
}
// "What is Doppelbock?"
func Example_doppelbock() {
c := NewClient(os.Getenv("BREWERYDB_API_KEY"))
styles, err := c.Menu.Styles()
if err != nil {
panic(err)
}
for _, style := range styles {
if style.ShortName == "Doppelbock" {
fmt.Println("Doppelbock: \n", style.Description)
}
}
}
// "What is in Dragon's Milk?"
func Example_dragonsmilk() {
c := NewClient(os.Getenv("BREWERYDB_API_KEY"))
bl, err := c.Search.Beer("Dragon's Milk", nil)
if err != nil {
panic(err)
}
var beerID string
for _, beer := range bl.Beers {
if beer.Name == "Dragon's Milk" {
beerID = beer.ID
}
}
if beerID == "" {
panic("Dragon's Milk not found")
}
ingredients, err := c.Beer.ListIngredients(beerID)
if err != nil {
panic(err)
}
adjuncts, err := c.Beer.ListAdjuncts(beerID)
if err != nil {
panic(err)
}
fermentables, err := c.Beer.ListFermentables(beerID)
if err != nil {
panic(err)
}
hops, err := c.Beer.ListHops(beerID)
if err != nil {
panic(err)
}
yeasts, err := c.Beer.ListYeasts(beerID)
if err != nil {
panic(err)
}
fmt.Println("Dragon's Milk:")
fmt.Println(" Ingredients:")
for _, ingredient := range ingredients {
fmt.Println(" " + ingredient.Name)
}
fmt.Println("\n Adjuncts:")
for _, adjunct := range adjuncts {
fmt.Println(" " + adjunct.Name)
}
fmt.Println(" Fermentables:")
for _, fermentable := range fermentables {
fmt.Println(" " + fermentable.Name)
}
fmt.Println(" Hops:")
for _, hop := range hops {
fmt.Println(" " + hop.Name)
}
fmt.Println(" Yeasts:")
for _, yeast := range yeasts {
fmt.Println(" " + yeast.Name)
}
}