-
Notifications
You must be signed in to change notification settings - Fork 3
/
request_test.go
104 lines (88 loc) · 2.51 KB
/
request_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
package rajaongkir
import (
"net/http"
"testing"
)
func TestCreateTargetURL(t *testing.T) {
ro := New("APIKEY12345", "api.rajaongkir.com/starter", nil)
tables := []struct {
endpoint string
expected string
}{
{"/city", "https://api.rajaongkir.com/starter/city"},
{"/province", "https://api.rajaongkir.com/starter/province"},
{"/cost", "https://api.rajaongkir.com/starter/cost"},
}
for _, table := range tables {
result := ro.createTargetURL(table.endpoint)
if result != table.expected {
t.Errorf("Wrong url returned. Got %s, expected %s", result, table.expected)
}
}
}
func TestCreateRequest(t *testing.T) {
ro := New("APIKEY12345", "api.rajaongkir.com/starter", nil)
tables := []struct {
method string
endpoint string
payload string
isErr bool
}{
{http.MethodGet, "/city", `{"foo":"bar"}`, false},
{http.MethodPost, "/city", `{"foo":"bar"}`, false},
{http.MethodPut, "/city", `{"foo":"bar"}`, false},
{http.MethodDelete, "/city^", `{"foo":"bar"}`, false},
{"øP", "/city", `{"foo":"bar"}`, true},
}
for _, table := range tables {
req, err := ro.createRequest(table.method, table.endpoint, table.payload)
isErr := false
if err != nil {
isErr = true
}
expectedIsErr := table.isErr
if isErr != expectedIsErr {
t.Errorf("Error mismatch. Got %s, expected %v", err, expectedIsErr)
}
if err == nil {
method := req.Method
expectedMethod := table.method
if method != expectedMethod {
t.Errorf("Method mismatch. Got %s, expected %s", method, expectedMethod)
}
key := req.Header.Get("key")
expectedKey := "APIKEY12345"
if key != expectedKey {
t.Errorf("APIKey mismatch. Got %s, expected %s", key, expectedKey)
}
}
}
}
func TestSendRequest(t *testing.T) {
provinceResObject := &provinceResponse{}
tables := []struct {
method string
endpoint string
payload string
responseObject interface{}
fakeResponse string
isErr bool
}{
{"GET", "/province", "", provinceResObject, provinceRes, false},
{"¶PR", "/province", "", provinceResObject, provinceRes, true}, // Create request error
}
for _, table := range tables {
ts, ro, _ := setupTest(table.fakeResponse)
defer ts.Close()
responseObject := table.responseObject
err := ro.sendRequest(table.method, table.endpoint, table.payload, responseObject)
isErr := false
if err != nil {
isErr = true
}
expectedIsErr := table.isErr
if isErr != expectedIsErr {
t.Errorf("Error mismatch. Got %s, expected %v", err, expectedIsErr)
}
}
}