Files
Chronos/tests/Chronos.App.Tests/Jobs/SchedulesViewModelTests.cs
T
Alby96 bc786c12c4 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)
2026-10-27 02:26:07 +01:00

248 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
}