-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient_test.go
82 lines (71 loc) · 2.14 KB
/
client_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
package client
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestClientCanHitAPI(t *testing.T) {
t.Run("happy path - can hit the api and return a pokemon", func(*testing.T) {
myClient := NewClient()
poke, err := myClient.GetPokemonByName(context.Background(), "pikachu")
assert.NoError(t, err)
assert.Equal(t, "pikachu", poke.Name)
})
t.Run("sad path - return an error when the pokemon does not exist", func(*testing.T) {
myClient := NewClient()
_, err := myClient.GetPokemonByName(context.Background(), "non-existant-pokemon")
assert.Error(t, err)
assert.Equal(t, PokemonFetchErr{
Message: "non-200 status code from the API",
StatusCode: 404,
}, err)
})
t.Run("happy path - testing the WithAPIURL option function", func(*testing.T) {
myClient := NewClient(
WithAPIURL("my-test-url"),
)
assert.Equal(t, "my-test-url", myClient.apiURL)
})
t.Run("happy path - tests with httpclient works", func(*testing.T) {
myClient := NewClient(
WithAPIURL("my-test-url"),
WithHTTPClient(&http.Client{
Timeout: 1 * time.Second,
}),
)
assert.Equal(t, "my-test-url", myClient.apiURL)
assert.Equal(t, 1*time.Second, myClient.httpClient.Timeout)
})
t.Run("happy test - able to hit locally running test server", func(t *testing.T) {
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `{"name": "pikachu", "height": 10}`)
}),
)
defer ts.Close()
myClient := NewClient(
WithAPIURL(ts.URL),
)
poke, err := myClient.GetPokemonByName(context.Background(), "pikachu")
assert.NoError(t, err)
assert.Equal(t, 10, poke.Height)
})
t.Run("sad path test - able to handle 500 status from the API", func(t *testing.T) {
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}),
)
defer ts.Close()
myClient := NewClient(
WithAPIURL(ts.URL),
)
poke, err := myClient.GetPokemonByName(context.Background(), "pikachu")
assert.Error(t, err)
assert.Equal(t, 0, poke.Height)
})
}