forked from rclone/rclone
-
Notifications
You must be signed in to change notification settings - Fork 3
/
run.go
344 lines (304 loc) · 8.96 KB
/
run.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
/*
This provides Run for use in creating test suites
To use this declare a TestMain
// TestMain drives the tests
func TestMain(m *testing.M) {
fstest.TestMain(m)
}
And then make and destroy a Run in each test
func TestMkdir(t *testing.T) {
r := fstest.NewRun(t)
defer r.Finalise()
// test stuff
}
This will make r.Fremote and r.Flocal for a remote remote and a local
remote. The remote is determined by the -remote flag passed in.
*/
package fstest
import (
"bytes"
"context"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"sort"
"testing"
"time"
"github.com/artpar/rclone/fs"
"github.com/artpar/rclone/fs/cache"
"github.com/artpar/rclone/fs/fserrors"
"github.com/artpar/rclone/fs/hash"
"github.com/artpar/rclone/fs/object"
"github.com/artpar/rclone/fs/walk"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Run holds the remotes for a test run
type Run struct {
LocalName string
Flocal fs.Fs
Fremote fs.Fs
FremoteName string
cleanRemote func()
mkdir map[string]bool // whether the remote has been made yet for the fs name
Logf, Fatalf func(text string, args ...interface{})
}
// TestMain drives the tests
func TestMain(m *testing.M) {
flag.Parse()
if !*Individual {
oneRun = newRun()
}
rc := m.Run()
if !*Individual {
oneRun.Finalise()
}
os.Exit(rc)
}
// oneRun holds the master run data if individual is not set
var oneRun *Run
// newRun initialise the remote and local for testing and returns a
// run object.
//
// r.Flocal is an empty local Fs
// r.Fremote is an empty remote Fs
//
// Finalise() will tidy them away when done.
func newRun() *Run {
r := &Run{
Logf: log.Printf,
Fatalf: log.Printf,
mkdir: make(map[string]bool),
}
Initialise()
var err error
r.Fremote, r.FremoteName, r.cleanRemote, err = RandomRemote()
if err != nil {
r.Fatalf("Failed to open remote %q: %v", *RemoteName, err)
}
r.LocalName, err = ioutil.TempDir("", "rclone")
if err != nil {
r.Fatalf("Failed to create temp dir: %v", err)
}
r.LocalName = filepath.ToSlash(r.LocalName)
r.Flocal, err = fs.NewFs(context.Background(), r.LocalName)
if err != nil {
r.Fatalf("Failed to make %q: %v", r.LocalName, err)
}
return r
}
// run f(), retrying it until it returns with no error or the limit
// expires and it calls t.Fatalf
func retry(t *testing.T, what string, f func() error) {
var err error
for try := 1; try <= *ListRetries; try++ {
err = f()
if err == nil {
return
}
t.Logf("%s failed - try %d/%d: %v", what, try, *ListRetries, err)
time.Sleep(time.Second)
}
t.Logf("%s failed: %v", what, err)
}
// newRunIndividual initialise the remote and local for testing and
// returns a run object. Pass in true to make individual tests or
// false to use the global one.
//
// r.Flocal is an empty local Fs
// r.Fremote is an empty remote Fs
//
// Finalise() will tidy them away when done.
func newRunIndividual(t *testing.T, individual bool) *Run {
ctx := context.Background()
var r *Run
if individual {
r = newRun()
} else {
// If not individual, use the global one with the clean method overridden
r = new(Run)
*r = *oneRun
r.cleanRemote = func() {
var toDelete []string
err := walk.ListR(ctx, r.Fremote, "", true, -1, walk.ListAll, func(entries fs.DirEntries) error {
for _, entry := range entries {
switch x := entry.(type) {
case fs.Object:
retry(t, fmt.Sprintf("removing file %q", x.Remote()), func() error { return x.Remove(ctx) })
case fs.Directory:
toDelete = append(toDelete, x.Remote())
}
}
return nil
})
if err == fs.ErrorDirNotFound {
return
}
require.NoError(t, err)
sort.Strings(toDelete)
for i := len(toDelete) - 1; i >= 0; i-- {
dir := toDelete[i]
retry(t, fmt.Sprintf("removing dir %q", dir), func() error {
return r.Fremote.Rmdir(ctx, dir)
})
}
// Check remote is empty
CheckListingWithPrecision(t, r.Fremote, []Item{}, []string{}, r.Fremote.Precision())
// Clear the remote cache
cache.Clear()
}
}
r.Logf = t.Logf
r.Fatalf = t.Fatalf
r.Logf("Remote %q, Local %q, Modify Window %q", r.Fremote, r.Flocal, fs.GetModifyWindow(ctx, r.Fremote))
return r
}
// NewRun initialise the remote and local for testing and returns a
// run object. Call this from the tests.
//
// r.Flocal is an empty local Fs
// r.Fremote is an empty remote Fs
//
// Finalise() will tidy them away when done.
func NewRun(t *testing.T) *Run {
return newRunIndividual(t, *Individual)
}
// NewRunIndividual as per NewRun but makes an individual remote for this test
func NewRunIndividual(t *testing.T) *Run {
return newRunIndividual(t, true)
}
// RenameFile renames a file in local
func (r *Run) RenameFile(item Item, newpath string) Item {
oldFilepath := path.Join(r.LocalName, item.Path)
newFilepath := path.Join(r.LocalName, newpath)
if err := os.Rename(oldFilepath, newFilepath); err != nil {
r.Fatalf("Failed to rename file from %q to %q: %v", item.Path, newpath, err)
}
item.Path = newpath
return item
}
// WriteFile writes a file to local
func (r *Run) WriteFile(filePath, content string, t time.Time) Item {
item := NewItem(filePath, content, t)
// FIXME make directories?
filePath = path.Join(r.LocalName, filePath)
dirPath := path.Dir(filePath)
err := os.MkdirAll(dirPath, 0770)
if err != nil {
r.Fatalf("Failed to make directories %q: %v", dirPath, err)
}
err = ioutil.WriteFile(filePath, []byte(content), 0600)
if err != nil {
r.Fatalf("Failed to write file %q: %v", filePath, err)
}
err = os.Chtimes(filePath, t, t)
if err != nil {
r.Fatalf("Failed to chtimes file %q: %v", filePath, err)
}
return item
}
// ForceMkdir creates the remote
func (r *Run) ForceMkdir(ctx context.Context, f fs.Fs) {
err := f.Mkdir(ctx, "")
if err != nil {
r.Fatalf("Failed to mkdir %q: %v", f, err)
}
r.mkdir[f.String()] = true
}
// Mkdir creates the remote if it hasn't been created already
func (r *Run) Mkdir(ctx context.Context, f fs.Fs) {
if !r.mkdir[f.String()] {
r.ForceMkdir(ctx, f)
}
}
// WriteObjectTo writes an object to the fs, remote passed in
func (r *Run) WriteObjectTo(ctx context.Context, f fs.Fs, remote, content string, modTime time.Time, useUnchecked bool) Item {
put := f.Put
if useUnchecked {
put = f.Features().PutUnchecked
if put == nil {
r.Fatalf("Fs doesn't support PutUnchecked")
}
}
r.Mkdir(ctx, f)
// calculate all hashes f supports for content
hash, err := hash.NewMultiHasherTypes(f.Hashes())
if err != nil {
r.Fatalf("Failed to make new multi hasher: %v", err)
}
_, err = hash.Write([]byte(content))
if err != nil {
r.Fatalf("Failed to make write to hash: %v", err)
}
hashSums := hash.Sums()
const maxTries = 10
for tries := 1; ; tries++ {
in := bytes.NewBufferString(content)
objinfo := object.NewStaticObjectInfo(remote, modTime, int64(len(content)), true, hashSums, nil)
_, err := put(ctx, in, objinfo)
if err == nil {
break
}
// Retry if err returned a retry error
if fserrors.IsRetryError(err) && tries < maxTries {
r.Logf("Retry Put of %q to %v: %d/%d (%v)", remote, f, tries, maxTries, err)
time.Sleep(2 * time.Second)
continue
}
r.Fatalf("Failed to put %q to %q: %v", remote, f, err)
}
return NewItem(remote, content, modTime)
}
// WriteObject writes an object to the remote
func (r *Run) WriteObject(ctx context.Context, remote, content string, modTime time.Time) Item {
return r.WriteObjectTo(ctx, r.Fremote, remote, content, modTime, false)
}
// WriteUncheckedObject writes an object to the remote not checking for duplicates
func (r *Run) WriteUncheckedObject(ctx context.Context, remote, content string, modTime time.Time) Item {
return r.WriteObjectTo(ctx, r.Fremote, remote, content, modTime, true)
}
// WriteBoth calls WriteObject and WriteFile with the same arguments
func (r *Run) WriteBoth(ctx context.Context, remote, content string, modTime time.Time) Item {
r.WriteFile(remote, content, modTime)
return r.WriteObject(ctx, remote, content, modTime)
}
// CheckWithDuplicates does a test but allows duplicates
func (r *Run) CheckWithDuplicates(t *testing.T, items ...Item) {
var want, got []string
// construct a []string of desired items
for _, item := range items {
want = append(want, fmt.Sprintf("%q %d", item.Path, item.Size))
}
sort.Strings(want)
// do the listing
objs, _, err := walk.GetAll(context.Background(), r.Fremote, "", true, -1)
if err != nil && err != fs.ErrorDirNotFound {
t.Fatalf("Error listing: %v", err)
}
// construct a []string of actual items
for _, o := range objs {
got = append(got, fmt.Sprintf("%q %d", o.Remote(), o.Size()))
}
sort.Strings(got)
assert.Equal(t, want, got)
}
// Clean the temporary directory
func (r *Run) cleanTempDir() {
err := os.RemoveAll(r.LocalName)
if err != nil {
r.Logf("Failed to clean temporary directory %q: %v", r.LocalName, err)
}
}
// Finalise cleans the remote and local
func (r *Run) Finalise() {
// r.Logf("Cleaning remote %q", r.Fremote)
r.cleanRemote()
// r.Logf("Cleaning local %q", r.LocalName)
r.cleanTempDir()
// Clear the remote cache
cache.Clear()
}