-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhash_test.go
112 lines (97 loc) · 2.6 KB
/
hash_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
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"testing"
"github.com/zeebo/xxh3"
)
func TestCreateFileHash(t *testing.T) {
tempDir := t.TempDir()
emptyFilePath := filepath.Join(tempDir, "empty.txt")
emptyFile, err := os.Create(emptyFilePath)
if err != nil {
t.Fatalf("Failed to create empty test file: %v", err)
}
defer emptyFile.Close()
contentFilePath := filepath.Join(tempDir, "content.txt")
contentFile, err := os.Create(contentFilePath)
if err != nil {
t.Fatalf("Failed to create content test file: %v", err)
}
content := "Hello, world!"
if _, err := contentFile.WriteString(content); err != nil {
t.Fatalf("Failed to write to test file: %v", err)
}
defer contentFile.Close()
hasher := xxh3.New()
n, err := io.WriteString(hasher, content)
if err != nil {
t.Error(err)
}
if n != len(content) {
t.Errorf("not all bytes are written, expected to write %d bytes, written: %d", len(content), n)
}
hash := hasher.Sum128()
expectedContentHash := fmt.Sprintf("%016x%016x", hash.Hi, hash.Lo)
emptyHash := xxh3.New()
if err != nil {
t.Fatalf("Failed to create XXH3 hash for empty file: %v", err)
}
hash = emptyHash.Sum128()
expectedEmptyHash := fmt.Sprintf("%016x%016x", hash.Hi, hash.Lo)
tests := []struct {
name string
filePath string
expectedHash string
expectedErrMsg string
}{
{
name: "Empty file",
filePath: emptyFilePath,
expectedHash: expectedEmptyHash,
expectedErrMsg: "",
},
{
name: "File with content",
filePath: contentFilePath,
expectedHash: expectedContentHash,
expectedErrMsg: "",
},
{
name: "Non-existent file",
filePath: filepath.Join(tempDir, "nonexistent.txt"),
expectedHash: "",
expectedErrMsg: "failed to open file",
},
{
name: "Directory instead of file",
filePath: tempDir,
expectedHash: "",
expectedErrMsg: "hashing failed",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
hash, err := createFileHash(tc.filePath)
if tc.expectedErrMsg != "" {
if err == nil {
t.Errorf("Expected error containing %q, got nil", tc.expectedErrMsg)
} else if msg := err.Error(); !contains(msg, tc.expectedErrMsg) {
t.Errorf("Expected error containing %q, got %q", tc.expectedErrMsg, msg)
}
return
}
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if hash != tc.expectedHash {
t.Errorf("Expected hash %q, got %q", tc.expectedHash, hash)
}
})
}
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && s[:len(substr)] == substr
}