Files
Chronos/tests/Chronos.App.Tests/Settings/SettingsLogicTests.cs
T
Alby96andClaude Opus 5.5 7e4a3b481d
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-27 21:58:39 +01:00

359 lines
20 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.ComponentModel;
using System.Globalization;
using System.IO;
using Chronos.App.Settings;
using Chronos.Core.Localization;
using Chronos.Core.Naming;
using Chronos.Core.Video;
using Chronos.Testing;
namespace Chronos.App.Tests.Settings;
public sealed class SettingsLogicTests
{
public SettingsLogicTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void DefaultTemplatesPreviewThreeNames()
{
var names = NamingPreview.FirstNames(TemplateDefaults.Folder, TemplateDefaults.File);
Assert.SequenceEqual(
[
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2",
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-13_0002.CR2",
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-15_0003.CR2",
],
names);
Assert.Null(NamingPreview.Validate(TemplateDefaults.Folder, isFolder: true));
Assert.Null(NamingPreview.Validate(TemplateDefaults.File, isFolder: false));
}
[Theory]
[Case("{date}_{time}_{n:0000", "Errors.Template.UnclosedBrace", "", 15)]
[Case("{date}_{nope}", "Errors.Template.UnknownToken", "nope", 8)]
[Case("{}_{n}", "Errors.Template.EmptyToken", "", 1)]
[Case("{n}}x", "Errors.Template.UnopenedBrace", "", 4)]
[Case(" ", "Errors.Template.Empty", "", 1)]
[Case("{date}", "Errors.Template.NotUnique", "", 0)]
[Case("{year}/{n}", "Errors.Template.FileSeparator", "", 0)]
[Case("{date:%}_{n}", "Errors.Template.Format", "", 0)]
[Case("{n}{ext}", "Errors.Template.Extension", "", 0)]
[Case("{title}_{ext}", "Errors.Template.Extension", "", 0)]
public void InvalidFileTemplatesExplainTheProblem(string template, string key, string token, int position)
{
var expected = position > 0 ? Loc.L(key, token, position) : Loc.L(key);
Assert.Equal(expected, NamingPreview.Validate(template, isFolder: false), template);
Assert.Empty(NamingPreview.FirstNames(TemplateDefaults.Folder, template));
}
[Test]
public void TemplateErrorsNameThePosition()
{
Assert.Equal("The brace opened at position 8 is never closed.", NamingPreview.Validate("{date}_{time", isFolder: false));
Assert.Equal("Unknown token “nope” at position 8.", NamingPreview.Validate("{date}_{nope}", isFolder: false));
}
[Test]
public void FolderTemplatesMayNestAndRepeat()
{
Assert.Null(NamingPreview.Validate("{year}/{month}/{camera}", isFolder: true));
Assert.Equal("2026/09/Canon EOS R5/IMG_4211.CR2", NamingPreview.FirstNames("{year}/{month}/{camera}", "{name}")[0]);
Assert.Null(NamingPreview.Validate("{name}.{ext}", isFolder: false));
}
[Theory]
[Case("Originals/{year}")]
[Case("{year}/exports")]
[Case(".archive/{date}")]
[Case("{year}/.chronos")]
public void FolderTemplatesScansWouldSkipAreRefused(string template)
{
Assert.Equal(Loc.L("Errors.Template.ReservedFolder"), NamingPreview.Validate(template, isFolder: true), template);
Assert.Empty(NamingPreview.FirstNames(template, TemplateDefaults.File));
}
[Test]
public void EnterCommitsAndEscReverts()
{
string? stored = null;
var field = new EditableField("8", v => int.TryParse(v, out var n) && n is >= 1 and <= 32 ? null : "1 to 32", v => stored = v, () => "Worker threads");
var changes = new List<string?>();
field.PropertyChanged += (_, e) => changes.Add(e.PropertyName);
var errors = 0;
field.ErrorsChanged += (_, _) => errors++;
field.Text = "12";
Assert.True(field.IsDirty);
Assert.False(field.HasErrors);
Assert.Equal("Worker threads", field.ToolTip);
Assert.True(field.Commit());
Assert.Equal("12", stored);
Assert.Equal("12", field.Value);
Assert.False(field.IsDirty);
field.Text = "99";
Assert.True(field.HasErrors);
Assert.Equal("1 to 32", field.ToolTip);
Assert.Equal("1 to 32", ((IEnumerable<string>)field.GetErrors(nameof(EditableField.Text))).Single());
Assert.False(field.Commit());
Assert.Equal("12", stored);
field.Revert();
Assert.Equal("12", field.Text);
Assert.False(field.HasErrors);
Assert.False(field.IsDirty);
Assert.Equal(2, errors);
Assert.Contains(nameof(EditableField.ToolTip), changes);
}
[Test]
public void LoadReplacesTheValueWithoutCommitting()
{
var commits = 0;
var field = new EditableField("a", v => v.Length == 0 ? "empty" : null, _ => commits++, () => "tip");
field.Load("b");
Assert.Equal("b", field.Value);
Assert.Equal("b", field.Text);
Assert.False(field.IsDirty);
Assert.Equal(0, commits);
Assert.True(field.Commit());
Assert.Equal(0, commits); // nothing changed, nothing stored
field.Load(string.Empty);
Assert.True(field.HasErrors);
}
[Test]
public void TheLanguageListHasEveryShippedCatalog()
{
var available = LanguageCatalog.Available;
Assert.Equal("en", available[0].Code);
Assert.Equal(available.Count, available.Select(l => l.Code).Distinct(StringComparer.OrdinalIgnoreCase).Count());
foreach (var option in available)
{
Assert.Contains(option.Code, Languages.Shipped);
Assert.True(LanguageCatalog.HasResources(option.Code), option.Code);
Assert.False(string.IsNullOrWhiteSpace(option.Name));
}
// Every culture folder of the catalog is offered, and nothing else.
var folders = Directory.EnumerateDirectories(Path.Combine(TestContext.RepositoryRoot, "i18n"))
.Select(Path.GetFileName)
.Where(n => n is not null && Directory.EnumerateFiles(Path.Combine(TestContext.RepositoryRoot, "i18n", n), "*.resx").Any())
.ToHashSet(StringComparer.OrdinalIgnoreCase);
Assert.Contains("it", folders);
Assert.SequenceEqual(folders.Order(StringComparer.OrdinalIgnoreCase), available.Select(o => o.Code).Order(StringComparer.OrdinalIgnoreCase));
Assert.Equal("Italiano", available.Single(o => o.Code == "it").Name);
Assert.Equal("it", LanguageCatalog.Match(CultureInfo.GetCultureInfo("it-CH")).Code);
Assert.Equal("en", LanguageCatalog.Match(CultureInfo.GetCultureInfo("sw")).Code);
}
[Test]
public void EachEncoderNamesThePresetsItServes()
{
var hevc = new EncoderRow("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc);
var av1 = hevc with { Codec = "AV1", Name = "NVIDIA AV1 Encoder MFT", VideoCodec = VideoCodec.Av1 };
var h264 = new EncoderRow("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264);
var animation = new EncoderRow("GIF · APNG", "Chronos", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null);
Assert.SequenceEqual(["8K archive", "4K archive", "4K HEVC", "DCI 4K", "Cinema 21:9", "4K 60 fps"], EncoderUse.Presets(hevc));
Assert.Equal("Animated GIF · Animated PNG", EncoderUse.Text(animation));
Assert.Contains("Share 1080p", EncoderUse.Presets(h264));
Assert.Equal("4K AV1", EncoderUse.Text(av1));
}
[Test]
public void ARenderNodeOffersHardwareEncodersOnlyWhenRendersMayUseThem()
{
EncoderRow[] rows =
[
new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc),
new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264),
new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264),
new("MJPEG · AVI", "Chronos", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg),
];
Assert.Equal("HEVC · H.264", EncoderUse.Codecs(EncoderUse.Node(rows, allowsHardware: true)));
Assert.Equal(3, EncoderUse.Node(rows, allowsHardware: true).Count);
Assert.Equal("H.264", EncoderUse.Codecs(EncoderUse.Node(rows, allowsHardware: false)));
Assert.Null(EncoderUse.Codecs([]));
}
[Test]
public void ThePreviewTitleSpeaksTheInterfaceLanguage()
{
// The sample's title is a catalog string read on every preview (so a language switch shows at once), not English text.
Assert.Equal("Harbour sunset", NamingPreview.FirstNames("{title}", "{n:0000}")[0].Split('/')[0]);
Assert.Equal("Harbour sunset", NamingPreview.SampleFrames[0].Title);
Assert.False(ReferenceEquals(NamingPreview.SampleFrames, NamingPreview.SampleFrames), "built on each call");
var italian = Loc.Get("Settings.Naming.SampleTitle", CultureInfo.GetCultureInfo("it"));
Assert.True(italian is { Length: > 0 } && italian != "Harbour sunset", italian);
}
[Test]
public void TheQualityProfileTunesTheJobs()
{
var settings = new Chronos.App.Infrastructure.AppSettings { Quality = Chronos.App.Infrastructure.QualityProfile.Best, Parallelism = 3, MemoryBudgetGb = 6 };
var basis = new Chronos.Data.Processing.ProcessingOptions();
// One job runs at a time (owner review 1): it has the whole 6 GB, and decodes and measures 3 photos at once.
var best = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((6L << 30, @"C:\cache", 8, 3), (best.FrameWindow.MemoryBudget, best.FrameWindow.SpillDirectory, best.FrameWindow.Ahead, best.FrameWindow.MaxConcurrentLoads));
Assert.Equal((1024, Chronos.Core.Project.FlowQualitySetting.Best), (best.Render.AnalysisLongEdge, best.Render.DefaultFlowQuality));
Assert.Equal(3, best.DeepAnalysis.MaxDegreeOfParallelism);
settings.Parallelism = 1;
var single = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((6L << 30, 1, 1), (single.FrameWindow.MemoryBudget, single.FrameWindow.MaxConcurrentLoads, single.DeepAnalysis.MaxDegreeOfParallelism));
// A parallelism beyond the read-ahead widens the window, so the decodes have frames to work on.
settings.Parallelism = 12;
var wide = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((12, 12, 12), (wide.FrameWindow.Ahead, wide.FrameWindow.MaxConcurrentLoads, wide.DeepAnalysis.MaxDegreeOfParallelism));
// Auto: a quarter of 32 GB, and half the 16 cores at once, with no cap of the analysis threads.
settings.Quality = Chronos.App.Infrastructure.QualityProfile.Fast;
settings.MemoryBudgetGb = null;
settings.Parallelism = null;
var fast = ProcessingTuning.Apply(basis, settings, 32L << 30, 16, @"C:\cache");
Assert.Equal((8L << 30, 8), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
Assert.Equal((8, 8), (fast.FrameWindow.MaxConcurrentLoads, fast.DeepAnalysis.MaxDegreeOfParallelism));
Assert.Equal((256, Chronos.Core.Project.FlowQualitySetting.Draft), (fast.Render.AnalysisLongEdge, fast.Render.DefaultFlowQuality));
Assert.Equal(512, ProcessingTuning.PreparationLongEdge(Chronos.App.Infrastructure.QualityProfile.Balanced));
}
[Test]
public void ParallelismAutoIsHalfTheCores()
{
// Photos the running job processes at once (owner review 1): half the cores, the archive engine's own default.
Assert.Equal(8, ProcessingTuning.ParallelismAuto(16));
Assert.Equal(2, ProcessingTuning.ParallelismAuto(4));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(1));
Assert.Equal(Chronos.Data.Archiving.ArchiveServiceOptions.DefaultParallelism, ProcessingTuning.ParallelismAuto(Environment.ProcessorCount));
Assert.Equal(1, new Chronos.Data.Jobs.JobEngineOptions().Workers);
Assert.Equal(8, ProcessingTuning.Parallelism(new Chronos.App.Infrastructure.AppSettings(), 16));
Assert.Equal(5, ProcessingTuning.Parallelism(new Chronos.App.Infrastructure.AppSettings { Parallelism = 5 }, 16));
}
[Test]
public void TheAnalysisSettingsBecomeTheDeepAnalysisParameters()
{
var defaults = new Chronos.App.Infrastructure.AppSettings().DeepAnalysis(Chronos.Core.Analysis.Deep.DeepAnalysisOptions.Default);
// The defaults of Settings › Analysis are the engine's own: nothing changes until the user does.
Assert.Equal(Chronos.Core.Analysis.Deep.DeepAnalysisOptions.Default.Fingerprint(), defaults.Fingerprint());
Assert.Equal(Chronos.Core.Analysis.Deep.DeepAnalysisOptions.Default.StarFieldDensity, defaults.StarFieldDensity);
var tuned = new Chronos.App.Infrastructure.AppSettings { AnalysisLongEdge = 1024, NightBrightnessPercent = 12.5, StarFieldDensity = 60 }
.DeepAnalysis(Chronos.Core.Analysis.Deep.DeepAnalysisOptions.Default);
Assert.Equal((1024, -3.0, 60.0), (tuned.MaxAnalysisLongEdge, tuned.DarkLogLuminance, tuned.StarFieldDensity));
}
[Test]
public void NewCardsStartFromSettingsImport()
{
var settings = new Chronos.App.Infrastructure.AppSettings
{
ImportSessionGapMinutes = 90,
ImportMinimumFrames = 20,
ImportSubfolders = false,
ImportVerify = false,
ImportDuplicates = Chronos.Core.Import.DuplicatePolicy.ImportAgain,
ImportAfter = Chronos.Data.Archiving.AfterImport.DeleteImported,
ImportEject = false,
DeepAnalysisAfterImport = false,
};
var profile = settings.ImportProfile("{year}", "{name}");
Assert.Equal(("{year}", "{name}", 90, 20), (profile.FolderTemplate, profile.FileTemplate, profile.SessionGapMinutes, profile.MinimumSessionFrames));
Assert.Equal((false, false, false, false), (profile.IncludeSubfolders, profile.VerifyCopies, profile.Eject, profile.DeepAnalysis));
Assert.Equal((Chronos.Core.Import.DuplicatePolicy.ImportAgain, Chronos.Data.Archiving.AfterImport.DeleteImported), (profile.Duplicates, profile.AfterImport));
// Untouched settings give the brief's card defaults.
Assert.Equal(new Chronos.Data.Archiving.CardProfile(), new Chronos.App.Infrastructure.AppSettings().ImportProfile(TemplateDefaults.Folder, TemplateDefaults.File));
}
[Test]
public void NewArchivesTakeSettingsArchive()
{
var settings = new Chronos.App.Infrastructure.AppSettings { FolderTemplate = "{year}", FileTemplate = "{name}", ProxyLongEdge = 2560, ThumbnailLongEdge = 480 };
var archive = settings.ArchiveDefaults();
Assert.Equal(("{year}", "{name}", 2560, 480), (archive.Templates.Folder, archive.Templates.File, archive.Proxies.LongEdge, archive.Thumbnails.LongEdge));
Assert.Null((new Chronos.App.Infrastructure.AppSettings().ArchiveDefaults() with { Name = "Archive" }).Problem());
}
[Test]
public void TheArchiveRowsEditOnlyTheArchiveAtTheArchiveFolder()
{
var main = new Chronos.Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive", Created = DateTimeOffset.UtcNow };
var travel = new Chronos.Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Travel", RootPath = "/media/travel", Created = DateTimeOffset.UtcNow };
Assert.Equal(travel.Id, Chronos.App.Archiving.CurrentArchive.At([main, travel], "/media/travel/")!.Id);
// A folder no archive of the index is at: no archive at all, never the first one (its archive.json is someone else's).
Assert.Null(Chronos.App.Archiving.CurrentArchive.At([main, travel], "/media/new"));
Assert.Equal(main.Id, Chronos.App.Archiving.CurrentArchive.Pick([main, travel], "/media/new")!.Id);
}
[Test]
public void SettingsSurviveARoundTripWithTheNewSections()
{
var settings = new Chronos.App.Infrastructure.AppSettings { ThumbnailLongEdge = 640, ScanIntervalMinutes = 30, NightBrightnessPercent = 3.5, DeepAnalysisAfterScan = true };
var copy = Chronos.App.Infrastructure.AppSettings.Parse(settings.ToJson())!;
Assert.Equal((640, 30, 3.5, true), (copy.ThumbnailLongEdge, copy.ScanIntervalMinutes, copy.NightBrightnessPercent, copy.DeepAnalysisAfterScan));
}
[Test]
public void BackgroundPriorityRaisesTheInterfaceOnlyInFront()
{
Assert.Equal(ThreadPriority.AboveNormal, InterfacePriority.For(enabled: true, active: true));
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: true, active: false));
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: false, active: true));
}
[Test]
public void FormatsShowTheirTierAndWhatToInstall()
{
Assert.Equal(("JPEG XL", "CR3", "3FR"), (FormatNames.Of(Chronos.Core.Imaging.ImageFileFormat.JpegXl), FormatNames.Of(Chronos.Core.Imaging.ImageFileFormat.Cr3),
FormatNames.Of(Chronos.Core.Imaging.ImageFileFormat.ThreeFr)));
var heif = Chronos.Core.Windows.Codecs.StoreExtension.Get(Chronos.Core.Windows.Codecs.StoreExtensionKind.HeifImage);
var format = Chronos.Core.Imaging.Decoders.DecoderFactory.DescribeFormats(Chronos.Core.Imaging.Decoders.DecoderFactory.CreateClient(null))
.First(f => f.Format.Format == Chronos.Core.Imaging.ImageFileFormat.Heif).Format;
var row = new FormatRowViewModel(new FormatRow(format, Chronos.Core.Imaging.DecodeTier.EmbeddedPreview, "managed", [heif]));
Assert.Equal(("Preview only", "Chronos", heif.ProductName), (row.TierText, row.DecoderText, row.NeedsText));
Assert.Equal(Chronos.Ui.Controls.StatusKind.Warning, row.TierKind);
Assert.Equal("HEIF: Preview only", row.Announcement);
var missing = new MissingExtensionViewModel(heif, new Chronos.Ui.Mvvm.RelayCommand(() => { }));
Assert.Equal(heif.ProductName + " missing", missing.Text);
var none = new FormatRowViewModel(new FormatRow(format, Chronos.Core.Imaging.DecodeTier.Unavailable, null, []));
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()
{
var keys = new List<string>();
keys.AddRange(Enum.GetNames<Chronos.Core.Model.JobKind>().Select(k => "Jobs.Kind." + k));
keys.AddRange(Enum.GetNames<Chronos.Core.Model.JobState>().Select(k => "Jobs.State." + k));
keys.AddRange(Enum.GetNames<Chronos.Core.Model.JobState>().Select(k => "Tooltips.Jobs.State." + k));
keys.AddRange(Enum.GetNames<Chronos.App.Jobs.JobFilter>().SelectMany(k => new[] { "Jobs.Filter." + k, "Tooltips.Jobs.Filter." + k }));
keys.AddRange(Enum.GetNames<Chronos.App.Library.StatusFilter>().Where(k => k != "Any").Select(k => "Library.Filter.Status." + k));
keys.AddRange(Enum.GetNames<Chronos.Data.Repositories.SequenceSort>().Select(k => "Library.Sort." + k));
keys.AddRange(Enum.GetNames<Chronos.App.Server.ConnectError>().Where(k => k != "None").Select(k => "Server.Error." + k));
keys.AddRange(Enum.GetNames<Chronos.Core.Model.UserRole>().SelectMany(k => new[] { "Server.Role." + k, "Tooltips.Server.Role." + k }));
keys.AddRange(Enum.GetNames<SettingsPage>().SelectMany(k => new[] { "Settings.Page." + k, "Tooltips.Settings.Page." + k }));
keys.AddRange(Enum.GetNames<Chronos.App.Infrastructure.QualityProfile>().Select(k => "Settings.Rendering.Quality." + k));
keys.AddRange(new[] { "UnclosedBrace", "EmptyToken", "UnknownToken", "UnopenedBrace", "Empty" }.Select(k => "Errors.Template." + k));
// Italian completeness is checked by `Chronos.Tools i18n check`; here every enum value must have its key.
var english = Loc.GetArea("Jobs", CultureInfo.InvariantCulture).Keys
.Concat(new[] { "Library", "Server", "Settings", "Tooltips", "Errors" }.SelectMany(a => Loc.GetArea(a, CultureInfo.InvariantCulture).Keys))
.ToHashSet(StringComparer.Ordinal);
foreach (var key in keys) Assert.True(english.Contains(key), key);
}
}