generated from ipfs/ipfs-repository-template
/
filewriter_test.go
100 lines (90 loc) · 2.5 KB
/
filewriter_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
package files
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWriteTo(t *testing.T) {
sf := NewMapDirectory(map[string]Node{
"1": NewBytesFile([]byte("Some text!\n")),
"2": NewBytesFile([]byte("beep")),
"3": NewMapDirectory(nil),
"4": NewBytesFile([]byte("boop")),
"5": NewMapDirectory(map[string]Node{
"a": NewBytesFile([]byte("foobar")),
}),
})
tmppath, err := os.MkdirTemp("", "files-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmppath)
path := filepath.Join(tmppath, "output")
err = WriteTo(sf, path)
if err != nil {
t.Fatal(err)
}
expected := map[string]string{
".": "",
"1": "Some text!\n",
"2": "beep",
"3": "",
"4": "boop",
"5": "",
filepath.FromSlash("5/a"): "foobar",
}
err = filepath.Walk(path, func(cpath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rpath, err := filepath.Rel(path, cpath)
if err != nil {
return err
}
data, ok := expected[rpath]
if !ok {
return fmt.Errorf("expected something at %q", rpath)
}
delete(expected, rpath)
if info.IsDir() {
if data != "" {
return fmt.Errorf("expected a directory at %q", rpath)
}
} else {
actual, err := os.ReadFile(cpath)
if err != nil {
return err
}
if string(actual) != data {
return fmt.Errorf("expected %q, got %q", data, string(actual))
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
if len(expected) > 0 {
t.Fatalf("failed to find: %#v", expected)
}
}
func TestDontAllowOverwrite(t *testing.T) {
tmppath, err := os.MkdirTemp("", "files-test")
assert.NoError(t, err)
defer os.RemoveAll(tmppath)
path := filepath.Join(tmppath, "output")
// Check we can actually write to the output path before trying invalid entries
// and leave an existing entry to test overwrite protection.
assert.NoError(t, WriteTo(NewMapDirectory(map[string]Node{
"exisiting-entry": NewBytesFile(nil),
}), path))
assert.Equal(t, ErrPathExistsOverwrite, WriteTo(NewBytesFile(nil), filepath.Join(path)))
assert.Equal(t, ErrPathExistsOverwrite, WriteTo(NewBytesFile(nil), filepath.Join(path, "exisiting-entry")))
// The directory in `path` has already been created so this should fail too:
assert.Equal(t, ErrPathExistsOverwrite, WriteTo(NewMapDirectory(map[string]Node{
"any-name": NewBytesFile(nil),
}), filepath.Join(path)))
os.RemoveAll(path)
}