diff --git a/golden/golden.go b/golden/golden.go index 2e01ee8c..54102dd2 100644 --- a/golden/golden.go +++ b/golden/golden.go @@ -72,13 +72,6 @@ func Path(filename string) string { return filepath.Join("testdata", filename) } -func update(filename string, actual []byte) error { - if *flagUpdate { - return ioutil.WriteFile(Path(filename), actual, 0644) - } - return nil -} - func removeCarriageReturn(in []byte) []byte { if !NormalizeCRLFToLF { return in @@ -180,3 +173,15 @@ func compare(actual []byte, filename string) (cmp.Result, []byte) { } return nil, expected } + +func update(filename string, actual []byte) error { + if dir := filepath.Dir(filename); dir != "." { + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + } + if *flagUpdate { + return ioutil.WriteFile(Path(filename), actual, 0644) + } + return nil +} diff --git a/golden/golden_test.go b/golden/golden_test.go index b6ba3af8..d7c88a38 100644 --- a/golden/golden_test.go +++ b/golden/golden_test.go @@ -211,3 +211,33 @@ func TestFlagUpdate(t *testing.T) { defer undo() assert.Assert(t, FlagUpdate()) } + +func TestUpdate_CreatesPathsAndFile(t *testing.T) { + undo := setUpdateFlag() + defer undo() + + dir := fs.NewDir(t, t.Name()) + + t.Run("creates the file", func(t *testing.T) { + filename := dir.Join("filename") + err := update(filename, nil) + assert.NilError(t, err) + + _, err = os.Stat(filename) + assert.NilError(t, err) + }) + + t.Run("creates directories", func(t *testing.T) { + filename := dir.Join("one/two/filename") + err := update(filename, nil) + assert.NilError(t, err) + + _, err = os.Stat(filename) + assert.NilError(t, err) + + t.Run("no error when directory exists", func(t *testing.T) { + err = update(filename, nil) + assert.NilError(t, err) + }) + }) +}