| 1 |
// Copyright 2024 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package cryptotest |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"encoding/json" |
| 10 |
"internal/testenv" |
| 11 |
"os" |
| 12 |
"os/exec" |
| 13 |
"testing" |
| 14 |
) |
| 15 |
|
| 16 |
// FetchModule fetches the module at the given version and returns the directory |
| 17 |
// containing its source tree. It skips the test if fetching modules is not |
| 18 |
// possible in this environment. |
| 19 |
func FetchModule(t *testing.T, module, version string) string { |
| 20 |
testenv.MustHaveExternalNetwork(t) |
| 21 |
|
| 22 |
// If the default GOMODCACHE doesn't exist, use a temporary directory |
| 23 |
// instead. (For example, run.bash sets GOPATH=/nonexist-gopath.) |
| 24 |
out, err := testenv.CleanCmdEnv(testenv.Command(t, testenv.GoToolPath(t), "env", "GOMODCACHE")).Output() |
| 25 |
if err != nil { |
| 26 |
t.Errorf("%s env GOMODCACHE: %v\n%s", testenv.GoToolPath(t), err, out) |
| 27 |
if ee, ok := err.(*exec.ExitError); ok { |
| 28 |
t.Logf("%s", ee.Stderr) |
| 29 |
} |
| 30 |
t.FailNow() |
| 31 |
} |
| 32 |
modcacheOk := false |
| 33 |
if gomodcache := string(bytes.TrimSpace(out)); gomodcache != "" { |
| 34 |
if _, err := os.Stat(gomodcache); err == nil { |
| 35 |
modcacheOk = true |
| 36 |
} |
| 37 |
} |
| 38 |
if !modcacheOk { |
| 39 |
t.Setenv("GOMODCACHE", t.TempDir()) |
| 40 |
// Allow t.TempDir() to clean up subdirectories. |
| 41 |
t.Setenv("GOFLAGS", os.Getenv("GOFLAGS")+" -modcacherw") |
| 42 |
} |
| 43 |
|
| 44 |
t.Logf("fetching %s@%s\n", module, version) |
| 45 |
|
| 46 |
output, err := testenv.Command(t, testenv.GoToolPath(t), "mod", "download", "-json", module+"@"+version).CombinedOutput() |
| 47 |
if err != nil { |
| 48 |
t.Fatalf("failed to download %s@%s: %s\n%s\n", module, version, err, output) |
| 49 |
} |
| 50 |
var j struct { |
| 51 |
Dir string |
| 52 |
} |
| 53 |
if err := json.Unmarshal(output, &j); err != nil { |
| 54 |
t.Fatalf("failed to parse 'go mod download': %s\n%s\n", err, output) |
| 55 |
} |
| 56 |
|
| 57 |
return j.Dir |
| 58 |
} |