-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_test.go
More file actions
65 lines (61 loc) · 1.77 KB
/
Copy pathfile_test.go
File metadata and controls
65 lines (61 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package editpro
import (
"errors"
"os"
"path/filepath"
"runtime"
"testing"
)
func TestEditFilePreservesMode(t *testing.T) {
path := filepath.Join(t.TempDir(), "input.txt")
if err := os.WriteFile(path, []byte("old old"), 0o640); err != nil {
t.Fatal(err)
}
result, err := EditFile(path, []byte("old"), []byte("new"), ReplaceOptions{ExpectedMatches: 2}, WriteOptions{})
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if string(data) != "new new" || result.Replaced != 2 || info.Mode().Perm() != 0o640 {
t.Fatalf("data=%q result=%#v mode=%o", data, result, info.Mode().Perm())
}
}
func TestEditFileValidationLeavesFileUnchanged(t *testing.T) {
path := filepath.Join(t.TempDir(), "input.txt")
if err := os.WriteFile(path, []byte("old old"), 0o600); err != nil {
t.Fatal(err)
}
_, err := EditFile(path, []byte("old"), []byte("new"), ReplaceOptions{ExpectedMatches: 1}, WriteOptions{})
if err == nil {
t.Fatal("expected an error")
}
data, readErr := os.ReadFile(path)
if readErr != nil || string(data) != "old old" {
t.Fatalf("file changed after validation error: %q, %v", data, readErr)
}
}
func TestEditFileRejectsSymlink(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("symlink creation commonly requires elevated privileges")
}
dir := t.TempDir()
target := filepath.Join(dir, "target")
link := filepath.Join(dir, "link")
if err := os.WriteFile(target, []byte("old"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
_, err := EditFile(link, []byte("old"), []byte("new"), ReplaceOptions{}, WriteOptions{})
if !errors.Is(err, ErrSymlink) {
t.Fatalf("error = %v, want ErrSymlink", err)
}
}