This repository has been archived by the owner on Jun 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
packngo_test.go
329 lines (300 loc) · 8.16 KB
/
packngo_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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package packngo
import (
"bytes"
"fmt"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strings"
"testing"
"time"
"github.com/dnaeon/go-vcr/cassette"
"github.com/dnaeon/go-vcr/recorder"
)
const (
apiURLEnvVar = "PACKET_API_URL"
packngoAccTestVar = "PACKNGO_TEST_ACTUAL_API"
testProjectPrefix = "PACKNGO_TEST_DELME_2d768716_"
testFacilityVar = "PACKNGO_TEST_FACILITY"
testMetroVar = "PACKNGO_TEST_METRO"
testPlanVar = "PACKNGO_TEST_PLAN"
testRecorderEnv = "PACKNGO_TEST_RECORDER"
testRecorderRecord = "record"
testRecorderPlay = "play"
testRecorderDisabled = "disabled"
recorderDefaultMode = recorder.ModeDisabled
// defaults should be available to most users
testFacilityDefault = "ny5"
testFacilityAlternate = "dc13"
testMetroDefault = "sv"
testPlanDefault = "c3.small.x86"
testOS = "ubuntu_18_04"
)
func testPlan() string {
envPlan := os.Getenv(testPlanVar)
if envPlan != "" {
return envPlan
}
return testPlanDefault
}
func testMetro() string {
envMet := os.Getenv(testMetroVar)
if envMet != "" {
return envMet
}
return testMetroDefault
}
func testFacility() string {
envFac := os.Getenv(testFacilityVar)
if envFac != "" {
return envFac
}
return testFacilityDefault
}
func randString8() string {
// test recorder needs replayable names, not randoms
mode, _ := testRecordMode()
if mode != recorder.ModeDisabled {
return "testrand"
}
n := 8
rand.Seed(time.Now().UnixNano())
letterRunes := []rune("acdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
// setupWithProject returns a client, project id, and teardown function
// configured for a new project with a test recorder for the named test
func setupWithProject(t *testing.T) (*Client, string, func()) {
c, stopRecord := setup(t)
p, _, err := c.Projects.Create(&ProjectCreateRequest{Name: testProjectPrefix + randString8()})
if err != nil {
t.Fatal(err)
}
return c, p.ID, func() {
_, err := c.Projects.Delete(p.ID)
if err != nil {
panic(fmt.Errorf("while deleting %s: %s", p, err))
}
stopRecord()
}
}
func skipUnlessAcceptanceTestsAllowed(t *testing.T) {
if os.Getenv(packngoAccTestVar) == "" {
t.Skipf("%s is not set", packngoAccTestVar)
}
}
// testRecorder creates the named recorder
func testRecorder(t *testing.T, name string, mode recorder.Mode) (*recorder.Recorder, func()) {
r, err := recorder.NewAsMode(path.Join("fixtures", name), mode, nil)
if err != nil {
t.Fatal(err)
}
r.AddFilter(func(i *cassette.Interaction) error {
delete(i.Request.Headers, "X-Auth-Token")
return nil
})
return r, func() {
if err := r.Stop(); err != nil {
t.Fatal(err)
}
}
}
func testRecordMode() (recorder.Mode, error) {
modeRaw := os.Getenv(testRecorderEnv)
mode := recorderDefaultMode
switch strings.ToLower(modeRaw) {
case testRecorderRecord:
mode = recorder.ModeRecording
case testRecorderPlay:
mode = recorder.ModeReplaying
case "":
// no-op
case testRecorderDisabled:
// no-op
default:
return mode, fmt.Errorf("invalid %s mode: %s", testRecorderEnv, modeRaw)
}
return mode, nil
}
func setup(t *testing.T) (*Client, func()) {
name := t.Name()
apiToken := os.Getenv(authTokenEnvVar)
if apiToken == "" {
t.Fatalf("If you want to run packngo test, you must export %s.", authTokenEnvVar)
}
mode, err := testRecordMode()
if err != nil {
t.Fatal(err)
}
apiURL := os.Getenv(apiURLEnvVar)
if apiURL == "" {
apiURL = baseURL
}
r, stopRecord := testRecorder(t, name, mode)
httpClient := http.DefaultClient
httpClient.Transport = r
c, err := NewClientWithBaseURL("packngo test", apiToken, httpClient, apiURL)
if err != nil {
t.Fatal(err)
}
return c, stopRecord
}
func projectTeardown(c *Client) {
ps, _, err := c.Projects.List(nil)
if err != nil {
panic(fmt.Errorf("while teardown: %s", err))
}
for _, p := range ps {
if strings.HasPrefix(p.Name, testProjectPrefix) {
_, err := c.Projects.Delete(p.ID)
if err != nil {
panic(fmt.Errorf("while deleting %s: %s", p, err))
}
}
}
}
func organizationTeardown(c *Client) {
ps, _, err := c.Organizations.List(nil)
if err != nil {
panic(fmt.Errorf("while teardown: %s", err))
}
for _, p := range ps {
if strings.HasPrefix(p.Name, testProjectPrefix) {
_, err := c.Organizations.Delete(p.ID)
if err != nil {
panic(fmt.Errorf("while deleting %s: %s", p, err))
}
}
}
}
func TestAccInvalidCredentials(t *testing.T) {
skipUnlessAcceptanceTestsAllowed(t)
c := NewClientWithAuth("packngo test", "wrongApiToken", nil)
_, r, expectedErr := c.Projects.List(nil)
matched, err := regexp.MatchString(".*Invalid.*", expectedErr.Error())
if err != nil {
t.Fatalf("Err while matching err string from response err %s: %s", expectedErr, err)
}
if r.StatusCode != 401 {
t.Fatalf("Expected 401 as response code, got: %d", r.StatusCode)
}
if !matched {
t.Fatalf("Unexpected error string: %s", expectedErr)
}
}
func Test_dumpDeprecation(t *testing.T) {
type args struct {
resp *http.Response
}
tests := []struct {
name string
args args
logged string
}{
{
name: "Deprecation",
args: args{
resp: &http.Response{
Header: http.Header{
"Deprecation": {
"Sat, 1 Aug 2020 23:59:59 GMT",
},
"Link": {
"<https://api.example.com/deprecation>; rel=\"deprecation\"; type=\"text/html\"",
},
},
Request: &http.Request{
Method: "POST",
URL: &url.URL{Path: "/deprecated"},
},
},
},
logged: "WARNING: \"POST /deprecated\" reported deprecation on Sat, 1 Aug 2020 23:59:59 GMT\nWARNING: See <https://api.example.com/deprecation> for deprecation details",
},
{
name: "Sunset",
args: args{
resp: &http.Response{
Header: http.Header{
"Sunset": {
"Sat, 1 Aug 2020 23:59:59 GMT",
},
"Link": {
"<https://api.example.com/sunset>; rel=\"sunset\"; type=\"text/html\"",
},
},
Request: &http.Request{
Method: "GET",
URL: &url.URL{Path: "/sunset"},
},
},
},
logged: "WARNING: \"GET /sunset\" reported sunsetting on Sat, 1 Aug 2020 23:59:59 GMT\nWARNING: See <https://api.example.com/sunset> for sunset details",
},
{
name: "DeprecateAndSunset",
args: args{
resp: &http.Response{
Header: http.Header{
"Sunset": {
"Sat, 1 Aug 2020 23:59:59 GMT",
},
"Deprecation": {
"true",
},
// comma separated header value and repeated header
"Link": {
"<https://api.example.com/deprecation/field-a>; rel=\"deprecation\"; type=\"text/html\"",
"<https://api.example.com/sunset/value-a>; rel=\"sunset\"; type=\"text/html\"",
"<https://api.example.com/sunset>; rel=\"sunset\"; type=\"text/html\",<https://api.example.com/deprecation>; rel=\"deprecation\"; type=\"text/html\"",
},
},
Request: func() *http.Request {
body := bytes.NewReader([]byte("{\"sunset\":true,\"deprecated\":true}"))
r, _ := http.NewRequest(
http.MethodPost,
"/deprecate-and-sunset", body)
return r
}(),
},
},
// only the comma separate header is returned by Header.Get()
logged: "WARNING: \"POST /deprecate-and-sunset\" reported deprecation\nWARNING: \"POST /deprecate-and-sunset\" reported sunsetting on Sat, 1 Aug 2020 23:59:59 GMT\nWARNING: See <https://api.example.com/deprecation/field-a> for deprecation details\nWARNING: See <https://api.example.com/sunset/value-a> for sunset details\nWARNING: See <https://api.example.com/sunset> for sunset details\nWARNING: See <https://api.example.com/deprecation> for deprecation details",
},
{
name: "None",
args: args{
resp: &http.Response{
Header: http.Header{},
},
},
logged: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
logged := &bytes.Buffer{}
log.SetOutput(logged)
f := log.Flags()
log.SetFlags(0)
defer func() {
log.SetOutput(os.Stderr)
log.SetFlags(f)
}()
dumpDeprecation(tt.args.resp)
got := strings.TrimSpace(logged.String())
if got != tt.logged {
t.Logf("%s failed; got %q, want %q", t.Name(), got, tt.logged)
t.Fail()
}
})
}
}