From d93af716c5935cd9954b3a4f60e9c585f991e5c1 Mon Sep 17 00:00:00 2001 From: Daniel Nephin Date: Sat, 9 Apr 2022 13:38:52 -0400 Subject: [PATCH] create any missing directories for {json,junit}file If the directory can not be created then the file creation operation will fail as it did before. No reason to force someone to create this directory ahead of time. --- cmd/handler.go | 3 +++ cmd/handler_test.go | 35 +++++++++++++++++++++++++++++++++++ go.mod | 2 +- 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/cmd/handler.go b/cmd/handler.go index 9a58baaf..c0863382 100644 --- a/cmd/handler.go +++ b/cmd/handler.go @@ -5,6 +5,7 @@ import ( "io" "os" "os/exec" + "path/filepath" "github.com/pkg/errors" "gotest.tools/gotestsum/internal/junitxml" @@ -68,6 +69,7 @@ func newEventHandler(opts *options) (*eventHandler, error) { } var err error if opts.jsonFile != "" { + _ = os.MkdirAll(filepath.Dir(opts.jsonFile), 0o755) handler.jsonFile, err = os.Create(opts.jsonFile) if err != nil { return handler, errors.Wrap(err, "failed to open JSON file") @@ -80,6 +82,7 @@ func writeJUnitFile(opts *options, execution *testjson.Execution) error { if opts.junitFile == "" { return nil } + _ = os.MkdirAll(filepath.Dir(opts.junitFile), 0o755) junitFile, err := os.Create(opts.junitFile) if err != nil { return fmt.Errorf("failed to open JUnit file: %v", err) diff --git a/cmd/handler_test.go b/cmd/handler_test.go index c31c766f..f5a742f2 100644 --- a/cmd/handler_test.go +++ b/cmd/handler_test.go @@ -4,12 +4,14 @@ import ( "bytes" "io/ioutil" "os" + "path/filepath" "strings" "testing" "gotest.tools/gotestsum/testjson" "gotest.tools/v3/assert" "gotest.tools/v3/env" + "gotest.tools/v3/fs" "gotest.tools/v3/golden" ) @@ -85,3 +87,36 @@ func TestEventHandler_Event_MaxFails(t *testing.T) { _, err := testjson.ScanTestOutput(cfg) assert.Error(t, err, "ending test run because max failures was reached") } + +func TestNewEventHandler_CreatesDirectory(t *testing.T) { + dir := fs.NewDir(t, t.Name()) + jsonFile := filepath.Join(dir.Path(), "new-path", "log.json") + + opts := &options{ + stdout: new(bytes.Buffer), + format: "testname", + jsonFile: jsonFile, + } + _, err := newEventHandler(opts) + assert.NilError(t, err) + + _, err = os.Stat(jsonFile) + assert.NilError(t, err) +} + +func TestWriteJunitFile_CreatesDirectory(t *testing.T) { + dir := fs.NewDir(t, t.Name()) + junitFile := filepath.Join(dir.Path(), "new-path", "junit.xml") + + opts := &options{ + junitFile: junitFile, + junitTestCaseClassnameFormat: &junitFieldFormatValue{}, + junitTestSuiteNameFormat: &junitFieldFormatValue{}, + } + exec := &testjson.Execution{} + err := writeJUnitFile(opts, exec) + assert.NilError(t, err) + + _, err = os.Stat(junitFile) + assert.NilError(t, err) +} diff --git a/go.mod b/go.mod index b3e72f0c..6aefe2f1 100644 --- a/go.mod +++ b/go.mod @@ -15,4 +15,4 @@ require ( gotest.tools/v3 v3.0.3 ) -go 1.11 +go 1.13