-
Notifications
You must be signed in to change notification settings - Fork 2
/
zomato_test.go
106 lines (86 loc) · 2.27 KB
/
zomato_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
package zomato_test
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"github.com/go-india/zomato"
"github.com/pkg/errors"
)
var (
testServer *url.URL
testDataDir = "./testdata/"
updateTestData = flag.Bool("update", false, "if True run integration tests; if False run internal tests")
)
// returns APIKey from the environment
func getAPIKey() string {
env := func(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
return env("ZOMATO_TEST_API_KEY", "API_KEY")
}
func TestMain(m *testing.M) {
flag.Parse()
// Run testServer for unit tests
if !*updateTestData {
server := httptest.NewServer(http.FileServer(http.Dir(testDataDir)))
surl, err := url.Parse(server.URL)
if err != nil {
fmt.Println("testServer URL parse failed:", err)
os.Exit(1)
}
testServer = surl
defer server.Close()
}
os.Exit(m.Run())
return
}
func testClient(c *zomato.Client, t *testing.T) {
c.HTTPClient = &http.Client{}
if *updateTestData {
c.HTTPClient.Transport = &saverTransport{t}
return
}
c.HTTPClient.Transport = &loaderTransport{t}
return
}
// saverTransport saves response body to testdata file
type saverTransport struct{ t *testing.T }
func (st saverTransport) RoundTrip(r *http.Request) (*http.Response, error) {
resp, err := http.DefaultTransport.RoundTrip(r)
if err != nil {
return resp, errors.Wrap(err, "request failed")
}
if resp.StatusCode != http.StatusOK {
return resp, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp, errors.Wrap(err, "read body failed")
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(body))
err = ioutil.WriteFile(testDataDir+filename(st.t), body, 0644)
return resp, errors.Wrap(err, "write file failed")
}
// loaderTransport loads response from testdata file
type loaderTransport struct{ t *testing.T }
func (lt loaderTransport) RoundTrip(r *http.Request) (*http.Response, error) {
return http.Get(testServer.String() + "/" + filename(lt.t))
}
func filename(t *testing.T) string {
name := t.Name()
if strings.Contains(name, "/") { // If a subtest
name = name[strings.LastIndex(t.Name(), "/")+1:]
}
name = strings.TrimPrefix(name, "Test")
return name + ".json"
}