You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.7 KiB
64 lines
1.7 KiB
package atomicfile
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"testing"
|
|
)
|
|
|
|
func TestWriteAtomicallyReplacesProtectedFile(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "state.json")
|
|
if err := os.WriteFile(path, []byte("old"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := Write(path, []byte("new\n"), 0o600); err != nil {
|
|
t.Fatalf("Write() error = %v", err)
|
|
}
|
|
content, err := os.ReadFile(path)
|
|
if err != nil || string(content) != "new\n" {
|
|
t.Fatalf("content = %q, %v", content, err)
|
|
}
|
|
if runtime.GOOS != "windows" {
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := info.Mode().Perm(); got != 0o600 {
|
|
t.Fatalf("mode = %o, want 600", got)
|
|
}
|
|
}
|
|
matches, err := filepath.Glob(filepath.Join(filepath.Dir(path), ".tera-store-*"))
|
|
if err != nil || len(matches) != 0 {
|
|
t.Fatalf("temporary files = %v, %v", matches, err)
|
|
}
|
|
}
|
|
|
|
func TestWriteRefusesNonRegularDestination(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "state")
|
|
if err := os.Mkdir(path, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := Write(path, []byte("new"), 0o600); err == nil {
|
|
t.Fatal("Write() replaced a directory")
|
|
}
|
|
}
|
|
|
|
func TestWriteRefusesSymbolicLinkDestination(t *testing.T) {
|
|
root := t.TempDir()
|
|
target := filepath.Join(root, "target.json")
|
|
link := filepath.Join(root, "state.json")
|
|
if err := os.WriteFile(target, []byte("preserve"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Symlink(target, link); err != nil {
|
|
t.Skipf("symbolic links unavailable: %v", err)
|
|
}
|
|
if err := Write(link, []byte("replace"), 0o600); err == nil {
|
|
t.Fatal("Write() followed a symbolic link")
|
|
}
|
|
content, err := os.ReadFile(target)
|
|
if err != nil || string(content) != "preserve" {
|
|
t.Fatalf("target content = %q, %v", content, err)
|
|
}
|
|
}
|
|
|