Source file src/crypto/internal/cryptotest/fetchmodule.go

     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  	"testing"
    13  )
    14  
    15  // FetchModule fetches the module at the given version and returns the directory
    16  // containing its source tree. It skips the test if fetching modules is not
    17  // possible in this environment.
    18  func FetchModule(t *testing.T, module, version string) string {
    19  	testenv.MustHaveExternalNetwork(t)
    20  	goTool := testenv.GoToolPath(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.Command(t, goTool, "env", "GOMODCACHE").Output()
    25  	if err != nil {
    26  		t.Fatalf("%s env GOMODCACHE: %v\n%s", goTool, err, out)
    27  	}
    28  	modcacheOk := false
    29  	if gomodcache := string(bytes.TrimSpace(out)); gomodcache != "" {
    30  		if _, err := os.Stat(gomodcache); err == nil {
    31  			modcacheOk = true
    32  		}
    33  	}
    34  	if !modcacheOk {
    35  		t.Setenv("GOMODCACHE", t.TempDir())
    36  		// Allow t.TempDir() to clean up subdirectories.
    37  		t.Setenv("GOFLAGS", os.Getenv("GOFLAGS")+" -modcacherw")
    38  	}
    39  
    40  	t.Logf("fetching %s@%s\n", module, version)
    41  
    42  	output, err := testenv.Command(t, goTool, "mod", "download", "-json", module+"@"+version).CombinedOutput()
    43  	if err != nil {
    44  		t.Fatalf("failed to download %s@%s: %s\n%s\n", module, version, err, output)
    45  	}
    46  	var j struct {
    47  		Dir string
    48  	}
    49  	if err := json.Unmarshal(output, &j); err != nil {
    50  		t.Fatalf("failed to parse 'go mod download': %s\n%s\n", err, output)
    51  	}
    52  
    53  	return j.Dir
    54  }
    55  

View as plain text