61 lines
1.8 KiB
Go
61 lines
1.8 KiB
Go
package httpdl
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestParseChecksum(t *testing.T) {
|
|
// A valid spec parses; the type and digest match case-insensitively.
|
|
good := "SHA-256=" + hex.EncodeToString(make([]byte, 32))
|
|
if _, want, err := parseChecksum(good); err != nil || len(want) != 64 {
|
|
t.Fatalf("parseChecksum(%q) = %q, %v; want a 64-char digest and nil error", good, want, err)
|
|
}
|
|
full := hex.EncodeToString(make([]byte, 32))
|
|
bad := map[string]string{
|
|
"no '='": "sha-256",
|
|
"unknown type": "sha-999=" + full,
|
|
"wrong type name": "sha256=" + full, // the type is spelled sha-256
|
|
"digest not hex": "sha-256=zzzz",
|
|
"wrong length": "sha-256=abcd",
|
|
}
|
|
for name, spec := range bad {
|
|
if _, _, err := parseChecksum(spec); err == nil {
|
|
t.Errorf("%s: parseChecksum(%q) = nil error, want error", name, spec)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestValidChecksum(t *testing.T) {
|
|
good := "sha-256=" + hex.EncodeToString(make([]byte, 32))
|
|
if err := ValidChecksum(good); err != nil {
|
|
t.Errorf("ValidChecksum(%q) = %v, want nil", good, err)
|
|
}
|
|
if err := ValidChecksum("crc32=deadbeef"); err == nil {
|
|
t.Errorf("ValidChecksum(crc32): want error (unsupported type)")
|
|
}
|
|
}
|
|
|
|
func TestVerifyFile(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
data := []byte("the data is the design")
|
|
if err := os.WriteFile(path, data, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sum := sha256.Sum256(data)
|
|
|
|
// A matching digest verifies clean.
|
|
if err := verifyFile(path, sha256.New, hex.EncodeToString(sum[:])); err != nil {
|
|
t.Errorf("verifyFile match: %v", err)
|
|
}
|
|
// A wrong digest returns ErrChecksum, which main maps to exit code 32.
|
|
wrong := hex.EncodeToString(make([]byte, 32))
|
|
if err := verifyFile(path, sha256.New, wrong); !errors.Is(err, ErrChecksum) {
|
|
t.Errorf("verifyFile mismatch = %v; want ErrChecksum", err)
|
|
}
|
|
}
|