5
5
package downloads
6
6
7
7
import (
8
+ "crypto/sha512"
9
+ "encoding/hex"
8
10
"fmt"
9
11
"net/http"
10
12
"net/http/httptest"
11
13
"os"
12
14
"path/filepath"
13
15
"testing"
14
16
17
+ "github.com/stretchr/testify/require"
18
+
15
19
"github.com/stretchr/testify/assert"
16
20
)
17
21
@@ -30,3 +34,59 @@ func TestDownloadFile(t *testing.T) {
30
34
assert .NotEmpty (t , dRequest .UnsanitizedFilePath )
31
35
defer os .Remove (filepath .Dir (dRequest .UnsanitizedFilePath ))
32
36
}
37
+
38
+ func TestVerifyChecksum (t * testing.T ) {
39
+ tmpDir := t .TempDir ()
40
+ content := "hello world"
41
+ hashBytes := sha512 .Sum512 ([]byte (content ))
42
+ hashHex := hex .EncodeToString (hashBytes [:])
43
+
44
+ t .Run ("valid checksum" , func (t * testing.T ) {
45
+ // Write the file to be verified
46
+ fileName := "testfile.txt"
47
+ require .NoError (t , os .WriteFile (filepath .Join (tmpDir , fileName ), []byte (content ), 0644 ))
48
+
49
+ // Write the checksum file
50
+ checksumContent := fmt .Sprintf ("%s %s" , hashHex , fileName )
51
+ checksumPath := filepath .Join (tmpDir , "checksum.txt" )
52
+ require .NoError (t , os .WriteFile (checksumPath , []byte (checksumContent ), 0644 ))
53
+
54
+ // Run test
55
+ err := verifyChecksum (checksumPath )
56
+ assert .NoError (t , err )
57
+ })
58
+
59
+ t .Run ("missing checksum file" , func (t * testing.T ) {
60
+ err := verifyChecksum (filepath .Join (tmpDir , "missing.txt" ))
61
+ assert .ErrorContains (t , err , "failed to read checksum file" )
62
+ })
63
+
64
+ t .Run ("malformed checksum content" , func (t * testing.T ) {
65
+ checksumPath := filepath .Join (tmpDir , "badchecksum.txt" )
66
+ require .NoError (t , os .WriteFile (checksumPath , []byte ("invalid-format-line" ), 0644 ))
67
+
68
+ err := verifyChecksum (checksumPath )
69
+ assert .ErrorContains (t , err , "invalid format" )
70
+ })
71
+
72
+ t .Run ("missing target file" , func (t * testing.T ) {
73
+ checksumContent := fmt .Sprintf ("%s %s" , hashHex , "nonexistent.txt" )
74
+ checksumPath := filepath .Join (tmpDir , "checksum_missing_target.txt" )
75
+ require .NoError (t , os .WriteFile (checksumPath , []byte (checksumContent ), 0644 ))
76
+
77
+ err := verifyChecksum (checksumPath )
78
+ assert .ErrorContains (t , err , "failed to open file for sha512 summing" )
79
+ })
80
+
81
+ t .Run ("checksum mismatch" , func (t * testing.T ) {
82
+ invalidContent := content + "x"
83
+ fileName := "file.txt"
84
+ require .NoError (t , os .WriteFile (filepath .Join (tmpDir , fileName ), []byte (invalidContent ), 0644 ))
85
+ checksumContent := fmt .Sprintf ("%s %s" , hashHex , fileName )
86
+ checksumPath := filepath .Join (tmpDir , "badhash.txt" )
87
+ require .NoError (t , os .WriteFile (checksumPath , []byte (checksumContent ), 0644 ))
88
+
89
+ err := verifyChecksum (checksumPath )
90
+ assert .ErrorContains (t , err , "does not match expected checksum" )
91
+ })
92
+ }
0 commit comments