feat(app): Jobs › Scheduled and the desktop scheduler
Owner review 2, R10 on the desktop: every timer that queued work out of sight is now a visible, editable schedule of this PC. - DesktopScheduleHost implements IScheduleHost: the PC's time zone, the archive at Settings › Archive's folder (refreshed from archive.json, none while it is offline), and three system schedules: archive-scan (every:<ScanIntervalMinutes>m, seeded once from the old setting, no catch-up), index-backup (every day with catch-up, replacing DatabaseBackups.RunDailyAsync) and housekeeping (daily 04:00 with catch-up: job history 90 days and the new cache-trim step). - AppServices starts the Scheduler after the engine, once the archive was reopened; an unplugged archive is looked for every minute and the scheduler woken when it is back. The rescan loop and the daily backup loop are gone; ApplyJobSettings wakes the scheduler. - CacheStore.Trim brings the cache to Settings › Storage › Cache limit, oldest files first, skipping files in use and the proxies, render-node and server-import folders; CacheTrimStep runs it as a clean-up step. - Jobs gets a Queue | Scheduled segmented control. Scheduled lists the schedules (switch, name, action, when, next run, last result) with Run now, Edit, Reset (system) or Delete (user's, confirmed), the selected schedule's last runs with Show in queue, and an in-window editor that checks every field with the scheduler's limits. Jobs a schedule queued carry a "Scheduled" pill; the history line follows the housekeeping's job-history days. - JobNotices: a scheduled background run raises a toast only when it fails (upkeep stays silent). - Settings › Archive › Rescan every is removed; ScanIntervalMinutes stays only as the seed. Strings in en and it; the others are retranslated. - The capture shows jobs-scheduled and jobs-schedule-editor on a stopped scheduler clock with sample schedules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit e25d812feb3f417cb9251c748c29e8035fd9b03c)
This commit is contained in:
1 parent
75daab7275
commit
bc786c12c4
108 files changed
+3724
-490
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,7 +35,10 @@ 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): its scan schedule queues a scan of it.
|
||||
Assert.True(await services.SchedulerReady, "the schedules started");
|
||||
var scan = Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
|
||||
Assert.Equal(ScheduleOutcome.Queued, (await services.Scheduler!.RunNowAsync(scan.Id, null))?.Outcome);
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while ((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count == 0)
|
||||
{
|
||||
@@ -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,16 @@ 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
|
||||
{
|
||||
|
||||
@@ -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,119 @@
|
||||
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));
|
||||
Assert.Equal(true, 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);
|
||||
}
|
||||
|
||||
[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));
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
@@ -142,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,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,247 @@
|
||||
using System.Globalization;
|
||||
using Chronos.App.Jobs;
|
||||
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));
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user