Owner review 2, phase 2 (R10) review findings on the desktop: - Showing the Scheduled tab (and coming back to Jobs on it) reads the actions' availability again, as does a Run now answered unavailable; rows and an open editor follow, so turning proxies on no longer needs a restart. - A delete the index refuses keeps the row: the failed call no longer reads as Deleted (the enum's default), so a live schedule never leaves the page. - SchedulerReady completes false when the index (or the engine) does not open, so the tab shows that the schedules do not run instead of an empty panel. - A read of a schedule's last job that started before a live change or a later read is ignored, so a finished job no longer shows as running. - The editor's Action, Unit and Priority dropdowns follow a language change, keeping what was chosen. - Weekly days in the table read from the UI language's first day, as the editor's toggles do. - Backup tooltips no longer promise daily copies with three kept (their translations are dropped for retranslation); two tooltips now name the real Settings rows (Proxy size; Spazio su disco › Limite della cache). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit c137e2c74cddef299b2e4179ef0417fa4977953c)
341 lines
19 KiB
C#
341 lines
19 KiB
C#
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);
|
||
}
|
||
}
|