feat: owner review 2 phase 2: scheduled jobs and log settings (#10)
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s

- Jobs > Scheduled on the desktop and the admin panel. Every timer that queued work is now a visible system schedule: archive scan, upload clean-up, index backup, job-history and audit clean-ups, desktop housekeeping. New actions: verify, thumbnails, proxies, analysis, maintenance, backup, clean-ups, reports.
- The scheduler: migration 0007, in-house recurrence, compare-and-set claim, catch-up, scan at start.
- Log settings: levels, retention, size parts, total limit, daily or hourly rotation, audit retention, diagnostics share; the server writes Debug/Trace to its files again; logging never fails a job.

Upgrade: CHRONOS_LOG_LEVEL set in an existing container locks both levels; migration 0007 is one-way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #10.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 11:19:26 +01:00
1 parent 1f089888e8
commit af9eeaab9b
349 files changed
+28341 -1304

No files matched your search

@@ -1,9 +1,11 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Tests.Uploader;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Scheduling;
using Chronos.Testing;
namespace Chronos.App.Tests.Infrastructure;
@@ -21,7 +23,7 @@ public sealed class AppServicesTests
[Test]
[WindowsOnly]
public void ExitStopsPollingAndTheEngineWhileTheUiThreadWaits()
public void ExitStopsTheSchedulesAndTheEngineWhileTheUiThreadWaits()
{
var environment = AppEnvironment.ForCapture();
try
@@ -33,11 +35,14 @@ public sealed class AppServicesTests
await new ArchiveService(setup).CreateAsync(root, "Exit");
var services = new AppServices(environment, new AppSettings { Language = "en", LastArchivePath = root }, () => { }, new NoDialogs());
await services.OpenAsync(environment.DatabasePath);
// The archive was reopened and its first rescan queued: polling now waits for the next one.
// The archive was reopened, then the schedules started (owner review 2, R10) and its scan schedule ran at once,
// as the rescans did at start: a scan of it is queued without waiting for the interval.
Assert.True(await services.SchedulerReady, "the schedules started");
var scan = Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while ((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count == 0)
while (!(await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Any(j => j.ScheduleId == scan.Id))
{
Assert.True(DateTime.UtcNow < until, "no rescan queued");
Assert.True(DateTime.UtcNow < until, "no scan at start");
await Task.Delay(50);
}
@@ -51,10 +56,13 @@ public sealed class AppServicesTests
}
}
/// <summary>BRIEF §7: polling follows the archive folder, also one chosen after the start (first run, Settings, relink).</summary>
/// <summary>
/// BRIEF §7, owner review 2 R10: the scheduled scans follow the archive folder, also one chosen after the start (first
/// run, Settings, relink).
/// </summary>
[Test]
[WindowsOnly]
public void RescansFollowTheArchiveFolderChosenAfterTheStart()
public void ScheduledScansFollowTheArchiveFolderChosenAfterTheStart()
{
var environment = AppEnvironment.ForCapture();
try
@@ -67,20 +75,21 @@ public sealed class AppServicesTests
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.Null(await services.RescanAsync());
// The rescans run all the same: Settings › Archive › Rescan every reaches them.
settings.ScanIntervalMinutes = 30;
services.SaveSettings();
Assert.Equal<TimeSpan?>(TimeSpan.FromMinutes(30), services.PollingPeriod);
Assert.True(await services.SchedulerReady, "the schedules started");
Assert.Null(await services.ScheduleHost.GetArchiveAsync(default));
// The scans run all the same, on the schedule seeded from the former Settings › Archive › Rescan every.
var scan = Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal("every:10m", scan.Recurrence);
Assert.Equal(ScheduleOutcome.SkippedOffline, (await services.Scheduler!.RunNowAsync(scan.Id, null))?.Outcome);
// The first-run dialog creates an archive: the next rescan is of it.
// The first-run dialog creates an archive: the schedules work on it.
var firstRoot = Path.Combine(environment.DataDirectory, "first");
await services.ArchiveSetup.CreateAsync(firstRoot);
var first = Assert.NotNull(await services.RescanAsync());
var first = Assert.NotNull(await services.ScheduleHost.GetArchiveAsync(default));
Assert.Equal("first", first.Name);
// Settings › Archive moves to another archive, which the index lists after the first one: the next rescan
// is of the archive at the folder, no longer of the first one.
// Settings › Archive moves to another archive, which the index lists after the first one: the next scheduled
// scan is of the archive at the folder, no longer of the first one.
var other = Path.Combine(environment.DataDirectory, "zeta");
await new ArchiveService(services.Database!).CreateAsync(other, "zeta");
Assert.Equal("first", (await services.Database!.Archives.ListAsync())[0].Name);
@@ -89,15 +98,57 @@ public sealed class AppServicesTests
var scansOfFirst = await ScansOfAsync(first.Id);
settings.LastArchivePath = other;
services.SaveSettings();
var rescanned = Assert.NotNull(await services.RescanAsync());
var rescanned = Assert.NotNull(await services.ScheduleHost.GetArchiveAsync(default));
Assert.Equal("zeta", rescanned.Name);
Assert.Equal(ScheduleOutcome.Queued, (await services.Scheduler.RunNowAsync(scan.Id, null))?.Outcome);
Assert.True(await ScansOfAsync(rescanned.Id) > 0, "the archive at the folder is rescanned");
Assert.Equal(scansOfFirst, await ScansOfAsync(first.Id));
// And back: the folder decides, whatever the order of the index.
settings.LastArchivePath = firstRoot;
services.SaveSettings();
Assert.Equal(first.Id, (await services.RescanAsync())?.Id);
Assert.Equal(first.Id, (await services.ScheduleHost.GetArchiveAsync(default))?.Id);
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
/// <summary>
/// Owner review 2, R10: when the index does not open, the schedules are known not to run at once, so Jobs › Scheduled
/// says so instead of waiting for them with an empty tab.
/// </summary>
[Test]
[WindowsOnly]
public void AnIndexThatDoesNotOpenTellsTheScheduledTabTheSchedulesDoNotRun()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
// "File is not a database", and no staged restore to recover it.
Directory.CreateDirectory(Path.GetDirectoryName(environment.DatabasePath)!);
await File.WriteAllBytesAsync(environment.DatabasePath, [.. Enumerable.Repeat((byte)0x5A, 8192)]);
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.NotNull(services.OpenError);
var ready = services.SchedulerReady;
Assert.Same(ready, await Task.WhenAny(ready, Task.Delay(TimeSpan.FromSeconds(TestTiming.Budget(10)))));
Assert.False(await ready, "no schedules without an index");
using var schedules = new SchedulesViewModel(() => services.Scheduler, () => services.Database, _ => false, (_, _, _) => { }, _ => Task.CompletedTask);
await schedules.AttachAsync(services.SchedulerReady);
Assert.True(schedules.IsLoaded && schedules.IsUnavailable && !schedules.IsRunning, "the tab shows that the schedules do not run");
}
finally
{
@@ -0,0 +1,77 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Infrastructure;
/// <summary>Owner review 2, R10: the housekeeping trims the cache to its limit, oldest files first, never what is in use or kept whole.</summary>
public sealed class CacheStoreTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 1, 8, 0, 0, DateTimeKind.Utc);
/// <summary>A cache file of <paramref name="bytes"/> last written <paramref name="day"/> days after <see cref="Start"/>.</summary>
private static string Write(string folder, string name, int bytes, int day)
{
var path = Path.Combine(folder, name);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, new byte[bytes]);
File.SetLastWriteTimeUtc(path, Start.AddDays(day));
return path;
}
[Test]
public void TheOldestFilesGoFirstUntilTheCacheFits()
{
var cache = context.CreateTempDirectory("cache");
CacheStore.Prepare(cache);
var oldest = Write(cache, "spill-1.bin", 400, 1);
var older = Write(cache, Path.Combine("render", "spill-2.bin"), 400, 2);
var recent = Write(cache, "spill-3.bin", 400, 3);
var size = CacheStore.Size(cache);
var result = Assert.NotNull(CacheStore.Trim(cache, size - 500));
// 400 bytes were not enough: the two oldest went, the newest and the marker stay.
Assert.Equal((size, 800L, 2), (result.Before, result.Freed, result.Deleted));
Assert.Equal(size - 800, result.After);
Assert.False(File.Exists(oldest));
Assert.False(File.Exists(older));
Assert.True(File.Exists(recent));
Assert.True(CacheStore.IsOwned(cache), "the marker stays");
// Within the limit: nothing to do.
Assert.Equal(0, CacheStore.Trim(cache, 1L << 30)!.Deleted);
}
[Test]
public void FilesInUseAndKeptFoldersStay()
{
var cache = context.CreateTempDirectory("cache");
CacheStore.Prepare(cache);
var proxies = Write(cache, Path.Combine("proxies", "server", "sequence", "frame.jpg"), 1000, 0);
var busy = Write(cache, "spill-busy.bin", 1000, 1);
var free = Write(cache, "spill-free.bin", 1000, 2);
using (new FileStream(busy, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var result = Assert.NotNull(CacheStore.Trim(cache, 0, CacheTrimStep.Kept));
Assert.Equal((1000L, 1), (result.Freed, result.Deleted));
}
Assert.True(File.Exists(proxies), "a kept folder is never trimmed");
Assert.True(File.Exists(busy), "a file in use is skipped");
Assert.False(File.Exists(free));
}
[Test]
public void AFolderChronosDidNotMakeIsLeftAlone()
{
var folder = context.CreateTempDirectory("photos");
var photo = Write(folder, "IMG_0001.JPG", 1000, 0);
Assert.Null(CacheStore.Trim(folder, 0));
Assert.True(File.Exists(photo));
Assert.Equal((0L, 0L, 0), CacheStore.Trim(Path.Combine(folder, "missing"), 0) is { } none ? (none.Before, none.Freed, none.Deleted) : (-1L, -1L, -1));
}
}
@@ -0,0 +1,191 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Housekeeping;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>
/// Owner review 2, R10: the desktop's timers became visible system schedules: the archive scan (seeded once from the
/// former Rescan every setting), the index backup that replaced the daily backup loop, and the housekeeping with the cache
/// trim; the schedules work on the archive at Settings › Archive's folder while it is online.
/// </summary>
public sealed class DesktopScheduleHostTests(TestContext context)
{
[Test]
public async Task TheScanScheduleIsSeededOnceFromTheFormerRescanInterval()
{
var settings = new AppSettings { Language = "en", ScanIntervalMinutes = 30, DeepAnalysisAfterScan = true };
await using var fx = await ScheduleFixture.CreateAsync(context, settings);
var scheduler = await fx.StartAsync();
var scan = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal(("every:30m", false, JobPriority.Background, true, ScheduleActions.Scan), (scan.Recurrence, scan.CatchUp, scan.Priority, scan.Enabled, scan.Action));
// The deep analysis is not frozen into the schedule: each run reads Settings › Analysis › After a scan.
Assert.Null(ScheduleMapping.Parameters(scan).Deep);
Assert.Equal(fx.Clock.Now.AddMinutes(30), scan.NextRun);
// The user edits the schedule in Jobs › Scheduled; the old setting changes (or never changes again): the next
// start keeps the schedule as it is.
Assert.Null((await scheduler.UpdateAsync(scan.Id, new UpdateScheduleRequest(Recurrence: new("every", Every: 2, Unit: "hours")))).Problem);
settings.ScanIntervalMinutes = 5;
await fx.StartAsync();
var kept = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal((scan.Id, "every:2h"), (kept.Id, kept.Recurrence));
Assert.Count(3, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
// Reset goes back to what the host seeds with.
Assert.Null((await fx.Scheduler!.ResetAsync(scan.Id)).Problem);
Assert.Equal("every:5m", (await fx.Db.Schedules.GetAsync(scan.Id))!.Recurrence);
}
/// <summary>
/// Owner review 2, R10: the scheduled scans follow Settings › Analysis › After a scan as it is at each run, like the
/// scans started by hand, so that checkbox's tooltip stays true; and the archive is scanned right after it was opened
/// (once per start, and again when an unplugged archive is back), as the rescans did.
/// </summary>
[Test]
public async Task TheScanRunsAtOnceAndFollowsTheDeepAnalysisSettingAtEachRun()
{
var settings = new AppSettings { Language = "en", DeepAnalysisAfterScan = false };
await using var fx = await ScheduleFixture.CreateAsync(context, settings);
var archive = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "archive"), "archive");
settings.LastArchivePath = archive.RootPath;
var started = fx.Clock.Now;
var scheduler = await fx.StartAsync();
// Right after the start, not one interval later.
var first = Assert.NotNull(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, started));
Assert.Equal(ScheduleOutcome.Queued, first.Outcome);
Assert.False(await DeepAsync(fx, first.JobId!.Value));
Assert.Null(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, started));
// The setting changes after the schedule was seeded: the next run follows it.
settings.DeepAnalysisAfterScan = true;
await fx.Db.Jobs.SetStateAsync(first.JobId!.Value, JobState.Done);
var second = Assert.NotNull(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal(ScheduleOutcome.Queued, second.Outcome);
Assert.True(await DeepAsync(fx, second.JobId!.Value));
Assert.True(fx.Host.DeepAnalysisAfterScan);
// The editor offers no deep switch for a scan (only for an analysis), so a scan schedule never freezes it.
using var vm = await fx.ViewModelAsync();
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Scan);
Assert.True(editor.ShowsForce && !editor.ShowsDeep, "a scan's switches: a full scan only");
}
/// <summary>Whether the scan job <paramref name="id"/> gives what it finds a deep analysis.</summary>
private static async Task<bool> DeepAsync(ScheduleFixture fx, Guid id)
{
var job = Assert.NotNull(await fx.Db.Jobs.GetAsync(id));
Assert.Equal(JobKind.Scan, job.Kind);
using var parameters = System.Text.Json.JsonDocument.Parse(job.ParametersJson!);
return parameters.RootElement.GetProperty("deepAnalysis").GetBoolean();
}
[Test]
public void TheFormerIntervalIsClampedToWhatAnIntervalAccepts()
{
Assert.Equal(ScheduleRecurrence.MinMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings { ScanIntervalMinutes = 1 }));
Assert.Equal(AppSettings.DefaultScanIntervalMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings()));
Assert.Equal(ScheduleRecurrence.MaxMinutes, DesktopScheduleHost.ScanMinutes(new AppSettings { ScanIntervalMinutes = 100_000 }));
}
[Test]
public async Task TheBackupScheduleReplacesTheDailyBackupLoop()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
var scheduler = await fx.StartAsync();
var backup = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup));
Assert.Equal(("every:1d", true, JobPriority.Background, ScheduleActions.Backup), (backup.Recurrence, backup.CatchUp, backup.Priority, backup.Action));
Assert.Equal(DatabaseBackups.Keep, ScheduleMapping.Parameters(backup).Keep);
Assert.Equal(fx.Clock.Now.AddDays(1), backup.NextRun);
// Chronos was closed for two days: the missed copy is made once at start (catch-up, as the housekeeping's run; the
// scan has none and just moves on).
fx.Clock.Advance(TimeSpan.FromDays(2.5));
Assert.Equal(2, await scheduler.RunDueAsync());
var job = (await fx.Db.Jobs.ListByScheduleAsync(backup.Id)).Single();
Assert.Equal((JobKind.Backup, JobPriority.Background, JobState.Queued), (job.Kind, job.Priority, job.State));
Assert.Equal(0, await scheduler.RunDueAsync());
// The engine makes the copy in the backups folder next to the index, as the loop did.
await fx.Engine.StartAsync();
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while ((await fx.Db.Jobs.GetAsync(job.Id))!.State is JobState.Queued or JobState.Running)
{
Assert.True(DateTime.UtcNow < until, "the backup job did not finish");
await Task.Delay(50);
}
Assert.Equal(JobState.Done, (await fx.Db.Jobs.GetAsync(job.Id))!.State);
Assert.Count(1, DatabaseBackups.List(fx.Backups, fx.DatabasePath));
}
/// <summary>
/// The first start after the upgrade: the daily loop made a copy at start once the newest was a day old, so the index
/// backup is seeded due when it is (copied in the first pass); a fresher copy waits for its first day as a new install does.
/// </summary>
[Test]
public async Task TheFirstStartAfterTheUpgradeCopiesWhenTheNewestCopyIsADayOld()
{
await using (var stale = await ScheduleFixture.CreateAsync(context))
{
Directory.CreateDirectory(stale.Backups);
File.WriteAllText(Path.Combine(stale.Backups, $"chronos-{ScheduleFixture.T0.AddDays(-7):yyyyMMdd-HHmmss}-000.db"), "copy");
await stale.StartAsync();
var backup = Assert.NotNull(await stale.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup));
Assert.Equal((ScheduleOutcome.Queued, ScheduleFixture.T0.AddDays(1)), (backup.LastOutcome!, backup.NextRun!.Value));
Assert.Equal(JobKind.Backup, Assert.NotNull(await stale.Db.Jobs.GetAsync(backup.LastJobId!.Value)).Kind);
}
await using var fresh = await ScheduleFixture.CreateAsync(context);
Directory.CreateDirectory(fresh.Backups);
File.WriteAllText(Path.Combine(fresh.Backups, $"chronos-{ScheduleFixture.T0.AddHours(-2):yyyyMMdd-HHmmss}-000.db"), "copy");
await fresh.StartAsync();
var waiting = Assert.NotNull(await fresh.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup));
Assert.Equal(((string?)null, ScheduleFixture.T0.AddDays(1)), (waiting.LastOutcome, waiting.NextRun!.Value));
}
[Test]
public async Task TheHousekeepingRemovesOldHistoryAndTrimsTheCache()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
await fx.StartAsync();
var housekeeping = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.Housekeeping));
Assert.Equal(("daily:04:00", true, ScheduleActions.Cleanup), (housekeeping.Recurrence, housekeeping.CatchUp, housekeeping.Action));
var parameters = ScheduleMapping.Parameters(housekeeping);
Assert.SequenceEqual([CleanupSteps.JobHistory, CacheTrimStep.StepName], parameters.Steps!);
Assert.Equal(CleanupSteps.DefaultHistoryDays, parameters.OlderThanDays);
// The host's step is one the clean-up jobs run, after the shared ones.
Assert.SequenceEqual([CleanupSteps.JobHistory, CleanupSteps.Audit, CleanupSteps.TrashReport, CacheTrimStep.StepName], fx.Host.CleanupSteps);
Assert.Equal(ScheduleRecurrence.DailyAt(new TimeOnly(4, 0)).Next(fx.Clock.Now, TimeZoneInfo.Utc), housekeeping.NextRun);
}
[Test]
public async Task SchedulesWorkOnTheArchiveAtTheFolderWhileItIsOnline()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
Assert.Null(await fx.Host.GetArchiveAsync(context.Cancellation));
var first = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "first"), "first");
var other = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "other"), "other");
// No folder chosen: the first archive of the index; then the one at the folder.
Assert.Equal(first.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
fx.Settings.LastArchivePath = other.RootPath;
Assert.Equal(other.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
// Unplugged: none, so the runs that need it are skipped (and the scheduler logs it) until it is back.
var moved = other.RootPath + "-away";
Directory.Move(other.RootPath, moved);
Assert.Null(await fx.Host.GetArchiveAsync(context.Cancellation));
Directory.Move(moved, other.RootPath);
Assert.Equal(other.Id, (await fx.Host.GetArchiveAsync(context.Cancellation))?.Id);
}
}
@@ -30,6 +30,7 @@ public sealed class JobNoticesTests
[Case(JobKind.LightAnalyse)]
[Case(JobKind.Thumbs)]
[Case(JobKind.Proxies)]
[Case(JobKind.Cleanup)]
public void UpkeepAndScansEndSilently(JobKind kind)
{
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Done)));
@@ -41,6 +42,7 @@ public sealed class JobNoticesTests
[Case(JobKind.Download)]
[Case(JobKind.Duplicates)]
[Case(JobKind.Orphans)]
[Case(JobKind.Backup)]
public void EveryOtherFailureIsSaid(JobKind kind)
{
// An import announces its result on the Import screen, a download on its Library card and Server row.
@@ -140,6 +142,44 @@ public sealed class JobNoticesTests
Assert.Empty(endings.Take(model.IsBusy));
}
/// <summary>Owner review 2, R10: a schedule's background run is said only when it fails, unless the next run repeats it anyway.</summary>
[Theory]
[Case(JobKind.Backup)]
[Case(JobKind.Verify)]
[Case(JobKind.Maintenance)]
[Case(JobKind.Duplicates)]
[Case(JobKind.DeepAnalyse)]
public void AScheduledBackgroundRunIsSaidOnlyWhenItFails(JobKind kind)
{
var schedule = Guid.CreateVersion7();
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Done, JobPriority.Background) with { ScheduleId = schedule }));
Assert.Equal(JobNotice.Failed, JobNotices.For(JobState.Running, Job(kind, JobState.Failed, JobPriority.Background) with { ScheduleId = schedule }));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Failed, Job(kind, JobState.Failed, JobPriority.Background) with { ScheduleId = schedule }));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Cancelled, JobPriority.Background) with { ScheduleId = schedule }));
// The same work queued in the background by something else stays silent.
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Failed, JobPriority.Background)));
}
[Theory]
[Case(JobKind.Scan)]
[Case(JobKind.Thumbs)]
[Case(JobKind.Proxies)]
[Case(JobKind.LightAnalyse)]
[Case(JobKind.Cleanup)]
public void AScheduledUpkeepRunEndsSilently(JobKind kind)
{
var schedule = Guid.CreateVersion7();
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Done, JobPriority.Background) with { ScheduleId = schedule }));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Failed, JobPriority.Background) with { ScheduleId = schedule }));
}
[Test]
public void AScheduledRunAtAHigherPriorityIsSaidAsAnyOther()
{
var verify = Job(JobKind.Verify, JobState.Done, JobPriority.Normal) with { ScheduleId = Guid.CreateVersion7() };
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, verify));
}
private static Job Job(JobKind kind, JobState state, JobPriority priority = JobPriority.User) => new()
{
Id = Guid.CreateVersion7(),
@@ -0,0 +1,97 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Scheduling;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>A clock the test moves by hand; its timers are the system's.</summary>
internal sealed class ManualClock(DateTimeOffset start) : TimeProvider
{
private long _ticks = start.UtcTicks;
public DateTimeOffset Now => GetUtcNow();
public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero);
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
}
/// <summary>
/// The desktop's schedules as <see cref="AppServices"/> composes them, without the shell: an SQLite index file, the archive
/// engine with the cache-trim step and a backups folder, a job engine that is not started (queued jobs stay queued), and a
/// <see cref="Scheduler"/> on <see cref="DesktopScheduleHost"/> with a clock the test moves.
/// </summary>
internal sealed class ScheduleFixture : IAsyncDisposable
{
public static readonly DateTimeOffset T0 = new(2026, 10, 2, 9, 0, 0, TimeSpan.Zero);
private ScheduleFixture(TestContext context, AppSettings settings, ChronosDatabase db, string folder)
{
Context = context;
Settings = settings;
Db = db;
Folder = folder;
Cache = Path.Combine(folder, "cache");
Backups = Path.Combine(folder, DatabaseBackups.DirectoryName);
Archives = new ArchiveService(db, new ArchiveServiceOptions
{
Owner = "test",
CleanupSteps = [new CacheTrimStep(() => Cache, () => CacheLimitBytes)],
BackupDirectory = Backups,
});
Engine = new JobEngine(db, Archives.CreateJobHandlers(), new JobEngineOptions { WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(100) });
Host = new DesktopScheduleHost(settings, () => Db, () => Archives) { TimeZone = TimeZoneInfo.Utc };
}
public TestContext Context { get; }
public AppSettings Settings { get; }
public ChronosDatabase Db { get; }
public string Folder { get; }
public string Cache { get; }
public string Backups { get; }
public long CacheLimitBytes { get; set; } = 1L << 30;
public ArchiveService Archives { get; }
public JobEngine Engine { get; }
public DesktopScheduleHost Host { get; }
public ManualClock Clock { get; } = new(T0);
public Scheduler? Scheduler { get; private set; }
public string DatabasePath => Path.Combine(Folder, "chronos.db");
public static async Task<ScheduleFixture> CreateAsync(TestContext context, AppSettings? settings = null)
{
var folder = context.CreateTempDirectory("schedules");
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation);
return new ScheduleFixture(context, settings ?? new AppSettings { Language = "en" }, db, folder);
}
/// <summary>Starts a scheduler on the host (a previous one is stopped first, as at the next start of the app).</summary>
public async Task<Scheduler> StartAsync()
{
if (Scheduler is not null) await Scheduler.DisposeAsync();
Scheduler = new Scheduler(Db, Engine, new SchedulerOptions { Time = Clock, Tick = TimeSpan.FromHours(1) });
await Scheduler.StartAsync(Host, Context.Cancellation);
return Scheduler;
}
/// <summary>The view model of Jobs › Scheduled on this scheduler; deletes and resets are confirmed with <paramref name="confirm"/>.</summary>
public async Task<SchedulesViewModel> ViewModelAsync(Func<ConfirmRequest, bool>? confirm = null, List<string>? toasts = null)
{
var scheduler = Scheduler ?? await StartAsync();
var vm = new SchedulesViewModel(() => scheduler, () => Db, confirm ?? (_ => true), (title, _, _) => toasts?.Add(title), _ => Task.CompletedTask);
await vm.AttachAsync(Task.FromResult(true));
return vm;
}
public async ValueTask DisposeAsync()
{
if (Scheduler is not null) await Scheduler.DisposeAsync();
await Engine.DisposeAsync();
await Db.DisposeAsync();
}
}
@@ -0,0 +1,79 @@
using System.Globalization;
using Chronos.App.Jobs;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>
/// Jobs › Scheduled in another language (owner review 2, R10). These switch the process-wide UI language, so the class is
/// serial: in parallel it would race with the English assertions of the classes running beside it.
/// </summary>
[Serial]
public sealed class ScheduleLanguageTests(TestContext context)
{
/// <summary>The days of a weekly schedule read in the order of the editor's toggles: from the UI language's first day.</summary>
[Test]
public void WeeklyDaysFollowTheWeekOfTheUiLanguage()
{
var weekend = ScheduleRecurrence.WeeklyAt([DayOfWeek.Saturday, DayOfWeek.Sunday], new TimeOnly(3, 0));
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Equal(DayOfWeek.Sunday, Loc.Culture.DateTimeFormat.FirstDayOfWeek);
Assert.Equal(Loc.L("Jobs.Schedule.DayList", ScheduleText.DayShort(DayOfWeek.Sunday), ScheduleText.DayShort(DayOfWeek.Saturday)),
ScheduleText.Days(weekend.Days));
Assert.Equal(Loc.L("Jobs.Schedule.When.Weekly", ScheduleText.Days(weekend.Days), ScheduleText.Time(new TimeOnly(3, 0))), ScheduleText.When(weekend));
Loc.SetCulture(CultureInfo.GetCultureInfo("it"));
Assert.Equal(DayOfWeek.Monday, Loc.Culture.DateTimeFormat.FirstDayOfWeek);
Assert.Equal(Loc.L("Jobs.Schedule.DayList", ScheduleText.DayShort(DayOfWeek.Saturday), ScheduleText.DayShort(DayOfWeek.Sunday)),
ScheduleText.Days(weekend.Days));
Assert.Equal(Loc.L("Jobs.Schedule.DayList", ScheduleText.DayShort(DayOfWeek.Monday), ScheduleText.DayShort(DayOfWeek.Thursday)),
ScheduleText.Days([DayOfWeek.Thursday, DayOfWeek.Monday]));
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
/// <summary>The editor's dropdowns say their choices in the new language, and keep what was chosen.</summary>
[Test]
public async Task TheOpenEditorSaysItsChoicesInTheNewLanguage()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
await using var fx = await ScheduleFixture.CreateAsync(context);
using var vm = await fx.ViewModelAsync();
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Verify);
editor.SelectedUnit = editor.Units.Single(u => u.Value == RecurrenceUnit.Minutes);
editor.SelectedPriority = editor.Priorities.Single(p => p.Value == JobPriority.Normal);
Assert.Equal(("minutes", "Normal"), (editor.SelectedUnit.Label, editor.SelectedPriority.Label));
var actions = editor.ActionOptions;
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("it"));
Assert.SequenceEqual(Enum.GetValues<RecurrenceUnit>().Select(u => Loc.L("Jobs.Editor.Unit." + u)), editor.Units.Select(u => u.Label));
Assert.SequenceEqual(["In background", "Normale", "Alta"], editor.Priorities.Select(p => p.Label));
Assert.Equal((RecurrenceUnit.Minutes, "minuti"), (editor.SelectedUnit.Value, editor.SelectedUnit.Label));
Assert.Equal((JobPriority.Normal, "Normale"), (editor.SelectedPriority.Value, editor.SelectedPriority.Label));
Assert.True(editor.Units.Any(u => ReferenceEquals(u, editor.SelectedUnit)) && editor.Priorities.Any(p => ReferenceEquals(p, editor.SelectedPriority)),
"the choices are among the new options");
// The actions are new options too, so their dropdown reads their names again.
Assert.False(ReferenceEquals(actions, editor.ActionOptions), "the action list was built again");
Assert.Equal(("Scansione archivio", ScheduleActions.Verify), (editor.ActionOptions[0].Label, editor.SelectedAction.Name));
Assert.True(editor.ActionOptions.Any(o => ReferenceEquals(o, editor.SelectedAction)), "the action is among the new options");
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
}
@@ -0,0 +1,117 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Chronos.App.Jobs;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.App.Tests.Jobs;
/// <summary>
/// Jobs › Scheduled on the capture sample (owner review 2, R10): the tab draws in both themes, every row and control is
/// named and has a tooltip, system rows reset and the user's delete, a schedule's run opens in the Queue tab with its
/// "Scheduled" pill, and the editor opens over the screen.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ScheduledTabTests
{
[Test]
public Task TheScheduledTabListsTheSchedulesAndLeadsToTheirJobs() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
await shell.Jobs.ReloadAsync();
var schedules = shell.Jobs.Schedules;
await schedules.Attached;
await schedules.ReloadAsync();
shell.Navigate(SectionKey.Jobs);
shell.Jobs.TabIndex = 1;
await app.ExpectAsync<SchedulesView>("jobs-scheduled");
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Weekly integrity check", "Monthly orphans report"], schedules.Rows.Select(r => r.Name));
var items = app.FindAll<ListBoxItem>().Where(i => i.DataContext is ScheduleRowViewModel && i.IsVisible).ToList();
Assert.Count(5, items);
foreach (var item in items)
{
var row = (ScheduleRowViewModel)item.DataContext;
Assert.Equal(row.AccessibleName, AutomationProperties.GetName(item));
var controls = Descendants<ButtonBase>(item).Where(b => b.IsVisible).ToList();
// The switch, Run now, Edit, and Reset or Delete.
Assert.Count(4, controls);
Assert.True(controls.All(c => c.ToolTip is not null && AutomationProperties.GetName(c).Contains(row.Name, StringComparison.Ordinal)),
$"every control of {row.Name} has a tooltip and names its row");
var last = Descendants<Button>(item).Last(b => b.IsVisible);
Assert.Equal(Loc.L(row.IsSystem ? "Jobs.Schedule.Reset" : "Jobs.Schedule.Delete"), last.Content);
}
// The queue's toolbar gives way to New schedule.
Assert.True(app.FindAll<Button>().Any(b => b.IsVisible && Equals(b.Content, Loc.L("Jobs.Schedule.New"))), "New schedule is on the toolbar");
Assert.False(app.FindAll<TextBox>().Any(t => t.IsVisible && AutomationProperties.GetName(t) == Loc.L("Jobs.Search")), "the queue's search is hidden");
// The weekly check's run waits in the queue: Show in queue opens it there, expanded.
var weekly = schedules.Rows.Single(r => r.Name == "Weekly integrity check");
schedules.Selected = weekly;
await schedules.RunsLoading;
var run = Assert.NotNull(schedules.Runs.SingleOrDefault());
Assert.Equal(weekly.Schedule.LastJobId, run.Id);
await shell.Jobs.ShowJobAsync(run.Id);
Assert.True(shell.Jobs.IsQueue, "the Queue tab is shown");
var shown = shell.Jobs.Rows.Single(r => r.Id == run.Id);
Assert.True(shown.IsExpanded && shown.IsScheduled, "the job is expanded and marked as scheduled");
await app.ExpectAsync<JobsView>("jobs-from-schedule");
var pills = app.FindAll<Border>().Where(b => b.IsVisible && Equals(b.ToolTip, Loc.L("Tooltips.Jobs.Scheduled"))).ToList();
Assert.True(pills.Count >= 1, "a scheduled job carries the pill");
});
[Test]
public Task TheEditorOpensOverTheScreenAndCloses() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
var schedules = shell.Jobs.Schedules;
await schedules.Attached;
await schedules.ReloadAsync();
shell.Navigate(SectionKey.Jobs);
shell.Jobs.TabIndex = 1;
var weekly = schedules.Rows.Single(r => r.Name == "Weekly integrity check");
weekly.EditCommand.Execute(null);
var editor = Assert.NotNull(schedules.Editor);
Assert.False(shell.Jobs.IsContentEnabled);
await app.ExpectAsync<SchedulesView>("jobs-schedule-editor");
// Weekly, on Sunday at 02:00, verifying 25 % of the sequences unverified for 30 days.
Assert.Equal(2, editor.KindIndex);
Assert.SequenceEqual([DayOfWeek.Sunday], editor.Days.Where(d => d.IsChecked).Select(d => d.Value));
Assert.Equal(("02:00", "30", "25"), (editor.Time.Text, editor.OlderThan.Text, editor.Percent.Text));
var fields = app.FindAll<TextBox>().Where(t => t.IsVisible && t.DataContext is ScheduleEditorViewModel).ToList();
Assert.True(fields.Count >= 4, "name, time, age and share are on screen");
Assert.True(fields.All(t => t.ToolTip is not null && !string.IsNullOrWhiteSpace(AutomationProperties.GetName(t))), "every field is named and has a tooltip");
var toggles = app.FindAll<ToggleButton>().Where(t => t.IsVisible && t.DataContext is ScheduleChoice<DayOfWeek>).ToList();
Assert.Count(7, toggles);
// Unavailable actions are listed disabled: the scheduler answers for this PC.
Assert.True(editor.ActionOptions.Any(a => a.IsAvailable), "actions are available");
editor.CloseCommand.Execute(null);
Assert.Null(schedules.Editor);
Assert.True(shell.Jobs.IsContentEnabled);
});
private static IEnumerable<T> Descendants<T>(DependencyObject node)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is T match) yield return match;
foreach (var nested in Descendants<T>(child)) yield return nested;
}
}
}
@@ -0,0 +1,340 @@
using System.Globalization;
using System.IO;
using Chronos.App.Jobs;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Housekeeping;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Jobs;
/// <summary>Jobs › Scheduled (owner review 2, R10): the list, the switch, the row commands and the editor, on a real scheduler.</summary>
public sealed class SchedulesViewModelTests
{
private readonly TestContext _context;
public SchedulesViewModelTests(TestContext context)
{
_context = context;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
[Test]
public async Task SystemSchedulesComeFirstInTheUsersLanguage()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
Assert.True(vm.IsRunning && vm.IsLoaded && vm.HasRows, "the schedules are listed");
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping"], vm.Rows.Select(r => r.Name));
Assert.SequenceEqual(["Every 10 minutes", "Every day", "Daily at " + ScheduleText.Time(new TimeOnly(4, 0))], vm.Rows.Select(r => r.WhenText));
Assert.SequenceEqual(["Archive scan", "Index backup", "Clean-up"], vm.Rows.Select(r => r.ActionText));
Assert.True(vm.Rows.All(r => r.IsSystem && r.IsEnabled && r.LastText == "never run" && r.LastKind == StatusKind.Offline), "nothing ran yet");
// The scan's next run is ten minutes away, today.
Assert.Equal(ScheduleText.Moment(fx.Clock.Now.AddMinutes(10)), vm.Rows[0].NextText);
Assert.Equal(CleanupSteps.DefaultHistoryDays, vm.HistoryDays);
// A schedule the user creates joins the list after the system ones.
var created = await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Weekly check", ScheduleActions.Verify, new RecurrenceDto("weekly", Time: "02:30", Days: ["mon", "thu"])), null);
Assert.Null(created.Problem);
Assert.Equal("Weekly check", vm.Rows[3].Name);
Assert.Equal(ScheduleText.DayShort(DayOfWeek.Monday) + ", " + ScheduleText.DayShort(DayOfWeek.Thursday) + " at " + ScheduleText.Time(new TimeOnly(2, 30)),
vm.Rows[3].WhenText);
}
[Test]
public void RecurrencesReadAsTheTableShowsThem()
{
var at3 = ScheduleText.Time(new TimeOnly(3, 0));
Assert.Equal("Every 5 minutes", ScheduleText.When(ScheduleRecurrence.Interval(5, RecurrenceUnit.Minutes)));
Assert.Equal("Every hour", ScheduleText.When(ScheduleRecurrence.Interval(1, RecurrenceUnit.Hours)));
Assert.Equal("Every 6 hours", ScheduleText.When(ScheduleRecurrence.Interval(6, RecurrenceUnit.Hours)));
Assert.Equal("Every 2 days", ScheduleText.When(ScheduleRecurrence.Interval(2, RecurrenceUnit.Days)));
Assert.Equal("Daily at " + at3, ScheduleText.When(ScheduleRecurrence.DailyAt(new TimeOnly(3, 0))));
Assert.Equal("Daily at " + at3, ScheduleText.When(ScheduleRecurrence.WeeklyAt(Enum.GetValues<DayOfWeek>(), new TimeOnly(3, 0))));
Assert.Equal("Sun at " + at3, ScheduleText.When(ScheduleRecurrence.WeeklyAt([DayOfWeek.Sunday], new TimeOnly(3, 0))));
Assert.Equal("Monthly, day 1 at " + at3, ScheduleText.When(ScheduleRecurrence.MonthlyAt(1, new TimeOnly(3, 0))));
Assert.Equal("Invalid recurrence", ScheduleText.When(new RecurrenceDto("hourly")));
// Outcomes: the job's state while it is known, else the run's own word.
Assert.Equal("skipped: busy", ScheduleText.Outcome(ScheduleOutcome.SkippedPending, null));
Assert.Equal("failed", ScheduleText.Outcome(ScheduleOutcome.Failed("disk full"), null));
Assert.Equal("queued", ScheduleText.Outcome(ScheduleOutcome.Queued, null));
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Backup, State = JobState.Done };
Assert.Equal("done", ScheduleText.Outcome(ScheduleOutcome.Queued, job));
Assert.Equal(StatusKind.Done, ScheduleText.OutcomeKind(ScheduleOutcome.Queued, job));
Assert.Equal(StatusKind.Failed, ScheduleText.OutcomeKind(ScheduleOutcome.Failed("x"), null));
Assert.Contains("disk full", ScheduleText.OutcomeToolTip(ScheduleOutcome.Failed("disk full"), DateTimeOffset.UtcNow, null));
Assert.Equal("Off", ScheduleText.Next(DateTimeOffset.UtcNow, enabled: false));
Assert.Equal("Cache trim", ScheduleText.Step(CacheTrimStep.StepName));
Assert.Equal("someone-else", ScheduleText.Step("someone-else"));
}
[Test]
public async Task TheSwitchTurnsAScheduleOffAndOn()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
var backup = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.IndexBackup);
await vm.SetEnabledAsync(backup, false);
Assert.False(backup.IsEnabled);
Assert.Equal("Off", backup.NextText);
var stored = (await fx.Db.Schedules.GetAsync(backup.Id))!;
Assert.Equal((false, (DateTimeOffset?)null), (stored.Enabled, stored.NextRun));
await vm.SetEnabledAsync(backup, true);
Assert.True(backup.IsEnabled);
Assert.Equal(fx.Clock.Now.AddDays(1), (await fx.Db.Schedules.GetAsync(backup.Id))!.NextRun);
// The housekeeping turned off keeps every job: the history line says so.
var housekeeping = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.Housekeeping);
await vm.SetEnabledAsync(housekeeping, false);
Assert.Null(vm.HistoryDays);
}
[Test]
public async Task RunNowShowsTheJobsStateAsTheLastResult()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
var toasts = new List<string>();
using var vm = await fx.ViewModelAsync(toasts: toasts);
var backup = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.IndexBackup);
var next = backup.Schedule.NextRun;
await vm.RunNowAsync(backup);
Assert.Equal(ScheduleOutcome.Queued, backup.Schedule.LastOutcome);
Assert.Equal(next, backup.Schedule.NextRun);
Assert.Empty(toasts);
var job = (await fx.Db.Jobs.ListByScheduleAsync(backup.Id)).Single();
Assert.Equal(job.Id, backup.Schedule.LastJobId);
// The Jobs screen forwards the job's changes: the last result follows it, and so do the selected schedule's runs.
vm.Selected = backup;
await vm.RunsLoading;
Assert.SequenceEqual([job.Id], vm.Runs.Select(r => r.Id));
vm.OnJob(job with { State = JobState.Done });
Assert.Equal(("done", StatusKind.Done), (backup.LastText, backup.LastKind));
Assert.Equal("done", vm.Runs[0].StateText);
// Run again while that job is still pending (the engine runs nothing here): nothing new is queued, and a toast says why.
await vm.RunNowAsync(backup);
Assert.Equal(ScheduleOutcome.SkippedPending, backup.Schedule.LastOutcome);
Assert.Count(1, toasts);
Assert.Count(1, await fx.Db.Jobs.ListByScheduleAsync(backup.Id));
}
[Test]
public async Task UsersSchedulesAreDeletedSystemOnesReset()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
var answer = false;
using var vm = await fx.ViewModelAsync(confirm: _ => answer);
await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Orphans", ScheduleActions.Orphans, new RecurrenceDto("monthly", Time: "05:00", DayOfMonth: 1)), null);
var mine = vm.Rows.Single(r => !r.IsSystem);
var scan = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.ArchiveScan);
Assert.False(scan.DeleteCommand.CanExecute(null));
Assert.False(mine.ResetCommand.CanExecute(null));
await vm.DeleteAsync(mine);
Assert.Count(4, vm.Rows);
answer = true;
vm.Selected = mine;
await vm.DeleteAsync(mine);
Assert.Count(3, vm.Rows);
Assert.Null(vm.Selected);
Assert.Null(await fx.Db.Schedules.GetAsync(mine.Id));
await fx.Scheduler.UpdateAsync(scan.Id, new UpdateScheduleRequest(Recurrence: new RecurrenceDto("every", Every: 1, Unit: "hours"), CatchUp: true));
Assert.Equal("Every hour", scan.WhenText);
await vm.ResetAsync(scan);
Assert.Equal(("Every 10 minutes", false), (scan.WhenText, scan.Schedule.CatchUp));
}
/// <summary>A delete the index refuses (busy, locked) keeps the row: the schedule still runs, so it stays in sight.</summary>
[Test]
public async Task ADeleteThatFailsKeepsTheRow()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
var toasts = new List<string>();
using var vm = await fx.ViewModelAsync(toasts: toasts);
await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Orphans", ScheduleActions.Orphans, new RecurrenceDto("monthly", Time: "05:00", DayOfMonth: 1)), null);
var mine = vm.Rows.Single(r => !r.IsSystem);
await using (var session = await fx.Db.Database.OpenAsync(_context.Cancellation))
{
await session.ExecuteScriptAsync("CREATE TRIGGER refuse_delete BEFORE DELETE ON schedules BEGIN SELECT RAISE(ABORT, 'the index is busy'); END;",
_context.Cancellation);
}
await vm.DeleteAsync(mine);
Assert.SequenceEqual([Loc.L("Jobs.Schedule.Failed")], toasts);
Assert.Count(4, vm.Rows);
Assert.Contains(mine, vm.Rows);
Assert.NotNull(await fx.Db.Schedules.GetAsync(mine.Id));
}
/// <summary>
/// Whether this PC runs an action is read again when Jobs › Scheduled is shown: proxies turned on in Settings › Archive
/// make the Proxies schedule runnable and the action selectable, without a restart.
/// </summary>
[Test]
public async Task ShowingTheTabReadsTheActionsAgain()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
var archive = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "archive"), "archive", proxies: new ProxyPolicy { LongEdge = ProxyPolicy.Disabled });
fx.Settings.LastArchivePath = archive.RootPath;
using var vm = await fx.ViewModelAsync();
Assert.Null((await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Proxies", ScheduleActions.Proxies, new RecurrenceDto("daily", Time: "01:00")), null)).Problem);
var proxies = vm.Rows.Single(r => !r.IsSystem);
Assert.False(vm.IsAvailable(ScheduleActions.Proxies));
Assert.False(proxies.RunNowCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Jobs.Schedule.Unavailable.ProxiesDisabled"), proxies.RunNowToolTip);
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
Assert.False(editor.ActionOptions.Single(a => a.Name == ScheduleActions.Proxies).IsAvailable);
await fx.Archives.UpdateSettingsAsync(archive.Id, a => a with { Proxies = a.Proxies with { LongEdge = 1920 } }, _context.Cancellation);
await vm.RefreshActionsAsync();
Assert.True(vm.IsAvailable(ScheduleActions.Proxies));
Assert.True(proxies.RunNowCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Jobs.Schedule.RunNow"), proxies.RunNowToolTip);
Assert.Equal(ScheduleText.ActionToolTip(ScheduleActions.Proxies), proxies.ActionToolTip);
// The open editor follows too; what it had chosen stays chosen.
var chosen = editor.SelectedAction.Name;
Assert.True(editor.ActionOptions.Single(a => a.Name == ScheduleActions.Proxies).IsAvailable);
Assert.Equal(chosen, editor.SelectedAction.Name);
Assert.True(editor.ActionOptions.Any(o => ReferenceEquals(o, editor.SelectedAction)), "the choice is one of the new options");
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Proxies);
Assert.Equal(ScheduleActions.Proxies, editor.SelectedAction.Name);
}
/// <summary>
/// The last result follows the newest news of the last job: a read of it that started before a live change (or before
/// a later read) does not put back an older state.
/// </summary>
[Test]
public async Task AReadOfTheLastJobNeverUndoesANewerChange()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Backup, State = JobState.Running };
// A row of its own: the view model reads nothing into it meanwhile.
var row = new ScheduleRowViewModel(vm.Rows[1].Schedule with { LastOutcome = ScheduleOutcome.Queued, LastJobId = job.Id }, vm);
// The job ends while it is read: the engine's Done comes first, the read's Running after it.
var read = row.BeginLastJobRead();
row.SetLastJob(job with { State = JobState.Done });
row.SetLoadedLastJob(job, read);
Assert.Equal(("done", StatusKind.Done), (row.LastText, row.LastKind));
// Two reads: the later one wins, whichever ends first.
var first = row.BeginLastJobRead();
var second = row.BeginLastJobRead();
row.SetLoadedLastJob(job with { State = JobState.Failed }, second);
row.SetLoadedLastJob(job, first);
Assert.Equal(StatusKind.Failed, row.LastKind);
// A read of the job of the previous run does not apply once the schedule has run again.
var stale = row.BeginLastJobRead();
row.Update(row.Schedule with { LastJobId = Guid.CreateVersion7() });
row.SetLoadedLastJob(job with { State = JobState.Done }, stale);
Assert.Null(row.LastJob);
Assert.Equal(("queued", StatusKind.Queued), (row.LastText, row.LastKind));
}
[Test]
public async Task TheEditorChecksEachFieldAndBuildsTheRecurrence()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
Assert.True(editor.IsNew && !editor.IsSystem && editor.CanChangeAction, "a new schedule of the user");
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.NameMissing"), editor.Problem());
Assert.False(editor.SaveCommand.CanExecute(null));
editor.Name.Text = "Nightly thumbnails";
Assert.Null(editor.Problem());
Assert.Equal(new RecurrenceDto("daily", Time: "03:00"), editor.Recurrence());
// Every: the unit decides the range.
editor.KindIndex = 0;
editor.SelectedUnit = editor.Units.Single(u => u.Value == RecurrenceUnit.Minutes);
editor.Every.Text = "3";
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.Number", "5", "1440"), editor.Problem());
Assert.Equal("—", editor.WhenText);
editor.SelectedUnit = editor.Units.Single(u => u.Value == RecurrenceUnit.Hours);
Assert.Null(editor.Problem());
Assert.Equal("Every 3 hours", editor.WhenText);
// Weekly: a time and at least one day.
editor.KindIndex = 2;
foreach (var day in editor.Days) day.IsChecked = false;
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.NoDays"), editor.Problem());
editor.Days.Single(d => d.Value == DayOfWeek.Thursday).IsChecked = true;
editor.Days.Single(d => d.Value == DayOfWeek.Monday).IsChecked = true;
editor.Time.Text = "25:00";
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.TimeInvalid"), editor.Problem());
editor.Time.Text = "2:30";
Assert.Equal("weekly:mon,thu@02:30", ScheduleMapping.FromDto(editor.Recurrence())!.Format());
// Monthly: days 1 to 28.
editor.KindIndex = 3;
editor.DayOfMonth.Text = "31";
Assert.NotNull(editor.Problem());
editor.DayOfMonth.Text = "28";
Assert.Equal("monthly:28@02:30", ScheduleMapping.FromDto(editor.Recurrence())!.Format());
// The action's own parameters, from its defaults.
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Verify);
Assert.True(editor.ShowsOlderThan && editor.ShowsPercent && !editor.ShowsSteps, "verify's parameters");
Assert.Equal(("30", "100"), (editor.OlderThan.Text, editor.Percent.Text));
editor.Percent.Text = "0";
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.Number", "1", "100"), editor.Problem());
editor.Percent.Text = "25";
Assert.Equal(new ScheduleParametersDto(OlderThanDays: 30, Percent: 25), editor.Parameters());
editor.SelectedPriority = editor.Priorities.Single(p => p.Value == JobPriority.Normal);
editor.CatchUp = false;
Assert.True(editor.SaveCommand.CanExecute(null), "the schedule can be saved");
await editor.SaveAsync();
Assert.Null(vm.Editor);
var saved = vm.Rows.Single(r => !r.IsSystem);
Assert.Equal((ScheduleActions.Verify, "monthly:28@02:30", "normal", false), (saved.Schedule.Action, ScheduleMapping.FromDto(saved.Schedule.Recurrence)!.Format(),
saved.Schedule.Priority, saved.Schedule.CatchUp));
Assert.Equal(new ScheduleParametersDto(OlderThanDays: 30, Percent: 25), saved.Schedule.Parameters);
Assert.Same(saved, vm.Selected);
}
[Test]
public async Task ASystemScheduleKeepsItsNameAndActionInTheEditor()
{
await using var fx = await ScheduleFixture.CreateAsync(_context);
using var vm = await fx.ViewModelAsync();
var housekeeping = vm.Rows.Single(r => r.Schedule.SystemKey == DesktopScheduleHost.Housekeeping);
housekeeping.EditCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
Assert.True(editor.IsSystem && !editor.CanChangeAction, "a system schedule");
Assert.Equal("Housekeeping", editor.SystemName);
// The steps this PC runs, the schedule's own checked.
Assert.SequenceEqual([CleanupSteps.JobHistory, CleanupSteps.Audit, CleanupSteps.TrashReport, CacheTrimStep.StepName], editor.Steps.Select(s => s.Value));
Assert.SequenceEqual([CleanupSteps.JobHistory, CacheTrimStep.StepName], editor.Steps.Where(s => s.IsChecked).Select(s => s.Value));
foreach (var step in editor.Steps) step.IsChecked = false;
Assert.Equal(Loc.L("Tooltips.Jobs.Editor.NoSteps"), editor.Problem());
editor.Steps[0].IsChecked = true;
editor.OlderThan.Text = "30";
var update = editor.BuildUpdate();
Assert.Equal(((string?)null, (string?)null), (update.Name, update.Action));
await editor.SaveAsync();
Assert.Null(vm.Editor);
Assert.Equal(30, vm.HistoryDays);
Assert.SequenceEqual([CleanupSteps.JobHistory], housekeeping.Schedule.Parameters.Steps!);
Assert.Equal("Housekeeping", housekeeping.Name);
}
}
@@ -0,0 +1,221 @@
using System.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.App.Tests.Settings;
/// <summary>Settings › Advanced › Logs (owner review 2, R11): the stored values, the file options they become and the rows.</summary>
public sealed class LogSettingsTests
{
private readonly TestContext _context;
public LogSettingsTests(TestContext context)
{
_context = context;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
[Test]
public void LogSettingsSurviveTheSettingsFileAndOlderFilesGetTheDefaults()
{
var settings = new AppSettings
{
LogLevel = LogLevel.Debug,
LogRetentionDays = 30,
LogMaxFileMb = 0,
LogMaxTotalMb = 2048,
LogRotation = LogRotation.Hourly,
DiagnosticsLogMb = 16,
};
var json = settings.ToJson();
Assert.Contains("\"LogLevel\": \"Debug\"", json);
Assert.Contains("\"LogRotation\": \"Hourly\"", json);
foreach (var copy in new[] { AppSettings.Parse(json)!, settings.Clone() })
{
Assert.Equal((LogLevel.Debug, 30, 0, 2048, LogRotation.Hourly, 16),
(copy.LogLevel, copy.LogRetentionDays, copy.LogMaxFileMb, copy.LogMaxTotalMb, copy.LogRotation, copy.DiagnosticsLogMb));
}
// A settings file written before these rows existed (or exported by such a copy) keeps the former behaviour's defaults.
var older = AppSettings.Parse("""{ "Theme": "Light" }""")!;
Assert.Equal((LogLevel.Info, 14, 50, 1024, LogRotation.Daily, 4),
(older.LogLevel, older.LogRetentionDays, older.LogMaxFileMb, older.LogMaxTotalMb, older.LogRotation, older.DiagnosticsLogMb));
}
[Test]
public void TheSettingsBecomeTheLogFileOptions()
{
Assert.Equal(new LogFileOptions(), AppLogging.Options(new AppSettings()));
Assert.Equal(4L << 20, AppLogging.DiagnosticsTailBytes(new AppSettings()));
var tuned = new AppSettings { LogLevel = LogLevel.Warning, LogRetentionDays = 3, LogMaxFileMb = 10, LogMaxTotalMb = 0, LogRotation = LogRotation.Hourly };
Assert.Equal(new LogFileOptions { Level = LogLevel.Warning, RetentionDays = 3, MaxFileMb = 10, MaxTotalMb = 0, Rotation = LogRotation.Hourly },
AppLogging.Options(tuned));
// A hand-edited file never makes the sink keep nothing or delete everything.
var odd = new AppSettings { LogLevel = (LogLevel)42, LogRetentionDays = 0, LogMaxFileMb = -3, LogMaxTotalMb = -1, LogRotation = (LogRotation)7, DiagnosticsLogMb = 0 };
Assert.Equal(new LogFileOptions { RetentionDays = 1, MaxFileMb = 0, MaxTotalMb = 0 }, AppLogging.Options(odd));
Assert.Equal(1L << 20, AppLogging.DiagnosticsTailBytes(odd));
var huge = new AppSettings { LogRetentionDays = 99_999, LogMaxFileMb = 99_999, LogMaxTotalMb = int.MaxValue, DiagnosticsLogMb = 5000 };
Assert.Equal(new LogFileOptions { RetentionDays = 3650, MaxFileMb = 10_240, MaxTotalMb = 1_048_576 }, AppLogging.Options(huge));
Assert.Equal(1024L << 20, AppLogging.DiagnosticsTailBytes(huge));
// A total below one file would delete each finished file as the next one opens: it is raised to the file (the
// server refuses it). Without a file limit any total holds.
Assert.True(LogFileOptions.TotalBelowFile(500, 256));
Assert.False(LogFileOptions.TotalBelowFile(256, 256) || LogFileOptions.TotalBelowFile(500, 0) || LogFileOptions.TotalBelowFile(0, 256));
var below = AppLogging.Options(new AppSettings { LogMaxFileMb = 500, LogMaxTotalMb = 256 });
Assert.Equal((500, 500), (below.MaxFileMb, below.MaxTotalMb));
var free = AppLogging.Options(new AppSettings { LogMaxFileMb = 0, LogMaxTotalMb = 256 });
Assert.Equal((0, 256), (free.MaxFileMb, free.MaxTotalMb));
var level = Log.MinimumLevel;
using var sink = new FileLogSink(_context.CreateTempDirectory(), "chronos");
try
{
AppLogging.Apply(sink, tuned);
Assert.Equal(AppLogging.Options(tuned), sink.Options);
Assert.Equal(LogLevel.Warning, Log.MinimumLevel);
}
finally
{
Log.MinimumLevel = level;
}
}
[Test]
public void TheLogFilesStartWithTheSettings()
{
// App opens its files with the settings: the first line opens a file and prunes, at every start and at every launch
// that only hands over to the running Chronos, so the defaults would delete what the user keeps longer.
var level = Log.MinimumLevel;
try
{
foreach (var (settings, kept) in new[] { (new AppSettings { LogLevel = LogLevel.Debug, LogRetentionDays = 365, LogMaxTotalMb = 0 }, true), (new AppSettings(), false) })
{
var dir = _context.CreateTempDirectory();
var old = Path.Combine(dir, $"chronos-{DateTime.UtcNow.AddDays(-30):yyyyMMdd}.log");
File.WriteAllText(old, "a month ago");
File.SetLastWriteTimeUtc(old, DateTime.UtcNow.AddDays(-30));
using var sink = AppLogging.Open(dir, settings);
Assert.Equal((AppLogging.Options(settings), settings.LogLevel), (sink.Options, Log.MinimumLevel));
sink.Write(LogLevel.Info, "app", "Chronos starting", null);
Assert.Equal(kept, File.Exists(old), $"retention {settings.LogRetentionDays} days");
Assert.FileExists(sink.CurrentPath);
}
}
finally
{
Log.MinimumLevel = level;
}
}
[Test]
public void EachRowStoresAndSavesItsChoice()
{
var settings = new AppSettings();
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
var changed = new List<string?>();
rows.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
Assert.SequenceEqual(["Trace", "Debug", "Information", "Warning", "Error"], rows.Levels.Select(l => l.Label));
Assert.Equal(("Information", "14 days", "50 MB", "1,024 MB", "Daily", "4 MB"), (rows.SelectedLevel.Label, rows.SelectedRetention.Label,
rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedRotation.Label, rows.SelectedDiagnostics.Label));
Assert.Equal("1 day", rows.RetentionChoices[0].Label);
// "No limit" closes both size lists.
Assert.Equal((0, "No limit"), (rows.FileSizeChoices[^1].Value, rows.FileSizeChoices[^1].Label));
Assert.Equal(0, rows.TotalSizeChoices[^1].Value);
Assert.SequenceEqual(["Daily", "Hourly"], rows.Rotations.Select(r => r.Label));
rows.SelectedLevel = rows.Levels.Single(l => l.Value == LogLevel.Debug);
rows.SelectedRetention = rows.RetentionChoices.Single(c => c.Value == 90);
rows.SelectedFileSize = rows.FileSizeChoices[^1];
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 5120);
rows.SelectedRotation = rows.Rotations.Single(r => r.Value == LogRotation.Hourly);
rows.SelectedDiagnostics = rows.DiagnosticsChoices.Single(c => c.Value == 16);
Assert.Equal((LogLevel.Debug, 90, 0, 5120, LogRotation.Hourly, 16),
(settings.LogLevel, settings.LogRetentionDays, settings.LogMaxFileMb, settings.LogMaxTotalMb, settings.LogRotation, settings.DiagnosticsLogMb));
Assert.Equal(6, saves);
// A size changes the choices of the other.
Assert.SequenceEqual(["SelectedLevel", "SelectedRetention", "SelectedFileSize", "TotalSizeChoices", "SelectedTotalSize", "SelectedTotalSize",
"FileSizeChoices", "SelectedFileSize", "SelectedRotation", "SelectedDiagnostics"], changed);
// The same choice again, or none (a list being rebuilt), changes nothing.
rows.SelectedLevel = rows.Levels.Single(l => l.Value == LogLevel.Debug);
rows.SelectedRotation = null!;
Assert.Equal(6, saves);
// Values set elsewhere are listed in order with the presets.
settings.LogRetentionDays = 45;
settings.LogMaxTotalMb = 3000;
Assert.SequenceEqual([1, 3, 7, 14, 30, 45, 90, 365], rows.RetentionChoices.Select(c => c.Value));
Assert.Equal("45 days", rows.SelectedRetention.Label);
Assert.SequenceEqual([256, 512, 1024, 2048, 3000, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
// Reset section on Advanced: the defaults, shown at once; the caller saves.
changed.Clear();
rows.Reset();
Assert.Equal((LogLevel.Info, 14, 50, 1024, LogRotation.Daily, 4),
(settings.LogLevel, settings.LogRetentionDays, settings.LogMaxFileMb, settings.LogMaxTotalMb, settings.LogRotation, settings.DiagnosticsLogMb));
Assert.Equal(string.Empty, changed.Single());
Assert.Equal(6, saves);
}
[Test]
public void TheSizeRowsNeverOfferATotalBelowOneFile()
{
var settings = new AppSettings { LogMaxFileMb = 500 };
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
Assert.SequenceEqual([512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
Assert.SequenceEqual([10, 20, 50, 100, 200, 500, 0], rows.FileSizeChoices.Select(c => c.Value));
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 512);
rows.SelectedFileSize = rows.FileSizeChoices.Single(c => c.Value == 100);
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 256);
Assert.Equal((100, 256, 3), (settings.LogMaxFileMb, settings.LogMaxTotalMb, saves));
Assert.SequenceEqual([10, 20, 50, 100, 200, 0], rows.FileSizeChoices.Select(c => c.Value));
// Without a file limit every total is offered, and without a total every file size.
rows.SelectedFileSize = rows.FileSizeChoices[^1];
Assert.SequenceEqual([256, 512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
rows.SelectedTotalSize = rows.TotalSizeChoices[^1];
Assert.SequenceEqual([10, 20, 50, 100, 200, 500, 0], rows.FileSizeChoices.Select(c => c.Value));
// An imported file with a total below its file size shows the total the files get.
settings.LogMaxFileMb = 500;
settings.LogMaxTotalMb = 256;
Assert.Equal(("500 MB", "500 MB"), (rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label));
Assert.SequenceEqual([500, 512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
}
[Test]
public void OutOfRangeValuesShowWhatTheFilesGet()
{
// A hand-edited or imported settings file: every row shows the value applied, and none fails to find its choice.
var settings = new AppSettings { LogLevel = (LogLevel)42, LogRetentionDays = 0, LogMaxFileMb = -3, LogMaxTotalMb = -1, LogRotation = (LogRotation)7, DiagnosticsLogMb = 0 };
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
Assert.Equal(("Information", "1 day", "No limit", "No limit", "Daily", "1 MB"), (rows.SelectedLevel.Label, rows.SelectedRetention.Label,
rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedRotation.Label, rows.SelectedDiagnostics.Label));
Assert.SequenceEqual(LogSettingsRows.RetentionPresets, rows.RetentionChoices.Select(c => c.Value));
Assert.SequenceEqual([.. LogSettingsRows.FileSizePresets, 0], rows.FileSizeChoices.Select(c => c.Value));
Assert.SequenceEqual(LogSettingsRows.DiagnosticsPresets, rows.DiagnosticsChoices.Select(c => c.Value));
// Choosing the value shown saves it as applied.
var (shownFile, shownRetention) = (rows.SelectedFileSize, rows.SelectedRetention);
rows.SelectedFileSize = shownFile;
rows.SelectedRetention = shownRetention;
Assert.Equal((0, 1, 2), (settings.LogMaxFileMb, settings.LogRetentionDays, saves));
settings.LogRetentionDays = 99_999;
settings.LogMaxFileMb = 99_999;
settings.LogMaxTotalMb = int.MaxValue;
settings.DiagnosticsLogMb = 5000;
Assert.Equal(("3650 days", "10,240 MB", "1,048,576 MB", "1,024 MB"),
(rows.SelectedRetention.Label, rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedDiagnostics.Label));
}
}
@@ -80,10 +80,13 @@ public sealed class SettingsScreenSmokeTests
var data = Field(app, Loc.L("Settings.Advanced.DataFolder"));
Assert.Equal(FlowDirection.LeftToRight, data.FlowDirection);
Assert.Equal(settings.DataFolder, data.ToolTip);
// Advanced has nothing to reset: no Reset section there.
Assert.False(settings.CanResetSection);
Assert.False(settings.ResetSectionCommand.CanExecute(null));
Assert.False(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "no Reset section on Advanced");
// Advanced's Reset section puts its log rows back to their defaults (owner review 2, R11).
Assert.True(settings.CanResetSection);
Assert.True(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "a Reset section on Advanced");
settings.Logs.SelectedRotation = settings.Logs.Rotations.Single(r => r.Value == Chronos.Core.Diagnostics.LogRotation.Hourly);
Assert.Equal(Chronos.Core.Diagnostics.LogRotation.Hourly, shell.Services.Settings.LogRotation);
settings.ResetSectionCommand.Execute(null);
Assert.Equal(Chronos.Core.Diagnostics.LogRotation.Daily, shell.Services.Settings.LogRotation);
// Forgetting a trusted certificate asks first, as on the Server screen; a "no" keeps it and the session.
settings.Page = SettingsPage.Server;