Skip to content

Commit e760786

Browse files
committed
testsuite: added env commands to download and extract files
1 parent a8d1734 commit e760786

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

testsuite/env.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,17 @@
1616
package integrationtest
1717

1818
import (
19+
"context"
20+
"crypto/md5"
21+
"encoding/hex"
22+
"io"
23+
"net/http"
24+
"net/url"
25+
"path/filepath"
1926
"testing"
2027

2128
"github.com/arduino/go-paths-helper"
29+
"github.com/codeclysm/extract/v3"
2230
"github.com/stretchr/testify/require"
2331
)
2432

@@ -57,3 +65,65 @@ func (e *Environment) CleanUp() {
5765
func (e *Environment) Root() *paths.Path {
5866
return e.rootDir
5967
}
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

Comments
 (0)