-
Notifications
You must be signed in to change notification settings - Fork 16
/
client_test.go
428 lines (333 loc) · 10.4 KB
/
client_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
package ftp4go
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
type connPars struct {
ftpAddress string
ftpPort int
username string
password string
homefolder string
debugFtp bool
}
var allpars = []*connPars{
&connPars{ftpAddress: "ftp.drivehq.com", ftpPort: 21, username: "goftptest", password: "g0ftpt3st", homefolder: "/publicFolder", debugFtp: false},
&connPars{ftpAddress: "ftp.fileserve.com", ftpPort: 21, username: "ftp4go", password: "52fe56bc", homefolder: "/", debugFtp: true},
&connPars{ftpAddress: "www.0catch.com", ftpPort: 21, username: "ftp4go.0catch.com", password: "g0ftpt3st", homefolder: "/", debugFtp: true},
}
var pars = allpars[0]
func NewFtpConn(t *testing.T) (ftpClient *FTP, err error) {
var logl int
if pars.debugFtp {
logl = 1
}
ftpClient = NewFTP(logl) // 1 for debugging
ftpClient.SetPassive(true)
// connect
_, err = ftpClient.Connect(pars.ftpAddress, pars.ftpPort, "")
if err != nil {
t.Fatalf("The FTP connection could not be established, error: %v", err.Error())
}
t.Logf("Connecting with username: %s and password %s", pars.username, pars.password)
_, err = ftpClient.Login(pars.username, pars.password, "")
if err != nil {
t.Fatalf("The user could not be logged in, error: %s", err.Error())
}
return
}
type asciiTestSet struct {
fname string
isascii bool
}
func _TestServerAsciiMode(t *testing.T) {
ftpClient, err := NewFtpConn(t)
defer ftpClient.Quit()
if err != nil {
return
}
_, err = ftpClient.Cwd(pars.homefolder) // home
if err != nil {
t.Fatalf("error: ", err)
}
fstochk := []*asciiTestSet{
&asciiTestSet{"test/test.txt", true},
&asciiTestSet{"test/test.txt", false},
}
var getPrefixedName = func(fn string, textmode bool) string {
f := filepath.Base(fn)
prefix := "remote_binary_"
if textmode {
prefix = "remote_ascii_"
}
return prefix + f
}
for _, entry := range fstochk {
r_filename := getPrefixedName(entry.fname, entry.isascii)
fmt.Printf("Uploading file %s\n", r_filename)
if err = ftpClient.UploadFile(r_filename, entry.fname, entry.isascii, nil); err != nil {
t.Fatalf("error: ", err)
}
t.Logf("Uploaded %s file in ASCII mode.\n", r_filename)
defer ftpClient.Delete(r_filename)
}
check := func(remotename string, localpath string, istext bool) {
s1, s2, tempFilePath := checkintegrityWithPaths(ftpClient, remotename, localpath, istext, false, t)
defer os.Remove(tempFilePath)
t.Logf("\n---Check results\nMode is text: %v.\nDownloaded %s file to local file%s.\n", istext, remotename, tempFilePath)
if s1 != s2 {
t.Logf("The size of real file %s and the downloaded copy %s differ, size local: %d, size remote: %d\n", localpath, remotename, s1, s2)
} else {
t.Logf("The size of real file %s and the downloaded copy %s are the same, size: %d\n", localpath, remotename, s1)
}
if istext && s1 != s2 {
t.Fatalf("The size of the file uploaded in ASCII mode should be the same as the downloaded in ASCII mode.")
}
}
for _, entry := range fstochk {
fn := getPrefixedName(entry.fname, entry.isascii)
check(fn, entry.fname, true)
check(fn, entry.fname, false)
}
}
func TestFeatures(t *testing.T) {
ftpClient, err := NewFtpConn(t)
defer ftpClient.Quit()
if err != nil {
return
}
homefolder := pars.homefolder
fmt.Println("The home folder is:", homefolder)
fts, err := ftpClient.Feat()
if err != nil {
t.Fatalf("error: ", err)
}
fmt.Printf("Supported feats\n")
for _, ft := range fts {
fmt.Printf("%s\n", ft)
}
fmt.Printf("Use UTF8\n")
_, err = ftpClient.Opts("UTF8 ON")
if err != nil {
t.Logf("UTF8 ON error: %v", err)
}
var cwd string
_, err = ftpClient.Cwd(homefolder) // home
if err != nil {
t.Fatalf("error: %v", err)
}
cwd, err = ftpClient.Pwd()
if err != nil {
t.Fatalf("error: ", err)
}
t.Log("The current folder is", cwd)
t.Log("Testings Mlsd")
//ls, err := ftpClient.Mlsd(".", []string{"type", "size"})
ls, err := ftpClient.Mlsd("", nil)
if err != nil {
t.Logf("The ftp command MLSD does not work or is not supported, error: %s", err.Error())
} else {
for _, l := range ls {
//t.Logf("\nMlsd entry: %s, facts: %v", l.Name, l.Facts)
t.Logf("\nMlsd entry and facts: %v", l)
}
}
t.Logf("Testing upload\n")
test_f := "test"
maxSimultaneousConns := 1
t.Log("Cleaning up before testing")
var cleanup = func() error { return cleanupFolderTree(ftpClient, test_f, homefolder, t) }
cleanup()
defer cleanup() // at the end again
var n int
n, err = ftpClient.UploadDirTree(test_f, homefolder, maxSimultaneousConns, nil, nil)
if err != nil {
t.Fatalf("Error uploading folder tree %s, error: %v\n", test_f, err)
}
t.Logf("Uploaded %d files.\n", n)
t.Log("Checking download integrity by downloading the uploaded files and comparing the sizes")
check := func(fi string, istext bool) {
s1, s2 := checkintegrity(ftpClient, fi, istext, t)
if s1 != s2 {
t.Errorf("The size of real file %s and the downloaded copy differ, size local: %d, size remote: %d", fi, s1, s2)
}
}
ftpClient.Cwd(homefolder)
fstochk := map[string]bool{"test/test.txt": true, "test/test.jpg": false}
for s, v := range fstochk {
check(s, v)
}
}
func _TestRecursion(t *testing.T) {
ftpClient, err := NewFtpConn(t)
defer ftpClient.Quit()
if err != nil {
return
}
test_f := "test"
noiterations := 1
maxSimultaneousConns := 1
homefolder := pars.homefolder
t.Log("Cleaning up before testing")
var cleanup = func() error { return cleanupFolderTree(ftpClient, test_f, homefolder, t) }
var check = func(f string) error { return checkFolder(ftpClient, f, homefolder, t) }
defer cleanup() // at the end again
stats, fileUploaded, _ := startStats()
var collector = func(info *CallbackInfo) {
if info.Eof {
stats <- info // pipe in for stats
}
} // do not block the call
var n int
for i := 0; i < noiterations; i++ {
t.Logf("\n -- Uploading folder tree: %s, iteration %d\n", filepath.Base(test_f), i+1)
cleanup()
t.Logf("Sleeping a second\n")
time.Sleep(1e9)
n, err = ftpClient.UploadDirTree(test_f, homefolder, maxSimultaneousConns, nil, collector)
if err != nil {
t.Fatalf("Error uploading folder tree %s, error:\n", test_f, err)
}
t.Logf("Uploaded %d files.\n", n)
// wait for all stats to finish
for k := 0; k < n; k++ {
<-fileUploaded
}
check("test")
check("test/subdir")
}
}
// FTP routine utils
func checkFolder(ftpClient *FTP, f string, homefolder string, t *testing.T) (err error) {
_, err = ftpClient.Cwd(homefolder)
if err != nil {
t.Fatalf("Error in Cwd for folder %s:", homefolder, err.Error())
}
defer ftpClient.Cwd(homefolder) //back to home at the end
t.Logf("Checking subfolder %s", f)
dirs := filepath.SplitList(f)
for _, d := range dirs {
_, err = ftpClient.Cwd(d)
if err != nil {
t.Fatalf("The folder %s was not created.", f)
}
ftpClient.Cwd("..")
}
var filelist []string
if filelist, err = ftpClient.Nlst(); err != nil {
t.Fatalf("No files in folder %s on the ftp server", f)
}
dir, _ := os.Open(f)
files, _ := dir.Readdirnames(-1)
fno := len(files)
t.Logf("No of files in local folder %s is: %d", f, fno)
for _, locF := range files {
t.Logf("Checking local file or folder %s", locF)
fi, err := os.Stat(locF)
if err == nil && !fi.IsDir() {
var found bool
for _, remF := range filelist {
if strings.Contains(strings.ToLower(remF), strings.ToLower(locF)) {
found = true
break
}
}
if !found {
t.Fatalf("The local file %s could not be found at the server", locF)
}
}
}
return
}
func cleanupFolderTree(ftpClient *FTP, test_f string, homefolder string, t *testing.T) (err error) {
_, err = ftpClient.Cwd(homefolder)
if err != nil {
t.Fatalf("Error in Cwd for folder %s:", homefolder, err.Error())
}
defer ftpClient.Cwd(homefolder) //back to home at the end
t.Logf("Removing directory tree %s.", test_f)
if err := ftpClient.RemoveRemoteDirTree(test_f); err != nil {
if err != DIRECTORY_NON_EXISTENT {
t.Fatalf("Error: %v", err)
}
}
return
}
func checkintegrity(ftpClient *FTP, remotename string, istext bool, t *testing.T) (sizeOriginal int64, sizeOnServer int64) {
sizeOriginal, sizeOnServer, _ = checkintegrityWithPaths(ftpClient, remotename, remotename, istext, true, t)
return
}
func checkintegrityWithPaths(ftpClient *FTP, remotename string, localpath string, istext bool, deleteTemporaryFile bool, t *testing.T) (sizeOriginal int64, sizeOnServer int64, tempFilePath string) {
t.Logf("Checking download integrity of remote file %s\n", remotename)
tkns := strings.Split(localpath, "/")
tempFilePath = "ftptest_" + tkns[len(tkns)-1]
fmt.Printf("Downloading file %s to temporary file %s\n", remotename, tempFilePath)
err := ftpClient.DownloadFile(remotename, tempFilePath, istext)
if err != nil {
t.Fatalf("Error downloading file %s, error: %s", remotename, err)
}
// delete if required
if deleteTemporaryFile {
defer os.Remove(tempFilePath)
}
var ofi, oficp *os.File
var e error
if ofi, e = os.Open(localpath); e != nil {
t.Fatalf("Error opening file %s, error: %s", localpath, e)
}
defer ofi.Close()
if oficp, e = os.Open(tempFilePath); e != nil {
t.Fatalf("Error opening file %s, error: %s", oficp, e)
}
defer oficp.Close()
s1, _ := ofi.Stat()
s2, _ := oficp.Stat()
return s1.Size(), s2.Size(), tempFilePath
}
func startStats() (stats chan *CallbackInfo, fileUploaded chan bool, quit chan bool) {
stats = make(chan *CallbackInfo, 100)
quit = make(chan bool)
fileUploaded = make(chan bool, 100)
files := make(map[string][2]int64, 100)
go func() {
for {
select {
case st := <-stats:
// do not wait here, the buffered request channel is the barrier
go func() {
pair, ok := files[st.Resourcename]
var pos, size int64
if !ok {
fi, _ := os.Stat(st.Filename)
files[st.Resourcename] = [2]int64{fi.Size(), pos}
size = fi.Size()
} else {
pos = pair[1] // position correctly for writing
size = pair[0]
}
mo := int((float32(st.BytesTransmitted)/float32(size))*100) / 10
msg := fmt.Sprintf("File: %s - received: %d percent\n", st.Resourcename, mo*10)
if st.Eof {
fmt.Println("Uploaded (reached EOF) file:", st.Resourcename)
fileUploaded <- true // done here
} else {
fmt.Print(msg)
}
/*
if size <= st.BytesTransmitted {
fileUploaded <- true // done here
}
*/
}()
case <-quit:
fmt.Println("Stopping workers")
return // get out
}
}
}()
return
}