|
16 | 16 | package integrationtest
|
17 | 17 |
|
18 | 18 | import (
|
| 19 | + "context" |
| 20 | + "crypto/md5" |
| 21 | + "encoding/hex" |
| 22 | + "io" |
| 23 | + "net/http" |
| 24 | + "net/url" |
| 25 | + "path/filepath" |
19 | 26 | "testing"
|
20 | 27 |
|
21 | 28 | "github.com/arduino/go-paths-helper"
|
| 29 | + "github.com/codeclysm/extract/v3" |
22 | 30 | "github.com/stretchr/testify/require"
|
23 | 31 | )
|
24 | 32 |
|
@@ -57,3 +65,65 @@ func (e *Environment) CleanUp() {
|
57 | 65 | func (e *Environment) Root() *paths.Path {
|
58 | 66 | return e.rootDir
|
59 | 67 | }
|
| 68 | + |
| 69 | +// Download downloads a file from a URL and returns the path to the downloaded file. |
| 70 | +// The file is saved and cached in a shared downloads directory. If the file already exists, it is not downloaded again. |
| 71 | +func (e *Environment) Download(rawURL string) *paths.Path { |
| 72 | + url, err := url.Parse(rawURL) |
| 73 | + e.t.NoError(err) |
| 74 | + |
| 75 | + filename := filepath.Base(url.Path) |
| 76 | + if filename == "/" { |
| 77 | + filename = "" |
| 78 | + } else { |
| 79 | + filename = "-" + filename |
| 80 | + } |
| 81 | + |
| 82 | + hash := md5.Sum([]byte(rawURL)) |
| 83 | + resource := e.downloadsDir.Join(hex.EncodeToString(hash[:]) + filename) |
| 84 | + |
| 85 | + // If the resource already exist, return it |
| 86 | + if resource.Exist() { |
| 87 | + return resource |
| 88 | + } |
| 89 | + |
| 90 | + // Download file |
| 91 | + resp, err := http.Get(rawURL) |
| 92 | + e.t.NoError(err) |
| 93 | + defer resp.Body.Close() |
| 94 | + |
| 95 | + // Copy data in a temp file |
| 96 | + tmp := resource.Parent().Join(resource.Base() + ".tmp") |
| 97 | + out, err := tmp.Create() |
| 98 | + e.t.NoError(err) |
| 99 | + defer tmp.Remove() |
| 100 | + defer out.Close() |
| 101 | + |
| 102 | + // Write the body to file |
| 103 | + _, err = io.Copy(out, resp.Body) |
| 104 | + e.t.NoError(err) |
| 105 | + e.t.NoError(out.Close()) |
| 106 | + |
| 107 | + // Rename the file to its final destination |
| 108 | + e.t.NoError(tmp.Rename(resource)) |
| 109 | + |
| 110 | + return resource |
| 111 | +} |
| 112 | + |
| 113 | +// Extract extracts a tarball to a directory named as the archive |
| 114 | +// with the "_content" suffix added. Returns the path to the directory. |
| 115 | +func (e *Environment) Extract(archive *paths.Path) *paths.Path { |
| 116 | + destDir := archive.Parent().Join(archive.Base() + "_content") |
| 117 | + if destDir.Exist() { |
| 118 | + return destDir |
| 119 | + } |
| 120 | + |
| 121 | + file, err := archive.Open() |
| 122 | + e.t.NoError(err) |
| 123 | + defer file.Close() |
| 124 | + |
| 125 | + err = extract.Archive(context.Background(), file, destDir.String(), nil) |
| 126 | + e.t.NoError(err) |
| 127 | + |
| 128 | + return destDir |
| 129 | +} |
0 commit comments