mirror of
https://github.com/AdguardTeam/AdGuardHome.git
synced 2024-11-24 14:05:45 +03:00
ee619b2dbd
Squashed commit of the following: commit a1bd3c249be043108c84a902d2e88bf80946d444 Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Thu Apr 4 14:59:37 2024 +0300 all: upd more commit 9e55bbb02c2af2064aa2a2ca7b49fd28b544a02c Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Thu Apr 4 14:12:45 2024 +0300 all: upd go code
100 lines
2.1 KiB
Go
100 lines
2.1 KiB
Go
package aghrenameio_test
|
|
|
|
import (
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/AdguardTeam/AdGuardHome/internal/aghrenameio"
|
|
"github.com/AdguardTeam/golibs/errors"
|
|
"github.com/AdguardTeam/golibs/testutil"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
// testPerm is the common permission mode for tests.
|
|
const testPerm fs.FileMode = 0o644
|
|
|
|
// Common file data for tests.
|
|
var (
|
|
initialData = []byte("initial data\n")
|
|
newData = []byte("new data\n")
|
|
)
|
|
|
|
func TestPendingFile(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
targetPath := newInitialFile(t)
|
|
f, err := aghrenameio.NewPendingFile(targetPath, testPerm)
|
|
require.NoError(t, err)
|
|
|
|
_, err = f.Write(newData)
|
|
require.NoError(t, err)
|
|
|
|
err = f.CloseReplace()
|
|
require.NoError(t, err)
|
|
|
|
gotData, err := os.ReadFile(targetPath)
|
|
require.NoError(t, err)
|
|
|
|
assert.Equal(t, newData, gotData)
|
|
}
|
|
|
|
// newInitialFile is a test helper that returns the path to the file containing
|
|
// [initialData].
|
|
func newInitialFile(t *testing.T) (targetPath string) {
|
|
t.Helper()
|
|
|
|
dir := t.TempDir()
|
|
targetPath = filepath.Join(dir, "target")
|
|
|
|
err := os.WriteFile(targetPath, initialData, 0o644)
|
|
require.NoError(t, err)
|
|
|
|
return targetPath
|
|
}
|
|
|
|
func TestWithDeferredCleanup(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const testError errors.Error = "test error"
|
|
|
|
testCases := []struct {
|
|
error error
|
|
name string
|
|
wantErrMsg string
|
|
wantData []byte
|
|
}{{
|
|
name: "success",
|
|
error: nil,
|
|
wantErrMsg: "",
|
|
wantData: newData,
|
|
}, {
|
|
name: "error",
|
|
error: testError,
|
|
wantErrMsg: testError.Error(),
|
|
wantData: initialData,
|
|
}}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
targetPath := newInitialFile(t)
|
|
f, err := aghrenameio.NewPendingFile(targetPath, testPerm)
|
|
require.NoError(t, err)
|
|
|
|
_, err = f.Write(newData)
|
|
require.NoError(t, err)
|
|
|
|
err = aghrenameio.WithDeferredCleanup(tc.error, f)
|
|
testutil.AssertErrorMsg(t, tc.wantErrMsg, err)
|
|
|
|
gotData, err := os.ReadFile(targetPath)
|
|
require.NoError(t, err)
|
|
|
|
assert.Equal(t, tc.wantData, gotData)
|
|
})
|
|
}
|
|
}
|