1
0
mirror of https://blitiri.com.ar/repos/chasquid synced 2025-12-23 15:37:01 +00:00

safeio: Add tests for error conditions

This patch adds tests to verify how safeio behaves when *os.File
operations return various errors.

To do this, we allow the possibility of wrapping os.CreateTemp, so we
can simulate the errors during testing.

This is not pretty, but the code is small enough that the readability
overhead is minimal, and we get a lot of tests from it.
This commit is contained in:
Alberto Bertogli
2024-03-07 00:26:24 +00:00
parent 06aea2f786
commit 3be7cd5160
2 changed files with 148 additions and 4 deletions

View File

@@ -8,6 +8,21 @@ import (
"syscall"
)
// osFile is an interface to the methods of os.File that we need, so we can
// simulate failures in tests.
type osFile interface {
Name() string
Chmod(os.FileMode) error
Chown(int, int) error
Write([]byte) (int, error)
Close() error
}
var createTemp func(dir, pattern string) (osFile, error) = func(
dir, pattern string) (osFile, error) {
return os.CreateTemp(dir, pattern)
}
// FileOp represents an operation on a file (passed by its name).
type FileOp func(fname string) error
@@ -27,7 +42,7 @@ func WriteFile(filename string, data []byte, perm os.FileMode, ops ...FileOp) er
// would have no expectation of Rename being atomic.
// We make the file names start with "." so there's no confusion with the
// originals.
tmpf, err := os.CreateTemp(path.Dir(filename), "."+path.Base(filename))
tmpf, err := createTemp(path.Dir(filename), "."+path.Base(filename))
if err != nil {
return err
}