using System.Text.RegularExpressions; using AttendanceHub.Sync.Host; using Xunit; namespace AttendanceHub.Sync.Tests; /// /// Guards the service log rotation added after the unbounded-growth incident /// (attendancehub_sync.log reached 53 MB in ~6 days with no rotation). /// public class RotatingFileWriterTests : IDisposable { private readonly string _dir = Path.Combine(Path.GetTempPath(), "ah_rot_" + Guid.NewGuid().ToString("N")); public RotatingFileWriterTests() => Directory.CreateDirectory(_dir); public void Dispose() { try { Directory.Delete(_dir, recursive: true); } catch { /* best effort */ } } [Fact] public void StaysUnderMaxBytes_AndKeepsRotatedHistory() { var path = Path.Combine(_dir, "svc.log"); // 64 KB floor is the constructor minimum; write well past 3× 64 KB. const long maxBytes = 64 * 1024; const int keep = 2; using (var w = new RotatingFileWriter(path, maxBytes, keep)) { var line = new string('x', 1024); // ~1 KB per line for (var i = 0; i < 512; i++) // ~512 KB total → must rotate several times w.WriteLine(line); } Assert.True(File.Exists(path), "active log must exist"); var active = new FileInfo(path).Length; Assert.True(active <= maxBytes + 1024, $"active log must stay near the cap but was {active} bytes"); Assert.True(File.Exists(path + ".1"), "first rotated file must exist"); // Note: Windows GetFiles("svc.log.*") also matches "svc.log" itself (8.3 quirk), // so filter to genuinely rotated names. var rotated = new DirectoryInfo(_dir).GetFiles() .Where(f => Regex.IsMatch(f.Name, @"^svc\.log\.\d+$")) .ToArray(); Assert.True(rotated.Length <= keep, $"rotation must cap history at {keep} files but found {rotated.Length}: " + string.Join(", ", rotated.Select(f => $"{f.Name}={f.Length}"))); foreach (var f in rotated) Assert.True(f.Length <= maxBytes + 1024, $"rotated file {f.Name} must respect the cap but was {f.Length} bytes"); } [Fact] public void WritesBelowCap_DoNotRotate() { var path = Path.Combine(_dir, "quiet.log"); using (var w = new RotatingFileWriter(path, 64 * 1024, 2)) w.WriteLine("hello"); Assert.True(File.Exists(path)); Assert.False(File.Exists(path + ".1"), "no rotation should happen below the cap"); Assert.Contains("hello", File.ReadAllText(path)); } [Fact] public void AppendsToExistingFile_AndCountsItsSize() { var path = Path.Combine(_dir, "append.log"); File.WriteAllText(path, new string('a', 100)); using (var w = new RotatingFileWriter(path, 64 * 1024, 2)) w.WriteLine("second"); var text = File.ReadAllText(path); Assert.StartsWith("aaa", text); Assert.Contains("second", text); } }