using Chronos.Core.IO; using Chronos.Testing; namespace Chronos.Core.Tests.Foundation; public sealed class AtomicFileTests(TestContext context) { [Test] public void ReplacesContentAndLeavesNoTemporaryFiles() { var dir = context.CreateTempDirectory(); var path = Path.Combine(dir, "sequence.json"); AtomicFile.WriteAllText(path, "one"); AtomicFile.WriteAllText(path, "two"); Assert.Equal("two", File.ReadAllText(path)); Assert.Count(1, Directory.GetFiles(dir)); } [Test] [WindowsOnly] public void AReadOnlyTargetFailsAtOnceAndTheTemporaryFileGoes() { // Only a handle that holds the target clears by itself (owner review 1); a read-only file never does, so the write // must not keep the caller waiting (a settings field on the UI thread, a pass over hundreds of sidecars). var dir = context.CreateTempDirectory(); var path = Path.Combine(dir, "settings.json"); AtomicFile.WriteAllText(path, "stable"); File.SetAttributes(path, FileAttributes.ReadOnly); try { var clock = System.Diagnostics.Stopwatch.StartNew(); Assert.Throws(() => AtomicFile.WriteAllText(path, "new")); Assert.Less(clock.Elapsed.TotalMilliseconds, 500, "no retries"); Assert.Equal("stable", File.ReadAllText(path)); Assert.Count(1, Directory.GetFiles(dir)); } finally { File.SetAttributes(path, FileAttributes.Normal); } } [Test] public void ReadsAreWholeAndShareTheFileWithOtherReaders() { var dir = context.CreateTempDirectory(); var path = Path.Combine(dir, "project.json"); File.WriteAllText(path, "é"); using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { // A byte order mark is read as File.ReadAllText reads it. Assert.Equal("é", AtomicFile.ReadAllText(path)); Assert.SequenceEqual(File.ReadAllBytes(path), AtomicFile.ReadAllBytes(path)); } File.WriteAllText(path, string.Empty); Assert.Equal(string.Empty, AtomicFile.ReadAllText(path)); Assert.Empty(AtomicFile.ReadAllBytes(path)); } [Test] public async Task FailedWriteKeepsPreviousContent() { var dir = context.CreateTempDirectory(); var path = Path.Combine(dir, "project.json"); AtomicFile.WriteAllText(path, "stable"); await Assert.ThrowsAsync(() => AtomicFile.WriteAsync(path, async (s, ct) => { await s.WriteAsync("partial"u8.ToArray(), ct); throw new InvalidOperationException("boom"); })); Assert.Equal("stable", File.ReadAllText(path)); Assert.Count(1, Directory.GetFiles(dir)); } }