Skip to content

Commit

Permalink
Test that panicking in the Tx callback properly calls Cancel.
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Jan 14, 2024
1 parent 1cdcc41 commit 7207be4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
6 changes: 3 additions & 3 deletions atomicfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ func New(target string, mode os.FileMode) (*File, error) {
}, nil
}

// Tx calls f with a file constructed by New. If f reports an error, the file
// is automatically cancelled and Tx returns the error from f. Otherwise, Tx
// returns the error from calling Close on the file.
// Tx calls f with a file constructed by New. If f reports an error or panics,
// the file is automatically cancelled and Tx returns the error from f.
// Otherwise, Tx returns the error from calling Close on the file.
func Tx(target string, mode os.FileMode, f func(*File) error) error {
tmp, err := New(target, mode)
if err != nil {
Expand Down
23 changes: 23 additions & 0 deletions atomicfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"testing"

"github.com/creachadair/atomicfile"
"github.com/creachadair/mtest"
)

var (
Expand Down Expand Up @@ -195,6 +196,28 @@ func TestTx(t *testing.T) {
}
checkFile(t, path, 0604, text)
})

t.Run("Panic", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "knucklebones.txt")
v := mtest.MustPanic(t, func() {
atomicfile.Tx(path, 0600, func(*atomicfile.File) error {
panic("ouchies")
})
})

// Make sure we got the panic from the callback.
if s, ok := v.(string); !ok || s != "ouchies" {
t.Errorf("Unexpected panic: %v", v)
}

// Make sure nothing was left in the output directory.
elts, err := os.ReadDir(filepath.Dir(path))
if err != nil {
t.Fatalf("Reading output directory: %v", err)
} else if len(elts) != 0 {
t.Errorf("Unexpected output: %v", elts)
}
})
}

func TestWrite(t *testing.T) {
Expand Down

0 comments on commit 7207be4

Please sign in to comment.