refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow) and pe-check. BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c99842cc86
commit
5f27a86406
1799 files changed
+11728
-10668
No files matched your search
@@ -0,0 +1,18 @@
|
||||
using System.IO;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Infrastructure;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class CoalescingWriterTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void KeepsTheNewestContent()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "uploader-queue.json");
|
||||
var writer = new CoalescingWriter();
|
||||
for (var i = 0; i < 50; i++) writer.Write(path, [(byte)i]);
|
||||
writer.Flush(TimeSpan.FromSeconds(10));
|
||||
Assert.SequenceEqual([(byte)49], File.ReadAllBytes(path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Infrastructure;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class CommandLineTests
|
||||
{
|
||||
[Test]
|
||||
public void PathsAndOptionsAreSeparated()
|
||||
{
|
||||
var c = CommandLine.Parse([@"E:\", "--tray", @"D:\Cam\IMG_0001.CR2"]);
|
||||
Assert.SequenceEqual([@"E:\", @"D:\Cam\IMG_0001.CR2"], c.Paths);
|
||||
Assert.True(c.StartInTray);
|
||||
Assert.Null(c.CaptureDirectory);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CaptureTakesAnOptionalDirectory()
|
||||
{
|
||||
Assert.Equal("out/shots", CommandLine.Parse(["--capture", "out/shots"]).CaptureDirectory);
|
||||
Assert.Equal("screenshots", CommandLine.Parse(["--capture"]).CaptureDirectory);
|
||||
Assert.Equal("screenshots", CommandLine.Parse(["--capture", "--tray"]).CaptureDirectory);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HandOverMessageRoundTrips()
|
||||
{
|
||||
string[] args = [@"E:\", @"\\garage-pi\cam\IMG 1.jpg"];
|
||||
Assert.SequenceEqual(args, SingleInstance.Decode(SingleInstance.Encode(args))!);
|
||||
Assert.Empty(SingleInstance.Decode(SingleInstance.Encode([]))!);
|
||||
Assert.Null(SingleInstance.Decode("hello\nE:\\"u8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using System.ComponentModel;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Server;
|
||||
using Chronos.Uploader.Shell;
|
||||
using Chronos.Uploader.Uploads;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
/// <summary>
|
||||
/// The sign-in form puts each failure where DESIGN §4 wants it: a refused address or password marks that field
|
||||
/// (message in its tooltip), other failures are one sentence, with Retry only where trying again can help.
|
||||
/// </summary>
|
||||
public sealed class ConnectViewModelTests
|
||||
{
|
||||
private const string Fingerprint = "AB:CD";
|
||||
|
||||
[Test]
|
||||
public void NoFieldShowsAnErrorBeforeSigningIn()
|
||||
{
|
||||
var form = Form(new FakeSession());
|
||||
|
||||
Assert.False(form.HasErrors);
|
||||
Assert.Empty(form.GetErrors(nameof(ConnectViewModel.Address)));
|
||||
Assert.Null(form.PasswordError);
|
||||
Assert.Null(form.ErrorText);
|
||||
Assert.False(form.CanRetry);
|
||||
Assert.Equal(Loc.L("Tooltips.Uploader.ServerAddress"), form.AddressToolTip);
|
||||
Assert.Equal(Loc.L("Tooltips.Uploader.Password"), form.PasswordToolTip);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnInvalidAddressMarksTheServerFieldUntilItChanges()
|
||||
{
|
||||
var form = Form(new FakeSession(SignInResult.InvalidAddress));
|
||||
var changed = new List<string?>();
|
||||
form.ErrorsChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
form.SignInCommand.Execute(null);
|
||||
|
||||
var message = Loc.L("Uploader.Connect.Error.InvalidAddress");
|
||||
Assert.True(form.HasErrors);
|
||||
Assert.SequenceEqual([message], form.GetErrors(nameof(ConnectViewModel.Address)).Cast<string>());
|
||||
Assert.Equal(message, form.AddressToolTip);
|
||||
Assert.Contains(nameof(ConnectViewModel.Address), changed);
|
||||
Assert.Null(form.ErrorText, "a field error is not repeated under the form");
|
||||
Assert.False(form.CanRetry);
|
||||
|
||||
form.Address = "https://nas.local:9443";
|
||||
Assert.False(form.HasErrors);
|
||||
Assert.Equal(Loc.L("Tooltips.Uploader.ServerAddress"), form.AddressToolTip);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AServerThatIsNotChronosMarksTheServerField()
|
||||
{
|
||||
var form = Form(new FakeSession(SignInResult.NotChronos));
|
||||
|
||||
form.SignInCommand.Execute(null);
|
||||
|
||||
Assert.Equal(Loc.L("Uploader.Connect.Error.NotChronos"), form.AddressError);
|
||||
Assert.Null(form.ErrorText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AWrongPasswordMarksThePasswordFieldUntilTheUserTypes()
|
||||
{
|
||||
var form = Form(new FakeSession(SignInResult.BadCredentials));
|
||||
|
||||
form.SignInCommand.Execute(null);
|
||||
|
||||
var message = Loc.L("Uploader.Connect.Error.BadCredentials");
|
||||
Assert.Equal(message, form.PasswordError);
|
||||
Assert.Equal(message, form.PasswordToolTip);
|
||||
Assert.False(form.HasErrors, "the address is not in question");
|
||||
Assert.Null(form.ErrorText);
|
||||
Assert.False(form.CanRetry, "the same password would fail again");
|
||||
|
||||
form.Password = "another";
|
||||
Assert.Null(form.PasswordError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(SignInResult.Unreachable, "Uploader.Connect.Error.Unreachable")]
|
||||
[Case(SignInResult.Failed, "Uploader.Connect.Error.Failed")]
|
||||
public void FailuresThatMayPassOfferRetry(SignInResult result, string key)
|
||||
{
|
||||
var form = Form(new FakeSession(result));
|
||||
|
||||
form.SignInCommand.Execute(null);
|
||||
|
||||
Assert.Equal(Loc.L(key), form.ErrorText);
|
||||
Assert.True(form.CanRetry);
|
||||
Assert.False(form.HasErrors);
|
||||
Assert.Null(form.PasswordError);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ADeclinedCertificateIsReportedWithoutRetry()
|
||||
{
|
||||
var session = new FakeSession(SignInResult.Untrusted);
|
||||
var form = Form(session, trust: false);
|
||||
|
||||
form.SignInCommand.Execute(null);
|
||||
|
||||
Assert.Equal(Loc.L("Uploader.Connect.Error.Untrusted"), form.ErrorText);
|
||||
Assert.False(form.CanRetry);
|
||||
Assert.Equal(1, session.Attempts);
|
||||
Assert.Null(session.Trusted);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATrustedCertificateSignsInAgainAndClearsEveryError()
|
||||
{
|
||||
var session = new FakeSession(SignInResult.BadCredentials, SignInResult.Untrusted, SignInResult.Success);
|
||||
var form = Form(session, trust: true);
|
||||
form.SignInCommand.Execute(null);
|
||||
Assert.NotNull(form.PasswordError);
|
||||
|
||||
form.SignInCommand.Execute(null);
|
||||
|
||||
Assert.Equal(Fingerprint, session.Trusted);
|
||||
Assert.Equal(3, session.Attempts);
|
||||
Assert.Null(form.PasswordError);
|
||||
Assert.Null(form.ErrorText);
|
||||
Assert.False(form.HasErrors);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheFormSaysWhileItsOwnSignInRuns()
|
||||
{
|
||||
var session = new FakeSession(SignInResult.Unreachable);
|
||||
var form = Form(session);
|
||||
session.During = () => Assert.True(form.IsSigningIn, "signing in while the request runs");
|
||||
|
||||
form.SignInCommand.Execute(null);
|
||||
|
||||
Assert.Equal(1, session.Attempts);
|
||||
Assert.False(form.IsSigningIn);
|
||||
}
|
||||
|
||||
private static ConnectViewModel Form(FakeSession session, bool trust = false) =>
|
||||
new(session, new FakeDialogs(trust), "https://nas.local:8443/", "alberto") { Password = "secret" };
|
||||
|
||||
/// <summary>Answers each sign-in with the next scripted result, moving through SigningIn as the real session does.</summary>
|
||||
private sealed class FakeSession(params SignInResult[] results) : IServerSession
|
||||
{
|
||||
private ConnectionState _state = ConnectionState.SignedOut;
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
public event EventHandler<ServerProblem>? SessionEnded
|
||||
{
|
||||
add { }
|
||||
remove { }
|
||||
}
|
||||
|
||||
public int Attempts { get; private set; }
|
||||
public string? Trusted { get; private set; }
|
||||
public Action? During { get; set; }
|
||||
|
||||
public ConnectionState State => _state;
|
||||
public string? Address => "https://nas.local:8443/";
|
||||
public string? Username => "alberto";
|
||||
public long QuotaBytes => 0;
|
||||
public long UsedBytes => 0;
|
||||
public int BandwidthLimit { get; set; }
|
||||
|
||||
public Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct)
|
||||
{
|
||||
var result = results[Math.Min(Attempts, results.Length - 1)];
|
||||
Attempts++;
|
||||
SetState(ConnectionState.SigningIn);
|
||||
During?.Invoke();
|
||||
SetState(result == SignInResult.Success ? ConnectionState.Connected : ConnectionState.SignedOut);
|
||||
return Task.FromResult<(SignInResult, string?)>((result, result == SignInResult.Untrusted ? Fingerprint : null));
|
||||
}
|
||||
|
||||
public void Trust(string fingerprint) => Trusted = fingerprint;
|
||||
|
||||
public Task SignOutAsync() => Task.CompletedTask;
|
||||
|
||||
public Task RefreshAsync() => Task.CompletedTask;
|
||||
|
||||
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<SequenceDto>>([]);
|
||||
|
||||
private void SetState(ConnectionState state)
|
||||
{
|
||||
_state = state;
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(State)));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeDialogs(bool trust) : IUploaderDialogs
|
||||
{
|
||||
public IReadOnlyList<string> PickFiles() => [];
|
||||
public string? PickFolder() => null;
|
||||
public string? PickWatchFolder() => null;
|
||||
public bool ConfirmTrust(string address, string fingerprint) => trust;
|
||||
public bool ConfirmDeleteAfterUpload() => false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.IO;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Sources;
|
||||
using Chronos.Uploader.Watching;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class ProcessedFileMemoryTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTime Written = new(2026, 9, 28, 16, 2, 11, DateTimeKind.Utc);
|
||||
|
||||
[Test]
|
||||
public void RemembersPathSizeAndWriteTime()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "roof");
|
||||
var photo = Path.Combine(root, "100CANON", "IMG_0413.CR2");
|
||||
var memory = new ProcessedFileMemory();
|
||||
Assert.False(memory.Contains(root, photo, 25_000_000, Written));
|
||||
|
||||
memory.Add(root, photo, 25_000_000, Written);
|
||||
Assert.True(memory.IsDirty);
|
||||
Assert.True(memory.Contains(root, photo, 25_000_000, Written));
|
||||
Assert.False(memory.Contains(root, photo, 25_000_001, Written), "a resized file is new");
|
||||
Assert.False(memory.Contains(root, photo, 25_000_000, Written.AddSeconds(1)), "a rewritten file is new");
|
||||
Assert.False(memory.Contains(Path.Combine(Path.GetTempPath(), "garden"), photo, 25_000_000, Written), "folders are separate");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PruneForgetsFilesNoLongerInTheFolder()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "roof");
|
||||
var kept = Path.Combine(root, "a.jpg");
|
||||
var gone = Path.Combine(root, "b.jpg");
|
||||
var memory = new ProcessedFileMemory();
|
||||
memory.Add(root, kept, 1, Written);
|
||||
memory.Add(root, gone, 2, Written);
|
||||
|
||||
memory.Prune(root, [kept]);
|
||||
Assert.True(memory.Contains(root, kept, 1, Written));
|
||||
Assert.False(memory.Contains(root, gone, 2, Written));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RoundTripKeepsFilesAndTheLastSession()
|
||||
{
|
||||
var dir = context.CreateTempDirectory();
|
||||
var root = Path.Combine(dir, "cam");
|
||||
var photo = Path.Combine(root, "IMG_0001.JPG");
|
||||
var memory = new ProcessedFileMemory();
|
||||
memory.Add(root, photo, 4_200_000, Written);
|
||||
memory.SetSession(root, new SessionContinuation("1a2b3c4d-20260928-180000", new DateTime(2026, 9, 28, 18, 40, 0)));
|
||||
|
||||
var path = Path.Combine(dir, "uploader-watch.json");
|
||||
File.WriteAllBytes(path, memory.Serialize());
|
||||
Assert.False(memory.IsDirty);
|
||||
var restored = ProcessedFileMemory.Load(path);
|
||||
|
||||
Assert.True(restored.Contains(root, photo, 4_200_000, Written));
|
||||
Assert.Equal(new SessionContinuation("1a2b3c4d-20260928-180000", new DateTime(2026, 9, 28, 18, 40, 0)), restored.GetSession(root));
|
||||
Assert.False(restored.IsDirty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RemovedFolderIsForgotten()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "roof");
|
||||
var memory = new ProcessedFileMemory();
|
||||
memory.Add(root, Path.Combine(root, "a.jpg"), 1, Written);
|
||||
memory.SetSession(root, new SessionContinuation("k", Written));
|
||||
memory.RemoveFolder(root);
|
||||
Assert.False(memory.Contains(root, Path.Combine(root, "a.jpg"), 1, Written));
|
||||
Assert.Null(memory.GetSession(root));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CorruptFileGivesAnEmptyMemory()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "uploader-watch.json");
|
||||
File.WriteAllText(path, "[1,2");
|
||||
var memory = ProcessedFileMemory.Load(path);
|
||||
Assert.False(memory.Contains("x", "x/a.jpg", 1, Written));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Server;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class ServerAddressTests
|
||||
{
|
||||
[Theory]
|
||||
[Case("nas.local:8443", "https://nas.local:8443/")]
|
||||
[Case("https://nas.local:8443", "https://nas.local:8443/")]
|
||||
[Case(" http://192.168.1.20:8080/chronos ", "http://192.168.1.20:8080/chronos/")]
|
||||
[Case("https://nas.local/?x=1#y", "https://nas.local/")]
|
||||
public void ServerAddressesBecomeApiBases(string typed, string expected)
|
||||
{
|
||||
Assert.True(ServerAddress.TryParse(typed, out var uri));
|
||||
Assert.Equal(expected, uri.ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("")]
|
||||
[Case(" ")]
|
||||
[Case("ftp://nas.local")]
|
||||
[Case("https://")]
|
||||
public void InvalidServerAddressesAreRejected(string typed) => Assert.False(ServerAddress.TryParse(typed, out _));
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.IO;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Sources;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class SessionGrouperTests
|
||||
{
|
||||
private static readonly DateTime Evening = new(2026, 9, 28, 18, 0, 0);
|
||||
|
||||
[Test]
|
||||
public void SplitsWhereTheGapExceedsFortyFiveMinutes()
|
||||
{
|
||||
var times = Series(Evening, 10).Concat(Series(Evening.AddMinutes(9 + 46), 10)).ToList();
|
||||
var result = SessionGrouper.Assign(times, "abcd1234");
|
||||
Assert.Equal(2, result.Keys.Distinct().Count());
|
||||
Assert.Equal("abcd1234-20260928-180000", result.Keys[0]);
|
||||
Assert.Equal("abcd1234-20260928-185500", result.Keys[^1]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GapOfExactlyFortyFiveMinutesStaysInOneSession()
|
||||
{
|
||||
var times = Series(Evening, 10).Concat(Series(Evening.AddMinutes(9 + 45), 10)).ToList();
|
||||
Assert.Equal(1, SessionGrouper.Assign(times, "t").Keys.Distinct().Count());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestShotsAfterASessionMergeIntoIt()
|
||||
{
|
||||
var times = Series(Evening, 20).Concat(Series(Evening.AddHours(3), 3)).ToList();
|
||||
var result = SessionGrouper.Assign(times, "t");
|
||||
Assert.Equal(1, result.Keys.Distinct().Count());
|
||||
Assert.Equal(Evening.AddHours(3).AddMinutes(2), result.Last!.LastCapture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LeadingTestShotsJoinTheFollowingSession()
|
||||
{
|
||||
var times = Series(Evening, 3).Concat(Series(Evening.AddHours(2), 30)).ToList();
|
||||
var result = SessionGrouper.Assign(times, "t");
|
||||
Assert.Equal(1, result.Keys.Distinct().Count());
|
||||
Assert.Equal("t-20260928-180000", result.Keys[0]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void KeysFollowTheInputOrder()
|
||||
{
|
||||
var first = Series(Evening, 10);
|
||||
var second = Series(Evening.AddHours(5), 10);
|
||||
var shuffled = new List<DateTime> { second[3], first[7], second[0], first[0] };
|
||||
shuffled.AddRange(first.Skip(1).Take(6));
|
||||
shuffled.AddRange(second.Skip(4));
|
||||
var result = SessionGrouper.Assign(shuffled, "t");
|
||||
Assert.Equal("t-20260928-230000", result.Keys[0]);
|
||||
Assert.Equal("t-20260928-180000", result.Keys[1]);
|
||||
Assert.Equal(result.Keys[0], result.Keys[2]);
|
||||
Assert.Equal(result.Keys[1], result.Keys[3]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NewFramesWithinTheGapContinueThePreviousSession()
|
||||
{
|
||||
var previous = new SessionContinuation("t-20260928-180000", Evening.AddMinutes(30));
|
||||
var result = SessionGrouper.Assign(Series(Evening.AddMinutes(40), 2), "t", previous);
|
||||
Assert.SequenceEqual(["t-20260928-180000", "t-20260928-180000"], result.Keys);
|
||||
Assert.Equal(Evening.AddMinutes(41), result.Last!.LastCapture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NewFramesAfterTheGapStartANewSession()
|
||||
{
|
||||
var previous = new SessionContinuation("t-20260928-180000", Evening.AddMinutes(30));
|
||||
var result = SessionGrouper.Assign(Series(Evening.AddHours(2), 10), "t", previous);
|
||||
Assert.Equal("t-20260928-200000", result.Keys[0]);
|
||||
Assert.Equal("t-20260928-200000", result.Last!.Key);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyInputKeepsThePreviousSession()
|
||||
{
|
||||
var previous = new SessionContinuation("k", Evening);
|
||||
var result = SessionGrouper.Assign([], "t", previous);
|
||||
Assert.Empty(result.Keys);
|
||||
Assert.Same(previous, result.Last);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SourceTagIsStableShortAndPerFolder()
|
||||
{
|
||||
var a = SessionGrouper.SourceTag(Path.Combine(Path.GetTempPath(), "cam", "roof"));
|
||||
Assert.Equal(8, a.Length);
|
||||
Assert.True(a.All(Uri.IsHexDigit));
|
||||
Assert.Equal(a, SessionGrouper.SourceTag(Path.Combine(Path.GetTempPath(), "cam", "roof") + Path.DirectorySeparatorChar));
|
||||
Assert.NotEqual(a, SessionGrouper.SourceTag(Path.Combine(Path.GetTempPath(), "cam", "garden")));
|
||||
}
|
||||
|
||||
private static List<DateTime> Series(DateTime start, int count) => [.. Enumerable.Range(0, count).Select(i => start.AddMinutes(i))];
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
/// <summary>Runs async test code on one thread, as the UI dispatcher does for the upload engine.</summary>
|
||||
internal sealed class SingleThreadedContext : SynchronizationContext
|
||||
{
|
||||
private readonly BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = [];
|
||||
|
||||
public override void Post(SendOrPostCallback d, object? state)
|
||||
{
|
||||
try
|
||||
{
|
||||
_queue.Add((d, state));
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Late progress reports after the test body finished are dropped.
|
||||
}
|
||||
}
|
||||
|
||||
public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException();
|
||||
|
||||
public static void Run(Func<Task> body)
|
||||
{
|
||||
var previous = Current;
|
||||
var context = new SingleThreadedContext();
|
||||
SetSynchronizationContext(context);
|
||||
try
|
||||
{
|
||||
var task = body();
|
||||
task.ContinueWith(_ => context._queue.CompleteAdding(), TaskScheduler.Default);
|
||||
foreach (var (callback, state) in context._queue.GetConsumingEnumerable()) callback(state);
|
||||
task.GetAwaiter().GetResult();
|
||||
}
|
||||
finally
|
||||
{
|
||||
SetSynchronizationContext(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Watching;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class StableFileTrackerTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 9, 28, 16, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
[Test]
|
||||
public void FileIsStableAfterTwoIdenticalChecks()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
var photo = new FileObservation("a.cr2", 25_000_000, T0);
|
||||
Assert.Empty(tracker.Check([photo]));
|
||||
Assert.Equal(1, tracker.PendingCount);
|
||||
Assert.SequenceEqual([photo], tracker.Check([photo]));
|
||||
Assert.Equal(0, tracker.PendingCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GrowingFileWaitsUntilItStopsGrowing()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
Assert.Empty(tracker.Check([new("a.cr2", 1_000, T0)]));
|
||||
Assert.Empty(tracker.Check([new("a.cr2", 9_000, T0.AddSeconds(1))]));
|
||||
Assert.Empty(tracker.Check([new("a.cr2", 25_000, T0.AddSeconds(2))]));
|
||||
Assert.Count(1, tracker.Check([new("a.cr2", 25_000, T0.AddSeconds(2))]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TouchedFileWithSameSizeRestartsTheCount()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
Assert.Empty(tracker.Check([new("a.jpg", 500, T0)]));
|
||||
Assert.Empty(tracker.Check([new("a.jpg", 500, T0.AddSeconds(5))]));
|
||||
Assert.Count(1, tracker.Check([new("a.jpg", 500, T0.AddSeconds(5))]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FileMissingFromAScanIsForgotten()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
var photo = new FileObservation("a.jpg", 500, T0);
|
||||
Assert.Empty(tracker.Check([photo]));
|
||||
Assert.Empty(tracker.Check([]));
|
||||
Assert.Empty(tracker.Check([photo]));
|
||||
Assert.Count(1, tracker.Check([photo]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FilesProgressIndependently()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
var done = new FileObservation("done.jpg", 500, T0);
|
||||
Assert.Empty(tracker.Check([done, new("growing.jpg", 10, T0)]));
|
||||
var stable = tracker.Check([done, new("growing.jpg", 20, T0.AddSeconds(1))]);
|
||||
Assert.SequenceEqual([done], stable);
|
||||
Assert.Equal(1, tracker.PendingCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SingleObservationsUseTheSameRule()
|
||||
{
|
||||
var tracker = new StableFileTracker();
|
||||
var photo = new FileObservation("a.nef", 42, T0);
|
||||
Assert.False(tracker.Observe(photo));
|
||||
Assert.True(tracker.Observe(photo));
|
||||
Assert.False(tracker.Observe(photo));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Infrastructure;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class TokenProtectorTests
|
||||
{
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TokenRoundTripsThroughDpapiWithoutPlainText()
|
||||
{
|
||||
const string token = "ttn_4f9a1c2e7b";
|
||||
var blob = TokenProtector.Protect(token);
|
||||
Assert.False(blob.Contains(token, StringComparison.Ordinal));
|
||||
Assert.Equal(token, TokenProtector.Unprotect(blob));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void DamagedBlobsGiveNoToken()
|
||||
{
|
||||
var blob = Convert.FromBase64String(TokenProtector.Protect("secret"));
|
||||
blob[^1] ^= 0xFF;
|
||||
Assert.Null(TokenProtector.Unprotect(Convert.ToBase64String(blob)));
|
||||
Assert.Null(TokenProtector.Unprotect("not base64!"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Uploads;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class UploadEngineTests(TestContext context)
|
||||
{
|
||||
private readonly ManualTime _time = new();
|
||||
|
||||
[Test]
|
||||
public void VerifiedUploadsKeepTheSourceByDefault() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 2);
|
||||
var transport = new FakeTransport();
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
var confirmed = new List<UploadItem>();
|
||||
engine.ItemConfirmed += (_, item) => confirmed.Add(item);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => queue.Items.All(i => i.IsDone));
|
||||
|
||||
Assert.True(queue.Items.All(i => i.State == UploadItemState.Verified && i.FrameId is not null));
|
||||
Assert.True(queue.Items.All(i => File.Exists(i.Path)));
|
||||
// Two workers hash in parallel, so calls arrive in either order.
|
||||
foreach (var item in queue.Items) Assert.Equal(Sha256(item.Path), transport.Calls.Single(c => c.Path == item.Path).Sha256);
|
||||
Assert.Equal(2, confirmed.Count);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void DeleteAfterUploadRemovesOnlyVerifiedUnchangedFiles() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 3);
|
||||
var (verified, existing, changed) = (queue.Items[0], queue.Items[1], queue.Items[2]);
|
||||
var transport = new FakeTransport
|
||||
{
|
||||
Respond = item =>
|
||||
{
|
||||
if (item == existing) return (UploadOutcome.AlreadyOnServer, null);
|
||||
// Written to after it was hashed: the bytes on disk are no longer the verified ones.
|
||||
if (item == changed) File.AppendAllText(item.Path, "more");
|
||||
return (UploadOutcome.Verified, Guid.CreateVersion7());
|
||||
},
|
||||
};
|
||||
using var engine = new UploadEngine(queue, transport, () => true, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => queue.Items.All(i => i.IsDone));
|
||||
|
||||
Assert.Equal(UploadItemState.Skipped, existing.State);
|
||||
Assert.False(File.Exists(verified.Path));
|
||||
// The server matched its hash without receiving these bytes: no verified copy, so the source stays.
|
||||
Assert.True(File.Exists(existing.Path), "a file the server already held is kept");
|
||||
Assert.True(File.Exists(changed.Path), "a file changed after verification is kept");
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void RejectedFileIsRetriedAfterThirtySeconds() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 1);
|
||||
var item = queue.Items[0];
|
||||
var attempts = 0;
|
||||
var transport = new FakeTransport
|
||||
{
|
||||
Respond = _ => ++attempts == 1
|
||||
? throw new ChronosApiException(HttpStatusCode.UnprocessableEntity, new ApiError("hash_mismatch", "Hash mismatch"))
|
||||
: (UploadOutcome.Verified, Guid.CreateVersion7()),
|
||||
};
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => item.State == UploadItemState.Failed);
|
||||
Assert.Equal(UploadFailure.ServerRejected, item.Failure);
|
||||
Assert.Equal("Hash mismatch", item.FailureDetail);
|
||||
Assert.Equal(_time.UtcNow + UploadQueue.RetryDelay, item.NextRetryUtc);
|
||||
|
||||
_time.Advance(TimeSpan.FromSeconds(29));
|
||||
engine.Pump();
|
||||
Assert.Equal(UploadItemState.Failed, item.State);
|
||||
|
||||
_time.Advance(TimeSpan.FromSeconds(1));
|
||||
engine.Pump();
|
||||
await Until(() => item.IsDone);
|
||||
Assert.Equal(1, item.Retries);
|
||||
Assert.Equal(UploadFailure.None, item.Failure);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void UnreachableServerRequeuesWithoutSpendingARetry() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 1);
|
||||
var item = queue.Items[0];
|
||||
var transport = new FakeTransport();
|
||||
transport.Respond = _ =>
|
||||
{
|
||||
transport.SetReady(false);
|
||||
throw new ServerUnavailableException(ServerProblem.Unreachable);
|
||||
};
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => item.State == UploadItemState.Queued && transport.Calls.Count == 1);
|
||||
Assert.Equal(0, item.Retries);
|
||||
Assert.NotNull(item.Sha256);
|
||||
Assert.Equal(EngineStatus.WaitingForServer, engine.Status);
|
||||
|
||||
transport.Respond = _ => (UploadOutcome.Verified, Guid.CreateVersion7());
|
||||
transport.SetReady(true);
|
||||
await Until(() => item.IsDone);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void NewSequenceIsCreatedOnceForTheBatch() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.NewSequence, 3);
|
||||
var transport = new FakeTransport();
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => queue.Items.All(i => i.IsDone));
|
||||
|
||||
Assert.Equal(1, transport.SequencesCreated);
|
||||
Assert.True(transport.Calls.All(c => c.SequenceId == FakeTransport.CreatedSequence));
|
||||
Assert.Equal(FakeTransport.CreatedSequence, queue.Batches.Single().SequenceId);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void AtMostTwoFilesAreInFlightAndPauseRequeuesThem() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var queue = Queue(UploadTargetMode.Sessions, 4);
|
||||
var transport = new FakeTransport { Block = true };
|
||||
using var engine = new UploadEngine(queue, transport, () => false, _time);
|
||||
|
||||
engine.Pump();
|
||||
await Until(() => queue.Items.Count(i => i.State == UploadItemState.Uploading) == UploadEngine.Parallelism);
|
||||
Assert.Equal(UploadEngine.Parallelism, queue.Items.Count(i => i.IsActive));
|
||||
|
||||
engine.Pause();
|
||||
await Until(() => queue.Items.All(i => i.State == UploadItemState.Queued));
|
||||
Assert.Equal(EngineStatus.Paused, engine.Status);
|
||||
|
||||
transport.Block = false;
|
||||
engine.Resume();
|
||||
await Until(() => queue.Items.All(i => i.IsDone));
|
||||
Assert.False(queue.IsPaused);
|
||||
});
|
||||
|
||||
private UploadQueue Queue(UploadTargetMode mode, int count)
|
||||
{
|
||||
var dir = context.CreateTempDirectory();
|
||||
var queue = new UploadQueue();
|
||||
var entries = Enumerable.Range(0, count).Select(i =>
|
||||
{
|
||||
var path = Path.Combine(dir, $"IMG_{i:0000}.JPG");
|
||||
File.WriteAllBytes(path, RandomNumberGenerator.GetBytes(4096 + i));
|
||||
var info = new FileInfo(path);
|
||||
return new QueueEntry(path, info.Length, info.LastWriteTimeUtc, info.LastWriteTime, "k", null);
|
||||
}).ToList();
|
||||
queue.Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = mode, Title = mode == UploadTargetMode.NewSequence ? "Roof" : null }, entries);
|
||||
return queue;
|
||||
}
|
||||
|
||||
private static string Sha256(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
|
||||
|
||||
private static async Task Until(Func<bool> condition)
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
while (!condition())
|
||||
{
|
||||
if (clock.Elapsed > TimeSpan.FromSeconds(15)) throw new TimeoutException("Condition not reached");
|
||||
await Task.Delay(5);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ManualTime : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = new(2026, 9, 28, 18, 0, 0, TimeSpan.Zero);
|
||||
|
||||
public DateTime UtcNow => _now.UtcDateTime;
|
||||
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
}
|
||||
|
||||
private sealed class FakeTransport : IUploadTransport
|
||||
{
|
||||
public static readonly Guid CreatedSequence = Guid.CreateVersion7();
|
||||
|
||||
public event EventHandler? ReadyChanged;
|
||||
|
||||
public bool IsReady { get; private set; } = true;
|
||||
public bool Block { get; set; }
|
||||
public int SequencesCreated { get; private set; }
|
||||
public List<(string Path, Guid? SequenceId, string Sha256)> Calls { get; } = [];
|
||||
public Func<UploadItem, (UploadOutcome, Guid?)> Respond { get; set; } = _ => (UploadOutcome.Verified, Guid.CreateVersion7());
|
||||
|
||||
public void SetReady(bool ready)
|
||||
{
|
||||
IsReady = ready;
|
||||
ReadyChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public async Task<(UploadOutcome Outcome, Guid? FrameId)> UploadAsync(UploadItem item, Guid? sequenceId, string sha256, IProgress<UploadProgress> progress, CancellationToken ct)
|
||||
{
|
||||
Calls.Add((item.Path, sequenceId, sha256));
|
||||
progress.Report(new UploadProgress(0, item.Size));
|
||||
while (Block) await Task.Delay(5, ct);
|
||||
await Task.Yield();
|
||||
progress.Report(new UploadProgress(item.Size, item.Size));
|
||||
return Respond(item);
|
||||
}
|
||||
|
||||
public Task<Guid> CreateSequenceAsync(string? title, CancellationToken ct)
|
||||
{
|
||||
SequencesCreated++;
|
||||
return Task.FromResult(CreatedSequence);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.IO;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Uploads;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class UploadQueueTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTime Now = new(2026, 9, 28, 18, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
[Test]
|
||||
public void PersistenceRoundTripKeepsBatchesItemsAndStates()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
var sessions = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
|
||||
var created = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.NewSequence, Title = "Harbour sunset", SequenceId = Guid.CreateVersion7() };
|
||||
queue.Add(sessions, [Entry("a.cr2", "k1", @"D:\Cam\Roof"), Entry("b.cr2", "k1", null)]);
|
||||
queue.Add(created, [Entry("c.jpg", null, null)]);
|
||||
var verified = queue.Items[0];
|
||||
verified.State = UploadItemState.Verified;
|
||||
verified.Sha256 = new string('a', 64);
|
||||
verified.FrameId = Guid.CreateVersion7();
|
||||
var failed = queue.Items[1];
|
||||
failed.Retries = 2;
|
||||
queue.Fail(failed, UploadFailure.ServerRejected, "quota exceeded", Now);
|
||||
queue.IsPaused = true;
|
||||
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "uploader-queue.json");
|
||||
File.WriteAllBytes(path, QueueStore.Serialize(queue));
|
||||
var restored = new UploadQueue();
|
||||
QueueStore.Load(path, restored);
|
||||
|
||||
Assert.True(restored.IsPaused);
|
||||
Assert.Equal(2, restored.Batches.Count);
|
||||
Assert.Equal("Harbour sunset", restored.GetBatch(created.Id)!.Title);
|
||||
Assert.Equal(created.SequenceId, restored.GetBatch(created.Id)!.SequenceId);
|
||||
Assert.Equal(3, restored.Items.Count);
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var (a, b) = (queue.Items[i], restored.Items[i]);
|
||||
Assert.Equal(a.Id, b.Id);
|
||||
Assert.Equal(a.BatchId, b.BatchId);
|
||||
Assert.Equal(a.Path, b.Path);
|
||||
Assert.Equal(a.Size, b.Size);
|
||||
Assert.Equal(a.ModifiedUtc, b.ModifiedUtc);
|
||||
Assert.Equal(a.CapturedAt, b.CapturedAt);
|
||||
Assert.Equal(a.SessionKey, b.SessionKey);
|
||||
Assert.Equal(a.WatchRoot, b.WatchRoot);
|
||||
Assert.Equal(a.State, b.State);
|
||||
}
|
||||
Assert.Equal(verified.Sha256, restored.Items[0].Sha256);
|
||||
Assert.Equal(verified.FrameId, restored.Items[0].FrameId);
|
||||
Assert.Equal(UploadFailure.ServerRejected, restored.Items[1].Failure);
|
||||
Assert.Equal("quota exceeded", restored.Items[1].FailureDetail);
|
||||
Assert.Equal(2, restored.Items[1].Retries);
|
||||
Assert.Equal(Now + UploadQueue.RetryDelay, restored.Items[1].NextRetryUtc);
|
||||
Assert.True(restored.ContainsPath("c.jpg"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InterruptedTransfersResumeAsQueued()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
queue.Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions }, [Entry("a.cr2", null, null), Entry("b.cr2", null, null)]);
|
||||
queue.Items[0].State = UploadItemState.Uploading;
|
||||
queue.Items[0].Sha256 = new string('b', 64);
|
||||
queue.Items[1].State = UploadItemState.Hashing;
|
||||
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "q.json");
|
||||
File.WriteAllBytes(path, QueueStore.Serialize(queue));
|
||||
var restored = new UploadQueue();
|
||||
QueueStore.Load(path, restored);
|
||||
|
||||
Assert.Equal(UploadItemState.Queued, restored.Items[0].State);
|
||||
Assert.Equal(UploadItemState.Queued, restored.Items[1].State);
|
||||
// The known hash is kept: the server resumes from the chunks it already holds.
|
||||
Assert.Equal(new string('b', 64), restored.Items[0].Sha256);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CorruptOrMissingFileGivesAnEmptyQueue()
|
||||
{
|
||||
var dir = context.CreateTempDirectory();
|
||||
var corrupt = Path.Combine(dir, "q.json");
|
||||
File.WriteAllText(corrupt, "{ not json");
|
||||
var queue = new UploadQueue();
|
||||
QueueStore.Load(corrupt, queue);
|
||||
QueueStore.Load(Path.Combine(dir, "missing.json"), queue);
|
||||
Assert.Empty(queue.Items);
|
||||
Assert.False(queue.IsPaused);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AddingSkipsPathsAlreadyQueued()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
|
||||
Assert.Equal(2, queue.Add(batch, [Entry("a.jpg", null, null), Entry("b.jpg", null, null)]));
|
||||
Assert.Equal(1, queue.Add(batch, [Entry("b.jpg", null, null), Entry("c.jpg", null, null)]));
|
||||
Assert.Equal(3, queue.Items.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedItemsComeBackAfterTheDelayUntilRetriesRunOut()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
queue.Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions }, [Entry("a.jpg", null, null)]);
|
||||
var item = queue.Items[0];
|
||||
item.State = UploadItemState.Hashing;
|
||||
queue.Fail(item, UploadFailure.FileUnreadable, null, Now);
|
||||
Assert.Null(queue.NextReady(Now.AddSeconds(29)));
|
||||
Assert.Same(item, queue.NextReady(Now + UploadQueue.RetryDelay));
|
||||
Assert.True(queue.HasPending);
|
||||
|
||||
item.Retries = UploadQueue.MaxRetries;
|
||||
queue.Fail(item, UploadFailure.FileUnreadable, null, Now);
|
||||
Assert.Null(item.NextRetryUtc);
|
||||
Assert.Null(queue.NextReady(Now.AddDays(1)));
|
||||
Assert.False(queue.HasPending);
|
||||
|
||||
queue.Requeue(item);
|
||||
Assert.Equal(0, item.Retries);
|
||||
Assert.Same(item, queue.NextReady(Now));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RemovingCompletedItemsKeepsTheRest()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
|
||||
queue.Add(batch, [Entry("a.jpg", null, null), Entry("b.jpg", null, null), Entry("c.jpg", null, null)]);
|
||||
queue.Items[0].State = UploadItemState.Verified;
|
||||
queue.Items[2].State = UploadItemState.Skipped;
|
||||
queue.RemoveCompleted();
|
||||
Assert.Equal(1, queue.Items.Count);
|
||||
Assert.False(queue.ContainsPath("a.jpg"));
|
||||
Assert.True(queue.ContainsPath("b.jpg"));
|
||||
Assert.Equal(1, queue.Batches.Count);
|
||||
}
|
||||
|
||||
private static QueueEntry Entry(string name, string? session, string? watchRoot) =>
|
||||
new(name, 1_000 + name.Length, new DateTime(2026, 9, 28, 16, 2, 11, DateTimeKind.Utc), new DateTime(2026, 9, 28, 18, 2, 11), session, watchRoot);
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Automation;
|
||||
using System.Windows.Automation.Peers;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Tests.Windows;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Theming;
|
||||
using Chronos.Uploader.DesignTime;
|
||||
using Chronos.Uploader.Shell;
|
||||
using Chronos.Uploader.Uploads;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
/// <summary>
|
||||
/// The uploader window on the <c>--capture</c> sample data, shown off screen: icon-only buttons and queue rows are
|
||||
/// named for screen readers, rows take keyboard focus, no field shows an error before use, disabled controls say
|
||||
/// why, and in a right-to-left language the window mirrors while paths, file names and the media glyph do not.
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(120_000)]
|
||||
public sealed class UploaderScreenSmokeTests
|
||||
{
|
||||
[Test]
|
||||
public Task EveryScreenIsNamedFocusableAndCalm() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
using var screen = await UploaderScreen.OpenAsync();
|
||||
var vm = screen.ViewModel;
|
||||
|
||||
screen.Sample.ShowConnect();
|
||||
await screen.SettleAsync();
|
||||
Assert.Equal(FlowDirection.LeftToRight, screen.Window.FlowDirection);
|
||||
Assert.False(vm.Connect.HasErrors, "the address is not marked before a sign-in");
|
||||
Assert.Null(vm.Connect.PasswordError);
|
||||
Assert.Null(vm.Connect.ErrorText);
|
||||
foreach (var box in screen.Visible<TextBox>())
|
||||
Assert.False(Validation.GetHasError(box), $"{AutomationProperties.GetName(box)} shows an error before use");
|
||||
Assert.False(Field.GetHasError(screen.Named<PasswordBox>("Password")), "the password box shows no error before use");
|
||||
screen.AssertIconButtonsNamed("connect");
|
||||
|
||||
// Enter signs in from the form, not from the settings panel drawn over it.
|
||||
var signIn = screen.Visible<Button>().Single(b => Equals(b.Content, Loc.L("Uploader.Connect.SignIn")));
|
||||
Assert.True(signIn.IsDefault, "Enter signs in");
|
||||
vm.IsSettingsOpen = true;
|
||||
await screen.SettleAsync();
|
||||
Assert.False(signIn.IsDefault, "Enter in the settings panel does not sign in");
|
||||
vm.IsSettingsOpen = false;
|
||||
await screen.SettleAsync();
|
||||
|
||||
screen.Sample.ShowQueue();
|
||||
await screen.SettleAsync();
|
||||
screen.AssertIconButtonsNamed("queue");
|
||||
Assert.Equal(Loc.L("Uploader.Queue.List"), AutomationProperties.GetName(screen.Named<ListBox>("ItemList")));
|
||||
var rows = screen.Visible<ListBoxItem>();
|
||||
Assert.NotEmpty(rows);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
Assert.True(row.Focusable, "queue rows take keyboard focus");
|
||||
var item = (UploadItem)row.DataContext;
|
||||
var name = UIElementAutomationPeer.CreatePeerForElement(row)?.GetName();
|
||||
Assert.Contains(item.FileName, name);
|
||||
Assert.Contains(UploadStateTextConverter.Text(item.State), name);
|
||||
}
|
||||
Assert.Contains(rows, r => r.DataContext == vm.CurrentItem);
|
||||
Assert.NotNull(vm.FirstFailed());
|
||||
Assert.NotNull(vm.FailedText);
|
||||
Assert.True(screen.Named<Button>("FailedLink").IsVisible, "the failure count is a link to the failed file");
|
||||
|
||||
// Disabled controls say why; the settings panel keeps Tab inside it.
|
||||
Assert.Equal(Loc.L("Tooltips.Uploader.SequenceDisabled"), vm.SequenceToolTip);
|
||||
Assert.Equal(Loc.L("Tooltips.Uploader.Pause"), vm.PauseToolTip);
|
||||
Assert.Equal(Loc.L("Tooltips.Uploader.Stop"), vm.StopToolTip);
|
||||
Assert.Equal(KeyboardNavigationMode.Cycle, KeyboardNavigation.GetTabNavigation(screen.Named<Border>("SettingsPanel")));
|
||||
|
||||
vm.IsSettingsOpen = true;
|
||||
await screen.SettleAsync();
|
||||
screen.AssertIconButtonsNamed("settings");
|
||||
vm.IsSettingsOpen = false;
|
||||
|
||||
// A failure interrupts the screen reader (assertive) instead of waiting its turn.
|
||||
Toast? shown = null;
|
||||
vm.PendingToasts.CollectionChanged += (_, e) => shown ??= e.NewItems?.OfType<Toast>().FirstOrDefault();
|
||||
vm.ReportError(new InvalidOperationException("The queue file cannot be read"));
|
||||
Assert.True(Assert.NotNull(shown).IsError, "an unexpected error is announced at once");
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheWindowMirrorsForRightToLeftLanguages() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
UiLanguage.Apply("ar");
|
||||
try
|
||||
{
|
||||
using var screen = await UploaderScreen.OpenAsync();
|
||||
screen.Sample.ShowQueue();
|
||||
await screen.SettleAsync();
|
||||
Assert.Equal(FlowDirection.RightToLeft, screen.Window.FlowDirection);
|
||||
|
||||
// File names, paths and addresses read left to right in every language.
|
||||
var fileNames = screen.Visible<ListBoxItem>().Select(r => ((UploadItem)r.DataContext).FileName).ToHashSet();
|
||||
var islands = screen.Visible<TextBlock>()
|
||||
.Where(t => fileNames.Contains(t.Text) || t.Text.Contains('\\') || t.Text.StartsWith("https://", StringComparison.Ordinal))
|
||||
.ToList();
|
||||
Assert.NotEmpty(islands);
|
||||
foreach (var text in islands) Assert.Equal(FlowDirection.LeftToRight, text.FlowDirection, text.Text);
|
||||
// Media glyphs (pause, play) are not mirrored.
|
||||
var pause = screen.Visible<Button>().Single(b => AutomationProperties.GetName(b) == screen.ViewModel.PauseLabel);
|
||||
Assert.Equal(FlowDirection.LeftToRight, pause.FlowDirection);
|
||||
|
||||
screen.Sample.ShowConnect();
|
||||
await screen.SettleAsync();
|
||||
Assert.Equal(FlowDirection.LeftToRight, screen.Named<TextBox>("AddressBox").FlowDirection);
|
||||
var mark = screen.Visible<BrandMarkIcon>().Single(m => m.ActualWidth >= 48);
|
||||
Assert.Equal(FlowDirection.LeftToRight, mark.FlowDirection);
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task StartWithWindowsShowsWhatTaskManagerLeftWhenTheSettingsOpen() => ScreenHost.RunAsync(() =>
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
var startup = new SignInEntry { IsEnabled = true };
|
||||
var vm = new SampleData().CreateViewModel(startup);
|
||||
Assert.True(vm.StartWithWindows);
|
||||
|
||||
// The Uploader runs for the whole session: Task Manager turns its entry off meanwhile, and the box follows when
|
||||
// the settings open.
|
||||
startup.IsEnabled = false;
|
||||
var changed = new List<string?>();
|
||||
vm.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
vm.OpenSettingsCommand.Execute(null);
|
||||
Assert.False(vm.StartWithWindows, "shown as Task Manager left it");
|
||||
Assert.Contains(nameof(MainViewModel.StartWithWindows), changed);
|
||||
vm.CloseSettingsCommand.Execute(null);
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
/// <summary>A sign-in entry another program (Task Manager) can turn off.</summary>
|
||||
private sealed class SignInEntry : Chronos.Uploader.Infrastructure.IStartupRegistration
|
||||
{
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
public void SetEnabled(bool enabled) => IsEnabled = enabled;
|
||||
}
|
||||
|
||||
/// <summary>A <see cref="MainWindow"/> on <see cref="SampleData"/>, shown off screen like <c>--capture</c>.</summary>
|
||||
private sealed class UploaderScreen : IDisposable
|
||||
{
|
||||
private UploaderScreen(SampleData sample, MainViewModel viewModel, MainWindow window)
|
||||
{
|
||||
Sample = sample;
|
||||
ViewModel = viewModel;
|
||||
Window = window;
|
||||
}
|
||||
|
||||
public SampleData Sample { get; }
|
||||
public MainViewModel ViewModel { get; }
|
||||
public MainWindow Window { get; }
|
||||
|
||||
public static async Task<UploaderScreen> OpenAsync()
|
||||
{
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
var sample = new SampleData();
|
||||
var vm = sample.CreateViewModel();
|
||||
var window = new MainWindow(vm, sample.Settings)
|
||||
{
|
||||
WindowStartupLocation = WindowStartupLocation.Manual,
|
||||
Left = -20000,
|
||||
Top = -20000,
|
||||
Width = 760,
|
||||
Height = 700,
|
||||
ShowActivated = false,
|
||||
ShowInTaskbar = false,
|
||||
};
|
||||
window.Show();
|
||||
var screen = new UploaderScreen(sample, vm, window);
|
||||
await screen.SettleAsync();
|
||||
return screen;
|
||||
}
|
||||
|
||||
public async Task SettleAsync()
|
||||
{
|
||||
Window.UpdateLayout();
|
||||
// Bindings, templates and the work the window defers to the dispatcher (scrolling, focus).
|
||||
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
await Task.Delay(30);
|
||||
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
Window.UpdateLayout();
|
||||
}
|
||||
|
||||
public List<T> Visible<T>()
|
||||
where T : FrameworkElement => [.. All<T>(Window).Where(e => e.IsVisible)];
|
||||
|
||||
public T Named<T>(string name)
|
||||
where T : FrameworkElement => All<T>(Window).Single(e => e.Name == name);
|
||||
|
||||
/// <summary>DESIGN §4: an icon-only button carries an accessible name (and a tooltip).</summary>
|
||||
public void AssertIconButtonsNamed(string screen)
|
||||
{
|
||||
foreach (var button in Visible<Button>().Where(b => b.Content is null))
|
||||
{
|
||||
Assert.False(string.IsNullOrWhiteSpace(AutomationProperties.GetName(button)), $"{screen}: an icon-only button has no name");
|
||||
Assert.True(button.ToolTip is not null, $"{screen}: {AutomationProperties.GetName(button)} has no tooltip");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Window.Close();
|
||||
ViewModel.Dispose();
|
||||
}
|
||||
|
||||
private static IEnumerable<T> All<T>(DependencyObject node)
|
||||
where T : DependencyObject
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(node, i);
|
||||
if (child is T match) yield return match;
|
||||
foreach (var nested in All<T>(child)) yield return nested;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Text;
|
||||
using Chronos.Uploader.Uploads;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
public sealed class UploaderTextTests
|
||||
{
|
||||
private static readonly CultureInfo En = CultureInfo.GetCultureInfo("en");
|
||||
private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it");
|
||||
|
||||
private static readonly QueueSummary Mockup = new(4_812, 96_200_000_000, 2_214, 2_201, 0, 0, 44_000_000_000, "2026-09-28_18-02-11_0413.CR2")
|
||||
{
|
||||
RemainingBytes = 93_480_000_000,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void QueueLineMatchesTheMockup()
|
||||
{
|
||||
var left = RateMeter.TimeLeft(Mockup.RemainingBytes, 38_000_000);
|
||||
Assert.Equal("4,812 files · 96.2 GB · 38 MB/s · 41 min left", UploaderText.QueueLine(Mockup, QueueActivity.Running, 38_000_000, left, En));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void QueueLineFollowsTheCulture()
|
||||
{
|
||||
Assert.Equal("4.812 file · 96,2 GB · 38 MB/s · mancano 41 min", UploaderText.QueueLine(Mockup, QueueActivity.Running, 38_000_000, TimeSpan.FromMinutes(41), It));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void QueueLineNamesTheActivityWhenNotRunning()
|
||||
{
|
||||
Assert.Equal("4,812 files · 96.2 GB · Paused", UploaderText.QueueLine(Mockup, QueueActivity.Paused, 0, null, En));
|
||||
Assert.Equal("4,812 files · 96.2 GB · Waiting for server", UploaderText.QueueLine(Mockup, QueueActivity.WaitingForServer, 0, null, En));
|
||||
Assert.Equal("1 file · 25 MB · Done", UploaderText.QueueLine(Mockup with { Files = 1, Bytes = 25_000_000 }, QueueActivity.Done, 0, null, En));
|
||||
Assert.Equal("Nothing queued", UploaderText.QueueLine(default, QueueActivity.Idle, 0, null, En));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RunningLineOmitsRateAndTimeUntilKnown()
|
||||
{
|
||||
Assert.Equal("4,812 files · 96.2 GB", UploaderText.QueueLine(Mockup, QueueActivity.Running, 0, null, En));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProgressLineMatchesTheMockup()
|
||||
{
|
||||
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 0 retries", UploaderText.ProgressLine(Mockup, En));
|
||||
Assert.Equal("2,214 of 4,812 sent · 2,201 verified by the server · 1 retry", UploaderText.ProgressLine(Mockup with { Retries = 1, Failed = 3 }, En));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailuresHaveTheirOwnTextOnlyWhenThereAreAny()
|
||||
{
|
||||
Assert.Null(UploaderText.Failed(Mockup, En));
|
||||
Assert.Equal("1,203 failed", UploaderText.Failed(Mockup with { Failed = 1_203 }, En));
|
||||
// Italian participles agree with the number ("1 non riuscito", "3 non riusciti"): the count follows a label instead.
|
||||
Assert.Equal("Non riusciti: 3", UploaderText.Failed(Mockup with { Failed = 3 }, It));
|
||||
Assert.Equal("Non riusciti: 1", UploaderText.Failed(Mockup with { Failed = 1 }, It));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ItalianProgressReadsForASingleFileToo()
|
||||
{
|
||||
Assert.Equal("Inviati: 1 di 1 · Verificati dal server: 1 · 0 nuovi tentativi",
|
||||
UploaderText.ProgressLine(Mockup with { Files = 1, Sent = 1, Verified = 1 }, It));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SizeUnitsFollowTheLanguage()
|
||||
{
|
||||
Assert.Equal("999 byte", UploaderText.Bytes(999, It));
|
||||
Assert.Equal("1,5 KB", UploaderText.Bytes(1_536, It));
|
||||
Assert.Equal("4,2 MB/s", UploaderText.Rate(4_240_000, It));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(0.0, "0 B/s")]
|
||||
[Case(950_000.0, "950 KB/s")]
|
||||
[Case(4_240_000.0, "4.2 MB/s")]
|
||||
[Case(38_400_000.0, "38 MB/s")]
|
||||
[Case(1_260_000_000.0, "1.3 GB/s")]
|
||||
public void RatesUseDecimalUnits(double bytesPerSecond, string expected) =>
|
||||
Assert.Equal(expected, UploaderText.Rate(bytesPerSecond, En));
|
||||
|
||||
[Theory]
|
||||
[Case(40.0, "40 s")]
|
||||
[Case(299.0, "5 min")]
|
||||
[Case(3_590.0, "1 h 00 m")]
|
||||
[Case(7_500.0, "2 h 05 m")]
|
||||
[Case(93_600.0, "1 d 2 h")]
|
||||
public void DurationsAreCompact(double seconds, string expected) =>
|
||||
Assert.Equal(expected, UploaderText.Duration(TimeSpan.FromSeconds(seconds), En));
|
||||
|
||||
[Theory]
|
||||
[Case(999L, "999 B")]
|
||||
[Case(1_536L, "1.5 KB")]
|
||||
[Case(96_200_000_000L, "96.2 GB")]
|
||||
[Case(1_900_000_000_000L, "1.9 TB")]
|
||||
public void SizesUseDecimalUnits(long bytes, string expected) => Assert.Equal(expected, UploaderText.Bytes(bytes, En));
|
||||
|
||||
[Test]
|
||||
public void TimeLeftNeedsAUsableRate()
|
||||
{
|
||||
Assert.Equal(TimeSpan.FromMinutes(41), RateMeter.TimeLeft(93_480_000_000, 38_000_000));
|
||||
Assert.Equal(TimeSpan.Zero, RateMeter.TimeLeft(0, 0));
|
||||
Assert.Null(RateMeter.TimeLeft(1_000, 10));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RateMeterAveragesTheWindowAndDecaysWhenStalled()
|
||||
{
|
||||
var meter = new RateMeter(TimeSpan.FromSeconds(10));
|
||||
Assert.Equal(0.0, meter.BytesPerSecond(TimeSpan.Zero));
|
||||
for (var s = 0; s <= 20; s++) meter.Add(4_000_000, TimeSpan.FromSeconds(s));
|
||||
Assert.Approximately(4_000_000, meter.BytesPerSecond(TimeSpan.FromSeconds(20)), 1);
|
||||
// Nothing sent for 20 s: the window holds no transfer any more.
|
||||
Assert.Equal(0.0, meter.BytesPerSecond(TimeSpan.FromSeconds(40)));
|
||||
meter.Reset();
|
||||
Assert.Equal(0.0, meter.BytesPerSecond(TimeSpan.FromSeconds(40)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SummaryCountsStatesAndBytes()
|
||||
{
|
||||
var queue = new UploadQueue();
|
||||
queue.Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions },
|
||||
Enumerable.Range(0, 5).Select(i => new QueueEntry($"{i}.jpg", 100, DateTime.UtcNow, null, null, null)));
|
||||
queue.Items[0].State = UploadItemState.Verified;
|
||||
queue.Items[1].State = UploadItemState.Skipped;
|
||||
queue.Items[2].State = UploadItemState.Uploading;
|
||||
queue.Items[2].BytesSent = 40;
|
||||
queue.Items[3].State = UploadItemState.Failed;
|
||||
queue.Items[3].Retries = 1;
|
||||
|
||||
var s = QueueSummary.From(queue.Items);
|
||||
Assert.Equal(5, s.Files);
|
||||
Assert.Equal(500L, s.Bytes);
|
||||
Assert.Equal(2, s.Sent);
|
||||
Assert.Equal(2, s.Verified);
|
||||
Assert.Equal(1, s.Failed);
|
||||
Assert.Equal(1, s.Retries);
|
||||
Assert.Equal(240L, s.DoneBytes);
|
||||
Assert.Equal(160L, s.RemainingBytes);
|
||||
Assert.Equal("2.jpg", s.CurrentFile);
|
||||
Assert.Approximately(0.48, s.Progress, 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Uploader.Shell;
|
||||
using Chronos.Uploader.Text;
|
||||
|
||||
namespace Chronos.App.Tests.Uploader;
|
||||
|
||||
/// <summary>A watch-folder chip shows the path (which it may shorten) and the interval apart; the tooltip carries the whole path.</summary>
|
||||
public sealed class WatchFolderViewModelTests
|
||||
{
|
||||
private const string Path = @"\\garage-pi\cam";
|
||||
|
||||
[Test]
|
||||
public void TheChipNamesThePathAndTheInterval()
|
||||
{
|
||||
var chip = Chip(isNetwork: false);
|
||||
var interval = UploaderText.Duration(TimeSpan.FromMinutes(5), Loc.Culture);
|
||||
|
||||
Assert.Equal(Loc.L("Uploader.Watch.Interval", interval), chip.IntervalText);
|
||||
Assert.Equal(Loc.L("Uploader.Watch.Chip", Path, interval), chip.Text);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheTooltipStartsWithTheWholePathKeptLeftToRight()
|
||||
{
|
||||
var interval = UploaderText.Duration(TimeSpan.FromMinutes(5), Loc.Culture);
|
||||
var embedded = "\u202A" + Path + "\u202C · ";
|
||||
|
||||
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolder", interval), Chip(isNetwork: false).ToolTip);
|
||||
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolderNetwork", interval), Chip(isNetwork: true).ToolTip);
|
||||
var missing = Chip(isNetwork: true);
|
||||
missing.IsAvailable = false;
|
||||
Assert.Equal(embedded + Loc.L("Tooltips.Uploader.WatchFolderMissing", interval), missing.ToolTip);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ANewIntervalRefreshesTheChip()
|
||||
{
|
||||
var chip = Chip(isNetwork: false);
|
||||
var changed = new List<string?>();
|
||||
chip.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
chip.IntervalSeconds = 60;
|
||||
|
||||
Assert.Contains(nameof(WatchFolderViewModel.IntervalText), changed);
|
||||
Assert.Contains(nameof(WatchFolderViewModel.Text), changed);
|
||||
Assert.Contains(nameof(WatchFolderViewModel.ToolTip), changed);
|
||||
Assert.Equal(Loc.L("Uploader.Watch.Interval", UploaderText.Duration(TimeSpan.FromMinutes(1), Loc.Culture)), chip.IntervalText);
|
||||
}
|
||||
|
||||
private static WatchFolderViewModel Chip(bool isNetwork) => new(Path, 300, isNetwork, (_, _) => { }, _ => { });
|
||||
}
|
||||
Reference in new issue
Block a user