TestFileHash is a unit test for FileHash()
(t *testing.T)
| 19 | |
| 20 | // TestFileHash is a unit test for FileHash() |
| 21 | func TestFileHash(t *testing.T) { |
| 22 | testCases := []struct { |
| 23 | content string |
| 24 | optionalExtra string |
| 25 | }{ |
| 26 | {"This is a test file for FileHash function.", ""}, |
| 27 | {"Another test case with different content.", ""}, |
| 28 | {"Test file with special characters: !@#$%^&*()_+-=[]{};':\"|,.<>?", ""}, |
| 29 | {"Test file with provided extra content", "random extra content"}, |
| 30 | } |
| 31 | |
| 32 | for i, tc := range testCases { |
| 33 | t.Run("", func(t *testing.T) { |
| 34 | tmpDir := testcommon.CreateTmpDir("TestFileHash_" + util.RandString(10)) |
| 35 | t.Cleanup(func() { |
| 36 | _ = os.RemoveAll(tmpDir) |
| 37 | }) |
| 38 | testFile := filepath.Join(tmpDir, fmt.Sprintf("TestFileHash_%d", i)) |
| 39 | err := fileutil.TemplateStringToFile(tc.content, nil, testFile) |
| 40 | require.NoError(t, err) |
| 41 | |
| 42 | // Use FileHash first |
| 43 | result, err := fileutil.FileHash(testFile, tc.optionalExtra) |
| 44 | require.NoError(t, err) |
| 45 | |
| 46 | // But we have to add the filepath to the testFile before |
| 47 | // we can use the externalComputeSha1Sum successfully |
| 48 | canonicalFileName := testFile |
| 49 | if nodeps.IsWindows() { |
| 50 | canonicalFileName = util.WindowsPathToCygwinPath(testFile) |
| 51 | } |
| 52 | f, err := os.OpenFile(testFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) |
| 53 | require.NoError(t, err) |
| 54 | _, err = f.WriteString(canonicalFileName) |
| 55 | require.NoError(t, err) |
| 56 | if tc.optionalExtra != "" { |
| 57 | _, err = f.WriteString(tc.optionalExtra) |
| 58 | require.NoError(t, err) |
| 59 | } |
| 60 | _ = f.Close() |
| 61 | |
| 62 | expectedHash, err := externalComputeSha1Sum(testFile) |
| 63 | require.NoError(t, err) |
| 64 | |
| 65 | require.Equal(t, expectedHash, result) |
| 66 | }) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | // externalComputeSha1Sum uses external tool (sha1sum for example) to compute shasum |
| 71 | // Used only in tests |
nothing calls this directly
no test coverage detected