forked from peterssonjesper/booli-api-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlisting_test.go
71 lines (53 loc) · 1.57 KB
/
listing_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
package client
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func getListing(testServer *httptest.Server, id int) ([]byte, error) {
client := New(testServer.URL, "my-caller-id", "my-api-key")
return client.Listing(id)
}
func TestReturnsListingWhenResponseIsValidJson(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, `{
"listings": [
{ "booliId" : 1234 }
]
}`)
}))
type envelope struct {
Listings []map[string]int
}
body, err := getListing(testServer, 1234)
var e envelope
json.Unmarshal(body, &e)
if e.Listings[0]["booliId"] != 1234 {
t.Error("Expected booli ID to be 1234, was %#v", e.Listings[0]["booliId"])
}
if err != nil {
t.Error("Expected error to be nil, was %#v", err)
}
}
func TestReturnsErrorWhenServerIsNotRespondingForListing(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, `{"error": "Internal server error"}`)
}))
_, err := getListing(testServer, 1234)
if err == nil {
t.Error("Expected an error to have been set")
}
}
func TestCallsCorrectUrlWhenFetchingListing(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, r.URL)
}))
url, _ := getListing(testServer, 1234)
expected := "/listings/1234"
if string(url)[:len(expected)] != expected {
t.Errorf("Expected url to start with %s, was %s", expected, url)
}
}