90 lines
2.2 KiB
Go
90 lines
2.2 KiB
Go
|
|
package hashx
|
||
|
|
|
||
|
|
import (
|
||
|
|
"crypto/md5"
|
||
|
|
"encoding/hex"
|
||
|
|
"os"
|
||
|
|
"path/filepath"
|
||
|
|
"testing"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestSha1StrMatchesSha1(t *testing.T) {
|
||
|
|
got := Sha1Str([]byte("abc"))
|
||
|
|
const want = "a9993e364706816aba3e25717850c26c9cd0d89d"
|
||
|
|
if got != want {
|
||
|
|
t.Fatalf("Sha1Str mismatch, got %s want %s", got, want)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestSM3AndCRC32A(t *testing.T) {
|
||
|
|
if len(SM3([]byte("abc"))) != 32 {
|
||
|
|
t.Fatalf("SM3 digest size must be 32")
|
||
|
|
}
|
||
|
|
if Crc32AStr([]byte("123456789")) != "181989fc" {
|
||
|
|
t.Fatalf("Crc32AStr mismatch")
|
||
|
|
}
|
||
|
|
if CheckCRC32A([]byte("123456789")) != 0x181989fc {
|
||
|
|
t.Fatalf("CheckCRC32A mismatch")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestSumAllUnknownMethodIgnored(t *testing.T) {
|
||
|
|
res, err := SumAll([]byte("abc"), []string{"sha1", "unknown"})
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("SumAll returned error: %v", err)
|
||
|
|
}
|
||
|
|
if _, ok := res["sha1"]; !ok {
|
||
|
|
t.Fatalf("expected sha1 in result")
|
||
|
|
}
|
||
|
|
if _, ok := res["unknown"]; ok {
|
||
|
|
t.Fatalf("unknown method should be ignored")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestFileSumAndFileSumAll(t *testing.T) {
|
||
|
|
dir := t.TempDir()
|
||
|
|
path := filepath.Join(dir, "sum.txt")
|
||
|
|
data := []byte("hash-file-content")
|
||
|
|
if err := os.WriteFile(path, data, 0o644); err != nil {
|
||
|
|
t.Fatalf("WriteFile failed: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
calls := 0
|
||
|
|
h, err := FileSum(path, "md5", func(float64) { calls++ })
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("FileSum failed: %v", err)
|
||
|
|
}
|
||
|
|
expected := md5.Sum(data)
|
||
|
|
if h != hex.EncodeToString(expected[:]) {
|
||
|
|
t.Fatalf("md5 mismatch, got %s want %s", h, hex.EncodeToString(expected[:]))
|
||
|
|
}
|
||
|
|
if calls == 0 {
|
||
|
|
t.Fatalf("progress callback should be called")
|
||
|
|
}
|
||
|
|
|
||
|
|
all, err := FileSumAll(path, []string{"sha1", "crc32", "unknown"}, nil)
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("FileSumAll failed: %v", err)
|
||
|
|
}
|
||
|
|
if _, ok := all["sha1"]; !ok {
|
||
|
|
t.Fatalf("expected sha1 in FileSumAll")
|
||
|
|
}
|
||
|
|
if _, ok := all["crc32"]; !ok {
|
||
|
|
t.Fatalf("expected crc32 in FileSumAll")
|
||
|
|
}
|
||
|
|
if _, ok := all["unknown"]; ok {
|
||
|
|
t.Fatalf("unknown method should not appear")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestFileSumUnsupportedMethod(t *testing.T) {
|
||
|
|
dir := t.TempDir()
|
||
|
|
path := filepath.Join(dir, "sum.txt")
|
||
|
|
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
|
||
|
|
t.Fatalf("WriteFile failed: %v", err)
|
||
|
|
}
|
||
|
|
if _, err := FileSum(path, "not-support", nil); err == nil {
|
||
|
|
t.Fatalf("expected unsupported method error")
|
||
|
|
}
|
||
|
|
}
|