跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

downloader_test.go

631 行 · 22.7 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package downloader
5
6import (
7 "compress/gzip"
8 "io"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "runtime"
15 "strings"
16 "testing"
17 "time"
18
19 "github.com/opencontainers/go-digest"
20 "gotest.tools/v3/assert"
21)
22
23func TestMain(m *testing.M) {
24 HideProgress = true
25 m.Run()
26}
27
28type downloadResult struct {
29 r *Result
30 err error
31}
32
33// We expect only few parallel downloads. Testing with larger number to find
34// races quicker. 20 parallel downloads take about 120 milliseconds on M1 Pro.
35const parallelDownloads = 20
36
37func TestDownloadRemote(t *testing.T) {
38 ts := httptest.NewServer(http.FileServer(http.Dir("testdata")))
39 t.Cleanup(ts.Close)
40 dummyRemoteFileURL := ts.URL + "/downloader.txt"
41 const dummyRemoteFileDigest = "sha256:380481d26f897403368be7cb86ca03a4bc14b125bfaf2b93bff809a5a2ad717e"
42 dummyRemoteFileStat, err := os.Stat(filepath.Join("testdata", "downloader.txt"))
43 assert.NilError(t, err)
44
45 t.Run("without cache", func(t *testing.T) {
46 t.Run("without digest", func(t *testing.T) {
47 ctx := t.Context()
48 localPath := filepath.Join(t.TempDir(), t.Name())
49 r, err := Download(ctx, localPath, dummyRemoteFileURL)
50 assert.NilError(t, err)
51 assert.Equal(t, StatusDownloaded, r.Status)
52
53 // download again, make sure StatusSkippedIsReturned
54 r, err = Download(ctx, localPath, dummyRemoteFileURL)
55 assert.NilError(t, err)
56 assert.Equal(t, StatusSkipped, r.Status)
57 })
58 t.Run("with digest", func(t *testing.T) {
59 ctx := t.Context()
60 wrongDigest := digest.Digest("sha256:8313944efb4f38570c689813f288058b674ea6c487017a5a4738dc674b65f9d9")
61 localPath := filepath.Join(t.TempDir(), t.Name())
62 _, err := Download(ctx, localPath, dummyRemoteFileURL, WithExpectedDigest(wrongDigest))
63 assert.ErrorContains(t, err, "expected digest")
64
65 wrongDigest2 := digest.Digest("8313944efb4f38570c689813f288058b674ea6c487017a5a4738dc674b65f9d9")
66 _, err = Download(ctx, localPath, dummyRemoteFileURL, WithExpectedDigest(wrongDigest2))
67 assert.ErrorContains(t, err, "invalid checksum digest format")
68
69 r, err := Download(ctx, localPath, dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest))
70 assert.NilError(t, err)
71 assert.Equal(t, StatusDownloaded, r.Status)
72
73 r, err = Download(ctx, localPath, dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest))
74 assert.NilError(t, err)
75 assert.Equal(t, StatusSkipped, r.Status)
76 })
77 })
78 t.Run("with cache", func(t *testing.T) {
79 t.Run("serial", func(t *testing.T) {
80 ctx := t.Context()
81 cacheDir := filepath.Join(t.TempDir(), "cache")
82 localPath := filepath.Join(t.TempDir(), t.Name())
83 r, err := Download(ctx, localPath, dummyRemoteFileURL,
84 WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
85 assert.NilError(t, err)
86 assert.Equal(t, StatusDownloaded, r.Status)
87
88 r, err = Download(ctx, localPath, dummyRemoteFileURL,
89 WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
90 assert.NilError(t, err)
91 assert.Equal(t, StatusSkipped, r.Status)
92
93 localPath2 := localPath + "-2"
94 r, err = Download(ctx, localPath2, dummyRemoteFileURL,
95 WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
96 assert.NilError(t, err)
97 assert.Equal(t, StatusUsedCache, r.Status)
98 })
99 t.Run("parallel", func(t *testing.T) {
100 ctx := t.Context()
101 cacheDir := filepath.Join(t.TempDir(), "cache")
102 results := make(chan downloadResult, parallelDownloads)
103 for range parallelDownloads {
104 go func() {
105 // Parallel download is supported only for different instances with unique localPath.
106 localPath := filepath.Join(t.TempDir(), t.Name())
107 r, err := Download(ctx, localPath, dummyRemoteFileURL,
108 WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
109 results <- downloadResult{r, err}
110 }()
111 }
112 // Only one thread should download, the rest should use the cache.
113 downloaded, cached := countResults(t, results)
114 assert.Equal(t, downloaded, 1)
115 assert.Equal(t, cached, parallelDownloads-1)
116 })
117 })
118 t.Run("caching-only mode", func(t *testing.T) {
119 t.Run("serial", func(t *testing.T) {
120 ctx := t.Context()
121 _, err := Download(ctx, "", dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest))
122 assert.ErrorContains(t, err, "cache directory to be specified")
123
124 cacheDir := filepath.Join(t.TempDir(), "cache")
125 r, err := Download(ctx, "", dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest),
126 WithCacheDir(cacheDir))
127 assert.NilError(t, err)
128 assert.Equal(t, StatusDownloaded, r.Status)
129
130 r, err = Download(ctx, "", dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest),
131 WithCacheDir(cacheDir))
132 assert.NilError(t, err)
133 assert.Equal(t, StatusUsedCache, r.Status)
134
135 localPath := filepath.Join(t.TempDir(), t.Name())
136 r, err = Download(ctx, localPath, dummyRemoteFileURL,
137 WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
138 assert.NilError(t, err)
139 assert.Equal(t, StatusUsedCache, r.Status)
140 })
141 t.Run("parallel", func(t *testing.T) {
142 ctx := t.Context()
143 cacheDir := filepath.Join(t.TempDir(), "cache")
144 results := make(chan downloadResult, parallelDownloads)
145 for range parallelDownloads {
146 go func() {
147 r, err := Download(ctx, "", dummyRemoteFileURL,
148 WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
149 results <- downloadResult{r, err}
150 }()
151 }
152 // Only one thread should download, the rest should use the cache.
153 downloaded, cached := countResults(t, results)
154 assert.Equal(t, downloaded, 1)
155 assert.Equal(t, cached, parallelDownloads-1)
156 })
157 })
158 t.Run("cached", func(t *testing.T) {
159 ctx := t.Context()
160 _, err := Cached(dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest))
161 assert.ErrorContains(t, err, "cache directory to be specified")
162
163 cacheDir := filepath.Join(t.TempDir(), "cache")
164 r, err := Download(ctx, "", dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
165 assert.NilError(t, err)
166 assert.Equal(t, StatusDownloaded, r.Status)
167
168 r, err = Cached(dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
169 assert.NilError(t, err)
170 assert.Equal(t, StatusUsedCache, r.Status)
171 assert.Assert(t, strings.HasPrefix(r.CachePath, cacheDir), "expected %s to be in %s", r.CachePath, cacheDir)
172
173 wrongDigest := digest.Digest("sha256:8313944efb4f38570c689813f288058b674ea6c487017a5a4738dc674b65f9d9")
174 _, err = Cached(dummyRemoteFileURL, WithExpectedDigest(wrongDigest), WithCacheDir(cacheDir))
175 assert.ErrorContains(t, err, "expected digest")
176 })
177 t.Run("metadata", func(t *testing.T) {
178 ctx := t.Context()
179 _, err := Cached(dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest))
180 assert.ErrorContains(t, err, "cache directory to be specified")
181
182 cacheDir := filepath.Join(t.TempDir(), "cache")
183 r, err := Download(ctx, "", dummyRemoteFileURL, WithExpectedDigest(dummyRemoteFileDigest), WithCacheDir(cacheDir))
184 assert.NilError(t, err)
185 assert.Equal(t, StatusDownloaded, r.Status)
186 assert.Equal(t, dummyRemoteFileStat.ModTime().Truncate(time.Second).UTC(), r.LastModified)
187 assert.Equal(t, "text/plain; charset=utf-8", r.ContentType)
188 })
189}
190
191func countResults(t *testing.T, results chan downloadResult) (downloaded, cached int) {
192 t.Helper()
193 for range parallelDownloads {
194 result := <-results
195 if result.err != nil {
196 t.Errorf("Download failed: %s", result.err)
197 } else {
198 switch result.r.Status {
199 case StatusDownloaded:
200 downloaded++
201 case StatusUsedCache:
202 cached++
203 default:
204 t.Errorf("Unexpected download status %#q", result.r.Status)
205 }
206 }
207 }
208 return downloaded, cached
209}
210
211func TestRemoveStaleTempFiles(t *testing.T) {
212 cacheDir := filepath.Join(t.TempDir(), "cache")
213 url := "https://example.com/image.img"
214 shad := cacheDirectoryPath(cacheDir, url)
215 assert.NilError(t, os.MkdirAll(shad, 0o700))
216
217 data := filepath.Join(shad, "data")
218 part := filepath.Join(shad, "data.part")
219 legacy := filepath.Join(shad, "data.tmp.123.1")
220 for _, f := range []string{data, part, legacy} {
221 assert.NilError(t, os.WriteFile(f, []byte("x"), 0o644))
222 }
223
224 // No cache dir configured is a no-op.
225 assert.NilError(t, RemoveStaleTempFiles())
226
227 assert.NilError(t, RemoveStaleTempFiles(WithCacheDir(cacheDir)))
228
229 // The completed "data" file is kept; partial/temp files are removed.
230 _, err := os.Stat(data)
231 assert.NilError(t, err)
232 _, err = os.Stat(part)
233 assert.Assert(t, os.IsNotExist(err), "data.part should have been removed")
234 _, err = os.Stat(legacy)
235 assert.Assert(t, os.IsNotExist(err), "data.tmp.* should have been removed")
236}
237
238func TestRedownloadRemote(t *testing.T) {
239 remoteDir := t.TempDir()
240 ts := httptest.NewServer(http.FileServer(http.Dir(remoteDir)))
241 t.Cleanup(ts.Close)
242
243 downloadDir := t.TempDir()
244
245 cacheOpt := WithCacheDir(t.TempDir())
246
247 t.Run("digest-less", func(t *testing.T) {
248 ctx := t.Context()
249 remoteFile := filepath.Join(remoteDir, "digest-less.txt")
250 assert.NilError(t, os.WriteFile(remoteFile, []byte("digest-less"), 0o644))
251 assert.NilError(t, os.Chtimes(remoteFile, time.Now(), time.Now().Add(-time.Hour)))
252 opt := []Opt{cacheOpt}
253
254 // Download on the first call
255 r, err := Download(ctx, filepath.Join(downloadDir, "1"), ts.URL+"/digest-less.txt", opt...)
256 assert.NilError(t, err)
257 assert.Equal(t, StatusDownloaded, r.Status)
258
259 // Next download will use the cached download
260 r, err = Download(ctx, filepath.Join(downloadDir, "2"), ts.URL+"/digest-less.txt", opt...)
261 assert.NilError(t, err)
262 assert.Equal(t, StatusUsedCache, r.Status)
263
264 // Modifying remote file will cause redownload
265 assert.NilError(t, os.Chtimes(remoteFile, time.Now(), time.Now()))
266 r, err = Download(ctx, filepath.Join(downloadDir, "3"), ts.URL+"/digest-less.txt", opt...)
267 assert.NilError(t, err)
268 assert.Equal(t, StatusDownloaded, r.Status)
269
270 // Next download will use the cached download
271 r, err = Download(ctx, filepath.Join(downloadDir, "4"), ts.URL+"/digest-less.txt", opt...)
272 assert.NilError(t, err)
273 assert.Equal(t, StatusUsedCache, r.Status)
274 })
275
276 // Regression test for https://github.com/lima-vm/lima/issues/5188: when the
277 // freshness HEAD check for a digest-less cached image fails (e.g. network
278 // error), Download must still fall back to the cache and actually copy the
279 // cached data to the local path, not just report StatusUsedCache.
280 t.Run("digest-less, HEAD failure falls back to cache", func(t *testing.T) {
281 ctx := t.Context()
282 flakyRemoteDir := t.TempDir()
283 flakyTS := httptest.NewServer(http.FileServer(http.Dir(flakyRemoteDir)))
284 remoteFile := filepath.Join(flakyRemoteDir, "flaky.txt")
285 assert.NilError(t, os.WriteFile(remoteFile, []byte("flaky"), 0o644))
286 remoteURL := flakyTS.URL + "/flaky.txt"
287 flakyCacheOpt := WithCacheDir(t.TempDir())
288
289 // First download populates the cache together with its last-modified time.
290 r, err := Download(ctx, filepath.Join(downloadDir, "flaky-1"), remoteURL, flakyCacheOpt)
291 assert.NilError(t, err)
292 assert.Equal(t, StatusDownloaded, r.Status)
293
294 // The server goes away, so the freshness HEAD check on the next
295 // download will fail.
296 flakyTS.Close()
297
298 localPath2 := filepath.Join(downloadDir, "flaky-2")
299 r, err = Download(ctx, localPath2, remoteURL, flakyCacheOpt)
300 assert.NilError(t, err)
301 assert.Equal(t, StatusUsedCache, r.Status)
302
303 got, err := os.ReadFile(localPath2)
304 assert.NilError(t, err)
305 assert.Equal(t, "flaky", string(got))
306 })
307
308 t.Run("has-digest", func(t *testing.T) {
309 ctx := t.Context()
310 remoteFile := filepath.Join(remoteDir, "has-digest.txt")
311 bytes := []byte("has-digest")
312 assert.NilError(t, os.WriteFile(remoteFile, bytes, 0o644))
313 assert.NilError(t, os.Chtimes(remoteFile, time.Now(), time.Now().Add(-time.Hour)))
314
315 digester := digest.SHA256.Digester()
316 _, err := digester.Hash().Write(bytes)
317 assert.NilError(t, err)
318 opt := []Opt{cacheOpt, WithExpectedDigest(digester.Digest())}
319
320 r, err := Download(ctx, filepath.Join(downloadDir, "has-digest1.txt"), ts.URL+"/has-digest.txt", opt...)
321 assert.NilError(t, err)
322 assert.Equal(t, StatusDownloaded, r.Status)
323 r, err = Download(ctx, filepath.Join(downloadDir, "has-digest2.txt"), ts.URL+"/has-digest.txt", opt...)
324 assert.NilError(t, err)
325 assert.Equal(t, StatusUsedCache, r.Status)
326
327 // modifying remote file won't cause redownload because expected digest is provided
328 assert.NilError(t, os.Chtimes(remoteFile, time.Now(), time.Now()))
329 r, err = Download(ctx, filepath.Join(downloadDir, "has-digest3.txt"), ts.URL+"/has-digest.txt", opt...)
330 assert.NilError(t, err)
331 assert.Equal(t, StatusUsedCache, r.Status)
332 })
333}
334
335func TestDownloadLocal(t *testing.T) {
336 const emptyFileDigest = "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
337 const testDownloadLocalDigest = "sha256:0c1e0fba69e8919b306d030bf491e3e0c46cf0a8140ff5d7516ba3a83cbea5b3"
338
339 t.Run("without digest", func(t *testing.T) {
340 localPath := filepath.Join(t.TempDir(), t.Name())
341 localFile := filepath.Join(t.TempDir(), "test-file")
342 f, err := os.Create(localFile)
343 assert.NilError(t, err)
344 t.Cleanup(func() { _ = f.Close() })
345 testLocalFileURL := "file://" + localFile
346
347 r, err := Download(t.Context(), localPath, testLocalFileURL)
348 assert.NilError(t, err)
349 assert.Equal(t, StatusDownloaded, r.Status)
350 })
351
352 t.Run("with file digest", func(t *testing.T) {
353 ctx := t.Context()
354 localPath := filepath.Join(t.TempDir(), t.Name())
355 localTestFile := filepath.Join(t.TempDir(), "some-file")
356 testDownloadFileContents := []byte("TestDownloadLocal")
357
358 assert.NilError(t, os.WriteFile(localTestFile, testDownloadFileContents, 0o644))
359 testLocalFileURL := "file://" + localTestFile
360 wrongDigest := digest.Digest(emptyFileDigest)
361
362 _, err := Download(ctx, localPath, testLocalFileURL, WithExpectedDigest(wrongDigest))
363 assert.ErrorContains(t, err, "expected digest")
364
365 r, err := Download(ctx, localPath, testLocalFileURL, WithExpectedDigest(testDownloadLocalDigest))
366 assert.NilError(t, err)
367 assert.Equal(t, StatusDownloaded, r.Status)
368 })
369
370 t.Run("cached", func(t *testing.T) {
371 localFile := filepath.Join(t.TempDir(), "test-file")
372 f, err := os.Create(localFile)
373 assert.NilError(t, err)
374 t.Cleanup(func() { _ = f.Close() })
375 testLocalFileURL := "file://" + localFile
376
377 cacheDir := filepath.Join(t.TempDir(), "cache")
378 _, err = Cached(testLocalFileURL, WithCacheDir(cacheDir))
379 assert.ErrorContains(t, err, "not cached")
380 })
381}
382
383func TestDownloadCompressed(t *testing.T) {
384 testContents := []byte("TestDownloadCompressed")
385
386 // check builds a compressed fixture via write, downloads it with
387 // decompression, and asserts the result round-trips. With noExternal set,
388 // PATH is emptied so the built-in decoder runs instead of a host binary.
389 check := func(t *testing.T, ext string, write func(io.Writer) error, noExternal bool) {
390 t.Helper()
391 if noExternal {
392 t.Setenv("PATH", t.TempDir())
393 }
394 localPath := filepath.Join(t.TempDir(), t.Name())
395 localFile := filepath.Join(t.TempDir(), "test-file"+ext)
396 f, err := os.Create(localFile)
397 assert.NilError(t, err)
398 assert.NilError(t, write(f))
399 assert.NilError(t, f.Close())
400
401 r, err := Download(t.Context(), localPath, "file://"+localFile, WithDecompress(true))
402 assert.NilError(t, err)
403 assert.Equal(t, StatusDownloaded, r.Status)
404 got, err := os.ReadFile(localPath)
405 assert.NilError(t, err)
406 assert.Equal(t, string(got), string(testContents))
407 }
408 writeGz := func(w io.Writer) error {
409 gz := gzip.NewWriter(w)
410 if _, err := gz.Write(testContents); err != nil {
411 return err
412 }
413 return gz.Close()
414 }
415
416 t.Run("gzip", func(t *testing.T) { check(t, ".gz", writeGz, false) })
417 t.Run("gzip without external binary", func(t *testing.T) { check(t, ".gz", writeGz, true) })
418
419 t.Run("bzip2", func(t *testing.T) {
420 if runtime.GOOS == "windows" {
421 // External bzip2 ships with MSYS2/Git for Windows but not
422 // vanilla Windows, and there is no in-process equivalent
423 // in the standard library.
424 t.Skip("bzip2 binary required to build the fixture")
425 }
426 ctx := t.Context()
427 localPath := filepath.Join(t.TempDir(), t.Name())
428 localFile := filepath.Join(t.TempDir(), "test-file")
429 testDownloadCompressedContents := []byte("TestDownloadCompressed")
430 assert.NilError(t, os.WriteFile(localFile, testDownloadCompressedContents, 0o644))
431 assert.NilError(t, exec.CommandContext(ctx, "bzip2", localFile).Run())
432 localFile += ".bz2"
433 testLocalFileURL := "file://" + localFile
434
435 r, err := Download(ctx, localPath, testLocalFileURL, WithDecompress(true))
436 assert.NilError(t, err)
437 assert.Equal(t, StatusDownloaded, r.Status)
438
439 got, err := os.ReadFile(localPath)
440 assert.NilError(t, err)
441 assert.Equal(t, string(got), string(testDownloadCompressedContents))
442 })
443
444 t.Run("unknown decompressor", func(t *testing.T) {
445 localPath := filepath.Join(t.TempDir(), t.Name())
446 localFile := filepath.Join(t.TempDir(), "test-file.rar")
447 testDownloadCompressedContents := []byte("TestDownloadCompressed")
448 assert.NilError(t, os.WriteFile(localFile, testDownloadCompressedContents, 0o644))
449 testLocalFileURL := "file://" + localFile
450
451 r, err := Download(t.Context(), localPath, testLocalFileURL, WithDecompress(true))
452 assert.NilError(t, err)
453 assert.Equal(t, StatusDownloaded, r.Status)
454
455 got, err := os.ReadFile(localPath)
456 assert.NilError(t, err)
457 assert.Equal(t, string(got), string(testDownloadCompressedContents))
458 })
459}
460
461// This test simulates the end-to-end flow of downloading a remote image and converting it.
462func TestDownloadImageConversion(t *testing.T) {
463 _, err := exec.LookPath("qemu-img")
464 if err != nil {
465 t.Skipf("qemu-img does not seem installed: %v", err)
466 }
467
468 remoteDir := t.TempDir()
469 ts := httptest.NewServer(http.FileServer(http.Dir(remoteDir)))
470 t.Cleanup(ts.Close)
471
472 qcow2Path := filepath.Join(remoteDir, "test.qcow2")
473 assert.NilError(t, exec.CommandContext(t.Context(), "qemu-img", "create", "-f", "qcow2", qcow2Path, "64K").Run())
474
475 t.Run("without-digest", func(t *testing.T) {
476 ctx := t.Context()
477 cacheDir := t.TempDir()
478 localPath := filepath.Join(t.TempDir(), "local")
479 remoteURL := ts.URL + "/test.qcow2"
480
481 // 1. First download, should convert to raw
482 r, err := Download(ctx, localPath, remoteURL,
483 WithCacheDir(cacheDir),
484 WithDescription("image"),
485 WithDecompress(true),
486 WithImageFormats([]string{"raw"}),
487 )
488 assert.NilError(t, err)
489 assert.Equal(t, StatusDownloaded, r.Status)
490
491 shad := cacheDirectoryPath(cacheDir, remoteURL)
492 rawPath := filepath.Join(shad, "imgconv", "raw")
493 _, err = os.Stat(rawPath)
494 assert.NilError(t, err)
495
496 // 2. Second download, should use cached raw
497 localPath2 := filepath.Join(t.TempDir(), "local2")
498 r, err = Download(ctx, localPath2, remoteURL,
499 WithCacheDir(cacheDir),
500 WithDescription("image"),
501 WithDecompress(true),
502 WithImageFormats([]string{"raw"}),
503 )
504 assert.NilError(t, err)
505 assert.Equal(t, StatusUsedCache, r.Status)
506 assert.Equal(t, rawPath, r.CachePath)
507 })
508
509 t.Run("with-digest", func(t *testing.T) {
510 ctx := t.Context()
511 cacheDir := t.TempDir()
512 localPath := filepath.Join(t.TempDir(), "local")
513 remoteURL := ts.URL + "/test.qcow2"
514
515 content, err := os.ReadFile(qcow2Path)
516 assert.NilError(t, err)
517 originalDigest := digest.SHA256.FromBytes(content)
518
519 // 1. First download, should convert to raw
520 r, err := Download(ctx, localPath, remoteURL,
521 WithCacheDir(cacheDir),
522 WithDescription("image"),
523 WithDecompress(true),
524 WithImageFormats([]string{"raw"}),
525 WithExpectedDigest(originalDigest),
526 )
527 assert.NilError(t, err)
528 assert.Equal(t, StatusDownloaded, r.Status)
529
530 shad := cacheDirectoryPath(cacheDir, remoteURL)
531 rawPath := filepath.Join(shad, "imgconv", "raw")
532 _, err = os.Stat(rawPath)
533 assert.NilError(t, err)
534
535 // 2. Second download, should use cached raw
536 localPath2 := filepath.Join(t.TempDir(), "local2")
537 r, err = Download(ctx, localPath2, remoteURL,
538 WithCacheDir(cacheDir),
539 WithDescription("image"),
540 WithDecompress(true),
541 WithImageFormats([]string{"raw"}),
542 WithExpectedDigest(originalDigest),
543 )
544 assert.NilError(t, err)
545 assert.Equal(t, StatusUsedCache, r.Status)
546 assert.Equal(t, rawPath, r.CachePath)
547 })
548}
549
550// This test focuses specifically on the scenario where the source image
551// is already in the Lima cache but the converted version does not exist yet.
552func TestDownloadImageConversionCached(t *testing.T) {
553 _, err := exec.LookPath("qemu-img")
554 if err != nil {
555 t.Skipf("qemu-img does not seem installed: %v", err)
556 }
557
558 ctx := t.Context()
559 tmpDir := t.TempDir()
560 cacheDir := filepath.Join(tmpDir, "cache")
561 remoteURL := "https://example.com/test.qcow2"
562
563 // Pre-populate cache with a qcow2 file
564 shad := cacheDirectoryPath(cacheDir, remoteURL)
565 assert.NilError(t, os.MkdirAll(shad, 0o700))
566 shadData := filepath.Join(shad, "data")
567 assert.NilError(t, exec.CommandContext(t.Context(), "qemu-img", "create", "-f", "qcow2", shadData, "64K").Run())
568
569 // Provide a cached digest to avoid HTTP HEAD / re-download.
570 content, err := os.ReadFile(shadData)
571 assert.NilError(t, err)
572 originalDigest := digest.SHA256.FromBytes(content)
573 shadDigest := filepath.Join(shad, "sha256.digest")
574 assert.NilError(t, os.WriteFile(shadDigest, []byte(originalDigest.String()), 0o644))
575
576 localPath := filepath.Join(tmpDir, "local")
577
578 // Call Download, it should find qcow2 in cache, see it's not supported, and convert it
579 r, err := Download(ctx, localPath, remoteURL,
580 WithCacheDir(cacheDir),
581 WithDescription("image"),
582 WithImageFormats([]string{"raw"}),
583 WithExpectedDigest(originalDigest),
584 )
585 assert.NilError(t, err)
586 assert.Equal(t, StatusUsedCache, r.Status)
587
588 // Verify conversion happened
589 rawPath := filepath.Join(shad, "imgconv", "raw")
590 _, err = os.Stat(rawPath)
591 assert.NilError(t, err)
592 assert.Equal(t, rawPath, r.CachePath)
593}
594
595func TestDownloadImageConversionCachedDigestMismatch(t *testing.T) {
596 _, err := exec.LookPath("qemu-img")
597 if err != nil {
598 t.Skipf("qemu-img does not seem installed: %v", err)
599 }
600
601 const lastModified = "Mon, 02 Jan 2006 15:04:05 GMT"
602 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
603 w.Header().Set("Last-Modified", lastModified)
604 }))
605 t.Cleanup(ts.Close)
606
607 ctx := t.Context()
608 tmpDir := t.TempDir()
609 cacheDir := filepath.Join(tmpDir, "cache")
610 remoteURL := ts.URL + "/test.qcow2"
611
612 // Pre-populate the cache the way a digest-less download does: "data" and
613 // "time", but no "<ALGO>.digest" file.
614 shad := cacheDirectoryPath(cacheDir, remoteURL)
615 assert.NilError(t, os.MkdirAll(shad, 0o700))
616 shadData := filepath.Join(shad, "data")
617 assert.NilError(t, exec.CommandContext(ctx, "qemu-img", "create", "-f", "qcow2", shadData, "64K").Run())
618 assert.NilError(t, os.WriteFile(filepath.Join(shad, "time"), []byte(lastModified), 0o644))
619
620 localPath := filepath.Join(tmpDir, "local")
621
622 // The cached image does not match the expected digest, so the download must fail
623 // even though the driver only supports raw and the image gets converted.
624 _, err = Download(ctx, localPath, remoteURL,
625 WithCacheDir(cacheDir),
626 WithDescription("image"),
627 WithImageFormats([]string{"raw"}),
628 WithExpectedDigest(digest.SHA256.FromString("unrelated")),
629 )
630 assert.ErrorContains(t, err, "expected digest")
631}