TestDownloadFile tests downloading a file with no sha, good sha, bad sha
(t *testing.T)
| 21 | |
| 22 | // TestDownloadFile tests downloading a file with no sha, good sha, bad sha |
| 23 | func TestDownloadFile(t *testing.T) { |
| 24 | testData := "hello world\n" |
| 25 | sum := fmt.Sprintf("%x", sha256.Sum256([]byte(testData))) |
| 26 | fileName := "testfile.txt" |
| 27 | |
| 28 | // HTTP test server |
| 29 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 30 | switch r.URL.Path { |
| 31 | case "/" + fileName: |
| 32 | _, _ = io.WriteString(w, testData) |
| 33 | case "/sha256sums.txt": |
| 34 | _, _ = fmt.Fprintf(w, "%s *%s\n", sum, fileName) |
| 35 | case "/badsha256sums.txt": |
| 36 | _, _ = fmt.Fprintf(w, "%s *%s\n", "deadbeef", fileName) |
| 37 | default: |
| 38 | http.NotFound(w, r) |
| 39 | } |
| 40 | })) |
| 41 | defer ts.Close() |
| 42 | |
| 43 | tmpDir := t.TempDir() |
| 44 | |
| 45 | t.Run("no shasum", func(t *testing.T) { |
| 46 | dest := filepath.Join(tmpDir, "plain.txt") |
| 47 | err := util.DownloadFile(dest, ts.URL+"/"+fileName, false, "") |
| 48 | require.NoError(t, err) |
| 49 | content, err := os.ReadFile(dest) |
| 50 | require.NoError(t, err) |
| 51 | require.Equal(t, testData, string(content)) |
| 52 | }) |
| 53 | |
| 54 | t.Run("correct shasum", func(t *testing.T) { |
| 55 | dest := filepath.Join(tmpDir, "verified.txt") |
| 56 | err := util.DownloadFile(dest, ts.URL+"/"+fileName, false, ts.URL+"/sha256sums.txt") |
| 57 | require.NoError(t, err) |
| 58 | content, err := os.ReadFile(dest) |
| 59 | require.NoError(t, err) |
| 60 | require.Equal(t, testData, string(content)) |
| 61 | }) |
| 62 | |
| 63 | t.Run("incorrect shasum", func(t *testing.T) { |
| 64 | dest := filepath.Join(tmpDir, "bad.txt") |
| 65 | err := util.DownloadFile(dest, ts.URL+"/"+fileName, false, ts.URL+"/badsha256sums.txt") |
| 66 | require.Error(t, err, "expected error due to SHA256 mismatch") |
| 67 | require.NoFileExistsf(t, dest, "expected file %s to be deleted after sha mismatch, but it exists", dest) |
| 68 | }) |
| 69 | } |
| 70 | |
| 71 | // TestDownloadFileRetryLogic tests the retry logic structure of DownloadFile |
| 72 | func TestDownloadFileRetryLogic(t *testing.T) { |
nothing calls this directly
no test coverage detected