feat: owner review 2 phase 1: :latest, Unraid array space, Settings with About, whole-folder import (#9)
CI / Build and test (push) Successful in 5m11s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 8m57s
CI / PostgreSQL 16 integration (push) Successful in 3m10s
CI / PostgreSQL 17 integration (push) Successful in 3m30s
CI / Docker image (push) Successful in 49s
Release / Server image (push) Successful in 1m4s
CI / Build and test (push) Successful in 5m11s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 8m57s
CI / PostgreSQL 16 integration (push) Successful in 3m10s
CI / PostgreSQL 17 integration (push) Successful in 3m30s
CI / Docker image (push) Successful in 49s
Release / Server image (push) Successful in 1m4s
- :latest follows the highest stable release, or the highest pre-release while none is stable (Chronos.Tools release-channels); bad tags are refused before anything is built. - Unraid: CHRONOS_SPACE_PATH and the template's Array view show the array's free space; the write volume (cache) is shown apart; completions check the archive volume (507). - Settings is a gear, docked at the foot of the admin sidebar; About is the last part of Settings on the desktop and the panel. - Import > Folder > Whole folder: one sequence per format (desktop only). 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 #9.
This commit is contained in:
1 parent
5acdf146c7
commit
1f089888e8
320 files changed
+3030
-927
No files matched your search
@@ -94,6 +94,16 @@ public sealed class ImportChoicesTests
|
||||
Assert.SequenceEqual([fresh.Id], joined.Without(own.Id).Cards);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheGroupingTravelsToThePlannerButNeverIntoACardProfile()
|
||||
{
|
||||
var whole = new ImportChoices { Grouping = ImportGrouping.WholeFolder };
|
||||
Assert.Equal(ImportGrouping.WholeFolder, whole.ToOptions().Grouping);
|
||||
Assert.Equal(ImportGrouping.Sessions, new ImportChoices().ToOptions().Grouping, "a source starts with its sessions");
|
||||
Assert.True(whole.NeedsNewPlan(new ImportChoices()), "the grouping changes which photos form which sequence");
|
||||
Assert.Equal(ImportGrouping.Sessions, ImportChoices.FromProfile(whole.ToProfile()).Grouping, "a card always imports by sessions");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SplitsAndMergesTravelToThePlanner()
|
||||
{
|
||||
|
||||
@@ -46,6 +46,9 @@ public sealed class ImportLanguageTests
|
||||
var time = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>())[0].TimeText;
|
||||
Assert.Contains("←", time);
|
||||
Assert.False(time.Contains('→'), "a right-to-left reader would see the arrow point back to the start");
|
||||
var days = ImportPlans.Sessions(OverEightDays(), ImportDestinationKind.Archive, new HashSet<string>())[0].TimeText;
|
||||
Assert.Contains("←", days);
|
||||
Assert.False(days.Contains('→'), "also between two dates");
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Testing;
|
||||
@@ -20,6 +22,10 @@ public sealed class ImportPlansTests
|
||||
Session(3, "2026/2026-09-30 Canon EOS R5", Item(7, Start.AddDays(2), action: ImportAction.SkipImported)));
|
||||
}
|
||||
|
||||
/// <summary>A whole folder shot over eight days, as one sequence.</summary>
|
||||
internal static ImportPlan OverEightDays() =>
|
||||
Plan(null, null, Session(1, "2026/Construction", Item(1, Start), Item(2, Start.AddDays(8).AddMinutes(3)))) with { Grouping = ImportGrouping.WholeFolder };
|
||||
|
||||
[Test]
|
||||
public void TotalsCountWhatIsCopiedSkippedAndDuplicated()
|
||||
{
|
||||
@@ -104,6 +110,21 @@ public sealed class ImportPlansTests
|
||||
Assert.Equal("Server", ImportPlans.Sessions(plan, ImportDestinationKind.Server, new HashSet<string>())[0].TargetText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASessionThatEndsOnAnotherDayShowsBothDates()
|
||||
{
|
||||
var plan = OverEightDays();
|
||||
var end = Start.AddDays(8).AddMinutes(3);
|
||||
var time = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>())[0].TimeText;
|
||||
Assert.Equal($"{Formatting.Date(Start)} {Start.ToString("t", Loc.Culture)} → {Formatting.Date(end)} {end.ToString("t", Loc.Culture)}", time);
|
||||
Assert.Equal(Loc.L("Import.Details.Session", 1, time), ImportPlans.Details(plan, ImportDestinationKind.Archive, verify: true).Rows[0].SourceText,
|
||||
"the Show plan heading reads the same");
|
||||
|
||||
var sameDay = ImportPlans.Sessions(ThreeSessions(), ImportDestinationKind.Archive, new HashSet<string>())[0].TimeText;
|
||||
Assert.Equal($"{Formatting.Date(Start)} · {Start.ToString("t", Loc.Culture)} → {Start.AddSeconds(8).ToString("t", Loc.Culture)}", sameDay,
|
||||
"a session within one day shows its date once");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShowPlanListsEveryFileItsDestinationAndTheConflicts()
|
||||
{
|
||||
@@ -175,6 +196,51 @@ public sealed class ImportPlansTests
|
||||
Assert.Equal(1, split[2].MergesInto, "the earlier session of the same body, skipping the other camera");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AWholeFolderRowShowsItsFormatAndCamerasWithTheFolderNameAsDefaultTitle()
|
||||
{
|
||||
var jpeg = Session(1, "2026/2026-09-28 Canon EOS R5", Item(1, Start), Item(2, Start.AddHours(5))) with
|
||||
{
|
||||
SessionKey = "folder-jpeg",
|
||||
Format = ImageFileFormat.Jpeg,
|
||||
Cameras = 2,
|
||||
Title = "Etna",
|
||||
DefaultTitle = "Etna",
|
||||
};
|
||||
var raw = Session(2, "2026/2026-09-28 Canon EOS R5 (2)", Item(3, Start), Item(4, Start.AddHours(5))) with
|
||||
{
|
||||
SessionKey = "folder-raw",
|
||||
Title = "Etna",
|
||||
DefaultTitle = "Etna",
|
||||
};
|
||||
var plan = Plan(null, null, jpeg, raw) with { Grouping = ImportGrouping.WholeFolder };
|
||||
|
||||
var rows = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>());
|
||||
Assert.Equal("2 cameras · JPEG", rows[0].CameraText);
|
||||
Assert.Equal("Canon EOS R5 · CR2", rows[1].CameraText);
|
||||
Assert.Null(rows[0].Title, "the folder's name is the placeholder, not typed text");
|
||||
Assert.Equal("Etna", rows[0].DefaultTitle);
|
||||
Assert.Null(rows[1].MergesInto, "another format never merges");
|
||||
var bySessions = ImportPlans.Sessions(plan with { Grouping = ImportGrouping.Sessions }, ImportDestinationKind.Archive, new HashSet<string>());
|
||||
Assert.Equal("Canon EOS R5", bySessions[1].CameraText);
|
||||
|
||||
var titled = ImportPlans.WithTitles(plan, new Dictionary<string, string> { ["folder-jpeg"] = "Etna at night" });
|
||||
Assert.Equal("Etna at night", titled.Sessions[0].Title);
|
||||
Assert.Equal("Etna", titled.Sessions[1].Title, "a sequence without a typed title keeps the folder's name");
|
||||
Assert.Equal("Etna at night", ImportPlans.Sessions(titled, ImportDestinationKind.Archive, new HashSet<string>())[0].Title);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AWholeFolderPartMergesBackIntoThePartBeforeItOfTheSameFormatWhateverItsCamera()
|
||||
{
|
||||
var first = Session(1, "2026/Etna", Item(1, Start));
|
||||
var second = Session(2, "2026/Etna (2)", Item(2, Start.AddHours(1))) with { CameraMake = "Nikon", CameraModel = "NIKON Z 8" };
|
||||
var plan = Plan(null, null, first, second) with { Grouping = ImportGrouping.WholeFolder };
|
||||
Assert.Equal(1, ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>())[1].MergesInto);
|
||||
Assert.Null(ImportPlans.Sessions(plan with { Grouping = ImportGrouping.Sessions }, ImportDestinationKind.Archive, new HashSet<string>())[1].MergesInto,
|
||||
"sessions of another camera never merge");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShowPlanOffersASplitOnEveryPhotoButTheFirstOfItsSession()
|
||||
{
|
||||
|
||||
@@ -9,6 +9,7 @@ using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Sections;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Tests.Windows;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Controls;
|
||||
@@ -222,6 +223,75 @@ public sealed class ImportScreenSmokeTests
|
||||
await import.WaitForPlanAsync();
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// "Group" (BRIEF §12.4) is offered for a picked folder only, and a card is always planned by sessions. Switching the
|
||||
/// grouping drops the splits made on the other grouping's sessions, and the session controls it turns off say why.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task AWholeFolderIsOfferedForAFolderOnlyAndDropsTheSplitsMadeBefore() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
var import = app.Shell.Import;
|
||||
var card = SampleCards.Card(app.Services.Environment.DataDirectory);
|
||||
|
||||
// A card: no Group choice, and asking for a whole folder changes nothing.
|
||||
await ShowAsync(app, "plan");
|
||||
Assert.False(import.CanGroupFolder);
|
||||
import.GroupWholeFolder = true;
|
||||
Assert.True(import.GroupBySessions);
|
||||
Assert.Equal(ImportGrouping.Sessions, import.Choices.Grouping);
|
||||
Assert.True(import.SessionsApply);
|
||||
|
||||
// The card's photos picked as a folder start by sessions: night, dawn and sunset.
|
||||
await import.ImportFolderAsync(card.Root);
|
||||
await import.WaitForPlanAsync();
|
||||
Assert.True(import.CanGroupFolder);
|
||||
Assert.True(import.GroupBySessions);
|
||||
Assert.Equal((ImportGrouping.Sessions, 3), (import.Plan!.Grouping, import.Plan.Sessions.Count));
|
||||
|
||||
// The sunset split in two halves of twelve photos.
|
||||
import.ShowPlanCommand.Execute(null);
|
||||
import.SplitCommand.Execute(import.Details!.Rows.Where(r => r.Kind == PlanRowKind.File).ToList()[^12]);
|
||||
await import.WaitForPlanAsync();
|
||||
Assert.Equal(4, import.Plan!.Sessions.Count, "the split starts a session");
|
||||
|
||||
// The whole folder is one sequence for its one format, not cut where the sessions were split.
|
||||
import.GroupWholeFolder = true;
|
||||
await WaitUntilAsync(app, () => import.Plan is { Grouping: ImportGrouping.WholeFolder } && import.Phase == ImportPhase.Ready, "the whole folder is planned");
|
||||
Assert.Equal(ImportGrouping.WholeFolder, import.Choices.Grouping);
|
||||
Assert.Equal(1, import.Plan!.Sessions.Count);
|
||||
Assert.False(import.SessionsApply);
|
||||
Assert.False(import.GapApplies);
|
||||
var why = Loc.L("Import.Blocked.WholeFolder");
|
||||
Assert.Equal((why, why, why), (import.SessionsToolTip, import.GapMinutes.ToolTip, import.MinimumFrames.ToolTip));
|
||||
var boxes = app.FindAll<TextBox>().Where(t => IsInImport(t) && EditBehavior.GetField(t) is { } f && (f == import.GapMinutes || f == import.MinimumFrames)).ToList();
|
||||
Assert.Equal(2, boxes.Count);
|
||||
foreach (var box in boxes)
|
||||
{
|
||||
Assert.False(box.IsEnabled);
|
||||
Assert.True(ToolTipService.GetShowOnDisabled(box), "a disabled session box still shows why");
|
||||
Assert.Equal(why, box.ToolTip as string);
|
||||
}
|
||||
|
||||
// Back to sessions: the split made before stays gone.
|
||||
import.GroupBySessions = true;
|
||||
await WaitUntilAsync(app, () => import.Plan is { Grouping: ImportGrouping.Sessions } && import.Phase == ImportPhase.Ready, "the sessions are planned again");
|
||||
Assert.Equal(3, import.Plan!.Sessions.Count);
|
||||
Assert.True(import.SessionsApply);
|
||||
Assert.Equal(Loc.L("Tooltips.Import.Gap"), import.GapMinutes.ToolTip);
|
||||
|
||||
// Choosing the card again leaves the folder's whole-folder choice behind.
|
||||
import.GroupWholeFolder = true;
|
||||
await WaitUntilAsync(app, () => import.Plan is { Grouping: ImportGrouping.WholeFolder } && import.Phase == ImportPhase.Ready, "the whole folder is planned");
|
||||
import.SelectSource(card.Identity);
|
||||
await import.WaitForPlanAsync();
|
||||
Assert.False(import.CanGroupFolder);
|
||||
Assert.True(import.GroupBySessions);
|
||||
Assert.Equal(ImportGrouping.Sessions, import.Choices.Grouping);
|
||||
Assert.Equal((ImportGrouping.Sessions, 3), (import.Plan!.Grouping, import.Plan.Sessions.Count));
|
||||
});
|
||||
|
||||
/// <summary>As <c>--capture</c> does: toasts of the previous state go, those of an insertion state stay.</summary>
|
||||
private static async Task ShowAsync(ScreenSmokeTests.SampleApp app, string state)
|
||||
{
|
||||
|
||||
@@ -46,6 +46,39 @@ public sealed class ServerImportSinkTests(TestContext context)
|
||||
Assert.Empty(Directory.EnumerateFileSystemEntries(staging));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWholeFolderImportedAgainKeepsTheNameItsSequenceWasGivenOnTheServer()
|
||||
{
|
||||
var folder = Card(Path.Combine(context.CreateTempDirectory("folder"), "Etna"), 4, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 4096);
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var destination = new UnindexedDestination(ImportDestinationKind.Server, staging);
|
||||
var options = new ImportChoices { Grouping = ImportGrouping.WholeFolder }.ToOptions();
|
||||
|
||||
var first = await destination.PlanAsync(folder, options, null, null, context.Cancellation);
|
||||
await LocalImport.RunAsync(first, new ServerImportSink(client, staging), "Etna", verify: true, null, context.Cancellation);
|
||||
var (sequence, title) = server.Titles.Single();
|
||||
Assert.Equal("Etna", title, "a new sequence takes the folder's name");
|
||||
|
||||
// Renamed on the server; a photo added to the folder joins the same sequence and leaves its name alone.
|
||||
server.Titles[sequence] = "Etna 2026 eruption";
|
||||
var photos = Path.Combine(folder, "DCIM", "100CANON");
|
||||
File.WriteAllBytes(Path.Combine(photos, "IMG_0005.JPG"), Jpeg(Start.AddMinutes(10), 5));
|
||||
var again = await destination.PlanAsync(folder, options, null, null, context.Cancellation);
|
||||
var outcome = await LocalImport.RunAsync(again, new ServerImportSink(client, staging), "Etna", verify: true, null, context.Cancellation);
|
||||
Assert.Equal((1, 4), (outcome.Copied, outcome.Duplicates));
|
||||
Assert.Equal("Etna 2026 eruption", server.Titles[sequence]);
|
||||
Assert.Equal(1, server.TitleUpdates, "only the new sequence was named");
|
||||
|
||||
// A title the user types still names it.
|
||||
File.WriteAllBytes(Path.Combine(photos, "IMG_0006.JPG"), Jpeg(Start.AddMinutes(20), 6));
|
||||
var typed = ImportPlans.WithTitles(await destination.PlanAsync(folder, options, null, null, context.Cancellation),
|
||||
new Dictionary<string, string> { [again.Sessions[0].SessionKey] = "Etna at night" });
|
||||
await LocalImport.RunAsync(typed, new ServerImportSink(client, staging), "Etna", verify: true, null, context.Cancellation);
|
||||
Assert.Equal("Etna at night", server.Titles.Single().Value);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PhotosTheServerAlreadyHoldsAreNotSentAgain()
|
||||
{
|
||||
@@ -233,7 +266,7 @@ public sealed class ServerImportSinkTests(TestContext context)
|
||||
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
|
||||
}
|
||||
|
||||
/// <summary>Start, chunk and complete of BRIEF §14.4, plus the title update and card reports; the hash is checked at completion.</summary>
|
||||
/// <summary>Start, chunk and complete of BRIEF §14.4, plus the sequence's title and card reports; the hash is checked at completion.</summary>
|
||||
private sealed class FakeUploadServer(int chunkSize) : HttpMessageHandler
|
||||
{
|
||||
private readonly Dictionary<Guid, Upload> _open = [];
|
||||
@@ -241,7 +274,11 @@ public sealed class ServerImportSinkTests(TestContext context)
|
||||
private readonly Dictionary<string, Guid> _frames = new(StringComparer.Ordinal);
|
||||
|
||||
public List<Upload> Committed { get; } = [];
|
||||
|
||||
/// <summary>Each sequence's title on the server (a test may rename one, as a user would there).</summary>
|
||||
public Dictionary<Guid, string> Titles { get; } = [];
|
||||
|
||||
public int TitleUpdates { get; private set; }
|
||||
public int ChunkCount { get; private set; }
|
||||
|
||||
/// <summary>Flip a byte of every chunk of this file (a damaged transfer).</summary>
|
||||
@@ -321,16 +358,21 @@ public sealed class ServerImportSinkTests(TestContext context)
|
||||
return Json(new CompleteUploadResponse(frame, sequence, Committed.Count(u => u.SessionKey == upload.SessionKey) - 1),
|
||||
ProtocolJson.Default.CompleteUploadResponse);
|
||||
}
|
||||
if (request.Method == HttpMethod.Get && path is ["api", "v1", "sequences", var read])
|
||||
return Json(Sequence(Guid.Parse(read), Titles.GetValueOrDefault(Guid.Parse(read))), ProtocolJson.Default.SequenceDto);
|
||||
if (request.Method == HttpMethod.Patch && path is ["api", "v1", "sequences", var sequenceId])
|
||||
{
|
||||
var update = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.UpdateSequenceRequest, cancellationToken))!;
|
||||
Titles[Guid.Parse(sequenceId)] = update.Title!;
|
||||
return Json(new SequenceDto(Guid.Parse(sequenceId), update.Title, update.Title!, "f", null, null, null, null, null, 0, null, 0, 0, 0, null, [], 0, null,
|
||||
1, 1, 0, null, DateTimeOffset.UtcNow), ProtocolJson.Default.SequenceDto);
|
||||
TitleUpdates++;
|
||||
return Json(Sequence(Guid.Parse(sequenceId), update.Title), ProtocolJson.Default.SequenceDto);
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
private static SequenceDto Sequence(Guid id, string? title) =>
|
||||
new(id, title, title ?? "f", "f", null, null, null, null, null, 0, null, 0, 0, 0, null, [], 0, null, 1, 1, 0, null, DateTimeOffset.UtcNow);
|
||||
|
||||
private static HttpResponseMessage Json<T>(T value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> type, HttpStatusCode status = HttpStatusCode.OK) =>
|
||||
new(status) { Content = JsonContent.Create(value, type) };
|
||||
|
||||
|
||||
@@ -308,6 +308,18 @@ public sealed class SettingsLogicTests
|
||||
Assert.Equal(("Not supported", "—", "—", false), (none.TierText, none.DecoderText, none.NeedsText, none.HasNeeds));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASettingsPageIsFoundOnlyByTheRowsItShows()
|
||||
{
|
||||
// About's translation row shows outside English only: its keyword is read at each search, not once (owner review 2).
|
||||
var shown = false;
|
||||
var about = new SettingsPageItem(SettingsPage.About, () => shown ? ["About.Translation"] : []);
|
||||
Assert.False(about.Matches(Loc.L("About.Translation")), "a hidden row does not match");
|
||||
shown = true;
|
||||
Assert.True(about.Matches(Loc.L("About.Translation")));
|
||||
Assert.True(new SettingsPageItem(SettingsPage.About, ["About.Build"]).Matches(Loc.L("About.Build")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EnumDrivenKeysExistInEveryRequiredLanguage()
|
||||
{
|
||||
|
||||
@@ -320,14 +320,62 @@ public sealed class SettingsScreenSmokeTests
|
||||
app.Shell.CompleteWelcome();
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task AboutIsTheLastSettingsPageAndOffersNothingTwice() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
// Owner review 2, R5: About left the rail for the end of Settings; Settings alone docks at the bottom of the rail.
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
var settings = shell.Settings;
|
||||
Assert.SequenceEqual([SectionKey.Settings], shell.BottomSections.Select(s => s.Key));
|
||||
Assert.Equal(SettingsPage.About, settings.AllPages[^1].Page);
|
||||
|
||||
shell.About.SetResult(null);
|
||||
shell.Navigate(SectionKey.Settings);
|
||||
settings.Page = SettingsPage.About;
|
||||
await app.ExpectAsync<SettingsView>("settings-about");
|
||||
Assert.Equal(Loc.L("Settings.Page.About"), settings.PageTitle);
|
||||
// This copy's identity: nothing to reset.
|
||||
Assert.False(settings.CanResetSection);
|
||||
Assert.False(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "no Reset section on About");
|
||||
Assert.True(app.FindAll<TextBlock>().Any(t => t.IsVisible && t.Text == shell.About.Build), "the build is shown");
|
||||
var licence = app.FindAll<Button>().Single(b => b.IsVisible && ReferenceEquals(b.Command, shell.About.OpenLicenceCommand));
|
||||
Assert.Equal(Loc.L("Tooltips.About.Licence"), licence.ToolTip);
|
||||
// English is the source language: no translation notice.
|
||||
Assert.False(app.FindAll<Button>().Any(b => b.IsVisible && ReferenceEquals(b.Command, shell.About.ReviewTranslationCommand)), "no review link in English");
|
||||
|
||||
// One place each in Settings: the update check (Updates), the data folder and the diagnostics bundle (Advanced).
|
||||
// (Rows build their content when first shown: those pages are shown once.)
|
||||
foreach (var page in (SettingsPage[])[SettingsPage.Updates, SettingsPage.Advanced, SettingsPage.About])
|
||||
{
|
||||
settings.Page = page;
|
||||
app.Window.UpdateLayout();
|
||||
}
|
||||
var buttons = app.FindAll<Button>();
|
||||
Assert.Count(1, buttons.Where(b => ReferenceEquals(b.Command, shell.About.CheckCommand)));
|
||||
Assert.Count(1, buttons.Where(b => ReferenceEquals(b.Command, settings.OpenDataFolderCommand)));
|
||||
Assert.Count(1, buttons.Where(b => ReferenceEquals(b.Command, settings.ExportDiagnosticsCommand)));
|
||||
|
||||
// The search finds About by its rows and Updates by its releases link.
|
||||
settings.SearchText = Loc.L("About.Build");
|
||||
Assert.Contains(settings.VisiblePages, p => p.Page == SettingsPage.About);
|
||||
settings.SearchText = Loc.L("About.Releases");
|
||||
Assert.Contains(settings.VisiblePages, p => p.Page == SettingsPage.Updates);
|
||||
settings.SearchText = Loc.L("About.Translation");
|
||||
Assert.False(settings.VisiblePages.Any(p => p.Page == SettingsPage.About), "the hidden translation row does not match");
|
||||
settings.SearchText = string.Empty;
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task ARightToLeftLanguageMirrorsEveryWindowAlsoThoseOpenedLater() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var settings = app.Shell.Settings;
|
||||
app.Shell.About.SetResult(null);
|
||||
app.Shell.Navigate(SectionKey.About);
|
||||
await app.ExpectAsync<AboutView>("about");
|
||||
var main = Window.GetWindow(app.FindAll<AboutView>().First(v => v.IsVisible));
|
||||
app.Shell.Navigate(SectionKey.Settings);
|
||||
settings.Page = SettingsPage.About;
|
||||
await app.ExpectAsync<SettingsView>("settings-about");
|
||||
var main = Window.GetWindow(app.FindAll<SettingsView>().First(v => v.IsVisible));
|
||||
Assert.Equal(FlowDirection.LeftToRight, main.FlowDirection);
|
||||
|
||||
UiLanguage.Apply("ar");
|
||||
@@ -350,13 +398,26 @@ public sealed class SettingsScreenSmokeTests
|
||||
dialog.Show();
|
||||
await loaded.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
Assert.Equal(FlowDirection.RightToLeft, dialog.FlowDirection, "a window opened after the switch (a dialog) is mirrored too");
|
||||
await app.ExpectAsync<AboutView>("about-ar");
|
||||
await app.ExpectAsync<SettingsView>("settings-about-ar");
|
||||
|
||||
// Inside the mirrored window, paths and the logo keep their left-to-right order.
|
||||
var path = app.FindAll<TextBlock>().First(t => t.IsVisible && t.Text == app.Shell.About.DataFolder);
|
||||
// Inside the mirrored window, the logo and the build keep their left-to-right order; the translation notice shows.
|
||||
var logos = app.FindAll<Chronos.Ui.Controls.BrandMarkIcon>().Where(b => b.IsVisible).ToList();
|
||||
Assert.NotEmpty(logos);
|
||||
Assert.True(logos.All(b => b.FlowDirection == FlowDirection.LeftToRight), "the logo is not mirrored");
|
||||
var build = app.FindAll<TextBlock>().First(t => t.IsVisible && t.Text == app.Shell.About.Build);
|
||||
Assert.Equal(FlowDirection.LeftToRight, build.FlowDirection);
|
||||
Assert.True(app.FindAll<Button>().Any(b => b.IsVisible && ReferenceEquals(b.Command, app.Shell.About.ReviewTranslationCommand)), "Arabic is machine-translated");
|
||||
|
||||
// Paths keep their left-to-right order and show whole in their tooltip.
|
||||
settings.Page = SettingsPage.Advanced;
|
||||
await app.ExpectAsync<SettingsView>("settings-advanced-ar");
|
||||
var path = Field(app, Loc.L("Settings.Advanced.DataFolder"));
|
||||
Assert.Equal(FlowDirection.LeftToRight, path.FlowDirection);
|
||||
Assert.Equal(app.Shell.About.DataFolder, path.ToolTip);
|
||||
Assert.Equal(settings.DataFolder, path.ToolTip);
|
||||
|
||||
// The update result is a live region: screen readers hear each new state.
|
||||
settings.Page = SettingsPage.Updates;
|
||||
await app.ExpectAsync<SettingsView>("settings-updates-ar");
|
||||
var update = app.FindAll<Chronos.Ui.Controls.StatusGlyph>().First(g => g.IsVisible && g.Text == app.Shell.About.UpdateText);
|
||||
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(update));
|
||||
Assert.Equal(app.Shell.About.UpdateAnnouncement, AutomationProperties.GetName(update));
|
||||
|
||||
@@ -92,6 +92,7 @@ public sealed class ScreenSmokeTests
|
||||
Assert.True(shell.Server.IsConnected, "the saved session is restored");
|
||||
await app.ExpectAsync<ServerView>("server");
|
||||
|
||||
// Every Settings page, About last (owner review 2, R5).
|
||||
shell.Navigate(SectionKey.Settings);
|
||||
Assert.Equal(3, shell.Settings.PreviewNames.Count);
|
||||
Assert.Equal(6, shell.Settings.Encoders.Count);
|
||||
@@ -101,9 +102,6 @@ public sealed class ScreenSmokeTests
|
||||
await app.ExpectAsync<SettingsView>("settings-" + page.ToString().ToLowerInvariant());
|
||||
}
|
||||
|
||||
shell.Navigate(SectionKey.About);
|
||||
await app.ExpectAsync<AboutView>("about");
|
||||
|
||||
shell.Navigate(SectionKey.Import);
|
||||
await app.ExpectAsync<ImportView>("import");
|
||||
// Edit with no sequence open: the picker lists the sequences (owner review 1, R7).
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Tests.Archiving;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Core.Tests.Import.ImportTestKit;
|
||||
@@ -163,6 +165,118 @@ public sealed class ImportPlannerTests(TestContext context)
|
||||
Assert.SequenceEqual([5, 5, 10], split.Sessions.Select(s => s.Items.Count));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWholeFolderIsOneSequenceWhateverTheCameraBodiesAndPauses()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("source"), "Etna eruption");
|
||||
TestPhotos.WriteSeries(folder, Start, 10, Interval, prefix: "CAN_");
|
||||
TestPhotos.WriteSeries(folder, Start.AddHours(3), 10, Interval, firstSeed: 20, prefix: "CAN_", firstNumber: 11);
|
||||
TestPhotos.WriteSeries(folder, Start.AddSeconds(5), 3, Interval, firstSeed: 40, prefix: "NIK_", make: "NIKON CORPORATION", model: "NIKON Z 8");
|
||||
var destination = context.CreateTempDirectory("archive");
|
||||
Assert.Equal(3, (await PlanAsync(folder, destination)).Sessions.Count, "by sessions: two Canon sessions and the Nikon");
|
||||
|
||||
var plan = await PlanAsync(folder, destination, new ImportOptions { Grouping = ImportGrouping.WholeFolder, FolderTemplate = "{year}/{title}" });
|
||||
Assert.Equal(ImportGrouping.WholeFolder, plan.Grouping);
|
||||
var session = plan.Sessions.Single();
|
||||
Assert.Equal(23, session.Items.Count);
|
||||
Assert.Equal(2, session.Cameras);
|
||||
Assert.Equal("Etna eruption", session.Title, "the folder's name is the default title");
|
||||
Assert.Equal("Etna eruption", session.DefaultTitle);
|
||||
Assert.Equal("2026/Etna eruption", session.Folder);
|
||||
Assert.SequenceEqual(session.Items.OrderBy(i => i.CapturedAt).Select(i => i.SourcePath), session.Items.Select(i => i.SourcePath),
|
||||
"both bodies in capture order");
|
||||
Assert.Equal("2026-09-28_21-01-30_0023.JPG", session.Items[^1].FileName);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWholeFolderOfRawAndJpegIsTwoSequencesSoNoFrameIsDoubled()
|
||||
{
|
||||
var photos = new List<CardPhoto>();
|
||||
for (var i = 0; i < 6; i++)
|
||||
{
|
||||
// An hour between shots: far beyond the session gap, ignored for a whole folder.
|
||||
var at = Start.AddHours(i);
|
||||
photos.Add(Photo($"IMG_{i:0000}.JPG", at, ImageFileFormat.Jpeg));
|
||||
photos.Add(Photo($"IMG_{i:0000}.CR3", at, ImageFileFormat.Cr3));
|
||||
}
|
||||
var plan = await ImportPlanner.PlanAsync(context.CreateTempDirectory("raw+jpeg"), context.CreateTempDirectory("archive"), photos, [],
|
||||
new ImportOptions { Grouping = ImportGrouping.WholeFolder }, new FakeLookup());
|
||||
|
||||
Assert.Equal(2, plan.Sessions.Count, "one sequence per format");
|
||||
Assert.SequenceEqual([ImageFileFormat.Jpeg, ImageFileFormat.Cr3], plan.Sessions.Select(s => s.Format).OrderBy(f => f));
|
||||
foreach (var session in plan.Sessions)
|
||||
{
|
||||
Assert.Equal(6, session.Items.Count);
|
||||
Assert.Equal(1, session.Items.Select(i => Path.GetExtension(i.SourcePath)).Distinct().Count(), "one format per sequence");
|
||||
}
|
||||
Assert.Equal(12, plan.Items.Select(i => i.SourcePath).Distinct().Count(), "every photo is planned once");
|
||||
Assert.NotEqual(plan.Sessions[0].SessionKey, plan.Sessions[1].SessionKey);
|
||||
Assert.NotEqual(plan.Sessions[0].Folder, plan.Sessions[1].Folder);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWholeFolderTakesItsSubfoldersOnlyWhenAsked()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("source"), "Construction");
|
||||
TestPhotos.WriteSeries(folder, Start, 4, Interval);
|
||||
TestPhotos.WriteSeries(Path.Combine(folder, "week 2"), Start.AddDays(7), 4, Interval, firstSeed: 50, firstNumber: 5);
|
||||
TestPhotos.WriteSeries(Path.Combine(folder, "week 2", "monday"), Start.AddDays(8), 4, Interval, firstSeed: 70, firstNumber: 9);
|
||||
var destination = context.CreateTempDirectory("archive");
|
||||
var whole = new ImportOptions { Grouping = ImportGrouping.WholeFolder };
|
||||
|
||||
var all = (await PlanAsync(folder, destination, whole)).Sessions.Single();
|
||||
Assert.Equal(12, all.Items.Count);
|
||||
Assert.Equal("week 2/monday/IMG_0012.JPG", all.Items[^1].SourcePath);
|
||||
var top = (await PlanAsync(folder, destination, whole with { IncludeSubfolders = false })).Sessions.Single();
|
||||
Assert.Equal(4, top.Items.Count);
|
||||
Assert.Equal(all.SessionKey, top.SessionKey, "the same folder's sequence, whatever is scanned in it");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWholeFolderKeepsItsKeySoAnInterruptedImportResumesIntoItsSequence()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("source"), "Etna");
|
||||
TestPhotos.WriteSeries(folder, Start, 10, Interval);
|
||||
var destination = context.CreateTempDirectory("archive");
|
||||
var whole = new ImportOptions { Grouping = ImportGrouping.WholeFolder };
|
||||
var first = (await PlanAsync(folder, destination, whole)).Sessions.Single();
|
||||
Assert.True(first.SessionKey.StartsWith("folder-", StringComparison.Ordinal), first.SessionKey);
|
||||
Assert.Equal(first.SessionKey, ImportPlanner.FolderKey(folder + Path.DirectorySeparatorChar, ImageFileFormat.Jpeg),
|
||||
"a trailing separator names the same folder");
|
||||
Assert.NotEqual(first.SessionKey, ImportPlanner.FolderKey(folder, ImageFileFormat.Cr3));
|
||||
Assert.NotEqual(first.SessionKey, ImportPlanner.FolderKey(Path.Combine(folder, "other"), ImageFileFormat.Jpeg));
|
||||
|
||||
// Photos added later, earlier ones too, keep the folder's key.
|
||||
TestPhotos.WriteSeries(folder, Start.AddDays(-1), 2, Interval, firstSeed: 90, prefix: "OLD_");
|
||||
Assert.Equal(first.SessionKey, (await PlanAsync(folder, destination, whole)).Sessions.Single().SessionKey);
|
||||
|
||||
var lookup = new FakeLookup();
|
||||
lookup.SessionFolders[first.SessionKey] = "2026/Etna";
|
||||
Assert.Equal("2026/Etna", (await PlanAsync(folder, destination, whole, lookup)).Sessions.Single().Folder, "the sequence of the interrupted import");
|
||||
|
||||
var typed = whole with { Titles = new Dictionary<string, string> { [first.SessionKey] = "Etna at night" } };
|
||||
var titled = (await PlanAsync(folder, destination, typed)).Sessions.Single();
|
||||
Assert.Equal("Etna at night", titled.Title);
|
||||
Assert.Equal("Etna", titled.DefaultTitle);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWholeFolderSplitsOnlyWhereTheUserSplitsIt()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("source"), "Harbour");
|
||||
TestPhotos.WriteSeries(folder, Start, 10, Interval);
|
||||
var destination = context.CreateTempDirectory("archive");
|
||||
var split = new ImportOptions { Grouping = ImportGrouping.WholeFolder, SplitBefore = new HashSet<string> { "IMG_0009.JPG" } };
|
||||
|
||||
var plan = await PlanAsync(folder, destination, split);
|
||||
Assert.SequenceEqual([8, 2], plan.Sessions.Select(s => s.Items.Count), "a part the user split off stays, however short");
|
||||
Assert.Equal(ImportPlanner.FolderKey(folder, ImageFileFormat.Jpeg), plan.Sessions[0].SessionKey);
|
||||
Assert.NotEqual(plan.Sessions[0].SessionKey, plan.Sessions[1].SessionKey);
|
||||
Assert.Equal(plan.Sessions[1].SessionKey, (await PlanAsync(folder, destination, split)).Sessions[1].SessionKey);
|
||||
var merged = split with { SplitBefore = new HashSet<string>(), MergeAt = new HashSet<string> { "IMG_0009.JPG" } };
|
||||
Assert.Equal(10, (await PlanAsync(folder, destination, merged)).Sessions.Single().Items.Count, "merging the part back undoes the split");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoWithoutExifIsPlannedAtItsFileTime()
|
||||
{
|
||||
@@ -177,4 +291,8 @@ public sealed class ImportPlannerTests(TestContext context)
|
||||
// No camera identity: it forms its own body group rather than joining the Canon session.
|
||||
Assert.SequenceEqual([8, 1], plan.Sessions.Select(s => s.Items.Count));
|
||||
}
|
||||
|
||||
/// <summary>A photo as the scanner reads it, without a file behind it (the planner hashes only duplicate candidates).</summary>
|
||||
private static CardPhoto Photo(string path, DateTime captured, ImageFileFormat format) => new(new CardFile(path, 1_000, captured),
|
||||
new FrameMetadata { Format = format, Make = "Canon", Model = "Canon EOS R5", BodySerial = "0431", CapturedAt = captured });
|
||||
}
|
||||
@@ -105,6 +105,35 @@ public sealed class ImportServiceTests(TestContext context)
|
||||
Assert.Equal(20, (await FramesAsync(fx, plan.Sessions.Single())).Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWholeFolderBecomesOneSequenceNamedAfterItThatALaterImportAddsTo()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var folder = Path.Combine(context.CreateTempDirectory("source"), "Etna eruption");
|
||||
Photos.WriteSeries(folder, Start, 5);
|
||||
Photos.WriteSeries(folder, Start.AddHours(4), 5, firstSeed: 20, prefix: "NIK_", make: "NIKON CORPORATION", model: "NIKON Z 8");
|
||||
var whole = new ImportOptions { Grouping = ImportGrouping.WholeFolder };
|
||||
|
||||
var plan = await fx.Service.PlanImportAsync(fx.Archive.Id, folder, whole, null, null, fx.Ct);
|
||||
var session = plan.Sessions.Single();
|
||||
await RunAsync(fx, plan);
|
||||
var id = await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, session.SessionKey);
|
||||
Assert.Equal("Etna eruption", (await fx.Db.Sequences.GetAsync(id!.Value))!.Title);
|
||||
Assert.Equal(10, (await FramesAsync(fx, session)).Count);
|
||||
|
||||
// Photos added to the folder later join the same sequence; those imported before are found in the archive.
|
||||
Photos.WriteSeries(folder, Start.AddDays(1), 3, firstSeed: 40, prefix: "LATE_");
|
||||
var later = await fx.Service.PlanImportAsync(fx.Archive.Id, folder, whole, null, null, fx.Ct);
|
||||
Assert.Equal(session.SessionKey, later.Sessions.Single().SessionKey);
|
||||
Assert.Equal(session.Folder, later.Sessions.Single().Folder);
|
||||
Assert.Equal(3, later.CopyCount);
|
||||
await RunAsync(fx, later);
|
||||
Assert.Equal(13, (await FramesAsync(fx, session)).Count);
|
||||
|
||||
static Task<ImportProgress> RunAsync(ArchiveFixture fx, ImportPlan plan) => fx.Service.Imports.ExecuteAsync(
|
||||
new ImportJobParameters(fx.Archive.Id, plan, null, true, null), Guid.NewGuid(), 0, _ => ValueTask.CompletedTask, null, fx.Ct);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ErasingTheCardDeletesOnlyVerifiedImports()
|
||||
{
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Tests;
|
||||
@@ -99,6 +101,23 @@ public sealed class FakeAssetLocator : IFrameAssetLocator
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Measures volumes for real, except the folders given figures of their own (a full archive, a separate array).</summary>
|
||||
public sealed class FakeVolumeSpace(ServerOptions options, ILogger<VolumeSpace> logger) : VolumeSpace(options, logger)
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, VolumeFigures> _figures = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Gives <paramref name="path"/> these figures; null measures it for real again.</summary>
|
||||
public void Set(string path, VolumeFigures? figures)
|
||||
{
|
||||
if (figures is null) _figures.TryRemove(Key(path), out _);
|
||||
else _figures[Key(path)] = figures;
|
||||
}
|
||||
|
||||
public override VolumeFigures? Measure(string path) => _figures.TryGetValue(Key(path), out var figures) ? figures : base.Measure(path);
|
||||
|
||||
private static string Key(string path) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
|
||||
}
|
||||
|
||||
/// <summary>A clock tests move by hand (token expiry, heartbeat timeouts).</summary>
|
||||
public sealed class ManualTimeProvider : TimeProvider
|
||||
{
|
||||
|
||||
@@ -142,8 +142,7 @@ public sealed class SystemEndpointTests(TestContext context)
|
||||
// The page container is not a live region: only toasts and form errors announce themselves.
|
||||
Assert.True(!index.Contains("aria-live", StringComparison.Ordinal), index);
|
||||
var app = await server.Client.GetStringAsync("/admin/app.js");
|
||||
var pages = Regex.Match(app, @"const pages = \[([^\]]*)\]").Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"'));
|
||||
var pending = new Queue<string>(pages.Select(p => $"pages/{p}.js").Prepend("app.js"));
|
||||
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("app.js"));
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
while (pending.TryDequeue(out var module))
|
||||
{
|
||||
@@ -154,9 +153,34 @@ public sealed class SystemEndpointTests(TestContext context)
|
||||
foreach (Match import in Regex.Matches(await response.Content.ReadAsStringAsync(), @"from ""(\.{1,2}/[^""]+)"""))
|
||||
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
|
||||
}
|
||||
Assert.True(seen.Count >= 14, string.Join(", ", seen));
|
||||
Assert.True(seen.Count >= 13, string.Join(", ", seen));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AdminPanelDocksSettingsAtTheFootAndFoldsAboutIntoIt()
|
||||
{
|
||||
// Owner review 2: Settings below the other pages, About its last group; old #/about bookmarks open it there.
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var app = await server.Client.GetStringAsync("/admin/app.js");
|
||||
var groups = MenuPages(app);
|
||||
Assert.Count(2, groups);
|
||||
Assert.SequenceEqual(new[] { "settings" }, groups[1]);
|
||||
Assert.DoesNotContain("about", groups[0]);
|
||||
Assert.Contains(@"about: ""settings?group=about""", app);
|
||||
using var about = await server.Client.GetAsync("/admin/pages/about.js");
|
||||
Assert.Equal(HttpStatusCode.NotFound, about.StatusCode);
|
||||
var settings = await server.Client.GetStringAsync("/admin/pages/settings.js");
|
||||
Assert.Contains(@"id=""about-title""", settings);
|
||||
// The page draws before the dashboard aggregate answers; these two rows fill in afterwards.
|
||||
Assert.Contains(@"id=""about-database""", settings);
|
||||
Assert.Contains(@"id=""about-uptime""", settings);
|
||||
}
|
||||
|
||||
/// <summary>The menu's page groups as app.js lists them: the top pages, then the ones docked at the foot.</summary>
|
||||
private static List<string[]> MenuPages(string app) =>
|
||||
[.. Regex.Matches(app, @"const (?:top|bottom)Pages = \[([^\]]*)\]")
|
||||
.Select(m => m.Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"')).ToArray())];
|
||||
|
||||
private static string Resolve(string folder, string relative)
|
||||
{
|
||||
var parts = (folder + relative).Split('/').ToList();
|
||||
|
||||
@@ -115,7 +115,7 @@ public sealed class JobApiTests(TestContext context)
|
||||
|
||||
public static async Task<JobDto> WaitForAsync(HttpClient client, Guid id, string state)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddSeconds(15);
|
||||
var deadline = DateTime.UtcNow.AddSeconds(TestTiming.Budget(15));
|
||||
while (true)
|
||||
{
|
||||
var job = await GetAsync(client, id);
|
||||
|
||||
@@ -416,7 +416,7 @@ public sealed class RenderNodeClientTests(TestContext context)
|
||||
|
||||
private static async Task UntilAsync(Func<Task<bool>> condition, string what)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddSeconds(30);
|
||||
var until = DateTime.UtcNow.AddSeconds(TestTiming.Budget(30));
|
||||
while (!await condition())
|
||||
{
|
||||
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace Chronos.Server.Tests.Jobs;
|
||||
[Category("server")]
|
||||
public sealed class RenderNodeTests(TestContext context)
|
||||
{
|
||||
private static readonly string HevcJob = JsonSerializer.Serialize(
|
||||
internal static readonly string HevcJob = JsonSerializer.Serialize(
|
||||
new RenderJobParameters("4K HEVC", """{"codec":"hevc","bitrate":60}""", "hevc", 3840, 2160, UseProxies: false, null), ProtocolJson.Default.RenderJobParameters);
|
||||
|
||||
[Test]
|
||||
@@ -147,7 +147,7 @@ public sealed class RenderNodeTests(TestContext context)
|
||||
new RenderJobParameters("H.264", """{"preset":{"isAuto":false,"manual":"4k-h264"}}""", "h264", width, height, UseProxies: false, null),
|
||||
ProtocolJson.Default.RenderJobParameters);
|
||||
|
||||
private static async Task<RenderNodeDto> RegisterAsync(HttpClient client, string name, string codec, int maxWidth)
|
||||
internal static async Task<RenderNodeDto> RegisterAsync(HttpClient client, string name, string codec, int maxWidth)
|
||||
{
|
||||
using var response = await client.PostAsJsonAsync("/api/v1/nodes/register",
|
||||
new RegisterNodeRequest(name, [new NodeEncoder(codec, codec.ToUpperInvariant() + " encoder", true, false)], maxWidth, maxWidth), ProtocolJson.Default.RegisterNodeRequest);
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Server.Tests.Jobs;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Storage;
|
||||
|
||||
/// <summary>Owner review 2 (R2): the free space of the Unraid array instead of the cache, and of the archive before an upload is filed.</summary>
|
||||
[Category("server")]
|
||||
public sealed class VolumeSpaceTests(TestContext context)
|
||||
{
|
||||
private const long GB = 1_000_000_000;
|
||||
|
||||
/// <summary>
|
||||
/// /proc/self/mountinfo of a Chronos container on Unraid: the overlay root, the share bind-mounted at /archive (FUSE
|
||||
/// shfs, whose root is the share's folder), its array view at /space, appdata at /data, a disk mounted inside the
|
||||
/// archive under a name with a space, and two mounts stacked on /tmp.
|
||||
/// </summary>
|
||||
private const string Unraid = """
|
||||
574 520 0:52 / / rw,relatime master:255 - overlay overlay rw,lowerdir=/var/lib/docker/overlay2/l/ABC:/var/lib/docker/overlay2/l/DEF,upperdir=/var/lib/docker/overlay2/1f/diff
|
||||
575 574 0:55 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw
|
||||
590 574 0:45 /Timelapse /archive rw,noatime - fuse.shfs shfs rw,user_id=0,group_id=0,default_permissions,allow_other
|
||||
591 574 0:46 /Timelapse /space ro,noatime - fuse.shfs shfs rw,user_id=0,group_id=0,default_permissions,allow_other
|
||||
592 574 0:31 /appdata/chronos /data rw,noatime shared:5 master:3 - btrfs /dev/nvme0n1p1 rw,ssd,space_cache=v2,subvolid=5,subvol=/
|
||||
593 590 9:1 / /archive/Big\040Trip rw,noatime - xfs /dev/md1p1 rw,attr2,inode64
|
||||
594 574 0:60 / /tmp rw - tmpfs tmpfs rw
|
||||
595 574 0:61 / /tmp rw - tmpfs scratch rw,size=1g
|
||||
this line is not a mount
|
||||
""";
|
||||
|
||||
[Theory]
|
||||
[Case("/archive", "/archive", "fuse.shfs")]
|
||||
[Case("/archive/2026/Roof/IMG_0001.CR3", "/archive", "fuse.shfs")]
|
||||
[Case("/archive/", "/archive", "fuse.shfs")]
|
||||
[Case("/space", "/space", "fuse.shfs")]
|
||||
[Case("/data/uploads", "/data", "btrfs")]
|
||||
[Case("/archive/Big Trip/IMG_0002.CR3", "/archive/Big Trip", "xfs")]
|
||||
[Case("/archive/Big", "/archive", "fuse.shfs")]
|
||||
[Case("/archived", "/", "overlay")]
|
||||
[Case("/", "/", "overlay")]
|
||||
[Case("/app/Chronos.Server.dll", "/", "overlay")]
|
||||
public void TheLongestMountPointHoldsAPath(string path, string mountPoint, string fileSystem)
|
||||
{
|
||||
var mount = Assert.NotNull(VolumeSpace.FindMount(Unraid, path));
|
||||
Assert.Equal((mountPoint, fileSystem), (mount.MountPoint, mount.FileSystem));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MountInfoLinesAreReadField()
|
||||
{
|
||||
var share = Assert.NotNull(VolumeSpace.FindMount(Unraid, "/archive"));
|
||||
Assert.Equal("shfs", share.Source);
|
||||
// Of mounts stacked on one point, the last listed is on top.
|
||||
Assert.Equal("scratch", Assert.NotNull(VolumeSpace.FindMount(Unraid, "/tmp/x")).Source);
|
||||
// Optional fields, a Windows line end and escapes in any field.
|
||||
var data = Assert.NotNull(VolumeSpace.ParseMountLine("592 574 0:31 / /mnt/My\\040Disk rw shared:5 master:3 propagate_from:2 - ext4 /dev/sd\\134b rw\r"));
|
||||
Assert.Equal(("/mnt/My Disk", "ext4", "/dev/sd\\b"), (data.MountPoint, data.FileSystem, data.Source));
|
||||
Assert.Null(VolumeSpace.ParseMountLine("592 574 0:31 / /data rw shared:5 btrfs /dev/sdb1 rw"));
|
||||
Assert.Null(VolumeSpace.ParseMountLine(""));
|
||||
Assert.Null(VolumeSpace.FindMount("", "/archive"));
|
||||
Assert.Null(VolumeSpace.FindMount("590 574 0:45 /Timelapse /archive rw - fuse.shfs shfs rw", "/data"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheFileSystemOfAFolderIsKnown()
|
||||
{
|
||||
var folder = context.CreateTempDirectory("fs");
|
||||
var fileSystem = Assert.NotNull(VolumeSpace.FileSystemOf(folder));
|
||||
Assert.NotEmpty(fileSystem);
|
||||
if (OperatingSystem.IsLinux()) Assert.Equal(fileSystem, Assert.NotNull(VolumeSpace.MountOf(folder)).FileSystem);
|
||||
else Assert.Null(VolumeSpace.MountOf(folder));
|
||||
Assert.Null(VolumeSpace.FileSystemOf(Path.Combine(folder, "missing")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheSpacePathIsShownWithTheWriteVolumeApartWhenTheyDiffer()
|
||||
{
|
||||
var root = context.CreateTempDirectory("report");
|
||||
var archive = Directory.CreateDirectory(Path.Combine(root, "archive")).FullName;
|
||||
var space = Directory.CreateDirectory(Path.Combine(root, "space")).FullName;
|
||||
var options = new ServerOptions { ArchivePath = archive };
|
||||
var logger = new CountingLogger();
|
||||
var volumes = new FakeVolumeSpace(options, logger);
|
||||
volumes.Set(archive, new VolumeFigures(120 * GB, 500 * GB));
|
||||
|
||||
// No space path: the archive's own volume.
|
||||
var plain = volumes.Report(archive);
|
||||
Assert.Equal((120 * GB, false, (VolumeFigures?)null), (plain.Space!.FreeBytes, plain.FromSpacePath, plain.Write));
|
||||
|
||||
// The cache and the array: the array is shown, the cache apart.
|
||||
options.SpacePath = space;
|
||||
volumes.Set(space, new VolumeFigures(9_000 * GB, 16_000 * GB));
|
||||
var separate = volumes.Report(archive);
|
||||
Assert.Equal((9_000 * GB, true), (separate.Space!.FreeBytes, separate.FromSpacePath));
|
||||
Assert.Equal(new VolumeFigures(120 * GB, 500 * GB), separate.Write);
|
||||
Assert.Equal(VolumeSpace.FileSystemOf(space), separate.FileSystem);
|
||||
|
||||
// One volume read twice a moment apart: no second line.
|
||||
volumes.Set(space, new VolumeFigures((120 * GB) - (8 << 20), 500 * GB));
|
||||
Assert.Null(volumes.Report(archive).Write);
|
||||
Assert.Equal(0, logger.Warnings);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASpacePathThatCannotBeMeasuredFallsBackWithOneWarning()
|
||||
{
|
||||
var root = context.CreateTempDirectory("fallback");
|
||||
var archive = Directory.CreateDirectory(Path.Combine(root, "archive")).FullName;
|
||||
var space = Path.Combine(root, "not-mapped");
|
||||
var logger = new CountingLogger();
|
||||
var volumes = new VolumeSpace(new ServerOptions { ArchivePath = archive, SpacePath = space }, logger);
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var report = volumes.Report(archive);
|
||||
Assert.False(report.FromSpacePath);
|
||||
Assert.True(Assert.NotNull(report.Space).TotalBytes > 0);
|
||||
Assert.Null(report.Write);
|
||||
}
|
||||
Assert.Equal(1, logger.Warnings);
|
||||
|
||||
// Mapped later: measured again, and a later outage is warned about once more.
|
||||
Directory.CreateDirectory(space);
|
||||
Assert.True(volumes.Report(archive).FromSpacePath);
|
||||
Directory.Delete(space);
|
||||
volumes.Report(archive);
|
||||
volumes.Report(archive);
|
||||
Assert.Equal(2, logger.Warnings);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheStatsReportTheSpacePathAndTheWriteVolume()
|
||||
{
|
||||
var space = context.CreateTempDirectory("space");
|
||||
await using var server = await TestServer.StartAsync(context, o => o.SpacePath = space, s =>
|
||||
{
|
||||
s.AddSingleton<FakeVolumeSpace>();
|
||||
s.AddSingleton<VolumeSpace>(sp => sp.GetRequiredService<FakeVolumeSpace>());
|
||||
});
|
||||
var admin = await server.AdminAsync();
|
||||
var stats = await admin.GetFromJsonAsync("/api/v1/archive/stats", ProtocolJson.Default.ArchiveStatsDto);
|
||||
Assert.True(Assert.NotNull(stats).UsesSpacePath);
|
||||
Assert.True(stats.CapacityBytes > 0 && stats.FreeBytes <= stats.CapacityBytes);
|
||||
Assert.Equal(VolumeSpace.FileSystemOf(space), stats.FileSystem);
|
||||
// Temporary folders share one volume: no write volume apart.
|
||||
Assert.Null(stats.WriteFreeBytes);
|
||||
|
||||
// The archive's own volume (an Unraid share's cache) differs: the panel gets it apart.
|
||||
server.Services.GetRequiredService<FakeVolumeSpace>().Set(server.Options.ArchivePath, new VolumeFigures(40 * GB, 250 * GB));
|
||||
using var dashboard = await admin.GetAsync("/api/v1/server/dashboard");
|
||||
var archive = (await dashboard.ReadAsync(ProtocolJson.Default.DashboardDto)).Archive;
|
||||
Assert.Equal((40 * GB, 250 * GB, true), (archive.WriteFreeBytes, archive.WriteCapacityBytes, archive.UsesSpacePath));
|
||||
Assert.NotEqual(40 * GB, archive.FreeBytes);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMissingSpacePathShowsTheArchiveVolume()
|
||||
{
|
||||
var root = context.CreateTempDirectory("unmapped");
|
||||
await using var server = await TestServer.StartAsync(context, o => o.SpacePath = Path.Combine(root, "space"));
|
||||
var admin = await server.AdminAsync();
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
var stats = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/archive/stats", ProtocolJson.Default.ArchiveStatsDto));
|
||||
Assert.False(stats.UsesSpacePath);
|
||||
Assert.True(stats.CapacityBytes > 0);
|
||||
Assert.Null(stats.WriteFreeBytes);
|
||||
Assert.Equal(VolumeSpace.FileSystemOf(server.Options.ArchivePath), stats.FileSystem);
|
||||
}
|
||||
// Warned at start, not at every request.
|
||||
var warnings = Directory.EnumerateFiles(server.Options.LogPath).Sum(log =>
|
||||
{
|
||||
using var reader = new StreamReader(new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
|
||||
return reader.ReadToEnd().Split('\n').Count(line => line.Contains("CHRONOS_SPACE_PATH", StringComparison.Ordinal));
|
||||
});
|
||||
Assert.Equal(1, warnings);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheDiagnosticsReportBothVolumes()
|
||||
{
|
||||
var space = context.CreateTempDirectory("space");
|
||||
await using var server = await TestServer.StartAsync(context, o => o.SpacePath = space);
|
||||
var admin = await server.AdminAsync();
|
||||
using var response = await admin.GetAsync("/api/v1/server/diagnostics");
|
||||
await response.ExpectAsync(HttpStatusCode.OK);
|
||||
await using var body = await response.Content.ReadAsStreamAsync();
|
||||
using var zip = new ZipArchive(body, ZipArchiveMode.Read);
|
||||
using var reader = new StreamReader(Assert.NotNull(zip.GetEntry("environment.txt")).Open());
|
||||
var report = await reader.ReadToEndAsync();
|
||||
var fileSystem = Assert.NotNull(VolumeSpace.FileSystemOf(space));
|
||||
Assert.Contains($"Archive {server.Options.ArchivePath} (", report);
|
||||
Assert.Contains($"Space {space} (", report);
|
||||
Assert.Contains($" GB, {fileSystem}", report);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFullArchiveVolumeRefusesTheCompletionUntilThereIsRoom()
|
||||
{
|
||||
const int chunk = 64 * 1024;
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = chunk, s =>
|
||||
{
|
||||
s.AddSingleton<FakeVolumeSpace>();
|
||||
s.AddSingleton<VolumeSpace>(sp => sp.GetRequiredService<FakeVolumeSpace>());
|
||||
});
|
||||
var volumes = server.Services.GetRequiredService<FakeVolumeSpace>();
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var data = Uploads.Photo(chunk + 500, 71);
|
||||
var start = await Uploads.StartAsync(editor, data, sessionKey: "roof");
|
||||
var id = Assert.NotNull(start.UploadId);
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
using var put = await Uploads.PutChunkAsync(editor, id, i, Uploads.Chunk(data, chunk, i));
|
||||
await put.ExpectAsync(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
// The upload volume (/data) has room, the archive's does not: nothing is staged, the upload keeps its chunks.
|
||||
volumes.Set(server.Options.ArchivePath, new VolumeFigures(32L << 20, 500 * GB));
|
||||
using (var full = await editor.PostAsync($"/api/v1/uploads/{id}/complete", null))
|
||||
await full.ExpectErrorAsync(HttpStatusCode.InsufficientStorage, "insufficient_storage");
|
||||
using (var state = await editor.GetAsync($"/api/v1/uploads/{id}"))
|
||||
Assert.Equal("receiving", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
|
||||
Assert.True(server.Services.GetRequiredService<UploadStore>().Exists(id));
|
||||
Assert.False(Directory.Exists(server.Options.StagingPath) && Directory.EnumerateFiles(server.Options.StagingPath).Any());
|
||||
|
||||
volumes.Set(server.Options.ArchivePath, new VolumeFigures(GB, 500 * GB));
|
||||
Guid sequence;
|
||||
using (var room = await editor.PostAsync($"/api/v1/uploads/{id}/complete", null))
|
||||
{
|
||||
await room.ExpectAsync(HttpStatusCode.OK);
|
||||
sequence = (await room.ReadAsync(ProtocolJson.Default.CompleteUploadResponse)).SequenceId;
|
||||
}
|
||||
|
||||
// A render sent into the archive is checked the same way.
|
||||
var output = Uploads.Photo(3000, 72);
|
||||
var request = new RenderUploadRequest(Guid.CreateVersion7(), "Roof.mp4", output.Length, Uploads.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, null);
|
||||
using var started = await editor.PostAsJsonAsync($"/api/v1/sequences/{sequence}/renders", request, ProtocolJson.Default.RenderUploadRequest);
|
||||
await started.ExpectAsync(HttpStatusCode.Created);
|
||||
var render = Assert.NotNull((await started.ReadAsync(ProtocolJson.Default.StartUploadResponse)).UploadId);
|
||||
using (var put = await Uploads.PutChunkAsync(editor, render, 0, output)) await put.ExpectAsync(HttpStatusCode.OK);
|
||||
volumes.Set(server.Options.ArchivePath, new VolumeFigures(0, 500 * GB));
|
||||
using (var full = await editor.PostAsync($"/api/v1/sequences/{sequence}/renders/{render}/complete", null))
|
||||
await full.ExpectErrorAsync(HttpStatusCode.InsufficientStorage, "insufficient_storage");
|
||||
volumes.Set(server.Options.ArchivePath, null);
|
||||
using (var room = await editor.PostAsync($"/api/v1/sequences/{sequence}/renders/{render}/complete", null))
|
||||
await room.ExpectAsync(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFullArchiveVolumeRefusesARenderNodeResultUntilThereIsRoom()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, s =>
|
||||
{
|
||||
s.AddSingleton<FakeVolumeSpace>();
|
||||
s.AddSingleton<VolumeSpace>(sp => sp.GetRequiredService<FakeVolumeSpace>());
|
||||
});
|
||||
var volumes = server.Services.GetRequiredService<FakeVolumeSpace>();
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
|
||||
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(5000, 73), "IMG_0001.CR3");
|
||||
var job = await JobApiTests.CreateAsync(editor, "render", frame.SequenceId, RenderNodeTests.HevcJob);
|
||||
var node = await RenderNodeTests.RegisterAsync(editor, "studio-pc", "hevc", 8192);
|
||||
using (var claim = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) await claim.ExpectAsync(HttpStatusCode.OK);
|
||||
|
||||
var output = Uploads.Photo(3000, 74);
|
||||
var request = new RenderResultRequest("Roof - 4K HEVC.mp4", output.Length, Uploads.Sha(output), "4K HEVC", "hevc", 3840, 2160, 25, 120);
|
||||
using var started = await editor.PostAsJsonAsync($"/api/v1/nodes/{node.Id}/jobs/{job.Id}/result", request, ProtocolJson.Default.RenderResultRequest);
|
||||
await started.ExpectAsync(HttpStatusCode.Created);
|
||||
var upload = Assert.NotNull((await started.ReadAsync(ProtocolJson.Default.StartUploadResponse)).UploadId);
|
||||
using (var put = await Uploads.PutChunkAsync(editor, upload, 0, output)) await put.ExpectAsync(HttpStatusCode.OK);
|
||||
|
||||
// Refused before the commit starts: the upload keeps receiving with its chunks and the node keeps the job.
|
||||
var complete = $"/api/v1/nodes/{node.Id}/jobs/{job.Id}/result/complete";
|
||||
volumes.Set(server.Options.ArchivePath, new VolumeFigures(0, 500 * GB));
|
||||
using (var full = await editor.PostAsync(complete, null))
|
||||
await full.ExpectErrorAsync(HttpStatusCode.InsufficientStorage, "insufficient_storage");
|
||||
Assert.Equal(Chronos.Data.Repositories.UploadState.Receiving, Assert.NotNull(await server.Database.Uploads.FindByJobAsync(job.Id)).State);
|
||||
Assert.True(server.Services.GetRequiredService<UploadStore>().Exists(upload));
|
||||
var waiting = await JobApiTests.GetAsync(editor, job.Id);
|
||||
Assert.Equal(("running", node.Id.ToString()), (waiting.State, waiting.NodeId));
|
||||
|
||||
volumes.Set(server.Options.ArchivePath, null);
|
||||
using (var room = await editor.PostAsync(complete, null))
|
||||
{
|
||||
await room.ExpectAsync(HttpStatusCode.OK);
|
||||
Assert.Equal("studio-pc", (await room.ReadAsync(ProtocolJson.Default.RenderDto)).ProducedBy);
|
||||
}
|
||||
Assert.Equal("done", (await JobApiTests.GetAsync(editor, job.Id)).State);
|
||||
Assert.Equal(Chronos.Data.Repositories.UploadState.Committed, Assert.NotNull(await server.Database.Uploads.FindByJobAsync(job.Id)).State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheSpacePathComesFromTheFileOrTheEnvironment()
|
||||
{
|
||||
var root = context.CreateTempDirectory("space-option");
|
||||
File.WriteAllText(Path.Combine(root, "server.json"), """{ "SpacePath": "/space" }""");
|
||||
var file = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" });
|
||||
Assert.Equal("/space", file.SpacePath);
|
||||
Assert.DoesNotContain("SpacePath", file.Locked);
|
||||
var environment = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = root,
|
||||
["CHRONOS_DB"] = "postgres",
|
||||
["CHRONOS_SPACE_PATH"] = "/mnt/array",
|
||||
});
|
||||
Assert.Equal("/mnt/array", environment.SpacePath);
|
||||
Assert.Contains("SpacePath", environment.Locked);
|
||||
Assert.Null(new ServerOptions().SpacePath);
|
||||
}
|
||||
|
||||
/// <summary>Counts the warnings a <see cref="VolumeSpace"/> logs.</summary>
|
||||
private sealed class CountingLogger : ILogger<VolumeSpace>
|
||||
{
|
||||
private int _warnings;
|
||||
|
||||
public int Warnings => Volatile.Read(ref _warnings);
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (logLevel == LogLevel.Warning) Interlocked.Increment(ref _warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,7 +134,7 @@ internal sealed class SyncClient : IAsyncDisposable
|
||||
|
||||
public async Task<Job> WaitAsync(Guid jobId, JobState state = JobState.Done)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddSeconds(60);
|
||||
var until = DateTime.UtcNow.AddSeconds(TestTiming.Budget(60));
|
||||
while (true)
|
||||
{
|
||||
var job = await Db.Jobs.GetAsync(jobId, Ct);
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.RegularExpressions;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// release-channels: the public content follows the highest stable release, the image's :latest the highest stable or,
|
||||
/// while none exists, the highest pre-release (BRIEF §19.3, amended 2026-10-26, R1).
|
||||
/// </summary>
|
||||
public sealed class ReleaseChannelsCommandTests(TestContext context)
|
||||
{
|
||||
private static readonly ReleaseChannels Both = new(Latest: true, ImageLatest: true);
|
||||
private static readonly ReleaseChannels ImageOnly = new(Latest: false, ImageLatest: true);
|
||||
private static readonly ReleaseChannels Neither = new(Latest: false, ImageLatest: false);
|
||||
|
||||
[Test]
|
||||
public void TheHighestStableReleaseMovesBothChannels()
|
||||
{
|
||||
Assert.Equal(Both, Decide("v0.2.0", Releases("v0.1.0-rc.1", "v0.1.0", "v0.2.0-rc.1", "v0.2.0")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnOlderStableReleasePublishedAgainMovesNothing()
|
||||
{
|
||||
Assert.Equal(Neither, Decide("v1.0.0", Releases("v1.0.0", "v1.1.0", "v0.9.0")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WithoutAStableReleaseTheHighestPreReleaseMovesOnlyTheImage()
|
||||
{
|
||||
var releases = Releases("v0.1.0-rc.1", "v0.1.0-rc.2");
|
||||
Assert.Equal(ImageOnly, Decide("v0.1.0-rc.2", releases));
|
||||
// An older pre-release published again does not take :latest back.
|
||||
Assert.Equal(Neither, Decide("v0.1.0-rc.1", releases));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APreReleaseAfterAStableReleaseMovesNothing()
|
||||
{
|
||||
Assert.Equal(Neither, Decide("v0.2.0-rc.1", Releases("v0.1.0-rc.2", "v0.1.0", "v0.2.0-rc.1")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NumericPreReleaseIdentifiersCompareByValue()
|
||||
{
|
||||
var releases = Releases("v0.1.0-rc.2", "v0.1.0-rc.10", "v0.1.0-rc.9");
|
||||
Assert.Equal(ImageOnly, Decide("v0.1.0-rc.10", releases), "rc.10 is above rc.2 and rc.9");
|
||||
Assert.Equal(Neither, Decide("v0.1.0-rc.2", releases), "rc.2 is below rc.10");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BuildMetadataIsIgnoredForPrecedenceAndIsNotAPreRelease()
|
||||
{
|
||||
Assert.Equal(Both, Decide("v1.0.0+build.5", Releases("v1.0.0+build.4", "v0.9.0")));
|
||||
Assert.Equal(Neither, Decide("v1.0.0+zzz", Releases("v1.0.1+aaa")));
|
||||
Assert.Equal(ImageOnly, Decide("v1.0.0-rc.1+sha.5114f85", Releases("v1.0.0-rc.1")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DraftsAreIgnored()
|
||||
{
|
||||
var releases = new JsonArray(Release("v2.0.0", draft: true), Release("v1.0.0", draft: true), Release("v0.1.0-rc.1")).ToJsonString();
|
||||
Assert.Equal(ImageOnly, Decide("v0.1.0-rc.1", releases));
|
||||
Assert.Equal(Both, Decide("v1.5.0", releases));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TagsThatAreNotSemVerAreIgnored()
|
||||
{
|
||||
var releases = Releases("latest", "nightly", "v9", "v9.9", "9.9.9", "V9.9.9", "v09.0.0", "v9.9.9.9", "v9.9.9-",
|
||||
"v9.9.9-rc..1", "v9.9.9-rc.01", "v9.9.9\n");
|
||||
Assert.Equal(Both, Decide("v0.1.0", releases));
|
||||
// Entries without a usable tag name are skipped; one without flags counts as published.
|
||||
Assert.Equal(Neither, Decide("v2.0.0", """[{"name":"no tag"},{"tag_name":42},{"tag_name":"v3.0.0"},7,null]"""));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryPageOfTheListCounts()
|
||||
{
|
||||
// Gitea lists 50 releases a page, newest first: 50 pre-releases after v1.0.0 push it to the second page.
|
||||
var first = Releases([.. Enumerable.Range(1, 50).Reverse().Select(n => $"v1.1.0-rc.{n}")]);
|
||||
var second = Releases("v1.0.0", "v0.9.0");
|
||||
Assert.Equal(ImageOnly, Decide("v1.1.0-rc.51", first), "the first page alone shows no stable release");
|
||||
Assert.Equal(Neither, Decide("v1.1.0-rc.51", first, second));
|
||||
Assert.Equal(Neither, Decide("v0.9.0", first, second));
|
||||
Assert.Equal(Both, Decide("v1.1.0", first, second, "[]"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheTagCountsAsPublishedWhenTheListIsEmpty()
|
||||
{
|
||||
Assert.Equal(Both, Decide("v1.0.0", "[]"));
|
||||
Assert.Equal(ImageOnly, Decide("v1.0.0-rc.1", "[]"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AStableTagGiteaFlagsAsAPreReleaseCountsAsAPreRelease()
|
||||
{
|
||||
var releases = new JsonArray(Release("v1.0.0", prerelease: true), Release("v0.9.0")).ToJsonString();
|
||||
Assert.Equal(Neither, Decide("v1.0.0", releases));
|
||||
Assert.Equal(Both, Decide("v0.9.0", releases));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void VersionsFollowTheSemVerPrecedence()
|
||||
{
|
||||
// semver.org §11's example, then the core numbers (one longer than a long integer): each is lower than the next.
|
||||
string[] ordered =
|
||||
[
|
||||
"v1.0.0-alpha", "v1.0.0-alpha.1", "v1.0.0-alpha.beta", "v1.0.0-beta", "v1.0.0-beta.2", "v1.0.0-beta.11",
|
||||
"v1.0.0-rc.1", "v1.0.0", "v1.0.1", "v1.1.0", "v2.0.0", "v10.0.0", "v12345678901234567890.0.0",
|
||||
];
|
||||
for (var i = 0; i + 1 < ordered.Length; i++)
|
||||
{
|
||||
var lower = Assert.NotNull(TagVersion.Parse(ordered[i]));
|
||||
var higher = Assert.NotNull(TagVersion.Parse(ordered[i + 1]));
|
||||
Assert.True(lower.CompareTo(higher) < 0 && higher.CompareTo(lower) > 0, $"{ordered[i]} < {ordered[i + 1]}");
|
||||
}
|
||||
Assert.Equal(0, Assert.NotNull(TagVersion.Parse("v1.0.0+a")).CompareTo(TagVersion.Parse("v1.0.0+b")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheOutputIsTwoLinesForTheWorkflow()
|
||||
{
|
||||
Assert.Equal("latest=false\nimage_latest=true\n", ReleaseChannelsCommand.Render(ImageOnly));
|
||||
Assert.Equal("latest=true\nimage_latest=true\n", ReleaseChannelsCommand.Render(Both));
|
||||
Assert.Equal("latest=false\nimage_latest=false\n", ReleaseChannelsCommand.Render(Neither));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnInvalidTagOrReleasesFileIsRefused()
|
||||
{
|
||||
var file = Path.Combine(context.CreateTempDirectory("release-channels"), "releases.json");
|
||||
await File.WriteAllTextAsync(file, "[]");
|
||||
var command = new ReleaseChannelsCommand();
|
||||
|
||||
var invalid = await Assert.ThrowsAsync<ToolException>(() => command.RunAsync(["--tag", "1.0.0", "--releases", file]));
|
||||
Assert.Contains("'1.0.0'", invalid.Message);
|
||||
await Assert.ThrowsAsync<ToolException>(() => command.RunAsync(["--tag", "v1.0.0-rc.01", "--releases", file]));
|
||||
await Assert.ThrowsAsync<ToolException>(() => command.RunAsync(["--releases", file]));
|
||||
await Assert.ThrowsAsync<ToolException>(() => command.RunAsync(["--tag", "v1.0.0", "--releases", file + ".missing"]));
|
||||
// Every page is read: a missing one is refused, not skipped.
|
||||
Assert.Equal(0, await command.RunAsync(["--tag", "v1.0.0", "--releases", file, "--releases", file]));
|
||||
await Assert.ThrowsAsync<ToolException>(() => command.RunAsync(["--tag", "v1.0.0", "--releases", file, "--releases", file + ".missing"]));
|
||||
// A sign-in page or an API error instead of the list, on any page.
|
||||
Assert.Throws<ToolException>(() => Decide("v1.0.0", "<html>Sign in</html>"));
|
||||
Assert.Throws<ToolException>(() => Decide("v1.0.0", """{"message":"not found"}"""));
|
||||
Assert.Throws<ToolException>(() => Decide("v1.0.0", "[]", """{"message":"not found"}"""));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheReleaseWorkflowRefusesTheTagsReleaseChannelsRefuses()
|
||||
{
|
||||
// release.yml checks the tag before building, so a tag release-channels would refuse never gets published.
|
||||
var lines = File.ReadAllLines(Path.Combine(Args.RepoRoot(), ".gitea", "workflows", "release.yml"))
|
||||
.Select(l => l.Trim()).Where(l => l.StartsWith("semver='", StringComparison.Ordinal) && l.EndsWith('\'')).ToList();
|
||||
Assert.Count(1, lines);
|
||||
var check = new Regex(lines[0]["semver='".Length..^1], RegexOptions.CultureInvariant);
|
||||
|
||||
string[] tags =
|
||||
[
|
||||
"v0.1.0", "v1.2.3", "v10.20.30", "v0.1.0-rc.1", "v1.0.0-alpha.beta", "v1.0.0-0", "v1.0.0-x-y.7z.92", "v1.0.0-rc.1+sha.5",
|
||||
"v1.0.0+build", "1.0.0", "V1.0.0", "v1.0", "v1.0.0.0", "v01.2.0", "v1.02.0", "v1.2.03", "v1.0.0-", "v1.0.0-rc.",
|
||||
"v1.0.0-rc..1", "v1.0.0-rc.01", "v1.0.0-rc_1", "latest",
|
||||
];
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
// Build metadata is refused by the workflow as well: an image tag cannot hold a "+".
|
||||
var expected = TagVersion.Parse(tag) is not null && !tag.Contains('+', StringComparison.Ordinal);
|
||||
Assert.Equal(expected, check.IsMatch(tag), tag);
|
||||
}
|
||||
}
|
||||
|
||||
private static ReleaseChannels Decide(string tag, params string[] releases) => ReleaseChannelsCommand.Decide(tag, releases);
|
||||
|
||||
private static string Releases(params string[] tags) => new JsonArray([.. tags.Select(t => Release(t))]).ToJsonString();
|
||||
|
||||
// The fields of Gitea's release list that matter, flagged as gitea-release publishes them.
|
||||
private static JsonObject Release(string tag, bool draft = false, bool? prerelease = null) => new()
|
||||
{
|
||||
["tag_name"] = tag,
|
||||
["draft"] = draft,
|
||||
["prerelease"] = prerelease ?? tag.Contains('-', StringComparison.Ordinal),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user