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
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:
1 parent
1f089888e8
commit
af9eeaab9b
349 files changed
+28341
-1304
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user