forked from WasabiAiR/stow
-
Notifications
You must be signed in to change notification settings - Fork 10
/
test.go
522 lines (443 loc) · 13.3 KB
/
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package test
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"os/exec"
"reflect"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/cheekybits/is"
"github.com/flyteorg/stow"
)
// All runs a generic suite of tests for Stow storage
// implementations.
// Passing the kind name and a configuration is enough,
// because implementations should have registered themselves
// via stow.Register.
// Locations should be empty.
func All(t *testing.T, kind string, config stow.Config) {
is, location := initTest(t, kind, config)
isWindows := false
if runtime.GOOS == "windows" {
isWindows = true
}
// testing for file descriptors won't work on Windows
var startFDs int
var fdsStart []byte
if !isWindows {
startFDs, fdsStart = totalNetFDs(t)
}
defer func() {
err := location.Close()
is.NoErr(err)
if !isWindows {
// Close Idle HTTP connectors before counting TCP File Descriptors
if tr, ok := http.DefaultTransport.(interface {
CloseIdleConnections()
}); ok {
tr.CloseIdleConnections()
}
endFDs, fds := totalNetFDs(t)
diffFDs := endFDs - startFDs
if diffFDs > 0 {
t.Log("File Descriptors test start")
t.Log(string(fdsStart))
t.Log("File Descriptors test end")
t.Log(string(fds))
t.Fatalf("Leaked %d TCP file descriptor", diffFDs)
}
}
}()
// create three containers
c1Name := "stowtest" + randName(10)
c1 := createContainer(is, location, c1Name)
c2 := createContainer(is, location, "stowtest"+randName(10))
c3 := createContainer(is, location, "stowtest"+randName(10))
is.NotEqual(c1.ID(), c2.ID())
defer func() {
err := location.RemoveContainer(c1.ID())
is.NoErr(err)
err = location.RemoveContainer(c2.ID())
is.NoErr(err)
err = location.RemoveContainer(c3.ID())
is.NoErr(err)
}()
// Item metadata. Keys are usually transposed differently depending on the sdk.
md1 := map[string]interface{}{"stowmetadata": "foo"}
// add three items to c1 + add metadata to one item, assert if the implementation allows.
// Tests metadata retrieval on PUTs.
item1Content := "item one"
item1Name := "a_first/the item"
item1, skip1 := putItem(is, c1, item1Name, item1Content, md1)
is.OK(item1)
if !skip1 {
is.NoErr(checkMetadata(t, is, item1, md1))
}
item2, _ := putItem(is, c1, "a_second/the item", "item two", nil)
is.OK(item2)
item3, _ := putItem(is, c1, "the_third/the item", "item three", nil)
is.OK(item3)
defer func() {
err := c1.RemoveItem(item1.ID())
is.NoErr(err)
err = c1.RemoveItem(item2.ID())
is.NoErr(err)
err = c1.RemoveItem(item3.ID())
is.NoErr(err)
}()
// make sure we can get a small set of paginated results
items, cursor, err := c1.Items(stow.NoPrefix, stow.CursorStart, 1)
is.NoErr(err)
is.Equal(len(items), 1)
is.NotEqual(cursor, "")
// get the items with a prefix (should only get 2)
items, _, err = c1.Items("a_", stow.CursorStart, 100)
is.NoErr(err)
is.Equal(len(items), 2)
// make sure we get these three items from the container
items, _, err = c1.Items(stow.NoPrefix, stow.CursorStart, 100)
is.NoErr(err)
is.Equal(len(items), 3)
// Test metadata retrieval on Items() method
if !skip1 {
is.NoErr(checkMetadata(t, is, items[0], md1))
}
// make sure the items are identical
is.OK(item1.ID())
is.OK(item1.Name())
is.Equal(items[0].ID(), item1.ID())
is.Equal(items[0].Name(), item1.Name())
is.Equal(size(is, items[0]), 8)
is.Equal(readItemContents(is, item1), "item one")
is.NoErr(acceptableTime(t, is, items[0], item1))
if ir, ok := item1.(stow.ItemRanger); ok {
rc, err := ir.OpenRange(0, 3)
is.NoErr(err)
defer rc.Close()
b, err := ioutil.ReadAll(rc)
is.NoErr(err)
is.Equal(b, []byte("item"))
}
is.OK(item2.ID())
is.OK(item2.Name())
is.Equal(items[1].ID(), item2.ID())
is.Equal(items[1].Name(), item2.Name())
is.Equal(size(is, items[1]), 8)
is.Equal(readItemContents(is, item2), "item two")
is.NoErr(acceptableTime(t, is, items[1], item2))
is.OK(item3.ID())
is.OK(item3.Name())
is.Equal(items[2].ID(), item3.ID())
is.Equal(items[2].Name(), item3.Name())
is.Equal(size(is, items[2]), 10)
is.Equal(readItemContents(is, item3), "item three")
is.NoErr(acceptableTime(t, is, items[2], item3))
// check ETags from items retrieved by the Items() method
is.OK(etag(t, is, items[0]))
is.OK(etag(t, is, items[1]))
is.OK(etag(t, is, items[2]))
// get container by ID
c1copy, err := location.Container(c1.ID())
is.NoErr(err)
is.OK(c1copy)
is.Equal(c1copy.ID(), c1.ID())
// get container by name
c1copy2, err := location.Container(c1Name)
is.NoErr(err)
is.OK(c1copy2)
is.Equal(c1copy2.ID(), c1.ID())
// get container that doesn't exist
noContainer, err := location.Container(c1.ID() + "nope")
is.Equal(stow.ErrNotFound, err)
is.Nil(noContainer)
// get item by ID
item1copy, err := c1copy.Item(item1.ID())
is.NoErr(err)
is.OK(item1copy)
is.Equal(item1copy.ID(), item1.ID())
is.Equal(item1copy.Name(), item1.Name())
is.Equal(size(is, item1copy), size(is, item1))
is.Equal(readItemContents(is, item1copy), item1Content)
is.OK(etag(t, is, item1copy))
if !skip1 {
is.NoErr(checkMetadata(t, is, item1copy, md1))
}
// get an item by ID that doesn't exist
noItem, err := c1copy.Item(item1.ID() + "nope")
is.Equal(stow.ErrNotFound, err)
is.Nil(noItem)
// get items by URL
u1 := item1.URL()
item1b, err := location.ItemByURL(u1)
is.NoErr(err)
is.OK(item1b)
is.Equal(item1b.ID(), item1.ID())
is.Equal(etag(t, is, item1b), etag(t, is, item1copy))
// get item by name
item1copy2, err := c1copy2.Item(item1Name)
is.NoErr(err)
is.OK(item1copy2)
is.Equal(item1copy2.ID(), item1.ID())
is.Equal(item1copy2.Name(), item1.Name())
is.Equal(size(is, item1copy2), len(item1Content))
is.Equal(readItemContents(is, item1copy2), item1Content)
is.OK(etag(t, is, item1copy2))
if !skip1 {
is.NoErr(checkMetadata(t, is, item1copy2, md1))
}
// **************************************************
// Walking
// **************************************************
// test walking
var walkedItems []stow.Item
err = stow.Walk(c1, stow.NoPrefix, 100, func(item stow.Item, err error) error {
if err != nil {
return err
}
walkedItems = append(walkedItems, item)
return nil
})
is.NoErr(err)
is.Equal(len(walkedItems), 3)
is.Equal(readItemContents(is, walkedItems[0]), "item one")
is.Equal(readItemContents(is, walkedItems[1]), "item two")
is.Equal(readItemContents(is, walkedItems[2]), "item three")
// test walking with a prefix
walkedItems = make([]stow.Item, 0)
err = stow.Walk(c1, "a_", 100, func(item stow.Item, err error) error {
if err != nil {
return err
}
walkedItems = append(walkedItems, item)
return nil
})
is.NoErr(err)
is.Equal(len(walkedItems), 2)
is.Equal(readItemContents(is, walkedItems[0]), "item one")
is.Equal(readItemContents(is, walkedItems[1]), "item two")
// test walking error
testErr := errors.New("test error")
err = stow.Walk(c1, stow.NoPrefix, 100, func(item stow.Item, err error) error {
return testErr
})
is.Equal(testErr, err)
// container walking
found := 0
err = stow.WalkContainers(location, stow.NoPrefix, 100, func(c stow.Container, err error) error {
if err != nil {
return err
}
switch c.Name() {
case c1.Name(), c2.Name(), c3.Name():
found++
}
return nil
})
is.NoErr(err)
is.Equal(found, 3) // should find three items
}
type PresignedRequestPreparer func(method stow.ClientMethod, r *http.Request) error
func ContainerPreSignRequest(
t *testing.T, kind string, config stow.Config, requestPreparer PresignedRequestPreparer,
) {
is, location := initTest(t, kind, config)
testContainer, err := location.CreateContainer("stowtest" + randName(10))
is.NoErr(err)
defer func() {
location.RemoveContainer(testContainer.ID())
}()
u, err := testContainer.PreSignRequest(
context.Background(),
stow.ClientMethodPut,
"presigned-put.txt",
stow.PresignRequestParams{
ExpiresIn: time.Minute * 5,
},
)
is.NoErr(err)
assert.NoError(t, err)
client := &http.Client{}
content := []byte("stowtest")
req, err := http.NewRequest("PUT", u.Url, bytes.NewReader(content))
is.NoErr(err)
req.ContentLength = int64(len(content))
req.Header.Set("Content-Type", "text/plain")
err = requestPreparer(stow.ClientMethodPut, req)
is.NoErr(err)
resp, err := client.Do(req)
is.NoErr(err)
if resp.StatusCode != 201 && resp.StatusCode != 200 {
io.Copy(os.Stdout, resp.Body)
}
is.Equal(201, resp.StatusCode)
u, err = testContainer.PreSignRequest(
context.TODO(),
stow.ClientMethodGet,
"presigned-put.txt",
stow.PresignRequestParams{
ExpiresIn: time.Minute * 5,
},
)
is.NoErr(err)
req, err = http.NewRequest("GET", u.Url, nil)
is.NoErr(err)
err = requestPreparer(stow.ClientMethodGet, req)
is.NoErr(err)
resp, err = client.Do(req)
is.NoErr(err)
is.Equal(200, resp.StatusCode)
respBytes, err := io.ReadAll(resp.Body)
is.NoErr(err)
is.Equal(content, respBytes)
}
func BigFileUpload(t *testing.T, kind string, config stow.Config, fileSize int64) {
is, location := initTest(t, kind, config)
testContainer, err := location.CreateContainer("uploadtest" + randName(10))
is.NoErr(err)
defer func() {
location.RemoveContainer(testContainer.ID())
}()
f, err := os.CreateTemp(".", "temp-file")
is.NoErr(err)
defer func() {
os.Remove(f.Name())
}()
f.Truncate(fileSize)
item, err := testContainer.Put("test-upload-file", f, fileSize, map[string]interface{}{})
is.NoErr(err)
itemSize, err := item.Size()
is.NoErr(err)
is.Equal(fileSize, itemSize)
}
func ExistingContainerDoesNotProduceAnError(t *testing.T, kind string, config stow.Config) {
is, location := initTest(t, kind, config)
testContainer, err := location.CreateContainer("stowtest-" + randName(10))
is.NoErr(err)
defer func() { location.RemoveContainer(testContainer.Name()) }()
dupAttempt, err := location.CreateContainer(testContainer.Name())
is.NoErr(err)
is.Equal(testContainer.Name(), dupAttempt.Name())
}
func initTest(t *testing.T, kind string, config stow.Config) (is.I, stow.Location) {
is := is.New(t)
err := stow.Validate(kind, config)
is.NoErr(err)
location, err := stow.Dial(kind, config)
is.NoErr(err)
is.OK(location)
return is, location
}
func totalNetFDs(t *testing.T) (int, []byte) {
lsof, err := exec.Command("lsof", "-b", "-n", "-p", strconv.Itoa(os.Getpid())).Output()
if err != nil {
if err, ok := err.(*exec.ExitError); ok {
t.Log(string(err.Stderr))
}
t.Errorf("error finding or running lsof: %s", err.Error())
}
return bytes.Count(lsof, []byte("TCP")), lsof
}
func createContainer(is is.I, location stow.Location, name string) stow.Container {
container, err := location.CreateContainer(name)
is.NoErr(err)
is.OK(container)
is.OK(container.ID())
is.Equal(container.Name(), name)
return container
}
func putItem(is is.I, container stow.Container, name, content string, md map[string]interface{}) (stow.Item, bool) {
var skipAssertion bool // skip metadata assertion
item, err := container.Put(name, strings.NewReader(content), int64(len(content)), md)
// Metadata retrieval isn't supported
if stow.IsNotSupported(err) {
item, err = container.Put(name, strings.NewReader(content), int64(len(content)), nil)
skipAssertion = true
}
is.NoErr(err)
is.OK(item)
return item, skipAssertion
}
func readItemContents(is is.I, item stow.Item) string {
r, err := item.Open()
is.NoErr(err)
defer r.Close()
if s, ok := r.(io.Seeker); ok {
_, err = s.Seek(0, io.SeekEnd)
is.NoErr(err)
_, err = s.Seek(0, io.SeekStart)
is.NoErr(err)
}
b, err := ioutil.ReadAll(r)
is.NoErr(err)
return string(b)
}
func etag(t *testing.T, is is.I, item stow.Item) string {
etag, err := item.ETag()
is.NoErr(err)
t.Logf("ETag value: %s", etag)
if strings.HasPrefix(etag, `W/`) {
is.Failf(`Item(%s) Etag value (%s) contains weak string prefix W/`, item.Name(), etag)
} else if strings.HasPrefix(etag, `"`) || strings.HasSuffix(etag, `"`) {
is.Failf("Item(%s) Etag value (%s) contains quotation mark in prefix or suffix", item.Name(), etag)
}
return etag
}
func size(is is.I, item stow.Item) int64 {
size, err := item.Size()
is.NoErr(err)
return size
}
func acceptableTime(t *testing.T, is is.I, item1, item2 stow.Item) error {
item1LastMod, err := item1.LastMod()
is.NoErr(err)
item2LastMod, err := item2.LastMod()
is.NoErr(err)
timeDiff := item2LastMod.Sub(item1LastMod)
threshold := time.Duration(8 * time.Second)
if timeDiff > threshold {
t.Logf("LastModified time for item1: %s", item1LastMod.String())
t.Logf("LastModified time for item2: %s", item2LastMod.String())
t.Logf("Difference: %s", timeDiff.String())
return fmt.Errorf("last modified time exceeds threshold (%v)", threshold.Seconds())
}
return nil
}
func lastMod(is is.I, item stow.Item) time.Time {
lastMod, err := item.LastMod()
is.NoErr(err)
return lastMod
}
var letters = []rune("abcdefghijklmnopqrstuvwxyz")
func init() {
rand.Seed(int64(time.Now().Nanosecond()))
}
func randName(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func checkMetadata(t *testing.T, is is.I, item stow.Item, md map[string]interface{}) error {
itemMD, err := item.Metadata()
if err != nil {
is.Failf("error retrieving item metadata: %v", err)
}
if !reflect.DeepEqual(itemMD, md) {
t.Logf("Item metadata: %v", itemMD)
t.Logf("Expected item metadata: %v", md)
return errors.New("metadata mismatch")
}
return nil
}