Skip to content

Commit

Permalink
Adding internal/file/hasher test cases (#1049)
Browse files Browse the repository at this point in the history
  • Loading branch information
noqcks committed Jan 4, 2023
1 parent 04a84a4 commit 3748e8e
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions internal/file/hasher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package file

import (
"fmt"
"testing"

"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
)

func TestValidateByHash(t *testing.T) {
testsCases := []struct {
name, path, hashStr, actualHash string
setup func(fs afero.Fs)
valid bool
err bool
errMsg error
}{
{
name: "Valid SHA256 hash",
path: "test.txt",
hashStr: "sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
setup: func(fs afero.Fs) {
afero.WriteFile(fs, "test.txt", []byte("test"), 0644)
},
actualHash: "sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
valid: true,
err: false,
},
{
name: "Invalid SHA256 hash",
path: "test.txt",
hashStr: "sha256:deadbeef",
setup: func(fs afero.Fs) {
afero.WriteFile(fs, "test.txt", []byte("test"), 0644)
},
actualHash: "sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
valid: false,
err: false,
},
{
name: "Unsupported hash function",
path: "test.txt",
hashStr: "md5:deadbeef",
setup: func(fs afero.Fs) {
afero.WriteFile(fs, "test.txt", []byte("test"), 0644)
},
actualHash: "",
valid: false,
err: true,
errMsg: fmt.Errorf("hasher not supported or specified (given: md5:deadbeef)"),
},
{
name: "File does not exist",
path: "nonexistent.txt",
hashStr: "sha256:deadbeef",
setup: func(fs afero.Fs) {},
valid: false,
actualHash: "",
err: true,
},
}

for _, tc := range testsCases {
t.Run(tc.name, func(t *testing.T) {
fs := afero.NewMemMapFs()
tc.setup(fs)

valid, actualHash, err := ValidateByHash(fs, tc.path, tc.hashStr)

assert.Equal(t, tc.valid, valid)
assert.Equal(t, tc.actualHash, actualHash)

if tc.err {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}

if tc.errMsg != nil {
assert.Equal(t, tc.errMsg, err)
}
})
}
}

0 comments on commit 3748e8e

Please sign in to comment.