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 1589a92
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
23 changes: 21 additions & 2 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,30 @@ var (

// initGoEnv initialises goEnv. It should only be called using goEnv.once.Do,
// as in Setup.
func initGoEnv() error {
var err error
//
// 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() (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 func() {
if rerr := os.RemoveAll(td); rerr != nil && err == nil {
err = fmt.Errorf("failed to remove temporary directory for go command tests: %w", rerr)
}
}()

// Write a temporary go.mod file in td. This ensures that we create
// a porcelain environment in which to run these probe commands.
if err := os.WriteFile(filepath.Join(td, "go.mod"), []byte("module gotooltest"), 0600); err != nil {
return fmt.Errorf("failed to write temporary go.mod file: %w", err)
}

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 := t.TempDir()

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

t.Cleanup(func() {
os.Chdir(wd)
os.Remove(td)
})

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 1589a92

Please sign in to comment.