forked from moov-io/go-sftp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock_client.go
91 lines (74 loc) · 1.63 KB
/
mock_client.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
// Copyright 2022 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package go_sftp
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
)
type MockClient struct {
root string
Err error
}
func NewMockClient(t *testing.T) *MockClient {
return &MockClient{
root: t.TempDir(),
}
}
func (c *MockClient) Ping() error {
return c.Err
}
func (c *MockClient) Dir() string {
return c.root
}
func (c *MockClient) Close() error {
return c.Err
}
func (c *MockClient) Open(path string) (*File, error) {
if c.Err != nil {
return nil, c.Err
}
file, err := os.Open(filepath.Join(c.root, path))
if err != nil {
return nil, err
}
_, name := filepath.Split(path)
return &File{
Filename: name,
Contents: file,
}, nil
}
func (c *MockClient) Delete(path string) error {
return os.Remove(filepath.Join(c.root, path))
}
func (c *MockClient) UploadFile(path string, contents io.ReadCloser) error {
if c.Err != nil {
return c.Err
}
dir, _ := filepath.Split(path)
if err := os.MkdirAll(filepath.Join(c.root, dir), 0777); err != nil {
return err
}
bs, _ := ioutil.ReadAll(contents)
return ioutil.WriteFile(filepath.Join(c.root, path), bs, 0600)
}
func (c *MockClient) ListFiles(dir string) ([]string, error) {
if c.Err != nil {
return nil, c.Err
}
os.MkdirAll(filepath.Join(c.root, dir), 0777)
fds, err := ioutil.ReadDir(filepath.Join(c.root, dir))
if err != nil {
return nil, err
}
var out []string
for i := range fds {
fd := filepath.Join(dir, strings.TrimPrefix(fds[i].Name(), c.root))
out = append(out, fd)
}
return out, nil
}