forked from mholt/archiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zip_test.go
89 lines (74 loc) · 2.08 KB
/
zip_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
package archiver
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestZipAndUnzip(t *testing.T) {
symmetricTest(t, ".zip", Zip, Unzip)
}
func symmetricTest(t *testing.T, ext string, cf CompressFunc, dcf DecompressFunc) {
tmp, err := ioutil.TempDir("", "archiver")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
// Test creating archive
outfile := filepath.Join(tmp, "test"+ext)
err = cf(outfile, []string{"testdata"})
if err != nil {
t.Fatalf("making archive: didn't expect an error, but got: %v", err)
}
var expectedFileCount int
filepath.Walk("testdata", func(fpath string, info os.FileInfo, err error) error {
expectedFileCount++
return nil
})
// Test extracting archive
dest := filepath.Join(tmp, "extraction_test")
os.Mkdir(dest, 0755)
err = dcf(outfile, dest)
if err != nil {
t.Fatalf("extracting archive: didn't expect an error, but got: %v", err)
}
// If outputs equals inputs, we're good; traverse output files
// and compare file names, file contents, and file count.
var actualFileCount int
filepath.Walk(dest, func(fpath string, info os.FileInfo, err error) error {
if fpath == dest {
return nil
}
actualFileCount++
origPath, err := filepath.Rel(dest, fpath)
if err != nil {
t.Fatalf("%s: Error inducing original file path: %v", fpath, err)
}
if info.IsDir() {
// stat dir instead of read file
_, err := os.Stat(origPath)
if err != nil {
t.Fatalf("%s: Couldn't stat original directory (%s): %v",
fpath, origPath, err)
}
return nil
}
expected, err := ioutil.ReadFile(origPath)
if err != nil {
t.Fatalf("%s: Couldn't open original file (%s) from disk: %v",
fpath, origPath, err)
}
actual, err := ioutil.ReadFile(fpath)
if err != nil {
t.Fatalf("%s: Couldn't open new file from disk: %v", fpath, err)
}
if !bytes.Equal(expected, actual) {
t.Fatalf("%s: File contents differed between on disk and compressed", origPath)
}
return nil
})
if got, want := actualFileCount, expectedFileCount; got != want {
t.Fatalf("Expected %d resulting files, got %d", want, got)
}
}