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,89 @@
|
||||
using System.Globalization;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
public sealed class CardPoolTests
|
||||
{
|
||||
internal static readonly CardDevice CardA = new(@"F:\", "EOS_DIGITAL", 0x3F2A9C11, 128_000_000_000, 31_800_000_000, true, true);
|
||||
private static readonly CardDevice GoPro = new(@"E:\", "GOPRO", 0x11112222, 64_000_000_000, 52_600_000_000, true, true);
|
||||
internal static readonly CardDevice Usb = new(@"G:\", "BACKUP", 0x99990000, 2_000_000_000_000, 1_800_000_000_000, true, false);
|
||||
|
||||
public CardPoolTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
private static MediaCard Known(CardDevice device, string nickname, DateTimeOffset seen) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Identity = device.Identity,
|
||||
VolumeSerial = device.SerialNumber,
|
||||
Label = device.Label,
|
||||
Capacity = device.TotalBytes,
|
||||
Nickname = nickname,
|
||||
CameraMake = "Canon",
|
||||
CameraModel = "Canon EOS R5",
|
||||
CameraSerial = "0431",
|
||||
LastSeen = seen,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void InsertedVolumesComeFirstThenRememberedCardsThenTheFolder()
|
||||
{
|
||||
var away = new CardDevice(@"H:\", "NIKON", 0x55556666, 64_000_000_000, 0, true, true);
|
||||
var cards = new[] { Known(CardA, "EOS R5 · card A", DateTimeOffset.UtcNow), Known(away, "Z 8 card", DateTimeOffset.UtcNow.AddDays(-3)) };
|
||||
var pool = CardPool.Build([Usb, CardA, GoPro], cards, @"D:\Shoots\2026");
|
||||
|
||||
Assert.SequenceEqual(new[] { GoPro.Identity, CardA.Identity, Usb.Identity, away.Identity, @"D:\Shoots\2026" }, pool.Select(s => s.Key));
|
||||
Assert.Equal(SourceKind.Card, pool[0].Kind);
|
||||
Assert.False(pool[0].IsKnown);
|
||||
Assert.Equal("GOPRO", pool[0].Title);
|
||||
Assert.Equal("New card", pool[0].StateText);
|
||||
Assert.Equal("EOS R5 · card A", pool[1].Title);
|
||||
Assert.Equal("Known card", pool[1].StateText);
|
||||
Assert.Equal("128 GB · 96.2 GB used", pool[1].Subtitle);
|
||||
Assert.Equal("128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[1].IdentityText);
|
||||
Assert.Equal(SourceKind.Drive, pool[2].Kind);
|
||||
Assert.Equal("no DCIM · 1.8 TB free", pool[2].Subtitle);
|
||||
Assert.False(pool[3].IsInserted);
|
||||
Assert.Null(pool[3].Root);
|
||||
Assert.Equal("Canon EOS R5 · not inserted", pool[3].Subtitle);
|
||||
Assert.Equal(SourceKind.Folder, pool[4].Kind);
|
||||
Assert.Equal(@"D:\Shoots\2026", pool[4].Root);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARememberedCardStaysNewUntilItHasANickname()
|
||||
{
|
||||
var unnamed = Known(GoPro, "GoPro 12", DateTimeOffset.UtcNow) with { Nickname = null };
|
||||
var source = CardPool.Build([GoPro], [unnamed], null).Single();
|
||||
Assert.NotNull(source.Card, "the first plan remembered it");
|
||||
Assert.False(source.IsKnown);
|
||||
Assert.Equal("New card", source.StateText);
|
||||
Assert.Equal("GOPRO", source.Title);
|
||||
|
||||
var named = CardPool.Build([GoPro], [unnamed with { Nickname = "GoPro 12" }], null).Single();
|
||||
Assert.True(named.IsKnown);
|
||||
Assert.Equal("Known card", named.StateText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheEntryTooltipCarriesTheStateAndTheWholeSubtitle()
|
||||
{
|
||||
var pool = CardPool.Build([CardA, Usb], [Known(CardA, "EOS R5 · card A", DateTimeOffset.UtcNow)], @"D:\Shoots\2026");
|
||||
Assert.Equal("Known card · 128 GB · 96.2 GB used", pool[0].ToolTip);
|
||||
Assert.Equal("no DCIM · 1.8 TB free", pool[1].ToolTip);
|
||||
Assert.Equal(@"Folder · D:\Shoots\2026", pool[2].ToolTip);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AKnownCardWithoutDcimIsStillACard()
|
||||
{
|
||||
var pool = CardPool.Build([Usb], [Known(Usb, "Backup card", DateTimeOffset.UtcNow)], null);
|
||||
Assert.Equal(SourceKind.Card, pool.Single().Kind);
|
||||
Assert.Equal("3F2A-9C11", ImportSource.SerialText(0x3F2A9C11));
|
||||
Assert.Equal("3F2A9C11-EOS_DIGITAL-128000000000", CardA.Identity);
|
||||
Assert.Equal("EOS_DIGITAL", CardA.ToVolume().Label);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
public sealed class ImportChoicesTests
|
||||
{
|
||||
[Test]
|
||||
public void ACardProfileRoundTripsThroughTheForm()
|
||||
{
|
||||
var profile = new CardProfile
|
||||
{
|
||||
FolderTemplate = "{year}/{title}",
|
||||
FileTemplate = "{name}",
|
||||
SessionGapMinutes = 30,
|
||||
MinimumSessionFrames = 4,
|
||||
IncludeSubfolders = false,
|
||||
VerifyCopies = false,
|
||||
Duplicates = DuplicatePolicy.ImportAgain,
|
||||
AfterImport = AfterImport.DeleteImported,
|
||||
Eject = false,
|
||||
DeepAnalysis = false,
|
||||
};
|
||||
var choices = ImportChoices.FromProfile(profile);
|
||||
Assert.True(choices.SplitSessions);
|
||||
Assert.Equal(30, choices.GapMinutes);
|
||||
Assert.Equal(profile, choices.ToProfile());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SessionsOffIsRememberedAsAZeroGapAndNeverSplits()
|
||||
{
|
||||
var off = new ImportChoices { SplitSessions = false, GapMinutes = 20 };
|
||||
Assert.Equal(0, off.ToProfile().SessionGapMinutes);
|
||||
Assert.Equal(TimeSpan.MaxValue, off.ToOptions().SessionGap);
|
||||
var back = ImportChoices.FromProfile(off.ToProfile());
|
||||
Assert.False(back.SplitSessions);
|
||||
Assert.Equal(new CardProfile().SessionGapMinutes, back.GapMinutes);
|
||||
Assert.Equal(TimeSpan.FromMinutes(20), (off with { SplitSessions = true }).ToOptions().SessionGap);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OptionsCarryTheFormAndTheTypedTitles()
|
||||
{
|
||||
var titles = new Dictionary<string, string> { ["k"] = "Harbour" };
|
||||
var options = new ImportChoices { MinimumFrames = 0, Duplicates = DuplicatePolicy.ImportAgain, VerifyCopies = false }.ToOptions(titles);
|
||||
Assert.Equal(1, options.MinimumSessionFrames);
|
||||
Assert.Equal(DuplicatePolicy.ImportAgain, options.Duplicates);
|
||||
Assert.False(options.VerifyCopies);
|
||||
Assert.Equal("Harbour", options.Titles["k"]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OnlyGroupingAndNamingChoicesNeedANewPlan()
|
||||
{
|
||||
var a = new ImportChoices();
|
||||
Assert.False((a with { Duplicates = DuplicatePolicy.ImportAgain, VerifyCopies = false, Eject = false, AfterImport = AfterImport.FormatCard }).NeedsNewPlan(a));
|
||||
Assert.False((a with { SplitSessions = false, GapMinutes = 5 }).NeedsNewPlan(a with { SplitSessions = false }));
|
||||
Assert.True((a with { GapMinutes = 5 }).NeedsNewPlan(a));
|
||||
Assert.True((a with { MinimumFrames = 2 }).NeedsNewPlan(a));
|
||||
Assert.True((a with { FileTemplate = "{name}" }).NeedsNewPlan(a));
|
||||
Assert.True((a with { Destination = ImportDestinationKind.Folder }).NeedsNewPlan(a));
|
||||
Assert.True((a with { IncludeSubfolders = false }).NeedsNewPlan(a));
|
||||
Assert.False((a with { FolderPath = @"D:\Shoots" }).NeedsNewPlan(a), "the folder path is not used for the archive");
|
||||
var folder = a with { Destination = ImportDestinationKind.Folder, FolderPath = @"D:\Shoots" };
|
||||
Assert.True((folder with { FolderPath = @"E:\Backup" }).NeedsNewPlan(folder));
|
||||
Assert.False((folder with { FolderPath = @"d:\shoots" }).NeedsNewPlan(folder), "paths compare without case");
|
||||
Assert.False(a.TitlesChangeNames);
|
||||
Assert.True((a with { FolderTemplate = "{year}/{Title:upper}" }).TitlesChangeNames);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACardFollowsItsCameraProfileWhenItJoinedItOrHasNoSettingsYet()
|
||||
{
|
||||
var shared = new CardProfile { SessionGapMinutes = 90 };
|
||||
var defaults = new CardProfile { SessionGapMinutes = 45 };
|
||||
var own = Card("Canon", "Canon EOS R5", new CardProfile { SessionGapMinutes = 20 }, daysAgo: 30);
|
||||
var fresh = Card("Canon", "Canon EOS R5", null, daysAgo: 0);
|
||||
var camera = new CameraProfile("Canon", "Canon EOS R5", shared, []);
|
||||
|
||||
Assert.Equal(new ResolvedProfile(shared, true), CameraProfiles.Resolve(fresh, camera, defaults), "a new card of a known camera needs no setup");
|
||||
Assert.Equal(new ResolvedProfile(defaults, false), CameraProfiles.Resolve(fresh, null, defaults));
|
||||
Assert.Equal(20, CameraProfiles.Resolve(own, camera, defaults).Profile.SessionGapMinutes, "a card with its own settings keeps them");
|
||||
Assert.False(CameraProfiles.Resolve(own, camera, defaults).FollowsCamera);
|
||||
Assert.Equal(new ResolvedProfile(shared, true), CameraProfiles.Resolve(own, camera.With(own.Id), defaults), "a card that joined follows the shared rules");
|
||||
|
||||
var joined = camera.With(own.Id).With(own.Id).With(fresh.Id);
|
||||
Assert.SequenceEqual([own.Id, fresh.Id], joined.Cards);
|
||||
Assert.SequenceEqual([fresh.Id], joined.Without(own.Id).Cards);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SplitsAndMergesTravelToThePlanner()
|
||||
{
|
||||
var options = new ImportChoices().ToOptions(null, new HashSet<string> { "DCIM/100CANON/IMG_0005.CR2" }, new HashSet<string> { "DCIM/100CANON/IMG_0009.CR2" });
|
||||
Assert.True(options.SplitBefore.Contains("DCIM/100CANON/IMG_0005.CR2"));
|
||||
Assert.True(options.MergeAt.Contains("DCIM/100CANON/IMG_0009.CR2"));
|
||||
Assert.Empty(new ImportChoices().ToOptions().SplitBefore);
|
||||
}
|
||||
|
||||
private static MediaCard Card(string make, string model, CardProfile? profile, int daysAgo) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Identity = Guid.NewGuid().ToString("N"),
|
||||
CameraMake = make,
|
||||
CameraModel = model,
|
||||
ProfileJson = profile is null ? null : JsonSerializer.Serialize(profile, StoredProfile),
|
||||
LastSeen = DateTimeOffset.UtcNow.AddDays(-daysAgo),
|
||||
};
|
||||
|
||||
/// <summary>How the card repository stores a profile (camel case, enum names).</summary>
|
||||
private static readonly JsonSerializerOptions StoredProfile = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Converters = { new JsonStringEnumConverter() } };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
/// <summary>A stopped import or plan says what happened in one localized sentence, never the exception's raw text.</summary>
|
||||
public sealed class ImportFailuresTests
|
||||
{
|
||||
public ImportFailuresTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
[Test]
|
||||
public void AnImportFailureIsOneSentenceByCause()
|
||||
{
|
||||
const string Card = "EOS R5 · card A";
|
||||
Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Import(new ImportSourceUnavailableException(@"C:\Users\me\AppData\Local\Temp\card\"), Card));
|
||||
Assert.Equal("The destination is full.", ImportFailures.Import(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)), Card));
|
||||
Assert.Equal("Chronos may not write to the destination.", ImportFailures.Import(new UnauthorizedAccessException(@"Access to D:\Shoots is denied."), Card));
|
||||
Assert.Equal("The server did not accept the photos.", ImportFailures.Import(new HttpRequestException("No such host is known."), Card));
|
||||
Assert.Equal("The server did not accept the photos.",
|
||||
ImportFailures.Import(new ChronosApiException(HttpStatusCode.InsufficientStorage, new ApiError("quota", "Quota exceeded", null)), Card));
|
||||
Assert.Equal("The import stopped before the end.", ImportFailures.Import(new InvalidDataException("Bad sidecar. Second sentence."), Card));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheCopiesAStoppedImportNeverReachedSayWhyInOneSentence()
|
||||
{
|
||||
const string Card = "EOS R5 · card A";
|
||||
Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Stop(new ImportSourceUnavailableException(@"E:\"), Card));
|
||||
Assert.Equal("The destination is full.", ImportFailures.Stop(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)), Card));
|
||||
Assert.Equal("Chronos may not write to the destination.", ImportFailures.Stop(new UnauthorizedAccessException(@"Access to D:\Shoots is denied."), Card));
|
||||
Assert.Equal("The import stopped before the end.", ImportFailures.Stop(new IOException("The specified network name is no longer available."), Card));
|
||||
// The server's own sentence, else why it could not be asked.
|
||||
Assert.Equal("Sign in again",
|
||||
ImportFailures.Stop(new ChronosApiException(HttpStatusCode.Unauthorized, new ApiError("unauthorized", "Sign in again", null)), Card));
|
||||
Assert.Equal(Loc.L("Server.Error.Unreachable"), ImportFailures.Stop(new HttpRequestException("An error occurred while sending the request."), Card));
|
||||
// A reverse proxy answered while the server restarted: its reason phrase is English, never the server's sentence.
|
||||
Assert.Equal(Loc.L("Server.Error.Unreachable"), ImportFailures.Stop(new ChronosApiException(HttpStatusCode.BadGateway, new ApiError("http_502", "Bad Gateway")), Card));
|
||||
Assert.Equal(Loc.L("Server.Error.Unreachable"), ImportFailures.Stop(new TaskCanceledException("The operation was canceled."), Card));
|
||||
Assert.Equal(Loc.L("Server.Error.Untrusted"), ImportFailures.Stop(new UntrustedCertificateException("AB:CD"), Card));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AServerImportStoppedOnThisPcNamesItsCacheFolderNotTheServer()
|
||||
{
|
||||
// The server import stages its copies in this PC's cache folder; the server answers for its own space and rights.
|
||||
const string Card = "EOS R5 · card A";
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests");
|
||||
var staging = Path.Combine(Path.GetTempPath(), "chronos-server-import");
|
||||
Assert.True(((IImportSink)new ServerImportSink(client, staging)).StagesOnThisPc);
|
||||
Assert.Equal("The drive of this PC's cache folder is full.",
|
||||
ImportFailures.Stop(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)), Card, stagesOnThisPc: true));
|
||||
Assert.Equal("Chronos may not write to this PC's cache folder.",
|
||||
ImportFailures.Stop(new UnauthorizedAccessException(@"Access to the path 'C:\Users\me\AppData\Local\Chronos\cache\server-import' is denied."), Card,
|
||||
stagesOnThisPc: true));
|
||||
Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Stop(new ImportSourceUnavailableException(@"E:\"), Card, stagesOnThisPc: true));
|
||||
Assert.Equal("The import stopped before the end.", ImportFailures.Stop(new IOException("The specified network name is no longer available."), Card, stagesOnThisPc: true));
|
||||
Assert.Equal(Loc.L("Server.Error.Unreachable"), ImportFailures.Stop(new HttpRequestException("No such host is known."), Card, stagesOnThisPc: true));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFailedImportJobShowsOnlyTheArchivesOwnSentences()
|
||||
{
|
||||
// The job engine keeps the text of what stopped the job: the archive's own failures are already catalog sentences.
|
||||
Assert.Equal("The archive D:\\Shoots is offline.", ImportFailures.Job(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.Offline).Message));
|
||||
Assert.Equal("The archive D:\\Shoots is read-only.", ImportFailures.Job(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.ReadOnly).Message));
|
||||
Assert.Equal("The card or folder E:\\ is no longer available.", ImportFailures.Job(new ImportSourceUnavailableException(@"E:\").Message));
|
||||
var busy = new LeaseUnavailableException("settings", new LeaseRecord("t", "Chronos Server (nas)", "nas", 42, DateTimeOffset.UnixEpoch, DateTimeOffset.UnixEpoch));
|
||||
Assert.Equal(busy.Message, ImportFailures.Job(busy.Message));
|
||||
var newer = new NewerFormatException(Path.Combine(Path.GetTempPath(), "archive.json"), 3);
|
||||
Assert.Equal("archive.json was written by a newer Chronos (format 3).", ImportFailures.Job(newer.Message));
|
||||
Assert.Equal("IMG_0001.CR3 could not be added to the sequence.", ImportFailures.Job(Loc.L("Archive.Error.DuplicateLost", "IMG_0001.CR3")));
|
||||
|
||||
// A database, framework or system text reads as the catalog's sentence; the tooltip keeps it.
|
||||
Assert.Equal("The import stopped before the end.", ImportFailures.Job("database is locked: no write lock within 30 s"));
|
||||
Assert.Equal("The import stopped before the end.",
|
||||
ImportFailures.Job(@"The process cannot access the file 'D:\Shoots\2026\IMG_0001.CR3' because it is being used by another process."));
|
||||
Assert.Equal("The import stopped before the end.", ImportFailures.Job("There is not enough space on the disk. : 'D:\\Shoots\\.chronos\\journal'"));
|
||||
Assert.Equal("The import stopped before the end.", ImportFailures.Job($"Sequence {Guid.Empty} is not indexed."));
|
||||
Assert.Equal("The import stopped before the end.", ImportFailures.Job(null));
|
||||
Assert.Equal("The import stopped before the end.", ImportFailures.Job(string.Empty));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APlanningFailureNamesTheSource()
|
||||
{
|
||||
const string Folder = @"D:\Shoots";
|
||||
Assert.Equal(@"D:\Shoots is no longer available.", ImportFailures.Plan(new DirectoryNotFoundException(@"Could not find a part of the path 'D:\Shoots\DCIM'."), Folder));
|
||||
Assert.Equal(@"D:\Shoots could not be read.", ImportFailures.Plan(new UnauthorizedAccessException("Access denied."), Folder));
|
||||
Assert.Equal(@"D:\Shoots could not be read.", ImportFailures.Plan(new IOException("The device is not ready."), Folder));
|
||||
Assert.Equal("The import could not be planned.", ImportFailures.Plan(new InvalidOperationException("Sequence contains no elements"), Folder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACardCheckOrDeleteFailureIsOneSentenceByCause()
|
||||
{
|
||||
const string Card = "EOS R5 · card A";
|
||||
var root = Directory.CreateTempSubdirectory("chronos-card-").FullName;
|
||||
try
|
||||
{
|
||||
Assert.Equal("A photo or its archive copy could not be read.", ImportFailures.Check(new IOException("The semaphore timeout period has expired."), Card, root));
|
||||
Assert.Equal("The index could not be read or written.", ImportFailures.Check(new DatabaseConnectionException("database is locked"), Card, root));
|
||||
Assert.Equal("The archive D:\\Shoots is offline.", ImportFailures.Check(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.Offline), Card, root));
|
||||
Assert.Equal("Something went wrong.", ImportFailures.Check(new InvalidOperationException("Collection was modified."), Card, root));
|
||||
Assert.Equal("EOS R5 · card A is write-protected or holds protected photos.",
|
||||
ImportFailures.Erase(new IOException("The media is write protected.", unchecked((int)0x80070013)), Card, root));
|
||||
Assert.Equal("EOS R5 · card A is write-protected or holds protected photos.",
|
||||
ImportFailures.Erase(new UnauthorizedAccessException(@"Access to the path 'E:\DCIM\IMG_0001.CR3' is denied."), Card, root));
|
||||
Assert.Equal("Something went wrong.", ImportFailures.Erase(new IOException("The request could not be performed because of an I/O device error."), Card, root));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(root);
|
||||
}
|
||||
// A card that left explains whatever failed while it was read or written.
|
||||
var gone = Path.Combine(Path.GetTempPath(), "chronos-card-" + Guid.NewGuid().ToString("N"));
|
||||
Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Check(new IOException("The device is not ready."), Card, gone));
|
||||
Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Erase(new UnauthorizedAccessException("Access denied."), Card, gone));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.App.Tests.Import.ImportTestData;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
/// <summary>Card to archive and card to folder on real files and a real index, and the card-erase gate around them.</summary>
|
||||
[Category("import")]
|
||||
public sealed class ImportFlowTests(TestContext context)
|
||||
{
|
||||
private static readonly CardVolume Volume = new("3F2A9C11-EOS_DIGITAL-127865454592", 0x3F2A9C11, "EOS_DIGITAL", 127_865_454_592);
|
||||
|
||||
[Test]
|
||||
public async Task AVerifiedArchiveImportUnlocksDeleteAndFormat()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
|
||||
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test" });
|
||||
var archive = await archives.AdoptAsync(context.CreateTempDirectory("archive"), "Main", context.Cancellation);
|
||||
var card = Card(context.CreateTempDirectory("card"), 10, Start, Start.AddHours(3), Start.AddDays(1));
|
||||
var media = await archives.Imports.RegisterCardAsync(Volume, context.Cancellation);
|
||||
var destination = new ArchiveDestination(archives, archive);
|
||||
var choices = new ImportChoices();
|
||||
|
||||
var plan = await destination.PlanAsync(card, choices.ToOptions(), media.Id, null, context.Cancellation);
|
||||
Assert.Equal(3, plan.Sessions.Count);
|
||||
Assert.Equal(30, plan.CopyCount);
|
||||
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, null, null, null);
|
||||
Assert.False(before.CanCheck, "no import, no erase");
|
||||
Assert.False(before.CanDelete);
|
||||
Assert.False(before.CanFormat);
|
||||
Assert.Equal(Loc.L("Import.Blocked.NothingImported"), before.CheckBlocker);
|
||||
var unverified = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
|
||||
Assert.Empty(unverified.ToDelete);
|
||||
|
||||
Job queued;
|
||||
await using (var engine = new JobEngine(db, archives.CreateJobHandlers(),
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }))
|
||||
{
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
queued = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, media.Id, choices.VerifyCopies), cancellationToken: context.Cancellation);
|
||||
await WaitDoneAsync(db, queued.Id);
|
||||
}
|
||||
|
||||
// The verification result comes from the job's own records: every planned copy has its frame.
|
||||
var job = (await db.Jobs.GetAsync(queued.Id, context.Cancellation))!;
|
||||
var outcome = await ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, media.Id, choices.VerifyCopies, context.Cancellation);
|
||||
Assert.Equal(30, outcome.Copied);
|
||||
Assert.True(outcome.IsComplete);
|
||||
Assert.Equal(30, (await ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, null, choices.VerifyCopies, context.Cancellation)).Copied,
|
||||
"a folder source, without import history, finds its frames in the sessions' sequences");
|
||||
var afterImport = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, null);
|
||||
Assert.True(afterImport.CanCheck);
|
||||
Assert.False(afterImport.CanDelete, "the dry run must come first");
|
||||
Assert.Equal(Loc.L("Import.Blocked.NoDryRun"), afterImport.DeleteBlocker);
|
||||
|
||||
var snapshot = CardSnapshot.Take(card, Volume.Identity);
|
||||
var erase = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
|
||||
var ready = afterImport with { Erase = erase, Card = snapshot };
|
||||
Assert.True(ready.CanDelete);
|
||||
Assert.True(ready.CanFormat);
|
||||
Assert.Equal(30, ready.DeleteCount);
|
||||
Assert.Equal("30 verified on the card · " + Chronos.App.Infrastructure.Formatting.Bytes(ready.DeleteBytes), ready.EraseText);
|
||||
Assert.False((ready with { Card = null }).CanDelete, "the dry run lists the card too");
|
||||
Assert.True(snapshot.IsUnchanged(CardSnapshot.Take(card, Volume.Identity)));
|
||||
Assert.False(snapshot.IsUnchanged(CardSnapshot.Take(card, "another card")), "another card with the same files is not the checked card");
|
||||
|
||||
// A video is not a photo: it never blocks formatting but is named as never imported.
|
||||
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "MVI_0031.MP4"), [1, 2, 3]);
|
||||
var withVideo = ready with { Card = CardSnapshot.Take(card, Volume.Identity) };
|
||||
Assert.True(withVideo.CanFormat);
|
||||
Assert.SequenceEqual(["DCIM/100CANON/MVI_0031.MP4"], withVideo.NotImported);
|
||||
Assert.Equal("30 verified on the card · " + Chronos.App.Infrastructure.Formatting.Bytes(ready.DeleteBytes) + " · 1 other file not imported", withVideo.EraseText);
|
||||
Assert.False(snapshot.IsUnchanged(withVideo.Card!), "a file added since the check changes the card");
|
||||
File.Delete(Path.Combine(card, "DCIM", "100CANON", "MVI_0031.MP4"));
|
||||
|
||||
// A photo added to the card after the import is not verified: formatting would lose it.
|
||||
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "IMG_0031.JPG"), Jpeg(Start.AddDays(2), 31));
|
||||
var withPhoto = ready with { Card = CardSnapshot.Take(card, Volume.Identity) };
|
||||
Assert.False(withPhoto.CanFormat);
|
||||
Assert.Equal(Loc.L("Import.Blocked.NotAllVerified"), withPhoto.FormatBlocker);
|
||||
Assert.True(withPhoto.CanDelete, "the verified photos may still be deleted");
|
||||
File.Delete(Path.Combine(card, "DCIM", "100CANON", "IMG_0031.JPG"));
|
||||
Assert.False((ready with { Outcome = outcome with { Verified = false } }).CanFormat);
|
||||
Assert.False((ready with { Destination = ImportDestinationKind.Folder }).CanDelete);
|
||||
Assert.False((ready with { IsInserted = false }).CanDelete);
|
||||
Assert.False((ready with { IsRemovable = false }).CanEject);
|
||||
|
||||
var result = CardEraser.Execute(erase, context.Cancellation);
|
||||
Assert.Equal(30, result.Deleted);
|
||||
Assert.Empty(Directory.EnumerateFiles(Path.Combine(card, "DCIM", "100CANON")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFolderImportCopiesWithoutAnIndexAndFindsItsOwnCopiesAgain()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start, Start.AddHours(2));
|
||||
var target = context.CreateTempDirectory("folder");
|
||||
var destination = new UnindexedDestination(ImportDestinationKind.Folder, target);
|
||||
var plan = await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
Assert.Equal(2, plan.Sessions.Count);
|
||||
Assert.Equal(16, plan.CopyCount);
|
||||
|
||||
var reports = new List<ImportProgress>();
|
||||
var outcome = await LocalImport.RunAsync(plan, new FolderImportSink(target), "EOS R5 · card A", verify: true, new Progress(reports), context.Cancellation);
|
||||
Assert.Equal(16, outcome.Copied);
|
||||
Assert.True(outcome.IsComplete);
|
||||
Assert.True(outcome.Verified);
|
||||
Assert.NotEmpty(reports);
|
||||
foreach (var (folder, name) in plan.Sessions.SelectMany(s => s.Items.Select(i => (s.Folder, i.FileName))))
|
||||
Assert.FileExists(Path.Combine(target, folder, name));
|
||||
|
||||
var again = await LocalImport.RunAsync(await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation),
|
||||
new FolderImportSink(target), "EOS R5 · card A", verify: true, null, context.Cancellation);
|
||||
Assert.Equal(0, again.Copied);
|
||||
Assert.Equal(16, again.Duplicates);
|
||||
Assert.False(new CardActions(ImportDestinationKind.Folder, false, true, true, outcome, null, null).CanCheck);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheIndexCheckReportsPlannedCopiesThatNeverArrivedWithTheJobsOwnError()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4), action: ImportAction.SkipImported),
|
||||
Item(4, Start.AddSeconds(6))));
|
||||
var errors = ImportOutcome.JobErrors("18:02:11 Not copied: DCIM/100CANON/IMG_0002.CR2 (Disk full)\n18:02:12 Imported 1, skipped 1, failed 1");
|
||||
var outcome = await ImportOutcome.CheckAsync(plan, true,
|
||||
(item, _) => Task.FromResult(item.SourcePath.EndsWith("0001.CR2", StringComparison.Ordinal) ? CommitCheck.Copied : CommitCheck.Missing), errors,
|
||||
context.Cancellation);
|
||||
Assert.Equal(1, outcome.Copied);
|
||||
Assert.Equal(1, outcome.Skipped);
|
||||
Assert.Equal(2, outcome.Failures.Count);
|
||||
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0002.CR2", "Disk full"), outcome.Failures[0]);
|
||||
Assert.Equal(Loc.L("Import.Result.NotCommitted"), outcome.Failures[1].Message, "no log line for it: not committed");
|
||||
Assert.False(outcome.IsComplete);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnAbortedRunCountsWhatTheDestinationCommittedAndFailsTheRest()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4)), Item(4, Start.AddSeconds(6),
|
||||
action: ImportAction.SkipImported)));
|
||||
var items = plan.Sessions[0].Items;
|
||||
var report = new ImportSinkReport();
|
||||
report.Committed[items[1].SourcePath] = new SinkCommit(Guid.NewGuid(), items[1].FileName, Duplicate: false);
|
||||
report.Rejected[items[0].SourcePath] = "Hash mismatch";
|
||||
var results = new[] { new ImportItemResult(plan.Sessions[0], items[0], ImportItemStatus.Copied, "a", new SinkCommit(null, items[0].FileName, false), null) };
|
||||
|
||||
var outcome = ImportOutcome.From(plan, results, verified: true, report, stopped: "Connection lost");
|
||||
Assert.Equal(1, outcome.Copied, "committed in the batch the abort interrupted");
|
||||
Assert.Equal(1, outcome.Skipped);
|
||||
Assert.SequenceEqual(
|
||||
[new ImportFailure(items[0].SourcePath, "Hash mismatch"), new ImportFailure(items[2].SourcePath, "Connection lost")],
|
||||
outcome.Failures);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARunTheServerStopsListsEveryPhotoLeftWithASentenceNotTheExceptionText()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null,
|
||||
context.Cancellation);
|
||||
|
||||
var outcome = await LocalImport.RunAsync(plan, new UnreachableSink(staging), "EOS R5 · card A", verify: true, null, context.Cancellation);
|
||||
Assert.Equal(0, outcome.Imported);
|
||||
Assert.Equal(8, outcome.Failures.Count);
|
||||
Assert.True(outcome.Failures.All(f => f.Message == Loc.L("Server.Error.Unreachable")), "the stop reason is the catalog's, never the exception's text");
|
||||
}
|
||||
|
||||
private async Task WaitDoneAsync(ChronosDatabase db, Guid jobId)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddSeconds(60);
|
||||
while (DateTime.UtcNow < until)
|
||||
{
|
||||
var job = await db.Jobs.GetAsync(jobId, context.Cancellation);
|
||||
if (job?.State == JobState.Done) return;
|
||||
if (job?.State is JobState.Failed or JobState.Cancelled) Assert.Fail($"Import job ended {job.State}: {job.Error}\n{job.LogTail}");
|
||||
await Task.Delay(25, context.Cancellation);
|
||||
}
|
||||
Assert.Fail("The import job did not finish");
|
||||
}
|
||||
|
||||
/// <summary>A server destination whose connection is gone: every commit fails as the HTTP stack reports it.</summary>
|
||||
private sealed class UnreachableSink(string staging) : IImportSink
|
||||
{
|
||||
public string StagingDirectory { get; } = staging;
|
||||
|
||||
public Task<IReadOnlyList<SinkCommit>> CommitAsync(PlannedSession session, IReadOnlyList<StagedFile> files, CancellationToken cancellationToken) =>
|
||||
throw new HttpRequestException("An error occurred while sending the request.");
|
||||
}
|
||||
|
||||
/// <summary>Collects reports synchronously (System.Progress posts to the thread pool).</summary>
|
||||
private sealed class Progress(List<ImportProgress> into) : IProgress<ImportProgress>
|
||||
{
|
||||
public void Report(ImportProgress value) => into.Add(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Globalization;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.App.Tests.Import.CardPoolTests;
|
||||
using static Chronos.App.Tests.Import.ImportPlansTests;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
/// <summary>
|
||||
/// Import texts in a right-to-left language. They switch the process-wide UI language, so the class is serial: in
|
||||
/// parallel it would race with the English assertions of the classes running beside it.
|
||||
/// </summary>
|
||||
[Serial]
|
||||
public sealed class ImportLanguageTests
|
||||
{
|
||||
public ImportLanguageTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
[Test]
|
||||
public void PathsAndSerialsStayLeftToRightInARightToLeftLanguage()
|
||||
{
|
||||
try
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
|
||||
var pool = CardPool.Build([Usb with { Label = string.Empty }, CardA], [], @"D:\Shoots\");
|
||||
Assert.Equal("\u202AG:\\\u202C", pool[1].Title, "a drive root keeps its separator at its end");
|
||||
Assert.Equal("\u202AD:\\Shoots\\\u202C", pool[2].Title);
|
||||
Assert.Equal("\u202AD:\\Shoots\\\u202C", pool[2].Subtitle);
|
||||
Assert.Contains("\u202A3F2A-9C11\u202C", pool[0].IdentityText);
|
||||
Assert.Equal("EOS_DIGITAL", pool[0].Title, "a label is left to bidi");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARightToLeftLanguageReadsTheSessionTimesWithItsOwnArrow()
|
||||
{
|
||||
var plan = ThreeSessions();
|
||||
Assert.Contains("→", ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>())[0].TimeText);
|
||||
try
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
|
||||
var time = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>())[0].TimeText;
|
||||
Assert.Contains("←", time);
|
||||
Assert.False(time.Contains('→'), "a right-to-left reader would see the arrow point back to the start");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using System.Globalization;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.App.Tests.Import.ImportTestData;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
public sealed class ImportPlansTests
|
||||
{
|
||||
public ImportPlansTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
internal static ImportPlan ThreeSessions(long? available = 200_000_000)
|
||||
{
|
||||
var duplicate = Guid.CreateVersion7();
|
||||
return Plan(available, [new ImportProblem("DCIM/100CANON/IMG_0099.CR2", "Access denied")],
|
||||
Session(1, "2026/2026-09-28 Canon EOS R5", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4)), Item(4, Start.AddSeconds(8))),
|
||||
Session(2, "2026/2026-09-29 Canon EOS R5", Item(5, Start.AddDays(1)), Item(6, Start.AddDays(1).AddSeconds(120), action: ImportAction.SkipInArchive, existing: duplicate)),
|
||||
Session(3, "2026/2026-09-30 Canon EOS R5", Item(7, Start.AddDays(2), action: ImportAction.SkipImported)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TotalsCountWhatIsCopiedSkippedAndDuplicated()
|
||||
{
|
||||
var totals = ImportPlans.Totals(ThreeSessions(), verify: true);
|
||||
Assert.Equal(3, totals.Sessions);
|
||||
Assert.Equal(7, totals.Photos);
|
||||
Assert.Equal(5, totals.CopyCount);
|
||||
Assert.Equal(5 * 24_000_000L, totals.CopyBytes);
|
||||
Assert.Equal(1, totals.Duplicates);
|
||||
Assert.Equal(1, totals.ImportedBefore);
|
||||
Assert.Equal(1, totals.Problems);
|
||||
Assert.Equal(80_000_000L, totals.FreeAfter);
|
||||
Assert.True(totals.HasEnoughSpace);
|
||||
Assert.Equal(TimeSpan.FromSeconds(3), totals.Estimate);
|
||||
Assert.Equal("3 sessions · 7 photos · 120 MB · about 3 s", totals.Text);
|
||||
Assert.Equal("3 sessions · 7 photos · 120 MB", totals.SummaryText);
|
||||
Assert.Equal("1 duplicate", totals.DuplicatesText);
|
||||
Assert.Equal("Import 5 photos", totals.ImportText);
|
||||
Assert.Equal("80 MB free after import", totals.SpaceText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASmallDestinationReportsTheMissingSpace()
|
||||
{
|
||||
var totals = ImportPlans.Totals(ThreeSessions(available: 100_000_000), verify: false);
|
||||
Assert.False(totals.HasEnoughSpace);
|
||||
Assert.Equal("20 MB missing", totals.SpaceText);
|
||||
Assert.Equal(string.Empty, ImportPlans.Totals(ThreeSessions(available: null), verify: false).SpaceText);
|
||||
Assert.Equal(TimeSpan.FromSeconds(2), ImportPlans.Totals(ThreeSessions(), verify: false).Estimate);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheDuplicateChoiceFlipsOnlyPhotosAlreadyInTheArchive()
|
||||
{
|
||||
var plan = ThreeSessions();
|
||||
var again = ImportPlans.WithDuplicates(plan, DuplicatePolicy.ImportAgain);
|
||||
Assert.Equal(6, again.CopyCount);
|
||||
var duplicate = again.Sessions[1].Items[1];
|
||||
Assert.Equal(ImportAction.Copy, duplicate.Action);
|
||||
Assert.NotNull(duplicate.ExistingFrameId);
|
||||
Assert.Equal(ImportAction.SkipImported, again.Sessions[2].Items[0].Action);
|
||||
|
||||
var skipped = ImportPlans.WithDuplicates(again, DuplicatePolicy.Skip);
|
||||
Assert.Equal(ImportAction.SkipInArchive, skipped.Sessions[1].Items[1].Action);
|
||||
Assert.Equal(plan.CopyCount, skipped.CopyCount);
|
||||
Assert.Equal("Import again", ImportPlans.Details(again, ImportDestinationKind.Archive, true).Rows.Single(r => r.Source.EndsWith("0006.CR2", StringComparison.Ordinal)).ActionText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TypedTitlesNameTheirSessions()
|
||||
{
|
||||
var plan = ThreeSessions();
|
||||
var titled = ImportPlans.WithTitles(plan, new Dictionary<string, string>
|
||||
{
|
||||
[plan.Sessions[0].SessionKey] = " Harbour sunset ",
|
||||
[plan.Sessions[1].SessionKey] = " ",
|
||||
["unknown"] = "ignored",
|
||||
});
|
||||
Assert.Equal("Harbour sunset", titled.Sessions[0].Title);
|
||||
Assert.Null(titled.Sessions[1].Title);
|
||||
Assert.Null(titled.Sessions[2].Title);
|
||||
Assert.SequenceEqual(plan.Items.Select(i => i.FileName), titled.Items.Select(i => i.FileName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SessionRowsShowTimesIntervalsAndWhereTheyGo()
|
||||
{
|
||||
var plan = ThreeSessions();
|
||||
var rows = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>(["2026/2026-09-29 Canon EOS R5"], StringComparer.OrdinalIgnoreCase));
|
||||
Assert.Equal(3, rows.Count);
|
||||
Assert.Equal("4 · 2 s", rows[0].FramesText);
|
||||
Assert.Equal("2 · 2 min", rows[1].FramesText);
|
||||
Assert.Equal("1", rows[2].FramesText);
|
||||
Assert.True(rows[0].IsNew);
|
||||
Assert.Equal("New · 2026/2026-09-28 Canon EOS R5", rows[0].TargetText);
|
||||
Assert.False(rows[1].IsNew);
|
||||
Assert.Equal("Adds to · 2026/2026-09-29 Canon EOS R5", rows[1].TargetText);
|
||||
Assert.Equal("2026-09-28 Canon EOS R5", rows[0].DefaultTitle);
|
||||
Assert.Equal("Canon EOS R5", rows[0].CameraText);
|
||||
Assert.Equal("96 MB", rows[0].SizeText);
|
||||
Assert.Contains("6:02", rows[0].TimeText);
|
||||
Assert.Equal("Server", ImportPlans.Sessions(plan, ImportDestinationKind.Server, new HashSet<string>())[0].TargetText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShowPlanListsEveryFileItsDestinationAndTheConflicts()
|
||||
{
|
||||
var plan = ThreeSessions(available: 100_000_000);
|
||||
var details = ImportPlans.Details(plan, ImportDestinationKind.Archive, verify: true);
|
||||
Assert.Equal(plan.FileCount + plan.Sessions.Count, details.Rows.Count);
|
||||
Assert.Equal(3, details.Rows.Count(r => r.Kind == PlanRowKind.Session));
|
||||
var first = details.Rows[1];
|
||||
Assert.Equal("DCIM/100CANON/IMG_0001.CR2", first.Source);
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5/originals/" + plan.Sessions[0].Items[0].FileName, first.Destination);
|
||||
Assert.Equal("Copy", first.ActionText);
|
||||
Assert.False(first.IsSkipped);
|
||||
Assert.True(details.Rows.Single(r => r.Source.EndsWith("0007.CR2", StringComparison.Ordinal)).IsSkipped);
|
||||
Assert.Equal(3, details.Conflicts.Count);
|
||||
Assert.Contains("IMG_0099.CR2", details.Conflicts[0]);
|
||||
Assert.Equal("7 files · copy 5 (120 MB) · 1 imported before · 1 duplicate", details.TotalsText);
|
||||
|
||||
var folder = ImportPlans.Details(plan, ImportDestinationKind.Folder, verify: true);
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, folder.Rows[1].Destination);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShowPlanShowsNamesUnderTheirSessionFolder()
|
||||
{
|
||||
var plan = ThreeSessions();
|
||||
var details = ImportPlans.Details(plan, ImportDestinationKind.Archive, verify: true);
|
||||
var session = details.Rows[0];
|
||||
Assert.True(session.SourceText.StartsWith("Session 1 · ", StringComparison.Ordinal), session.SourceText);
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5/originals", session.DestinationText);
|
||||
var file = details.Rows[2];
|
||||
Assert.Equal("IMG_0002.CR2", file.SourceText);
|
||||
Assert.Equal(plan.Sessions[0].Items[1].FileName, file.DestinationText);
|
||||
Assert.Equal("DCIM/100CANON/IMG_0002.CR2", file.Source, "the full path stays for the tooltip");
|
||||
Assert.Equal("Split at IMG_0002.CR2", file.SplitName);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheNamePreviewShowsTheFirstThreeCopiedFiles()
|
||||
{
|
||||
var plan = ThreeSessions();
|
||||
var names = ImportPlans.FirstDestinations(plan, ImportDestinationKind.Archive);
|
||||
Assert.Equal(3, names.Count);
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, names[0]);
|
||||
Assert.Equal("→ " + names[0] + " · " + plan.Sessions[0].Items[1].FileName + " · " + plan.Sessions[0].Items[2].FileName, ImportPlans.NamePreview(names));
|
||||
Assert.Equal(plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestinations(plan, ImportDestinationKind.Server)[0]);
|
||||
|
||||
// A name in another folder keeps its folder.
|
||||
var across = ImportPlans.FirstDestinations(plan, ImportDestinationKind.Archive, 5);
|
||||
Assert.Equal(5, across.Count);
|
||||
Assert.True(ImportPlans.NamePreview(across).EndsWith(" · " + across[4], StringComparison.Ordinal), "the third session's folder is shown");
|
||||
var nothing = ImportPlans.WithDuplicates(Plan(null, null, Session(1, "x", Item(1, Start, action: ImportAction.SkipImported))), DuplicatePolicy.Skip);
|
||||
Assert.Empty(ImportPlans.FirstDestinations(nothing, ImportDestinationKind.Archive));
|
||||
Assert.Equal(string.Empty, ImportPlans.NamePreview([]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASessionMergesOnlyIntoTheEarlierSessionOfTheSameCameraAndFormat()
|
||||
{
|
||||
var plan = ThreeSessions();
|
||||
var rows = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>());
|
||||
Assert.Null(rows[0].MergesInto);
|
||||
Assert.Equal(1, rows[1].MergesInto);
|
||||
Assert.Equal(2, rows[2].MergesInto);
|
||||
Assert.Equal("DCIM/100CANON/IMG_0005.CR2", rows[1].FirstPath);
|
||||
|
||||
var otherBody = plan with { Sessions = [plan.Sessions[0], plan.Sessions[1] with { CameraSerial = "9999" }, plan.Sessions[2]] };
|
||||
var split = ImportPlans.Sessions(otherBody, ImportDestinationKind.Archive, new HashSet<string>());
|
||||
Assert.Null(split[1].MergesInto, "another camera body never merges");
|
||||
Assert.Equal(1, split[2].MergesInto, "the earlier session of the same body, skipping the other camera");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShowPlanOffersASplitOnEveryPhotoButTheFirstOfItsSession()
|
||||
{
|
||||
var details = ImportPlans.Details(ThreeSessions(), ImportDestinationKind.Archive, verify: true);
|
||||
Assert.False(details.Rows[0].CanSplit, "a session heading");
|
||||
Assert.False(details.Rows[1].CanSplit, "the first photo already starts the session");
|
||||
Assert.True(details.Rows[2].CanSplit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Automation;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Sections;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Tests.Windows;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
/// <summary>
|
||||
/// Every Import state of <c>--capture</c> (<see cref="ImportScenes"/>) on the simulated cards, rendered in both themes
|
||||
/// in the real main window at the 1200 × 788 capture size, with the figures and gates each state must show — and the
|
||||
/// buttons really enabled, named for screen readers, nothing that matters cut off, and paths, numbers and times
|
||||
/// readable in a right-to-left language.
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(300_000)]
|
||||
public sealed class ImportScreenSmokeTests
|
||||
{
|
||||
[Test]
|
||||
public Task EveryImportStateRendersInBothThemes() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
var import = app.Shell.Import;
|
||||
|
||||
await ShowAsync(app, "inserted");
|
||||
await UseCaptureSizeAsync(app);
|
||||
Assert.NotEmpty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts), "the insertion toast");
|
||||
Assert.False(import.FolderPath.HasErrors, "the folder path is not checked while Archive is the destination");
|
||||
await app.ExpectAsync<ImportView>("import-inserted");
|
||||
|
||||
await ShowAsync(app, "plan");
|
||||
Assert.Equal(ImportPhase.Ready, import.Phase);
|
||||
Assert.Equal("EOS R5 · card A", import.SourceTitle);
|
||||
Assert.Equal(3, import.Sessions.Count, "night, dawn and sunset");
|
||||
Assert.Equal(50, import.Plan!.CopyCount);
|
||||
Assert.Equal("Harbour sunset", import.Plan.Sessions[^1].Title);
|
||||
Assert.Null(import.StartBlocker);
|
||||
Assert.Empty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts));
|
||||
await app.ExpectAsync<ImportView>("import-plan");
|
||||
Assert.True(ButtonFor(app, import.StartCommand).IsEnabled, "the Import button is enabled once the plan is ready");
|
||||
Assert.True(ButtonFor(app, import.Sessions[1].MergeCommand).IsEnabled, "a session can merge into the one before");
|
||||
Assert.False(Validation.GetHasError(Named<TextBox>(app, "FolderPathBox")), "the folder path is not checked while Archive is the destination");
|
||||
foreach (var session in import.Sessions)
|
||||
Assert.True(Fits(TextFor(app, session.Row.TimeText)), $"the session time '{session.Row.TimeText}' is cut at 1200 px");
|
||||
foreach (var item in DeviceItems(app))
|
||||
{
|
||||
Assert.NotNull(item.FocusVisualStyle, "a device shows keyboard focus");
|
||||
Assert.Equal(((ImportSource)item.DataContext).ToolTip, item.ToolTip as string);
|
||||
}
|
||||
AssertEveryButtonIsNamed(app);
|
||||
await AssertFourDigitsFitAsync(app, import);
|
||||
await AssertFolderPathIsCheckedOnlyForFolderAsync(app, import);
|
||||
|
||||
await ShowAsync(app, "showplan");
|
||||
Assert.True(import.IsDetailsOpen);
|
||||
Assert.Equal(50 + 3, import.Details!.Rows.Count);
|
||||
await app.ExpectAsync<ImportView>("import-showplan");
|
||||
var file = import.Details.Rows[2];
|
||||
Assert.True(Fits(TextFor(app, file.SourceText)), "a file's name on the card is shown whole");
|
||||
Assert.True(Fits(TextFor(app, file.DestinationText)), "a file's new name is shown whole");
|
||||
Assert.True(Fits(TextFor(app, import.Details.Rows[0].SourceText)), "a session heading is shown whole");
|
||||
Assert.Within(Left(app, TextFor(app, Loc.L("Import.Details.Column.Action"))), 0, Left(app, TextFor(app, file.ActionText)), 0, 2,
|
||||
"the Action header lines up with its cells");
|
||||
AssertEveryButtonIsNamed(app);
|
||||
|
||||
await ShowAsync(app, "running");
|
||||
Assert.True(import.IsRunning);
|
||||
Assert.False(import.IsFormEnabled);
|
||||
Assert.False(import.Sessions[0].IsEditable, "titles lock while copying");
|
||||
await app.ExpectAsync<ImportView>("import-running");
|
||||
Assert.True(ButtonFor(app, import.CancelCommand).IsEnabled, "Cancel is enabled while copying");
|
||||
foreach (var item in DeviceItems(app))
|
||||
{
|
||||
Assert.False(item.IsEnabled, "the source of a running import stays selected");
|
||||
Assert.Equal(Loc.L("Import.Blocked.Copying"), item.ToolTip as string);
|
||||
}
|
||||
Assert.Equal(0.4, TextFor(app, Loc.L("Import.Scan.Frames")).Opacity, "unit words dim with their field");
|
||||
var progress = Named<TextBlock>(app, "ProgressLine");
|
||||
Assert.Equal(AutomationLiveSetting.Polite, AutomationProperties.GetLiveSetting(progress));
|
||||
Assert.Same(progress, AutomationProperties.GetLabeledBy(app.FindAll<ProgressBar>().First(p => p.IsVisible && IsInImport(p))));
|
||||
|
||||
await ShowAsync(app, "failed");
|
||||
Assert.True(import.IsFailed);
|
||||
Assert.Equal("EOS R5 · card A is no longer available.", import.ErrorText);
|
||||
Assert.Contains(SampleCards.Card(app.Services.Environment.DataDirectory).Root, import.FailureToolTip);
|
||||
await app.ExpectAsync<ImportView>("import-failed");
|
||||
Assert.True(ButtonFor(app, import.RetryCommand).IsEnabled, "Retry is enabled after a failure");
|
||||
var failure = Named<TextBlock>(app, "FailureLine");
|
||||
Assert.Equal(AutomationLiveSetting.Assertive, AutomationProperties.GetLiveSetting(failure));
|
||||
Assert.True(Fits(failure), "the failure sentence is shown whole");
|
||||
Assert.Null(app.FindAll<Button>().FirstOrDefault(b => b.IsVisible && ReferenceEquals(b.Command, app.Shell.NavigateCommand) && IsInImport(b)),
|
||||
"an error offers one action");
|
||||
|
||||
await ShowAsync(app, "done");
|
||||
Assert.True(import.IsDone);
|
||||
var result = import.Result!;
|
||||
Assert.True(result.IsComplete);
|
||||
Assert.True(result.OffersDelete);
|
||||
Assert.True(result.Actions.CanDelete, "a verified import and its dry run allow deleting");
|
||||
Assert.Equal(49, result.Actions.DeleteCount);
|
||||
Assert.False(result.Actions.CanFormat, "a photo touched since the import keeps the card from being formatted");
|
||||
Assert.Empty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts));
|
||||
Assert.False(import.IsFormEnabled, "a finished import keeps its form until New import");
|
||||
Assert.False(import.TotalsText.Contains(Loc.L("Import.Plan.About", string.Empty).Trim(), StringComparison.Ordinal), "no estimate after the import");
|
||||
Assert.Equal(string.Empty, import.SpaceText);
|
||||
await app.ExpectAsync<ImportView>("import-done");
|
||||
Assert.True(ButtonFor(app, result.DeleteCommand).IsEnabled, "the Delete button follows the dry run");
|
||||
AssertEveryButtonIsNamed(app);
|
||||
|
||||
await ShowAsync(app, "newcard");
|
||||
Assert.True(import.IsNicknameOpen, "a new card asks for its nickname");
|
||||
Assert.Equal("SONY", import.SourceTitle);
|
||||
Assert.False(import.SelectedSource!.IsKnown, "a card without a nickname is still new, though its plan remembered it");
|
||||
Assert.NotEmpty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts));
|
||||
await app.ExpectAsync<ImportView>("import-newcard");
|
||||
AssertEveryButtonIsNamed(app);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task PathsNumbersAndTimesStayReadableRightToLeft() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
UiLanguage.Apply("ar");
|
||||
try
|
||||
{
|
||||
var import = app.Shell.Import;
|
||||
await ShowAsync(app, "plan");
|
||||
Assert.Equal(ImportPhase.Ready, import.Phase);
|
||||
Assert.Equal(FlowDirection.RightToLeft, WindowOf(app).FlowDirection);
|
||||
Assert.Equal(FlowDirection.LeftToRight, Named<TextBox>(app, "FolderPathBox").FlowDirection);
|
||||
Assert.Equal(FlowDirection.LeftToRight, Named<TextBox>(app, "GapBox").FlowDirection);
|
||||
foreach (var template in app.FindAll<TextBox>().Where(t => EditBehavior.GetField(t) is { } f && (f == import.FolderTemplate || f == import.FileTemplate)))
|
||||
Assert.Equal(FlowDirection.LeftToRight, template.FlowDirection, "name templates read left to right");
|
||||
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, import.NamePreview).FlowDirection, "the name preview reads left to right");
|
||||
// A size carries the language's unit, so it reads in the language's direction, whole, at the end of its cell.
|
||||
var size = TextFor(app, import.Sessions[0].Row.SizeText);
|
||||
Assert.Equal(FlowDirection.RightToLeft, size.FlowDirection);
|
||||
Assert.Equal(TextAlignment.Right, size.TextAlignment);
|
||||
var shown = size.ActualWidth + size.Margin.Left + size.Margin.Right;
|
||||
size.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
|
||||
Assert.True(shown >= size.DesiredSize.Width - 0.5, $"the size column fits the whole size ({shown:0.#} < {size.DesiredSize.Width:0.#})");
|
||||
Assert.Contains("←", import.Sessions[0].Row.TimeText);
|
||||
await app.ExpectAsync<ImportView>("import-plan-ar");
|
||||
|
||||
await ShowAsync(app, "showplan");
|
||||
var file = import.Details!.Rows[2];
|
||||
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, file.SourceText).FlowDirection);
|
||||
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, file.DestinationText).FlowDirection);
|
||||
await app.ExpectAsync<ImportView>("import-showplan-ar");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// An archive import whose job ends before the screen records its id (here cancelled inside the engine's own "queued"
|
||||
/// event, so the screen sees none of its events) still ends the screen's run instead of leaving it copying forever.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task AnImportJobThatEndsBeforeItIsRecordedStillEndsTheRun() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
var import = app.Shell.Import;
|
||||
await ShowAsync(app, "plan");
|
||||
var engine = Assert.NotNull(app.Services.Engine);
|
||||
void CancelAtOnce(Core.Model.Job job)
|
||||
{
|
||||
if (job is { Kind: Core.Model.JobKind.Import, State: Core.Model.JobState.Queued }) engine.CancelAsync(job.Id).GetAwaiter().GetResult();
|
||||
}
|
||||
engine.JobChanged += CancelAtOnce;
|
||||
try
|
||||
{
|
||||
Assert.True(import.StartCommand.CanExecute(null), "the plan can be imported");
|
||||
import.StartCommand.Execute(null);
|
||||
for (var i = 0; i < 300 && !import.IsFailed; i++) await Task.Delay(50);
|
||||
}
|
||||
finally
|
||||
{
|
||||
engine.JobChanged -= CancelAtOnce;
|
||||
}
|
||||
Assert.True(import.IsFailed, "the screen left Running though no event of the job reached it");
|
||||
Assert.Equal(Loc.L("Import.Status.Cancelled"), import.ErrorText);
|
||||
});
|
||||
|
||||
/// <summary>A result replaced by New import stops following the language: nothing keeps it, or its plan, alive.</summary>
|
||||
[Test]
|
||||
public Task AReplacedResultStopsFollowingTheLanguage() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
var import = app.Shell.Import;
|
||||
await ShowAsync(app, "done");
|
||||
var replaced = Assert.NotNull(import.Result);
|
||||
var refreshed = 0;
|
||||
replaced.PropertyChanged += (_, _) => refreshed++;
|
||||
import.NewImportCommand.Execute(null);
|
||||
Assert.Null(import.Result);
|
||||
try
|
||||
{
|
||||
UiLanguage.Apply("it");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
Assert.Equal(0, refreshed, "the replaced result was disposed");
|
||||
await import.WaitForPlanAsync();
|
||||
});
|
||||
|
||||
/// <summary>As <c>--capture</c> does: toasts of the previous state go, those of an insertion state stay.</summary>
|
||||
private static async Task ShowAsync(ScreenSmokeTests.SampleApp app, string state)
|
||||
{
|
||||
DismissToasts(app);
|
||||
await ImportScenes.ShowAsync(app.Shell, state);
|
||||
if (!ImportScenes.ShowsToast(state)) DismissToasts(app);
|
||||
await SettleAsync(app);
|
||||
}
|
||||
|
||||
private static void DismissToasts(ScreenSmokeTests.SampleApp app)
|
||||
{
|
||||
foreach (var host in app.FindAll<ToastHost>())
|
||||
{
|
||||
foreach (var toast in host.Toasts.ToList()) host.Dismiss(toast);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The size CI captures at (and the window's minimum width): nothing may be cut there.</summary>
|
||||
private static async Task UseCaptureSizeAsync(ScreenSmokeTests.SampleApp app)
|
||||
{
|
||||
var window = WindowOf(app);
|
||||
window.Width = 1200;
|
||||
window.Height = 788;
|
||||
await SettleAsync(app);
|
||||
}
|
||||
|
||||
private static async Task SettleAsync(ScreenSmokeTests.SampleApp app)
|
||||
{
|
||||
var window = WindowOf(app);
|
||||
window.UpdateLayout();
|
||||
await window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
|
||||
window.UpdateLayout();
|
||||
}
|
||||
|
||||
private static async Task WaitUntilAsync(ScreenSmokeTests.SampleApp app, Func<bool> condition, string what)
|
||||
{
|
||||
for (var i = 0; i < 200 && !condition(); i++) await Task.Delay(25);
|
||||
Assert.True(condition(), what);
|
||||
await SettleAsync(app);
|
||||
}
|
||||
|
||||
/// <summary>The empty folder path is fine for the archive; choosing Folder makes it invalid and offers "Choose folder".</summary>
|
||||
private static async Task AssertFolderPathIsCheckedOnlyForFolderAsync(ScreenSmokeTests.SampleApp app, ImportViewModel import)
|
||||
{
|
||||
var box = Named<TextBox>(app, "FolderPathBox");
|
||||
import.IsFolderDestination = true;
|
||||
await WaitUntilAsync(app, () => import.Phase == ImportPhase.NoSource, "the plan stops without a folder");
|
||||
Assert.True(Validation.GetHasError(box), "an empty path is an error once Folder is chosen");
|
||||
Assert.True(import.HasStatusAction);
|
||||
Assert.Equal(Loc.L("Import.Destination.Choose"), import.StatusActionText);
|
||||
Assert.True(Named<Button>(app, "StatusActionButton").IsVisible, "the status sentence comes with its action");
|
||||
import.IsArchiveDestination = true;
|
||||
await WaitUntilAsync(app, () => import.Phase == ImportPhase.Ready, "the archive plan is back");
|
||||
Assert.False(Validation.GetHasError(box));
|
||||
Assert.Equal("Harbour sunset", import.Plan!.Sessions[^1].Title, "typed titles survive the round trip");
|
||||
}
|
||||
|
||||
/// <summary>The 56 px gap box shows its largest value, 1440, whole.</summary>
|
||||
private static async Task AssertFourDigitsFitAsync(ScreenSmokeTests.SampleApp app, ImportViewModel import)
|
||||
{
|
||||
import.GapMinutes.Text = "1440";
|
||||
await SettleAsync(app);
|
||||
var host = Descendants(Named<TextBox>(app, "GapBox")).OfType<ScrollViewer>().First();
|
||||
Assert.LessOrEqual(host.ExtentWidth, host.ViewportWidth + 1, "1440 fits the gap box");
|
||||
import.GapMinutes.Revert();
|
||||
}
|
||||
|
||||
/// <summary>Every button, check box and radio button of the screen has a name screen readers can announce.</summary>
|
||||
private static void AssertEveryButtonIsNamed(ScreenSmokeTests.SampleApp app)
|
||||
{
|
||||
foreach (var button in app.FindAll<ButtonBase>().Where(b => b.IsVisible && b.Focusable && IsInImport(b)))
|
||||
{
|
||||
var name = AutomationProperties.GetName(button);
|
||||
if (string.IsNullOrEmpty(name)) name = button.Content as string;
|
||||
Assert.False(string.IsNullOrWhiteSpace(name), $"{button.GetType().Name} '{button.Name}' bound to {button.Command} has no accessible name");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Beside the 200 px rail at the 1200 px minimum (owner review 1, R1), in every shipped language: the session rows' Merge and the
|
||||
/// plan rows' Split stay inside their rows (shown or not yet revealed), and the result line inside its card.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task RowButtonsAndTheResultFitAtTheMinimumWidthInEveryLanguage() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
foreach (var (state, list) in new[] { ("plan", "SessionRows"), ("showplan", "PlanRows") })
|
||||
{
|
||||
await ShowAsync(app, state);
|
||||
await UseCaptureSizeAsync(app);
|
||||
await InEveryLanguageAsync(app, language =>
|
||||
{
|
||||
var rows = Named<ListBox>(app, list);
|
||||
var viewport = Descendants(rows).OfType<ScrollContentPresenter>().First();
|
||||
var (left, right) = Span(viewport, WindowOf(app));
|
||||
foreach (var button in Descendants(rows).OfType<Button>().Where(b => b.Visibility != Visibility.Collapsed && b.ActualWidth > 0))
|
||||
{
|
||||
var (start, end) = Span(button, WindowOf(app));
|
||||
Assert.True(start >= left - 0.5 && end <= right + 0.5, $"{language} {state}: '{button.Content}' spans {start:0}–{end:0} px, its rows {left:0}–{right:0} px");
|
||||
}
|
||||
});
|
||||
}
|
||||
await ShowAsync(app, "done");
|
||||
await UseCaptureSizeAsync(app);
|
||||
await InEveryLanguageAsync(app, language =>
|
||||
{
|
||||
var result = app.FindAll<StatusGlyph>().First(g => g.IsVisible && g.DataContext is ImportResultViewModel && IsInImport(g));
|
||||
var line = (FrameworkElement)VisualTreeHelper.GetParent(result);
|
||||
var card = (FrameworkElement)VisualTreeHelper.GetParent(line);
|
||||
var (left, right) = Span(card, WindowOf(app));
|
||||
foreach (var text in Descendants(line).OfType<TextBlock>().Where(t => t.IsVisible))
|
||||
{
|
||||
var (start, end) = Span(text, WindowOf(app));
|
||||
Assert.True(start >= left - 0.5 && end <= right + 0.5, $"{language}: '{text.Text}' spans {start:0}–{end:0} px, its card {left:0}–{right:0} px");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
private static async Task InEveryLanguageAsync(ScreenSmokeTests.SampleApp app, Action<string> check)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var language in Languages.Shipped)
|
||||
{
|
||||
UiLanguage.Apply(language);
|
||||
await SettleAsync(app);
|
||||
check(language);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The left and right edges of an element in window coordinates, whichever way the window reads.</summary>
|
||||
private static (double Left, double Right) Span(FrameworkElement element, Window window)
|
||||
{
|
||||
var a = element.TranslatePoint(new Point(0, 0), window).X;
|
||||
var b = element.TranslatePoint(new Point(element.ActualWidth, 0), window).X;
|
||||
return (Math.Min(a, b), Math.Max(a, b));
|
||||
}
|
||||
|
||||
private static Window WindowOf(ScreenSmokeTests.SampleApp app) => Window.GetWindow(app.FindAll<FrameworkElement>().First())!;
|
||||
|
||||
private static ImportView View(ScreenSmokeTests.SampleApp app) => app.FindAll<ImportView>().First(v => v.IsVisible);
|
||||
|
||||
private static bool IsInImport(DependencyObject element) => FindAncestor<ImportView>(element) is not null;
|
||||
|
||||
private static T? FindAncestor<T>(DependencyObject element)
|
||||
where T : DependencyObject
|
||||
{
|
||||
for (var node = VisualTreeHelper.GetParent(element); node is not null; node = VisualTreeHelper.GetParent(node))
|
||||
{
|
||||
if (node is T match) return match;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static IEnumerable<DependencyObject> Descendants(DependencyObject root)
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(root, i);
|
||||
yield return child;
|
||||
foreach (var below in Descendants(child)) yield return below;
|
||||
}
|
||||
}
|
||||
|
||||
private static T Named<T>(ScreenSmokeTests.SampleApp app, string name)
|
||||
where T : FrameworkElement =>
|
||||
Assert.NotNull(app.FindAll<T>().FirstOrDefault(e => e.Name == name), $"{typeof(T).Name} {name}");
|
||||
|
||||
private static TextBlock TextFor(ScreenSmokeTests.SampleApp app, string text) =>
|
||||
Assert.NotNull(app.FindAll<TextBlock>().FirstOrDefault(t => t.IsVisible && t.Text == text && IsInImport(t)), $"a visible text '{text}'");
|
||||
|
||||
private static IEnumerable<ListBoxItem> DeviceItems(ScreenSmokeTests.SampleApp app) =>
|
||||
app.FindAll<ListBoxItem>().Where(i => i.IsVisible && i.DataContext is ImportSource);
|
||||
|
||||
/// <summary>
|
||||
/// The text is shown whole: a copy with the same font, numerals and padding, measured by the same layout engine,
|
||||
/// needs no more room than the layout gave the shown one (a formatted-text estimate differs by a few pixels).
|
||||
/// </summary>
|
||||
private static bool Fits(TextBlock text)
|
||||
{
|
||||
var probe = new TextBlock
|
||||
{
|
||||
Text = text.Text,
|
||||
FontFamily = text.FontFamily,
|
||||
FontSize = text.FontSize,
|
||||
FontStyle = text.FontStyle,
|
||||
FontWeight = text.FontWeight,
|
||||
FontStretch = text.FontStretch,
|
||||
FlowDirection = text.FlowDirection,
|
||||
Language = text.Language,
|
||||
Padding = text.Padding,
|
||||
TextWrapping = text.TextWrapping,
|
||||
};
|
||||
System.Windows.Documents.Typography.SetNumeralAlignment(probe, System.Windows.Documents.Typography.GetNumeralAlignment(text));
|
||||
TextOptions.SetTextFormattingMode(probe, TextOptions.GetTextFormattingMode(text));
|
||||
if (text.TextWrapping != TextWrapping.NoWrap)
|
||||
{
|
||||
probe.Measure(new Size(text.ActualWidth, double.PositiveInfinity));
|
||||
return probe.DesiredSize.Height <= text.ActualHeight + 0.5;
|
||||
}
|
||||
probe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
|
||||
return probe.DesiredSize.Width <= text.ActualWidth + 1;
|
||||
}
|
||||
|
||||
private static double Left(ScreenSmokeTests.SampleApp app, FrameworkElement element) => element.TranslatePoint(new Point(0, 0), View(app)).X;
|
||||
|
||||
private static Button ButtonFor(ScreenSmokeTests.SampleApp app, ICommand command) =>
|
||||
Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => ReferenceEquals(b.Command, command) && b.IsVisible), "a visible button bound to the command");
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.IO;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Metadata;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
/// <summary>Synthetic cards (small JPEGs with Exif) and hand-made plans for the Import tests.</summary>
|
||||
internal static class ImportTestData
|
||||
{
|
||||
public static readonly DateTime Start = new(2026, 9, 28, 18, 2, 11);
|
||||
|
||||
/// <summary>A real JPEG with Exif make, model, body serial and capture time; each seed gives distinct bytes.</summary>
|
||||
public static byte[] Jpeg(DateTime captured, int seed)
|
||||
{
|
||||
using var image = new ImageBuffer(32, 24);
|
||||
var random = new Random(seed);
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
var plane = image.Plane(c);
|
||||
var level = (float)random.NextDouble();
|
||||
for (var i = 0; i < plane.Length; i++) plane[i] = level * (0.5f + 0.5f * (i % 32) / 32f);
|
||||
}
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = "Canon", Model = "Canon EOS R5", BodySerial = "0431", CapturedAt = captured, Iso = 100 });
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
/// <summary>A card folder with <c>DCIM/100CANON</c>: one series per start time, <paramref name="perSession"/> photos 2 s apart.</summary>
|
||||
public static string Card(string root, int perSession, params DateTime[] starts)
|
||||
{
|
||||
var folder = Path.Combine(root, "DCIM", "100CANON");
|
||||
Directory.CreateDirectory(folder);
|
||||
var n = 1;
|
||||
foreach (var start in starts)
|
||||
{
|
||||
for (var i = 0; i < perSession; i++, n++)
|
||||
File.WriteAllBytes(Path.Combine(folder, $"IMG_{n:0000}.JPG"), Jpeg(start.AddSeconds(2 * i), n));
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
public static PlannedItem Item(int n, DateTime captured, long size = 24_000_000, ImportAction action = ImportAction.Copy, Guid? existing = null) => new()
|
||||
{
|
||||
SourcePath = $"DCIM/100CANON/IMG_{n:0000}.CR2",
|
||||
Size = size,
|
||||
ModifiedUtc = captured,
|
||||
CapturedAt = captured,
|
||||
FileName = $"{captured:yyyy-MM-dd_HH-mm-ss}_{n:0000}.CR2",
|
||||
Action = action,
|
||||
ExistingFrameId = existing,
|
||||
};
|
||||
|
||||
public static PlannedSession Session(int number, string folder, params PlannedItem[] items) => new()
|
||||
{
|
||||
Number = number,
|
||||
SessionKey = $"card-0000000{number}-key",
|
||||
CameraMake = "Canon",
|
||||
CameraModel = "Canon EOS R5",
|
||||
Format = ImageFileFormat.Cr2,
|
||||
Start = items[0].CapturedAt,
|
||||
End = items[^1].CapturedAt,
|
||||
Folder = folder,
|
||||
Items = items,
|
||||
};
|
||||
|
||||
public static ImportPlan Plan(long? available, IReadOnlyList<ImportProblem>? problems = null, params PlannedSession[] sessions) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SourceRoot = "/card",
|
||||
DestinationRoot = "/archive",
|
||||
Sessions = sessions,
|
||||
Problems = problems ?? [],
|
||||
AvailableBytes = available,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
/// <summary>The simulated card behind the Import captures plans like a real one and gates the after-import actions.</summary>
|
||||
[Category("import")]
|
||||
public sealed class SampleCardsTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheSampleCardPlansThreeSessionsAndAllowsOnlyAVerifiedDelete()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
|
||||
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test" });
|
||||
var archive = await archives.AdoptAsync(context.CreateTempDirectory("archive"), "Main", context.Cancellation);
|
||||
var devices = new SampleDeviceMonitor();
|
||||
await SampleCards.InsertAsync(db, devices, context.CreateTempDirectory("data"));
|
||||
|
||||
var contents = devices.Devices.Where(d => d.HasDcim).ToDictionary(d => d.Identity, d => CardContents.Read(d.Root));
|
||||
var pool = CardPool.Build(devices.Devices, await db.MediaCards.ListAsync(context.Cancellation), null, contents);
|
||||
Assert.SequenceEqual(new[] { SourceKind.Card, SourceKind.Card, SourceKind.Drive, SourceKind.Card }, pool.Select(s => s.Kind));
|
||||
Assert.Equal("EOS R5 · card A", pool[0].Title);
|
||||
Assert.Equal("128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[0].IdentityText);
|
||||
Assert.Equal("Canon EOS R5 · 50 photos", pool[0].ToastText);
|
||||
Assert.Contains("50 photos", pool[0].Subtitle);
|
||||
Assert.Equal("SONY", pool[1].Title);
|
||||
Assert.False(pool[1].IsKnown);
|
||||
Assert.Equal("12 photos · not yet known to Chronos", pool[1].ToastText[(pool[1].ToastText.IndexOf(" · ", StringComparison.Ordinal) + 3)..],
|
||||
"the camera of its first photo, its photos, and that it is new");
|
||||
Assert.Equal("GoPro 12", pool[3].Title);
|
||||
Assert.False(pool[3].IsInserted);
|
||||
var card = pool[0].Card!;
|
||||
Assert.Equal(new DateTimeOffset(2026, 9, 21, 19, 40, 0, TimeSpan.Zero), (await db.MediaCards.ListImportsAsync(card.Id, 1, context.Cancellation))[0].ImportedAt);
|
||||
|
||||
var plan = await new ArchiveDestination(archives, archive).PlanAsync(pool[0].Root!, new ImportChoices().ToOptions(), card.Id, null, context.Cancellation);
|
||||
Assert.Equal(3, plan.Sessions.Count);
|
||||
Assert.SequenceEqual(new[] { 10, 16, 24 }, plan.Sessions.Select(s => s.Items.Count));
|
||||
Assert.Equal(50, plan.CopyCount);
|
||||
Assert.Equal("Canon EOS R5", plan.Sessions[0].CameraModel);
|
||||
|
||||
var outcome = SampleCards.Outcome(plan);
|
||||
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, null);
|
||||
Assert.False(before.CanDelete, "no dry run yet");
|
||||
var actions = before with { Erase = SampleCards.Erase(plan), Card = CardSnapshot.Take(pool[0].Root!, pool[0].Key) };
|
||||
Assert.True(actions.CanDelete);
|
||||
Assert.Equal(49, actions.DeleteCount);
|
||||
Assert.Equal(1, actions.KeptCount);
|
||||
Assert.False(actions.CanFormat, "a kept photo would be lost by formatting");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.App.Tests.Import.ImportTestData;
|
||||
|
||||
namespace Chronos.App.Tests.Import;
|
||||
|
||||
/// <summary>The "Server" destination over the real protocol client against an in-memory upload endpoint.</summary>
|
||||
[Category("import")]
|
||||
public sealed class ServerImportSinkTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task EveryPhotoIsUploadedInChunksUnderItsCardNameAndVerifiedByHash()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start, Start.AddHours(2));
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 256);
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
plan = plan with { Sessions = [plan.Sessions[0] with { Title = "Harbour sunset" }, .. plan.Sessions.Skip(1)] };
|
||||
|
||||
var outcome = await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), "EOS R5 · card A", verify: true, null, context.Cancellation);
|
||||
|
||||
Assert.Equal(16, outcome.Copied);
|
||||
Assert.True(outcome.IsComplete);
|
||||
Assert.Equal(16, server.Committed.Count);
|
||||
foreach (var item in plan.Items)
|
||||
{
|
||||
var bytes = File.ReadAllBytes(Path.Combine(card, item.SourcePath));
|
||||
var upload = server.Committed.Single(u => u.FileName == Path.GetFileName(item.SourcePath));
|
||||
Assert.BytesEqual(bytes, upload.Bytes);
|
||||
Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(bytes)), upload.Sha256);
|
||||
Assert.True(upload.Chunks > 1, "files larger than a chunk travel in several chunks");
|
||||
}
|
||||
Assert.SequenceEqual(plan.Sessions.Select(s => s.SessionKey).Order(StringComparer.Ordinal),
|
||||
server.Committed.Select(u => u.SessionKey).Distinct().Order(StringComparer.Ordinal));
|
||||
Assert.Equal("Harbour sunset", server.Titles.Single().Value);
|
||||
Assert.Empty(Directory.EnumerateFileSystemEntries(staging));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PhotosTheServerAlreadyHoldsAreNotSentAgain()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 4096);
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var destination = new UnindexedDestination(ImportDestinationKind.Server, staging);
|
||||
var plan = await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), "EOS R5 · card A", verify: true, null, context.Cancellation);
|
||||
var chunks = server.ChunkCount;
|
||||
|
||||
var again = await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), "EOS R5 · card A", verify: true, null, context.Cancellation);
|
||||
Assert.Equal(0, again.Copied);
|
||||
Assert.Equal(8, again.Duplicates);
|
||||
Assert.Equal(chunks, server.ChunkCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFileTheServerRefusesIsListedAndTheImportGoesOn()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 4096) { CorruptFile = "IMG_0003.JPG" };
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
var sink = new ServerImportSink(client, staging);
|
||||
|
||||
var outcome = await LocalImport.RunAsync(plan, sink, "EOS R5 · card A", true, null, context.Cancellation, sink.Report);
|
||||
Assert.Equal(7, outcome.Copied);
|
||||
Assert.Equal(7, server.Committed.Count);
|
||||
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0003.JPG", "Hash mismatch"), outcome.Failures.Single());
|
||||
Assert.Empty(Directory.EnumerateFileSystemEntries(staging));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFileAProxyRefusesIsListedWithTheCatalogsSentence()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 4096) { ProxyRefusesFile = "IMG_0005.JPG" };
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
var sink = new ServerImportSink(client, staging);
|
||||
|
||||
var outcome = await LocalImport.RunAsync(plan, sink, "EOS R5 · card A", true, null, context.Cancellation, sink.Report);
|
||||
Assert.Equal(7, outcome.Copied);
|
||||
// The proxy's page says "Request Entity Too Large" in English: the photo reads the catalog's sentence instead.
|
||||
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0005.JPG", Chronos.Core.Localization.Loc.L("Server.Error.TooLarge")), outcome.Failures.Single());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALostSignInStopsTheImportAndKeepsWhatWasUploaded()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 4096) { SignedOutAfter = 3 };
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
var sink = new ServerImportSink(client, staging);
|
||||
|
||||
var outcome = await LocalImport.RunAsync(plan, sink, "EOS R5 · card A", true, null, context.Cancellation, sink.Report);
|
||||
Assert.Equal(3, outcome.Copied, "the uploads the server committed before the sign-in was lost");
|
||||
Assert.Equal(5, outcome.Failures.Count);
|
||||
Assert.Equal("Sign in again", outcome.Failures[0].Message, "the server's sentence");
|
||||
Assert.False(outcome.IsComplete);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheQuotaIsTheRoomOfAServerImport()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging) { ServerSpace = 1_000 }
|
||||
.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
Assert.Equal(1_000L, plan.AvailableBytes);
|
||||
Assert.False(ImportPlans.Totals(plan, verify: true).HasEnoughSpace, "eight photos do not fit in 1 KB of quota");
|
||||
|
||||
var unlimited = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null,
|
||||
context.Cancellation);
|
||||
Assert.Null(unlimited.AvailableBytes);
|
||||
Assert.True(ImportPlans.Totals(unlimited, verify: true).HasEnoughSpace);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnImportIntoTheServerIsReportedAsCardEventsFromStartToFinish()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 4096);
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
var progress = new List<ImportProgress>();
|
||||
|
||||
var outcome = await new ServerImportSink(client, staging).RunAsync(plan, "EOS R5 · card A", true, new SyncProgress<ImportProgress>(progress.Add),
|
||||
context.Cancellation);
|
||||
|
||||
Assert.True(outcome.IsComplete);
|
||||
Assert.NotEmpty(progress);
|
||||
var reports = server.Cards.ToList();
|
||||
Assert.Equal(CardImportStates.Started, reports[0].State);
|
||||
Assert.Equal((CardImportStates.Finished, plan.FileCount, plan.FileCount, 0), (reports[^1].State, reports[^1].Done, reports[^1].Total, reports[^1].Failed));
|
||||
Assert.True(reports.All(r => r.ImportId == plan.Id && r.Card == "EOS R5 · card A"), "every report names the import");
|
||||
Assert.True(reports.Skip(1).SkipLast(1).All(r => r.State == CardImportStates.Progress), "progress in between");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerWithoutCardEventsStillTakesTheImport()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 4096) { CardsUnsupported = true };
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
|
||||
|
||||
var outcome = await new ServerImportSink(client, staging).RunAsync(plan, "EOS R5 · card A", true, null, context.Cancellation);
|
||||
|
||||
Assert.Equal(8, outcome.Copied);
|
||||
Assert.Equal(1, server.CardAttempts, "a server that answers 404 gets no further reports");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReportsWaitingForASlowServerAreReplacedByNewerOnes()
|
||||
{
|
||||
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var server = new FakeUploadServer(chunkSize: 4096) { CardGate = gate.Task };
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var time = new ManualTime();
|
||||
var reporter = new CardImportReporter(client, Guid.CreateVersion7(), "EOS R5 · card A", 100, time);
|
||||
|
||||
reporter.Started();
|
||||
await server.CardArrived.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
reporter.Report(Progress(10));
|
||||
reporter.Report(Progress(20));
|
||||
time.Advance(TimeSpan.FromSeconds(1));
|
||||
reporter.Report(Progress(30));
|
||||
var finished = reporter.FinishedAsync(null);
|
||||
gate.SetResult();
|
||||
await finished.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
|
||||
// The start was on its way; progress 10 waited and was replaced by 30 (20 came within the second), then by the end.
|
||||
Assert.SequenceEqual([(CardImportStates.Started, 0), (CardImportStates.Finished, 30)], server.Cards.Select(r => (r.State, r.Done)));
|
||||
// Nothing follows the end, not even progress a second later.
|
||||
time.Advance(TimeSpan.FromSeconds(1));
|
||||
reporter.Report(Progress(40));
|
||||
await reporter.FinishedAsync(null).WaitAsync(TimeSpan.FromSeconds(10));
|
||||
Assert.Equal(2, server.CardAttempts);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnImportOverDoesNotWaitForAServerThatDoesNotAnswer()
|
||||
{
|
||||
var server = new FakeUploadServer(chunkSize: 4096) { CardGate = new TaskCompletionSource().Task };
|
||||
using var client = new ChronosClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
|
||||
var reporter = new CardImportReporter(client, Guid.CreateVersion7(), "EOS R5 · card A", 100);
|
||||
|
||||
reporter.Started();
|
||||
await server.CardArrived.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
await reporter.FinishedAsync(null).WaitAsync(TimeSpan.FromSeconds(8));
|
||||
|
||||
// The start hangs (each report would wait 10 s): the end gives both up after two seconds.
|
||||
Assert.True(clock.Elapsed < TimeSpan.FromSeconds(6), $"finished after {clock.Elapsed}");
|
||||
Assert.Empty(server.Cards);
|
||||
for (var i = 0; i < 25 && server.CardAttempts < 2; i++) await Task.Delay(20);
|
||||
Assert.Equal(1, server.CardAttempts, "the end was never sent once given up");
|
||||
}
|
||||
|
||||
private static ImportProgress Progress(int done) => new(done, 100, done * 10L, 1000, done, 0, 0, null);
|
||||
|
||||
/// <summary>Reports synchronously (Progress<T> posts and may arrive late).</summary>
|
||||
private sealed class SyncProgress<T>(Action<T> report) : IProgress<T>
|
||||
{
|
||||
public void Report(T value) => report(value);
|
||||
}
|
||||
|
||||
private sealed class ManualTime : TimeProvider
|
||||
{
|
||||
private long _ticks;
|
||||
|
||||
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
|
||||
|
||||
public override long GetTimestamp() => Interlocked.Read(ref _ticks);
|
||||
|
||||
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
|
||||
}
|
||||
|
||||
/// <summary>Start, chunk and complete of BRIEF §14.4, plus the title update and card reports; the hash is checked at completion.</summary>
|
||||
private sealed class FakeUploadServer(int chunkSize) : HttpMessageHandler
|
||||
{
|
||||
private readonly Dictionary<Guid, Upload> _open = [];
|
||||
private readonly Dictionary<string, Guid> _sequences = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, Guid> _frames = new(StringComparer.Ordinal);
|
||||
|
||||
public List<Upload> Committed { get; } = [];
|
||||
public Dictionary<Guid, string> Titles { get; } = [];
|
||||
public int ChunkCount { get; private set; }
|
||||
|
||||
/// <summary>Flip a byte of every chunk of this file (a damaged transfer).</summary>
|
||||
public string? CorruptFile { get; init; }
|
||||
|
||||
/// <summary>A reverse proxy in front of the server refuses the chunks of this file: 413 with its own HTML page.</summary>
|
||||
public string? ProxyRefusesFile { get; init; }
|
||||
|
||||
/// <summary>Answer 401 to new uploads once this many were committed (the sign-in expired).</summary>
|
||||
public int? SignedOutAfter { get; init; }
|
||||
|
||||
/// <summary>Card reports taken, in order (they arrive on another thread than the uploads).</summary>
|
||||
public ConcurrentQueue<CardImportReport> Cards { get; } = new();
|
||||
|
||||
public int CardAttempts => _cardAttempts;
|
||||
|
||||
/// <summary>A server from before card events: 404.</summary>
|
||||
public bool CardsUnsupported { get; init; }
|
||||
|
||||
/// <summary>Card reports wait for this (a slow server); <see cref="CardArrived"/> says when the first one is waiting.</summary>
|
||||
public Task? CardGate { get; init; }
|
||||
|
||||
public TaskCompletionSource CardArrived { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
private int _cardAttempts;
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
|
||||
if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads", "cards"])
|
||||
{
|
||||
Interlocked.Increment(ref _cardAttempts);
|
||||
if (CardsUnsupported) return new HttpResponseMessage(HttpStatusCode.NotFound);
|
||||
var report = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.CardImportReport, cancellationToken))!;
|
||||
CardArrived.TrySetResult();
|
||||
if (CardGate is { } gate) await gate.WaitAsync(cancellationToken);
|
||||
Cards.Enqueue(report);
|
||||
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
||||
}
|
||||
if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads"])
|
||||
{
|
||||
var start = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.StartUploadRequest, cancellationToken))!;
|
||||
if (Committed.Count >= SignedOutAfter)
|
||||
return Json(new ApiError("unauthorized", "Sign in again"), ProtocolJson.Default.ApiError, HttpStatusCode.Unauthorized);
|
||||
if (_frames.TryGetValue(start.Sha256, out var existing))
|
||||
return Json(new StartUploadResponse(null, chunkSize, [], true, existing), ProtocolJson.Default.StartUploadResponse);
|
||||
var upload = new Upload(Guid.NewGuid(), start.FileName, start.Size, start.Sha256, start.SessionKey ?? "user");
|
||||
_open[upload.Id] = upload;
|
||||
return Json(new StartUploadResponse(upload.Id, chunkSize, [], false, null), ProtocolJson.Default.StartUploadResponse);
|
||||
}
|
||||
if (request.Method == HttpMethod.Put && path is ["api", "v1", "uploads", var id, "chunks", var n])
|
||||
{
|
||||
var upload = _open[Guid.Parse(id)];
|
||||
if (upload.FileName == ProxyRefusesFile)
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.RequestEntityTooLarge)
|
||||
{
|
||||
Content = new StringContent("<html><body><h1>413 Request Entity Too Large</h1></body></html>", System.Text.Encoding.UTF8, "text/html"),
|
||||
};
|
||||
}
|
||||
var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
|
||||
if (upload.FileName == CorruptFile) bytes[0] ^= 0xFF;
|
||||
upload.Parts[int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)] = bytes;
|
||||
ChunkCount++;
|
||||
return Json(new ChunkReceived(int.Parse(n, System.Globalization.CultureInfo.InvariantCulture), [.. upload.Parts.Keys]), ProtocolJson.Default.ChunkReceived);
|
||||
}
|
||||
if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads", var done, "complete"])
|
||||
{
|
||||
var upload = _open[Guid.Parse(done)];
|
||||
if (Convert.ToHexStringLower(SHA256.HashData(upload.Bytes)) != upload.Sha256)
|
||||
return Json(new ApiError("hash_mismatch", "Hash mismatch"), ProtocolJson.Default.ApiError, HttpStatusCode.UnprocessableEntity);
|
||||
_open.Remove(upload.Id);
|
||||
Committed.Add(upload);
|
||||
var frame = Guid.NewGuid();
|
||||
_frames[upload.Sha256] = frame;
|
||||
if (!_sequences.TryGetValue(upload.SessionKey, out var sequence)) _sequences[upload.SessionKey] = sequence = Guid.NewGuid();
|
||||
return Json(new CompleteUploadResponse(frame, sequence, Committed.Count(u => u.SessionKey == upload.SessionKey) - 1),
|
||||
ProtocolJson.Default.CompleteUploadResponse);
|
||||
}
|
||||
if (request.Method == HttpMethod.Patch && path is ["api", "v1", "sequences", var sequenceId])
|
||||
{
|
||||
var update = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.UpdateSequenceRequest, cancellationToken))!;
|
||||
Titles[Guid.Parse(sequenceId)] = update.Title!;
|
||||
return Json(new SequenceDto(Guid.Parse(sequenceId), update.Title, update.Title!, "f", null, null, null, null, null, 0, null, 0, 0, 0, null, [], 0, null,
|
||||
1, 1, 0, null, DateTimeOffset.UtcNow), ProtocolJson.Default.SequenceDto);
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
private static HttpResponseMessage Json<T>(T value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> type, HttpStatusCode status = HttpStatusCode.OK) =>
|
||||
new(status) { Content = JsonContent.Create(value, type) };
|
||||
|
||||
public sealed record Upload(Guid Id, string FileName, long Size, string Sha256, string SessionKey)
|
||||
{
|
||||
public SortedDictionary<int, byte[]> Parts { get; } = [];
|
||||
public byte[] Bytes => [.. Parts.Values.SelectMany(p => p)];
|
||||
public int Chunks => Parts.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user