feat(app): library, jobs, settings, server, welcome and about screens
Local-mode composition root (SQLite index, one JobEngine fed by a single handler registration list), keyset-paged library with thumbnail cache and hover scrub, live job list with throttled updates and the shell job bar, settings with live template validation and encoder self-test, server connection with trust-on-first-use and DPAPI token, first-run welcome, About with update check, and --capture screenshots with synthetic data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
94 files changed
+10130
-374
No files matched your search
@@ -0,0 +1,74 @@
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using Titano.App.About;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.About;
|
||||
|
||||
public sealed class UpdateCheckTests
|
||||
{
|
||||
[Theory]
|
||||
[Case("v1.2.3", "1.2.3")]
|
||||
[Case("1.2", "1.2.0")]
|
||||
[Case("V0.10.0-beta.2", "0.10.0")]
|
||||
[Case("v2.0.1+abc", "2.0.1")]
|
||||
public void TagsParseToVersions(string tag, string expected) =>
|
||||
Assert.Equal(Version.Parse(expected), UpdateCheck.ParseVersion(tag));
|
||||
|
||||
[Theory]
|
||||
[Case(null)]
|
||||
[Case("")]
|
||||
[Case("latest")]
|
||||
[Case("v-one")]
|
||||
public void OtherTagsAreIgnored(string? tag) => Assert.Null(UpdateCheck.ParseVersion(tag));
|
||||
|
||||
[Test]
|
||||
public void TheLatestReleaseIsComparedWithTheRunningVersion()
|
||||
{
|
||||
var release = UpdateCheck.Parse("""{ "tag_name": "v0.2.0", "html_url": "https://github.com/o/r/releases/tag/v0.2.0", "draft": false, "prerelease": false }""");
|
||||
Assert.NotNull(release);
|
||||
Assert.Equal(new Version(0, 2, 0), release!.Version);
|
||||
Assert.True(UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion("0.1.0")));
|
||||
Assert.False(UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion("0.2.0+local")));
|
||||
Assert.False(UpdateCheck.IsNewer(release, new Version(0, 2, 0, 0)));
|
||||
Assert.False(UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion("1.0.0")));
|
||||
Assert.Equal("0.2.0", UpdateCheck.Display(release.Version));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DraftsPrereleasesAndOddLinksAreIgnored()
|
||||
{
|
||||
Assert.Null(UpdateCheck.Parse("""{ "tag_name": "v9.0.0", "html_url": "https://x", "prerelease": true }"""));
|
||||
Assert.Null(UpdateCheck.Parse("""{ "tag_name": "v9.0.0", "html_url": "https://x", "draft": true }"""));
|
||||
Assert.Null(UpdateCheck.Parse("""{ "tag_name": "v9.0.0", "html_url": "javascript:alert(1)" }"""));
|
||||
Assert.Null(UpdateCheck.Parse("""{ "html_url": "https://x" }"""));
|
||||
Assert.Null(UpdateCheck.Parse("[]"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FetchReadsTheApiAndToleratesMissingReleases()
|
||||
{
|
||||
using var ok = new HttpClient(new Reply(HttpStatusCode.OK, """{ "tag_name": "v1.0.0", "html_url": "https://github.com/o/r/releases/tag/v1.0.0" }"""));
|
||||
var release = await UpdateCheck.FetchAsync(ok, "https://api.github.com/repos/o/r/releases/latest", "0.1.0", CancellationToken.None);
|
||||
Assert.Equal(new Version(1, 0, 0), release!.Version);
|
||||
|
||||
using var none = new HttpClient(new Reply(HttpStatusCode.NotFound, "{}"));
|
||||
Assert.Null(await UpdateCheck.FetchAsync(none, "https://api.github.com/repos/o/r/releases/latest", "0.1.0", CancellationToken.None));
|
||||
|
||||
using var garbage = new HttpClient(new Reply(HttpStatusCode.OK, "<html>"));
|
||||
Assert.Null(await UpdateCheck.FetchAsync(garbage, "https://api.github.com/repos/o/r/releases/latest", "0.1.0", CancellationToken.None));
|
||||
|
||||
using var broken = new HttpClient(new Reply(HttpStatusCode.InternalServerError, "{}"));
|
||||
await Assert.ThrowsAsync<HttpRequestException>(() => UpdateCheck.FetchAsync(broken, "https://api.github.com/repos/o/r/releases/latest", "0.1.0", CancellationToken.None));
|
||||
}
|
||||
|
||||
private sealed class Reply(HttpStatusCode status, string body) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Assert.True(request.Headers.UserAgent.ToString().StartsWith("Titano/", StringComparison.Ordinal), "GitHub requires a User-Agent");
|
||||
return Task.FromResult(new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using System.Globalization;
|
||||
using Titano.App.Jobs;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Jobs;
|
||||
|
||||
public sealed class JobListModelTests
|
||||
{
|
||||
private static readonly DateTimeOffset T0 = new(2026, 9, 28, 10, 0, 0, TimeSpan.Zero);
|
||||
|
||||
[Test]
|
||||
public void OrderIsRunningPausedQueueThenNewestHistory()
|
||||
{
|
||||
var model = new JobListModel();
|
||||
var oldDone = Job(JobState.Done, created: -60, started: -60, finished: -50);
|
||||
var newDone = Job(JobState.Done, created: -40, started: -40, finished: -10);
|
||||
var failed = Job(JobState.Failed, created: -30, started: -30, finished: -20);
|
||||
var queuedLow = Job(JobState.Queued, created: -50, priority: JobPriority.Background);
|
||||
var queuedOld = Job(JobState.Queued, created: -45);
|
||||
var queuedNew = Job(JobState.Queued, created: -5);
|
||||
var queuedUrgent = Job(JobState.Queued, created: -1, priority: JobPriority.User);
|
||||
var paused = Job(JobState.Paused, created: -35, started: -35);
|
||||
var runningLate = Job(JobState.Running, created: -8, started: -3);
|
||||
var runningEarly = Job(JobState.Running, created: -9, started: -7);
|
||||
foreach (var j in new[] { oldDone, newDone, failed, queuedLow, queuedOld, queuedNew, queuedUrgent, paused, runningLate, runningEarly }) model.Apply(j);
|
||||
|
||||
var order = model.Ordered().Select(e => e.Id).ToList();
|
||||
Assert.SequenceEqual(
|
||||
new[] { runningEarly, runningLate, paused, queuedUrgent, queuedOld, queuedNew, queuedLow, newDone, failed, oldDone }.Select(j => j.Id),
|
||||
order);
|
||||
|
||||
Assert.Equal(1, model.QueuePosition(queuedUrgent.Id));
|
||||
Assert.Equal(2, model.QueuePosition(queuedOld.Id));
|
||||
Assert.Equal(4, model.QueuePosition(queuedLow.Id));
|
||||
Assert.Equal(0, model.QueuePosition(runningEarly.Id));
|
||||
Assert.Equal(2, model.RunningCount);
|
||||
Assert.Equal(4, model.QueuedCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FiltersCountAndHideClearedHistory()
|
||||
{
|
||||
var model = new JobListModel();
|
||||
model.Apply(Job(JobState.Running, started: -1));
|
||||
model.Apply(Job(JobState.Paused, started: -2));
|
||||
model.Apply(Job(JobState.Queued));
|
||||
model.Apply(Job(JobState.Done, started: -30, finished: -20));
|
||||
model.Apply(Job(JobState.Done, started: -5, finished: -2));
|
||||
model.Apply(Job(JobState.Failed, started: -6, finished: -4));
|
||||
model.Apply(Job(JobState.Cancelled, started: -7, finished: -6));
|
||||
|
||||
Assert.Equal(7, model.CountOf(JobFilter.All));
|
||||
Assert.Equal(2, model.CountOf(JobFilter.Running));
|
||||
Assert.Equal(1, model.CountOf(JobFilter.Queued));
|
||||
Assert.Equal(2, model.CountOf(JobFilter.Done));
|
||||
Assert.Equal(2, model.CountOf(JobFilter.Failed));
|
||||
|
||||
var cleared = T0.AddMinutes(-10);
|
||||
Assert.Equal(1, model.CountOf(JobFilter.Done, cleared));
|
||||
Assert.Equal(6, model.Ordered(JobFilter.All, null, cleared).Count);
|
||||
Assert.Equal(3, model.Ordered(JobFilter.All, null, T0).Count); // only the active jobs remain
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SearchMatchesTargetAndKind()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var model = new JobListModel();
|
||||
model.Apply(Job(JobState.Queued, kind: JobKind.Render, label: "Harbour sunset → 4K"));
|
||||
model.Apply(Job(JobState.Queued, kind: JobKind.Verify, label: "Archive · 2024"));
|
||||
Assert.Equal(1, model.Ordered(JobFilter.All, "harbour").Count);
|
||||
Assert.Equal(1, model.Ordered(JobFilter.All, "verify").Count);
|
||||
Assert.Equal(2, model.Ordered(JobFilter.All, " ").Count);
|
||||
Assert.Empty(model.Ordered(JobFilter.All, "comet"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProgressMergesIntoRunningJobsOnly()
|
||||
{
|
||||
var model = new JobListModel();
|
||||
var running = Job(JobState.Running, started: -1, done: 10, total: 100);
|
||||
var queued = Job(JobState.Queued);
|
||||
model.Apply(running);
|
||||
model.Apply(queued);
|
||||
|
||||
Assert.True(model.Apply(Progress(running.Id, 62, 100, 11.3, TimeSpan.FromMinutes(2))));
|
||||
Assert.False(model.Apply(Progress(queued.Id, 5, 100)));
|
||||
Assert.False(model.Apply(Progress(Guid.CreateVersion7(), 5, 100)));
|
||||
|
||||
var entry = model[running.Id]!;
|
||||
Assert.Equal(62, entry.Done);
|
||||
Assert.Approximately(0.62, entry.Fraction!.Value, 1e-9);
|
||||
Assert.Equal(11.3, entry.ItemsPerSecond);
|
||||
Assert.Same(entry, model.Current);
|
||||
Assert.Equal(0, model[queued.Id]!.Done);
|
||||
|
||||
// Finishing drops the live progress and falls back to the stored snapshot.
|
||||
model.Apply(running with { State = JobState.Done, ProgressDone = 100, Finished = T0 });
|
||||
Assert.Null(model[running.Id]!.Live);
|
||||
Assert.Equal(100, model[running.Id]!.Done);
|
||||
Assert.Null(model.Current);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ALoadedPageNeverOverwritesANewerEvent()
|
||||
{
|
||||
var model = new JobListModel();
|
||||
var queued = Job(JobState.Queued);
|
||||
var readAt = model.Stamp; // page requested
|
||||
model.Apply(queued with { State = JobState.Running, Started = T0 }); // event arrives first
|
||||
Assert.False(model.ApplyLoaded(queued, readAt)); // the stale page row is ignored
|
||||
Assert.Equal(JobState.Running, model[queued.Id]!.State);
|
||||
|
||||
var other = Job(JobState.Done, started: -3, finished: -1);
|
||||
Assert.True(model.ApplyLoaded(other, model.Stamp));
|
||||
Assert.True(model.Apply(other with { State = JobState.Queued, Finished = null }));
|
||||
Assert.Equal(JobState.Queued, model[other.Id]!.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CurrentPrefersTheJobWithLiveProgress()
|
||||
{
|
||||
var model = new JobListModel();
|
||||
var a = Job(JobState.Running, started: -10);
|
||||
var b = Job(JobState.Running, started: -1);
|
||||
model.Apply(a);
|
||||
model.Apply(b);
|
||||
Assert.Equal(a.Id, model.Current!.Id);
|
||||
model.Apply(Progress(b.Id, 1, 2));
|
||||
Assert.Equal(b.Id, model.Current!.Id);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClaimOrderMatchesTheRepository()
|
||||
{
|
||||
var older = Job(JobState.Queued, created: -10);
|
||||
var newer = Job(JobState.Queued, created: -5);
|
||||
var urgent = Job(JobState.Queued, created: -1, priority: JobPriority.User);
|
||||
Assert.True(JobListModel.ClaimsBefore(older, newer));
|
||||
Assert.True(JobListModel.ClaimsBefore(urgent, older));
|
||||
Assert.False(JobListModel.ClaimsBefore(newer, older));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TextsDescribeTheJob()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var running = new JobEntry(Job(JobState.Running, kind: JobKind.Render, label: "Harbour sunset", started: -3))
|
||||
{
|
||||
Live = Progress(Guid.Empty, 2232, 3600, 11.3, TimeSpan.FromMinutes(2)),
|
||||
};
|
||||
Assert.Equal("Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left", JobText.Bar(running));
|
||||
Assert.Equal("2 min", JobText.Left(running, 0));
|
||||
Assert.Equal("118/s", JobText.Speed(JobKind.Import, 118));
|
||||
Assert.Equal(string.Empty, JobText.Speed(JobKind.Render, null));
|
||||
Assert.Equal("this PC", JobText.Where("STUDIO#2", "studio"));
|
||||
Assert.Equal("render-box", JobText.Where("render-box", "studio"));
|
||||
|
||||
var queued = new JobEntry(Job(JobState.Queued));
|
||||
Assert.Equal("next", JobText.Left(queued, 1));
|
||||
Assert.Equal("after 2", JobText.Left(queued, 3));
|
||||
|
||||
var done = new JobEntry(Job(JobState.Done, started: -10, finished: -7));
|
||||
Assert.Equal("done · 3:00", JobText.State(done));
|
||||
}
|
||||
|
||||
private static Job Job(JobState state, int created = 0, int? started = null, int? finished = null, JobPriority priority = JobPriority.Normal,
|
||||
JobKind kind = JobKind.Proxies, string? label = null, long done = 0, long total = 0) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
State = state,
|
||||
Priority = priority,
|
||||
TargetLabel = label,
|
||||
ProgressDone = done,
|
||||
ProgressTotal = total,
|
||||
Created = T0.AddMinutes(created),
|
||||
Started = started is { } s ? T0.AddMinutes(s) : null,
|
||||
Finished = finished is { } f ? T0.AddMinutes(f) : null,
|
||||
};
|
||||
|
||||
private static JobProgressInfo Progress(Guid id, long done, long total, double? rate = null, TimeSpan? eta = null) =>
|
||||
new(id, JobKind.Render, null, done, total, rate, eta, null);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Titano.App.Jobs;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Jobs;
|
||||
|
||||
public sealed class JobUpdateBufferTests
|
||||
{
|
||||
[Test]
|
||||
public void ThousandsOfEventsCoalesceToTheLatestPerJob()
|
||||
{
|
||||
var buffer = new JobUpdateBuffer();
|
||||
var ids = Enumerable.Range(0, 3).Select(_ => Guid.CreateVersion7()).ToArray();
|
||||
Parallel.For(0, 3000, i =>
|
||||
{
|
||||
var id = ids[i % 3];
|
||||
buffer.Post(new JobProgressInfo(id, JobKind.Render, null, i, 3000, null, null, null));
|
||||
});
|
||||
Assert.Equal(3000, buffer.Posted);
|
||||
var (jobs, progress) = buffer.Drain();
|
||||
Assert.Empty(jobs);
|
||||
Assert.Equal(3, progress.Count);
|
||||
Assert.True(buffer.IsEmpty);
|
||||
Assert.Empty(buffer.Drain().Progress);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AStateChangeSupersedesEarlierProgress()
|
||||
{
|
||||
var buffer = new JobUpdateBuffer();
|
||||
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Running };
|
||||
Assert.True(buffer.Post(new JobProgressInfo(job.Id, job.Kind, null, 5, 10, null, null, null)));
|
||||
Assert.False(buffer.Post(job with { State = JobState.Done }));
|
||||
var (jobs, progress) = buffer.Drain();
|
||||
Assert.Equal(JobState.Done, jobs.Single().State);
|
||||
Assert.Empty(progress);
|
||||
|
||||
// Progress after the snapshot is kept: it is newer.
|
||||
buffer.Post(job);
|
||||
buffer.Post(new JobProgressInfo(job.Id, job.Kind, null, 7, 10, null, null, null));
|
||||
(jobs, progress) = buffer.Drain();
|
||||
Assert.Equal(1, jobs.Count);
|
||||
Assert.Equal(7, progress.Single().Done);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheThrottleFlushesAtMostOncePerInterval()
|
||||
{
|
||||
var flushes = new ConcurrentQueue<long>();
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
using var throttle = new CoalescingThrottle(TimeSpan.FromMilliseconds(100), null, () => flushes.Enqueue(clock.ElapsedMilliseconds));
|
||||
|
||||
// A burst of signals from several threads for about 550 ms.
|
||||
var stop = DateTime.UtcNow.AddMilliseconds(550);
|
||||
await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => Task.Run(async () =>
|
||||
{
|
||||
while (DateTime.UtcNow < stop)
|
||||
{
|
||||
throttle.Signal();
|
||||
await Task.Delay(1);
|
||||
}
|
||||
})));
|
||||
await Task.Delay(250);
|
||||
|
||||
var times = flushes.ToArray();
|
||||
Assert.InRange(times.Length, 3, 8);
|
||||
for (var i = 1; i < times.Length; i++) Assert.GreaterOrEqual(times[i] - times[i - 1], 80, $"flush {i} came too early");
|
||||
Assert.Equal(times.Length, throttle.Flushes);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheFirstSignalFlushesWithoutWaiting()
|
||||
{
|
||||
var flushed = new TaskCompletionSource();
|
||||
using var throttle = new CoalescingThrottle(TimeSpan.FromSeconds(30), null, () => flushed.TrySetResult());
|
||||
throttle.Signal();
|
||||
await flushed.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal(1, throttle.Flushes);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FlushesRunOnTheGivenContext()
|
||||
{
|
||||
var context = new RecordingContext();
|
||||
var flushed = new TaskCompletionSource();
|
||||
using var throttle = new CoalescingThrottle(TimeSpan.FromMilliseconds(10), context, () => flushed.TrySetResult());
|
||||
throttle.Signal();
|
||||
await flushed.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal(1, context.Posts);
|
||||
}
|
||||
|
||||
private sealed class RecordingContext : SynchronizationContext
|
||||
{
|
||||
private int _posts;
|
||||
|
||||
public int Posts => Volatile.Read(ref _posts);
|
||||
|
||||
public override void Post(SendOrPostCallback d, object? state)
|
||||
{
|
||||
Interlocked.Increment(ref _posts);
|
||||
ThreadPool.QueueUserWorkItem(_ => d(state));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using Titano.App.Library;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Library;
|
||||
|
||||
public sealed class LibraryPagerTests
|
||||
{
|
||||
[Test]
|
||||
public async Task PagesFollowTheCursorUntilTheEnd()
|
||||
{
|
||||
var source = new FakeSource(450);
|
||||
var pager = new LibraryPager(source.FetchAsync, pageSize: 200);
|
||||
|
||||
var first = Assert.NotNull(await pager.ResetAsync(new LibraryFilter()));
|
||||
Assert.True(first.IsFirst);
|
||||
Assert.Equal(200, first.Items.Count);
|
||||
Assert.True(pager.HasMore);
|
||||
Assert.Null(source.Queries[0].Cursor);
|
||||
|
||||
var second = Assert.NotNull(await pager.LoadMoreAsync());
|
||||
Assert.False(second.IsFirst);
|
||||
Assert.Equal(200, second.Items.Count);
|
||||
Assert.Equal("200", source.Queries[1].Cursor);
|
||||
|
||||
var third = Assert.NotNull(await pager.LoadMoreAsync());
|
||||
Assert.Equal(50, third.Items.Count);
|
||||
Assert.False(third.HasMore);
|
||||
Assert.False(pager.HasMore);
|
||||
Assert.Equal(450, pager.Loaded);
|
||||
|
||||
Assert.Null(await pager.LoadMoreAsync());
|
||||
Assert.Equal(3, source.Queries.Count);
|
||||
var ids = first.Items.Concat(second.Items).Concat(third.Items).Select(s => s.Id).ToList();
|
||||
Assert.Equal(450, ids.Distinct().Count());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FilterAndSortReachTheQuery()
|
||||
{
|
||||
var source = new FakeSource(10);
|
||||
var pager = new LibraryPager(source.FetchAsync, pageSize: 50);
|
||||
await pager.ResetAsync(new LibraryFilter
|
||||
{
|
||||
Text = " harbour ",
|
||||
Year = 2026,
|
||||
Camera = "Canon EOS R5",
|
||||
Status = StatusFilter.NotAnalysed,
|
||||
Tag = "sunset",
|
||||
Sort = SequenceSort.Title,
|
||||
});
|
||||
var q = source.Queries.Single();
|
||||
Assert.Equal("harbour", q.Text);
|
||||
Assert.Equal(2026, q.Year);
|
||||
Assert.Equal("Canon EOS R5", q.Camera);
|
||||
Assert.Equal("sunset", q.Tag);
|
||||
Assert.Equal(SequenceStatus.None, q.WithStatus);
|
||||
Assert.Equal(SequenceStatus.AnalyzedLight, q.WithoutStatus);
|
||||
Assert.Equal(SequenceSort.Title, q.Sort);
|
||||
Assert.Equal(50, q.Limit);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AResetDropsThePageOfTheOldFilter()
|
||||
{
|
||||
var source = new FakeSource(1000) { Gate = new TaskCompletionSource() };
|
||||
var pager = new LibraryPager(source.FetchAsync, pageSize: 100);
|
||||
var stale = pager.ResetAsync(new LibraryFilter { Text = "old" });
|
||||
|
||||
source.Gate = null;
|
||||
var fresh = await pager.ResetAsync(new LibraryFilter { Text = "new" });
|
||||
Assert.NotNull(fresh);
|
||||
Assert.Equal(2, fresh!.Generation);
|
||||
|
||||
// The first request was cancelled; even if its data had arrived it must not be applied.
|
||||
Assert.Null(await stale);
|
||||
Assert.True(source.Cancelled > 0);
|
||||
Assert.Equal("new", pager.Filter.Text);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASupersededResultIsDroppedEvenWithoutCancellation()
|
||||
{
|
||||
var gate = new TaskCompletionSource();
|
||||
var source = new FakeSource(1000) { Gate = gate, IgnoreCancellation = true };
|
||||
var pager = new LibraryPager(source.FetchAsync, pageSize: 100);
|
||||
var stale = pager.ResetAsync(new LibraryFilter { Text = "old" });
|
||||
source.Gate = null;
|
||||
var fresh = await pager.ResetAsync(new LibraryFilter { Text = "new" });
|
||||
gate.SetResult();
|
||||
Assert.Null(await stale);
|
||||
Assert.Equal(100, fresh!.Items.Count);
|
||||
Assert.Equal(100, pager.Loaded);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OnlyOnePageLoadsAtATime()
|
||||
{
|
||||
var source = new FakeSource(1000);
|
||||
var pager = new LibraryPager(source.FetchAsync, pageSize: 100);
|
||||
await pager.ResetAsync(new LibraryFilter());
|
||||
source.Gate = new TaskCompletionSource();
|
||||
var a = pager.LoadMoreAsync();
|
||||
var b = pager.LoadMoreAsync();
|
||||
Assert.True(pager.IsLoading);
|
||||
Assert.Null(await b);
|
||||
source.Gate.SetResult();
|
||||
Assert.Equal(100, (await a)!.Items.Count);
|
||||
Assert.Equal(2, source.Queries.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFailedPageStopsScrollLoadingUntilTheNextReset()
|
||||
{
|
||||
var source = new FakeSource(1000);
|
||||
var pager = new LibraryPager(source.FetchAsync, pageSize: 100);
|
||||
await pager.ResetAsync(new LibraryFilter());
|
||||
source.Fail = true;
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => pager.LoadMoreAsync());
|
||||
Assert.False(pager.HasMore);
|
||||
Assert.Null(await pager.LoadMoreAsync());
|
||||
source.Fail = false;
|
||||
Assert.NotNull(await pager.ResetAsync(new LibraryFilter()));
|
||||
Assert.True(pager.HasMore);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StatusChoicesMapToFlags()
|
||||
{
|
||||
Assert.Equal((SequenceStatus.AnalyzedLight, SequenceStatus.None), LibraryFilter.Flags(StatusFilter.Analysed));
|
||||
Assert.Equal((SequenceStatus.None, SequenceStatus.ProxiesBuilt), LibraryFilter.Flags(StatusFilter.NoProxies));
|
||||
Assert.Equal((SequenceStatus.Verified, SequenceStatus.None), LibraryFilter.Flags(StatusFilter.Verified));
|
||||
Assert.Equal((SequenceStatus.HasWarnings, SequenceStatus.None), LibraryFilter.Flags(StatusFilter.Warnings));
|
||||
Assert.Equal((SequenceStatus.None, SequenceStatus.None), LibraryFilter.Flags(StatusFilter.Any));
|
||||
Assert.True(new LibraryFilter { Sort = SequenceSort.Size }.IsUnfiltered);
|
||||
Assert.False(new LibraryFilter { Text = "x" }.IsUnfiltered);
|
||||
Assert.False(new LibraryFilter { Status = StatusFilter.Proxies }.IsUnfiltered);
|
||||
var cleared = new LibraryFilter { Text = "x", Year = 2020, Sort = SequenceSort.Oldest }.Cleared();
|
||||
Assert.True(cleared.IsUnfiltered);
|
||||
Assert.Equal(SequenceSort.Oldest, cleared.Sort);
|
||||
Assert.Null(new LibraryFilter { Text = " " }.ToQuery(10, null).Text);
|
||||
}
|
||||
|
||||
/// <summary>An in-memory library: cursors are offsets, optionally held back by a gate.</summary>
|
||||
private sealed class FakeSource(int count)
|
||||
{
|
||||
private readonly Guid _archive = Guid.CreateVersion7();
|
||||
|
||||
public List<SequenceQuery> Queries { get; } = [];
|
||||
public TaskCompletionSource? Gate { get; set; }
|
||||
public bool IgnoreCancellation { get; init; }
|
||||
public bool Fail { get; set; }
|
||||
public int Cancelled { get; private set; }
|
||||
|
||||
public async Task<Page<Sequence>> FetchAsync(SequenceQuery query, CancellationToken ct)
|
||||
{
|
||||
Queries.Add(query);
|
||||
if (Gate is { } gate)
|
||||
{
|
||||
try
|
||||
{
|
||||
await gate.Task.WaitAsync(IgnoreCancellation ? CancellationToken.None : ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Cancelled++;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
if (Fail) throw new InvalidOperationException("database gone");
|
||||
var start = query.Cursor is null ? 0 : int.Parse(query.Cursor, System.Globalization.CultureInfo.InvariantCulture);
|
||||
var items = Enumerable.Range(start, Math.Max(0, Math.Min(query.Limit, count - start)))
|
||||
.Select(i => new Sequence { Id = Guid.CreateVersion7(), ArchiveId = _archive, Folder = "s" + i, Title = "S" + i })
|
||||
.ToList();
|
||||
var next = start + items.Count < count ? (start + items.Count).ToString(System.Globalization.CultureInfo.InvariantCulture) : null;
|
||||
return new Page<Sequence>(items, next);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using Titano.App.Library;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Library;
|
||||
|
||||
public sealed class ThumbnailCacheTests
|
||||
{
|
||||
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10);
|
||||
|
||||
[Test]
|
||||
public async Task LeastRecentlyUsedEntriesAreEvicted()
|
||||
{
|
||||
var loads = new ConcurrentBag<int>();
|
||||
using var cache = new ThumbnailCache<int, string>(3, (k, _) =>
|
||||
{
|
||||
loads.Add(k);
|
||||
return Task.FromResult<string?>("img" + k);
|
||||
});
|
||||
Assert.Equal("img1", await cache.GetAsync(1, CancellationToken.None));
|
||||
await cache.GetAsync(2, CancellationToken.None);
|
||||
await cache.GetAsync(3, CancellationToken.None);
|
||||
Assert.True(cache.TryGet(1, out _)); // 1 becomes the most recent
|
||||
await cache.GetAsync(4, CancellationToken.None); // evicts 2
|
||||
|
||||
Assert.Equal(3, cache.Count);
|
||||
Assert.False(cache.TryGet(2, out _));
|
||||
Assert.True(cache.TryGet(1, out var one));
|
||||
Assert.Equal("img1", one);
|
||||
Assert.True(cache.TryGet(3, out _));
|
||||
Assert.True(cache.TryGet(4, out _));
|
||||
|
||||
await cache.GetAsync(1, CancellationToken.None);
|
||||
Assert.Equal(4, loads.Count); // the cached key was not decoded again
|
||||
|
||||
cache.Capacity = 1;
|
||||
Assert.Equal(1, cache.Count);
|
||||
Assert.True(cache.TryGet(1, out _));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task MissingThumbnailsAreCachedButFailuresAreNot()
|
||||
{
|
||||
var calls = 0;
|
||||
using var cache = new ThumbnailCache<int, string>(8, (k, _) =>
|
||||
{
|
||||
Interlocked.Increment(ref calls);
|
||||
return k == 13 ? throw new IOException("unreadable") : Task.FromResult<string?>(null);
|
||||
});
|
||||
Assert.Null(await cache.GetAsync(1, CancellationToken.None));
|
||||
Assert.Null(await cache.GetAsync(1, CancellationToken.None));
|
||||
Assert.True(cache.TryGet(1, out var none));
|
||||
Assert.Null(none);
|
||||
await Assert.ThrowsAsync<IOException>(() => cache.GetAsync(13, CancellationToken.None));
|
||||
await Assert.ThrowsAsync<IOException>(() => cache.GetAsync(13, CancellationToken.None));
|
||||
Assert.Equal(3, calls);
|
||||
Assert.Equal(0, cache.PendingLoads);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConcurrentRequestsShareOneLoad()
|
||||
{
|
||||
var release = new TaskCompletionSource();
|
||||
var calls = 0;
|
||||
using var cache = new ThumbnailCache<int, string>(8, async (k, ct) =>
|
||||
{
|
||||
Interlocked.Increment(ref calls);
|
||||
await release.Task.WaitAsync(ct);
|
||||
return "img" + k;
|
||||
});
|
||||
var a = cache.GetAsync(7, CancellationToken.None);
|
||||
var b = cache.GetAsync(7, CancellationToken.None);
|
||||
release.SetResult();
|
||||
Assert.Equal("img7", await a.WaitAsync(Wait));
|
||||
Assert.Equal("img7", await b.WaitAsync(Wait));
|
||||
Assert.Equal(1, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALoadStopsWhenEveryRequestIsCancelled()
|
||||
{
|
||||
var started = new TaskCompletionSource();
|
||||
var observed = new TaskCompletionSource();
|
||||
using var cache = new ThumbnailCache<int, string>(8, async (_, ct) =>
|
||||
{
|
||||
started.TrySetResult();
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
observed.TrySetResult();
|
||||
throw;
|
||||
}
|
||||
return "never";
|
||||
});
|
||||
using var first = new CancellationTokenSource();
|
||||
using var second = new CancellationTokenSource();
|
||||
var a = cache.GetAsync(5, first.Token);
|
||||
var b = cache.GetAsync(5, second.Token);
|
||||
await started.Task.WaitAsync(Wait);
|
||||
|
||||
first.Cancel();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => a);
|
||||
Assert.False(observed.Task.IsCompleted, "the load must continue while another card still waits");
|
||||
Assert.Equal(1, cache.PendingLoads);
|
||||
|
||||
second.Cancel();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => b);
|
||||
await observed.Task.WaitAsync(Wait);
|
||||
Assert.Equal(0, cache.PendingLoads);
|
||||
Assert.False(cache.TryGet(5, out _));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALoadAfterACancelledOneStartsFresh()
|
||||
{
|
||||
var attempts = 0;
|
||||
using var cache = new ThumbnailCache<int, string>(8, async (k, ct) =>
|
||||
{
|
||||
if (Interlocked.Increment(ref attempts) == 1) await Task.Delay(Timeout.Infinite, ct);
|
||||
return "img" + k;
|
||||
});
|
||||
using var scrolledAway = new CancellationTokenSource();
|
||||
var first = cache.GetAsync(9, scrolledAway.Token);
|
||||
scrolledAway.Cancel();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => first);
|
||||
Assert.Equal("img9", await cache.GetAsync(9, CancellationToken.None).WaitAsync(Wait));
|
||||
Assert.Equal(2, attempts);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadsRunConcurrentlyUpToTheLimit()
|
||||
{
|
||||
var running = 0;
|
||||
var peak = 0;
|
||||
var gate = new TaskCompletionSource();
|
||||
using var cache = new ThumbnailCache<int, string>(64, async (k, ct) =>
|
||||
{
|
||||
var now = Interlocked.Increment(ref running);
|
||||
InterlockedMax(ref peak, now);
|
||||
await gate.Task.WaitAsync(ct);
|
||||
Interlocked.Decrement(ref running);
|
||||
return "img" + k;
|
||||
}, maxConcurrentLoads: 2);
|
||||
var tasks = Enumerable.Range(0, 10).Select(i => cache.GetAsync(i, CancellationToken.None)).ToList();
|
||||
await Task.Delay(100);
|
||||
Assert.LessOrEqual(Volatile.Read(ref running), 2);
|
||||
gate.SetResult();
|
||||
await Task.WhenAll(tasks).WaitAsync(Wait);
|
||||
Assert.LessOrEqual(peak, 2);
|
||||
Assert.Equal(10, cache.Count);
|
||||
}
|
||||
|
||||
private static void InterlockedMax(ref int target, int value)
|
||||
{
|
||||
int current;
|
||||
while ((current = Volatile.Read(ref target)) < value && Interlocked.CompareExchange(ref target, value, current) != current)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using Titano.App.Server;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Server;
|
||||
|
||||
public sealed class ConnectFlowTests
|
||||
{
|
||||
private const string Fingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE";
|
||||
|
||||
[Test]
|
||||
public async Task AnUnknownCertificateIsConfirmedBeforeThePasswordIsSent()
|
||||
{
|
||||
var server = new FakeServer { SelfSigned = true };
|
||||
var trust = new MemoryTrust();
|
||||
using var flow = new ConnectFlow(server, trust);
|
||||
|
||||
Assert.Equal(ConnectStep.AwaitingTrust, await flow.ProbeAsync("nas.local:8443"));
|
||||
Assert.Equal(Fingerprint, flow.PendingFingerprint);
|
||||
Assert.Equal(new Uri("https://nas.local:8443/"), flow.Address);
|
||||
// The password cannot be sent while the certificate waits for a decision.
|
||||
Assert.Equal(ConnectStep.AwaitingTrust, await flow.SignInAsync("alberto", "secret"));
|
||||
Assert.Equal(0, server.Logins);
|
||||
|
||||
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ConfirmTrustAsync(true));
|
||||
Assert.Contains(Fingerprint, trust.Fingerprints);
|
||||
Assert.Equal("https://nas.local:8443", trust.Servers.Single());
|
||||
Assert.Equal("Studio NAS", flow.Info!.Name);
|
||||
Assert.NotNull(flow.Latency);
|
||||
|
||||
Assert.Equal(ConnectStep.Connected, await flow.SignInAsync("alberto", "secret"));
|
||||
Assert.Equal(1, server.Logins);
|
||||
Assert.Equal("token-1", flow.Token);
|
||||
Assert.Equal("alberto", flow.User!.Username);
|
||||
Assert.NotNull(flow.Api);
|
||||
// Every client got the trust list current at its creation.
|
||||
Assert.Empty(server.Created[0]);
|
||||
Assert.Contains(Fingerprint, server.Created[^1]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RejectingTheCertificateSendsNothing()
|
||||
{
|
||||
var server = new FakeServer { SelfSigned = true };
|
||||
using var flow = new ConnectFlow(server, new MemoryTrust());
|
||||
await flow.ProbeAsync("https://nas.local:8443");
|
||||
Assert.Equal(ConnectStep.Failed, await flow.ConfirmTrustAsync(false));
|
||||
Assert.Equal(ConnectError.Untrusted, flow.Error);
|
||||
Assert.Equal(ConnectStep.Failed, await flow.SignInAsync("alberto", "secret"));
|
||||
Assert.Equal(0, server.Logins);
|
||||
Assert.Null(flow.Token);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APubliclyValidCertificateNeedsNoQuestion()
|
||||
{
|
||||
var server = new FakeServer();
|
||||
using var flow = new ConnectFlow(server, new MemoryTrust());
|
||||
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ProbeAsync("https://titano.example.com"));
|
||||
Assert.Null(flow.PendingFingerprint);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWrongPasswordReturnsToTheForm()
|
||||
{
|
||||
var server = new FakeServer { Password = "right" };
|
||||
using var flow = new ConnectFlow(server, new MemoryTrust());
|
||||
await flow.ProbeAsync("nas.local");
|
||||
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.SignInAsync("alberto", "wrong"));
|
||||
Assert.Equal(ConnectError.BadCredentials, flow.Error);
|
||||
Assert.Equal(ConnectStep.Connected, await flow.SignInAsync("alberto", "right"));
|
||||
Assert.Equal(ConnectError.None, flow.Error);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("", ConnectError.InvalidAddress)]
|
||||
[Case("ftp://nas.local", ConnectError.InvalidAddress)]
|
||||
[Case("down.local", ConnectError.Unreachable)]
|
||||
[Case("web.local", ConnectError.NotTitano)]
|
||||
public async Task ProbeFailuresAreClassified(string address, ConnectError error)
|
||||
{
|
||||
using var flow = new ConnectFlow(new FakeServer(), new MemoryTrust());
|
||||
Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync(address));
|
||||
Assert.Equal(error, flow.Error);
|
||||
Assert.Null(flow.Api);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASavedSessionIsRestoredWithoutAPassword()
|
||||
{
|
||||
var server = new FakeServer { SelfSigned = true };
|
||||
var trust = new MemoryTrust();
|
||||
trust.Trust("https://nas.local:8443", Fingerprint);
|
||||
using var flow = new ConnectFlow(server, trust);
|
||||
Assert.Equal(ConnectStep.Connected, await flow.RestoreAsync("https://nas.local:8443", "token-7"));
|
||||
Assert.Equal(0, server.Logins);
|
||||
Assert.Equal("token-7", flow.Token);
|
||||
Assert.Equal("token-7", server.LastTokenSeen);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExpiredTokenAsksForTheLoginAgain()
|
||||
{
|
||||
var server = new FakeServer { ValidToken = "fresh" };
|
||||
using var flow = new ConnectFlow(server, new MemoryTrust());
|
||||
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.RestoreAsync("nas.local", "stale"));
|
||||
Assert.Equal(ConnectError.SessionExpired, flow.Error);
|
||||
Assert.Null(flow.Token);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AChangedCertificateNeverReceivesTheSavedToken()
|
||||
{
|
||||
var server = new FakeServer { SelfSigned = true };
|
||||
var trust = new MemoryTrust();
|
||||
trust.Trust("https://nas.local:8443", "00:11:22"); // trusted earlier: a different certificate
|
||||
using var flow = new ConnectFlow(server, trust);
|
||||
Assert.Equal(ConnectStep.AwaitingTrust, await flow.RestoreAsync("nas.local:8443", "token-7"));
|
||||
Assert.Equal(ConnectError.CertificateChanged, flow.Error);
|
||||
Assert.Null(server.LastTokenSeen);
|
||||
Assert.Null(flow.Token);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SignOutForgetsTheSession()
|
||||
{
|
||||
var server = new FakeServer();
|
||||
using var flow = new ConnectFlow(server, new MemoryTrust());
|
||||
await flow.ProbeAsync("nas.local");
|
||||
await flow.SignInAsync("alberto", "secret");
|
||||
var changes = 0;
|
||||
flow.Changed += (_, _) => changes++;
|
||||
await flow.SignOutAsync();
|
||||
Assert.Equal(1, server.Logouts);
|
||||
Assert.Equal(ConnectStep.Idle, flow.Step);
|
||||
Assert.Null(flow.Token);
|
||||
Assert.Null(flow.Api);
|
||||
Assert.Equal(1, changes);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AddressesAreNormalised()
|
||||
{
|
||||
Assert.True(ServerAddress.TryParse("nas.local:8443", out var a));
|
||||
Assert.Equal("https://nas.local:8443/", a.ToString());
|
||||
Assert.True(ServerAddress.TryParse(" http://10.0.0.5:8080/titano?x=1 ", out var b));
|
||||
Assert.Equal("http://10.0.0.5:8080/titano/", b.ToString());
|
||||
Assert.False(ServerAddress.TryParse(" ", out _));
|
||||
Assert.False(ServerAddress.TryParse("ftp://nas", out _));
|
||||
Assert.Equal("https://nas.local:8443", ServerAddress.Display(a));
|
||||
Assert.Equal("https://nas.local:8443", ServerAddress.Display("https://nas.local:8443/"));
|
||||
}
|
||||
|
||||
private sealed class MemoryTrust : ITrustStore
|
||||
{
|
||||
private readonly List<string> _fingerprints = [];
|
||||
|
||||
public List<string> Servers { get; } = [];
|
||||
|
||||
public IReadOnlyCollection<string> Fingerprints => [.. _fingerprints];
|
||||
|
||||
public void Trust(string server, string fingerprint)
|
||||
{
|
||||
Servers.Add(server);
|
||||
_fingerprints.Add(fingerprint);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A server with configurable behaviour, reached through clients that pin certificates like the real one.</summary>
|
||||
private sealed class FakeServer : IServerApiFactory
|
||||
{
|
||||
public bool SelfSigned { get; init; }
|
||||
public string Password { get; init; } = "secret";
|
||||
public string? ValidToken { get; init; }
|
||||
public int Logins { get; set; }
|
||||
public int Logouts { get; set; }
|
||||
public string? LastTokenSeen { get; set; }
|
||||
public List<IReadOnlyCollection<string>> Created { get; } = [];
|
||||
|
||||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints)
|
||||
{
|
||||
Created.Add(trustedFingerprints);
|
||||
return new Client(this, baseAddress, trustedFingerprints);
|
||||
}
|
||||
|
||||
private sealed class Client(FakeServer server, Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
|
||||
{
|
||||
public Uri BaseAddress { get; } = baseAddress;
|
||||
public string? Token { get; set; }
|
||||
|
||||
public Task<ServerInfo> GetInfoAsync(CancellationToken ct)
|
||||
{
|
||||
Handshake();
|
||||
return Task.FromResult(new ServerInfo("Studio NAS", "1.3.0", 1, [], server.SelfSigned ? Fingerprint : null, [], new ServerLimits(0, 0)));
|
||||
}
|
||||
|
||||
public Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct)
|
||||
{
|
||||
Handshake();
|
||||
server.Logins++;
|
||||
if (password != server.Password) throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("bad_credentials", "Wrong"));
|
||||
return Task.FromResult(new LoginResponse("token-" + server.Logins, User(username), false, DateTimeOffset.UtcNow.AddDays(1)));
|
||||
}
|
||||
|
||||
public Task<UserDto> MeAsync(CancellationToken ct)
|
||||
{
|
||||
Handshake();
|
||||
server.LastTokenSeen = Token;
|
||||
if (server.ValidToken is { } valid && Token != valid) throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("expired", "Expired"));
|
||||
return Task.FromResult(User("alberto"));
|
||||
}
|
||||
|
||||
public Task LogoutAsync(CancellationToken ct)
|
||||
{
|
||||
server.Logouts++;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>What TLS would do: a self-signed certificate is accepted only when pinned.</summary>
|
||||
private void Handshake()
|
||||
{
|
||||
if (BaseAddress.Host == "down.local") throw new HttpRequestException("No such host");
|
||||
if (BaseAddress.Host == "web.local") throw new TitanoApiException(HttpStatusCode.NotFound, new ApiError("http_404", "Not Found"));
|
||||
if (server.SelfSigned && !trusted.Contains(Fingerprint)) throw new UntrustedCertificateException(Fingerprint);
|
||||
}
|
||||
|
||||
private static UserDto User(string name) =>
|
||||
new(Guid.Empty, name, null, "editor", 0, 5_000_000_000_000, 2_100_000_000_000, false, false, DateTimeOffset.UtcNow, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Titano.App.Settings;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Naming;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.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)]
|
||||
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]);
|
||||
}
|
||||
|
||||
[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 EnumDrivenKeysExistInEveryRequiredLanguage()
|
||||
{
|
||||
var keys = new List<string>();
|
||||
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobKind>().Select(k => "Jobs.Kind." + k));
|
||||
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobState>().Select(k => "Jobs.State." + k));
|
||||
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobState>().Select(k => "Tooltips.Jobs.State." + k));
|
||||
keys.AddRange(Enum.GetNames<Titano.App.Jobs.JobFilter>().SelectMany(k => new[] { "Jobs.Filter." + k, "Tooltips.Jobs.Filter." + k }));
|
||||
keys.AddRange(Enum.GetNames<Titano.App.Library.StatusFilter>().Where(k => k != "Any").Select(k => "Library.Filter.Status." + k));
|
||||
keys.AddRange(Enum.GetNames<Titano.Data.Repositories.SequenceSort>().Select(k => "Library.Sort." + k));
|
||||
keys.AddRange(Enum.GetNames<Titano.App.Server.ConnectError>().Where(k => k != "None").Select(k => "Server.Error." + k));
|
||||
keys.AddRange(Enum.GetNames<Titano.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<Titano.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 `Titano.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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user