Skip to content

Commit

Permalink
gotooltest: run probe commands in temporary directory
Browse files Browse the repository at this point in the history
This ensures we don't make any assumptions about the caller's working
directory, which might contain an invalid go.mod, for example.
  • Loading branch information
myitcv committed Nov 21, 2022
1 parent bdb7893 commit a106d76
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
11 changes: 11 additions & 0 deletions gotooltest/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
Expand All @@ -36,12 +37,22 @@ var (

// initGoEnv initialises goEnv. It should only be called using goEnv.once.Do,
// as in Setup.
//
// Run all of these probe commands in a temporary directory, so as not to make
// any assumptions about the caller's working directory.
func initGoEnv() error {
var err error

td, err := os.MkdirTemp("", "gotooltest-initGoEnv")
if err != nil {
return fmt.Errorf("failed to create temporary directory for go command tests: %w", err)
}
defer os.RemoveAll(td)

run := func(args ...string) (*bytes.Buffer, *bytes.Buffer, error) {
var stdout, stderr bytes.Buffer
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = td
cmd.Stdout = &stdout
cmd.Stderr = &stderr
return &stdout, &stderr, cmd.Run()
Expand Down
30 changes: 30 additions & 0 deletions gotooltest/setup_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package gotooltest

import (
"os"
"testing"
)

func TestInitGoEnv(t *testing.T) {
// Set up a temp directory containing a bad go.mod file to
// ensure the working directory does not influence the probe
// commands run during initGoEnv
td, err := os.MkdirTemp("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(td)

// If these commands fail we are in bigger trouble
wd, _ := os.Getwd()
os.Chdir(td)
defer os.Chdir(wd)

if err := os.WriteFile("go.mod", []byte("this is rubbish"), 0600); err != nil {
t.Fatal(err)
}

if err := initGoEnv(); err != nil {
t.Fatal(err)
}
}

0 comments on commit a106d76

Please sign in to comment.