返回 DeepSeek-Reasonix
atomicwrite_test.go
根目录 / internal / fileutil / atomicwrite_test.go
1 package fileutil
2
3 import (
4 "errors"
5 "os"
6 "path/filepath"
7 "runtime"
8 "syscall"
9 "testing"
10 "time"
11 )
12
13 func TestReplaceFileNoRetryWhenTmpMissing(t *testing.T) {
14 oldBase := replaceRetryBase
15 replaceRetryBase = 10 * time.Second
16 t.Cleanup(func() { replaceRetryBase = oldBase })
17
18 dir := t.TempDir()
19 start := time.Now()
20 err := ReplaceFile(filepath.Join(dir, "missing.tmp"), filepath.Join(dir, "x.txt"))
21 if err == nil {
22 t.Fatal("want error when tmp source is missing")
23 }
24 if elapsed := time.Since(start); elapsed > time.Second {
25 t.Errorf("missing tmp should fail fast, took %v — it retried", elapsed)
26 }
27 }
28
29 func TestReplaceFileRetriesThenReturnsError(t *testing.T) {
30 oldBase, oldMax := replaceRetryBase, maxReplaceRetries
31 replaceRetryBase, maxReplaceRetries = 0, 3
32 t.Cleanup(func() { replaceRetryBase, maxReplaceRetries = oldBase, oldMax })
33
34 dir := t.TempDir()
35 tmp := filepath.Join(dir, "x.tmp")
36 if err := os.WriteFile(tmp, []byte("payload"), 0o644); err != nil {
37 t.Fatal(err)
38 }
39 dest := filepath.Join(dir, "blocked")
40 if err := os.Mkdir(dest, 0o755); err != nil {
41 t.Fatal(err)
42 }
43 if err := ReplaceFile(tmp, dest); err == nil {
44 t.Fatal("want error when dest can never be replaced")
45 }
46 if !fileExists(tmp) {
47 t.Error("tmp should survive a failed replace so the next launch can retry")
48 }
49 }
50
51 func TestReplaceFileRenamesInPlace(t *testing.T) {
52 dir := t.TempDir()
53 tmp := filepath.Join(dir, "x.tmp")
54 dest := filepath.Join(dir, "x.txt")
55 if err := os.WriteFile(tmp, []byte("hello"), 0o644); err != nil {
56 t.Fatal(err)
57 }
58 if err := ReplaceFile(tmp, dest); err != nil {
59 t.Fatal(err)
60 }
61 if b, _ := os.ReadFile(dest); string(b) != "hello" {
62 t.Errorf("dest = %q, want hello", b)
63 }
64 if _, err := os.Stat(tmp); !os.IsNotExist(err) {
65 t.Error("tmp should be gone after ReplaceFile")
66 }
67 }
68
69 func TestReplaceFileTransientFailureNeverTruncatesDest(t *testing.T) {
70 // A rename blocked by a transient lock must surface the error, never fall
71 // back to the in-place copy: the copy truncates dest first, so a reader
72 // racing it can observe an empty or half-written file — the torn state
73 // AtomicWriteFile promises its callers (session leases, credentials,
74 // plugin state) can never happen.
75 oldBase, oldMax, oldRename := replaceRetryBase, maxReplaceRetries, renameFile
76 replaceRetryBase, maxReplaceRetries = 0, 2
77 renameCalls := 0
78 renameFile = func(oldpath, newpath string) error {
79 renameCalls++
80 return &os.LinkError{Op: "rename", Old: oldpath, New: newpath, Err: errors.New("transient sharing violation")}
81 }
82 t.Cleanup(func() { replaceRetryBase, maxReplaceRetries, renameFile = oldBase, oldMax, oldRename })
83
84 dir := t.TempDir()
85 tmp := filepath.Join(dir, "x.tmp")
86 dest := filepath.Join(dir, "x.txt")
87 if err := os.WriteFile(tmp, []byte("new"), 0o644); err != nil {
88 t.Fatal(err)
89 }
90 if err := os.WriteFile(dest, []byte("old"), 0o644); err != nil {
91 t.Fatal(err)
92 }
93 if err := ReplaceFile(tmp, dest); err == nil {
94 t.Fatal("want the rename error to surface once retries are exhausted")
95 }
96 if want := maxReplaceRetries + 1; renameCalls != want {
97 t.Errorf("rename attempts = %d, want %d (initial try plus retries)", renameCalls, want)
98 }
99 if b, _ := os.ReadFile(dest); string(b) != "old" {
100 t.Fatalf("dest = %q, want the old content intact — anything else means the non-atomic copy ran", b)
101 }
102 if !fileExists(tmp) {
103 t.Error("tmp should survive a failed replace so the caller can clean up")
104 }
105 }
106
107 func TestReplaceFileCrossDeviceCopiesImmediately(t *testing.T) {
108 // The cross-device class (Windows encryption filter drivers, #2696) fails
109 // identically on every retry, so ReplaceFile must take the copy fallback
110 // straight away instead of sleeping through the retry ladder.
111 oldBase, oldMax, oldRename := replaceRetryBase, maxReplaceRetries, renameFile
112 // Any retry sleep would trip the elapsed-time check below.
113 replaceRetryBase, maxReplaceRetries = 10*time.Second, 8
114 renameCalls := 0
115 renameFile = func(oldpath, newpath string) error {
116 renameCalls++
117 return &os.LinkError{Op: "rename", Old: oldpath, New: newpath, Err: syscall.EXDEV}
118 }
119 t.Cleanup(func() { replaceRetryBase, maxReplaceRetries, renameFile = oldBase, oldMax, oldRename })
120
121 dir := t.TempDir()
122 tmp := filepath.Join(dir, "x.tmp")
123 dest := filepath.Join(dir, "x.txt")
124 if err := os.WriteFile(tmp, []byte("new"), 0o644); err != nil {
125 t.Fatal(err)
126 }
127 if err := os.WriteFile(dest, []byte("old"), 0o644); err != nil {
128 t.Fatal(err)
129 }
130 start := time.Now()
131 if err := ReplaceFile(tmp, dest); err != nil {
132 t.Fatalf("ReplaceFile should succeed via the copy fallback: %v", err)
133 }
134 if renameCalls != 1 {
135 t.Errorf("rename attempts = %d, want 1 — a structurally impossible rename must not be retried", renameCalls)
136 }
137 if elapsed := time.Since(start); elapsed > time.Second {
138 t.Errorf("cross-device fallback took %v — it slept through the retry ladder", elapsed)
139 }
140 if b, _ := os.ReadFile(dest); string(b) != "new" {
141 t.Errorf("dest = %q, want the new content from the copy fallback", b)
142 }
143 if fileExists(tmp) {
144 t.Error("tmp should be consumed by the copy fallback")
145 }
146 }
147
148 func TestAtomicWriteFileStrictCrossDeviceKeepsExistingDestination(t *testing.T) {
149 oldRename := renameFile
150 renameFile = func(oldpath, newpath string) error {
151 return &os.LinkError{Op: "rename", Old: oldpath, New: newpath, Err: syscall.EXDEV}
152 }
153 t.Cleanup(func() { renameFile = oldRename })
154
155 dir := t.TempDir()
156 dest := filepath.Join(dir, "current.json")
157 if err := os.WriteFile(dest, []byte("old-pointer"), 0o644); err != nil {
158 t.Fatal(err)
159 }
160 if err := AtomicWriteFileStrict(dest, []byte("new-pointer"), 0o644); err == nil {
161 t.Fatal("strict atomic write accepted a cross-device rename")
162 }
163 if got, err := os.ReadFile(dest); err != nil || string(got) != "old-pointer" {
164 t.Fatalf("destination changed after strict replace failure: %q, %v", got, err)
165 }
166 entries, err := os.ReadDir(dir)
167 if err != nil {
168 t.Fatal(err)
169 }
170 if len(entries) != 1 || entries[0].Name() != "current.json" {
171 t.Fatalf("strict write left temporary files: %v", entries)
172 }
173 }
174
175 func TestCopyOntoOverwritesAndPreservesMode(t *testing.T) {
176 dir := t.TempDir()
177 tmp := filepath.Join(dir, "x.tmp")
178 dest := filepath.Join(dir, "x.txt")
179 if err := os.WriteFile(tmp, []byte("new"), 0o600); err != nil {
180 t.Fatal(err)
181 }
182 if err := os.WriteFile(dest, []byte("old-and-longer"), 0o644); err != nil {
183 t.Fatal(err)
184 }
185 if err := copyOnto(tmp, dest); err != nil {
186 t.Fatal(err)
187 }
188 if b, _ := os.ReadFile(dest); string(b) != "new" {
189 t.Errorf("dest = %q, want new (fully overwritten)", b)
190 }
191 if _, err := os.Stat(tmp); !os.IsNotExist(err) {
192 t.Error("tmp should be removed after copyOnto")
193 }
194 // Mode preservation is meaningful on Unix; Windows only tracks the read-only bit.
195 if info, err := os.Stat(dest); err == nil && info.Mode().Perm() != 0o600 {
196 t.Logf("dest mode = %o (want 0600 on Unix)", info.Mode().Perm())
197 }
198 }
199
200 func TestAtomicWriteFileReplacesExisting(t *testing.T) {
201 dir := t.TempDir()
202 path := filepath.Join(dir, "config.toml")
203 if err := os.WriteFile(path, []byte("old"), 0o644); err != nil {
204 t.Fatal(err)
205 }
206 if err := AtomicWriteFile(path, []byte("new-content"), 0o600); err != nil {
207 t.Fatalf("AtomicWriteFile: %v", err)
208 }
209 got, err := os.ReadFile(path)
210 if err != nil {
211 t.Fatal(err)
212 }
213 if string(got) != "new-content" {
214 t.Fatalf("content = %q, want %q", got, "new-content")
215 }
216 info, err := os.Stat(path)
217 if err != nil {
218 t.Fatal(err)
219 }
220 if perm := info.Mode().Perm(); runtime.GOOS != "windows" && perm != 0o600 {
221 t.Fatalf("perm = %o, want 600", perm)
222 }
223 // No leftover tmp files in the directory.
224 entries, _ := os.ReadDir(dir)
225 for _, e := range entries {
226 if e.Name() != "config.toml" {
227 t.Fatalf("unexpected leftover file: %s", e.Name())
228 }
229 }
230 }
231
232 func TestAtomicWriteFileCreatesParentDir(t *testing.T) {
233 dir := t.TempDir()
234 path := filepath.Join(dir, "nested", "deep", "creds")
235 if err := AtomicWriteFile(path, []byte("x"), 0o600); err != nil {
236 t.Fatalf("AtomicWriteFile into missing dir: %v", err)
237 }
238 if _, err := os.Stat(path); err != nil {
239 t.Fatalf("file not created: %v", err)
240 }
241 }
242
243 func TestAtomicCreateFileNeverOverwritesExisting(t *testing.T) {
244 dir := t.TempDir()
245 path := filepath.Join(dir, "config.toml")
246 if err := os.WriteFile(path, []byte("concurrent"), 0o600); err != nil {
247 t.Fatal(err)
248 }
249 if err := AtomicCreateFile(path, []byte("confirmed"), 0o600); err == nil {
250 t.Fatal("AtomicCreateFile overwrote an existing target")
251 }
252 if got, err := os.ReadFile(path); err != nil || string(got) != "concurrent" {
253 t.Fatalf("existing target changed: %q, %v", got, err)
254 }
255 entries, err := os.ReadDir(dir)
256 if err != nil {
257 t.Fatal(err)
258 }
259 if len(entries) != 1 || entries[0].Name() != "config.toml" {
260 t.Fatalf("temporary files leaked: %v", entries)
261 }
262 }
263
264 func TestAtomicCreateFilePublishesCompleteContent(t *testing.T) {
265 path := filepath.Join(t.TempDir(), "nested", "config.toml")
266 if err := AtomicCreateFile(path, []byte("confirmed"), 0o600); err != nil {
267 t.Fatal(err)
268 }
269 if got, err := os.ReadFile(path); err != nil || string(got) != "confirmed" {
270 t.Fatalf("created target = %q, %v", got, err)
271 }
272 }
273
273 lines GO