Files
Chronos/tests/Titano.Core.Tests/Import/ImportPlannerTests.cs
T
Claude 6e213d4997 fix(import): say what a proxy's reply means instead of its English reason phrase
A reply that is not the server's JSON (a reverse proxy's 502 page while the
container restarts, its 413 for a large body, a bare 500) reached the Import
screen as the HTTP reason phrase, in English, beside every photo. ErrorText now
uses an ApiError's message only when the server wrote it (a code that is not
TitanoClient's http_<status> fallback) and otherwise says what the status means:
too large, rate limited, not answering (gateway and timeout statuses) or a
server error. A card file that cannot be read while planning is listed with the
executor's catalog sentence instead of the system's text and full path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 16:21:10 +00:00

181 lines
9.6 KiB
C#

using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Tests.Archiving;
using Titano.Testing;
using static Titano.Core.Tests.Import.ImportTestKit;
namespace Titano.Core.Tests.Import;
[Category("import")]
public sealed class ImportPlannerTests(TestContext context)
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(10);
[Test]
public async Task ADcimCardIsPlannedWithTheDefaultTemplates()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 10, Interval);
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "._IMG_0001.JPG"), [0, 5, 22]);
File.WriteAllText(Path.Combine(card, "DCIM", "100CANON", "notes.txt"), "x");
TestPhotos.Write(Path.Combine(card, "MISC", "IMG_9999.JPG"), Start, 99);
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
var session = plan.Sessions.Single();
Assert.Equal("2026/2026-09-28 Canon EOS R5", session.Folder);
Assert.Equal(10, plan.FileCount);
Assert.Equal(10, plan.CopyCount);
Assert.SequenceEqual(
["2026-09-28_18-00-00_0001.JPG", "2026-09-28_18-00-10_0002.JPG", "2026-09-28_18-00-20_0003.JPG"],
session.Items.Take(3).Select(i => i.FileName));
Assert.Equal("DCIM/100CANON/IMG_0001.JPG", session.Items[0].SourcePath);
Assert.Equal(plan.Items.Sum(i => i.Size), plan.CopyBytes);
Assert.NotNull(plan.AvailableBytes);
Assert.True(plan.HasEnoughSpace);
Assert.Empty(plan.Problems);
}
[Test]
public void AFileThatCannotBeReadIsAProblemWithOneLocalizedSentence()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 3, Interval);
var files = CardScanner.Find(card, includeSubfolders: true);
// A photo leaves the card between listing and reading; another name is a folder the system refuses to read as a file.
File.Delete(Path.Combine(card, files[1].RelativePath));
Directory.CreateDirectory(Path.Combine(card, "DCIM", "100CANON", "IMG_9999.JPG"));
var problems = new List<ImportProblem>();
var photos = CardScanner.ReadMetadata(card, [.. files, new CardFile("DCIM/100CANON/IMG_9999.JPG", 0, Start)], problems);
Assert.Equal(2, photos.Count);
Assert.SequenceEqual([files[1].RelativePath, "DCIM/100CANON/IMG_9999.JPG"], problems.Select(p => p.RelativePath));
Assert.Equal(Loc.L("Import.Failed.Photo"), problems[0].Message);
Assert.Contains(problems[1].Message, new[] { Loc.L("Import.Failed.Photo"), Loc.L("Import.Failed.PhotoAccess") });
Assert.False(problems.Any(p => p.Message.Contains(card, StringComparison.Ordinal)), "the system's text, with the card's path, stays in the log");
}
[Test]
public async Task AFlatFolderIncludesSubfoldersOnlyWhenAsked()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 8, Interval);
TestPhotos.WriteSeries(Path.Combine(card, "more"), Start.AddSeconds(80), 8, Interval, firstSeed: 50, firstNumber: 9);
var destination = context.CreateTempDirectory("archive");
Assert.Equal(16, (await PlanAsync(card, destination)).FileCount);
Assert.Equal(8, (await PlanAsync(card, destination, new ImportOptions { IncludeSubfolders = false })).FileCount);
}
[Test]
public async Task SessionsAreSplitPerCameraBodyAndNumberedFromOne()
{
var card = context.CreateTempDirectory("card");
var dcim = Path.Combine(card, "DCIM", "100MEDIA");
TestPhotos.WriteSeries(dcim, Start, 10, Interval, prefix: "CAN_");
TestPhotos.WriteSeries(dcim, Start.AddHours(2), 10, Interval, firstSeed: 20, prefix: "CAN_", firstNumber: 11);
TestPhotos.WriteSeries(dcim, Start.AddSeconds(5), 9, Interval, firstSeed: 40, prefix: "NIK_", make: "NIKON CORPORATION", model: "NIKON Z 8");
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
Assert.SequenceEqual(
["2026/2026-09-28 Canon EOS R5", "2026/2026-09-28 Nikon Z 8", "2026/2026-09-28 Canon EOS R5 (2)"],
plan.Sessions.Select(s => s.Folder));
Assert.SequenceEqual([1, 2, 3], plan.Sessions.Select(s => s.Number));
Assert.Equal("2026-09-28_20-00-00_0001.JPG", plan.Sessions[2].Items[0].FileName);
Assert.Equal(3, plan.Sessions.Select(s => s.SessionKey).Distinct().Count());
Assert.True(plan.Sessions.All(s => s.Items.All(i => i.SourcePath.Contains(s.CameraModel == "NIKON Z 8" ? "NIK_" : "CAN_"))));
}
[Test]
public async Task NamesTakenTwiceGetASuffix()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 3, Interval);
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = "{date}", MinimumSessionFrames = 1 });
Assert.SequenceEqual(["2026-09-28.JPG", "2026-09-28_2.JPG", "2026-09-28_3.JPG"], plan.Sessions[0].Items.Select(i => i.FileName));
}
[Test]
public async Task ImportedAndArchivedPhotosAreSkippedAfterAHashMatch()
{
var card = context.CreateTempDirectory("card");
var files = TestPhotos.WriteSeries(card, Start, 10, Interval);
var lookup = new FakeLookup();
lookup.Imported.Add("IMG_0001.JPG");
var archived = await ContentHash.Sha256Async(files[1]);
lookup.Archive.Add((new FileInfo(files[1]).Length, Start + Interval, new ArchiveMatch(Guid.NewGuid(), archived)));
lookup.Archive.Add((new FileInfo(files[2]).Length, Start + 2 * Interval, new ArchiveMatch(Guid.NewGuid(), new string('0', 64))));
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), lookup: lookup);
var items = plan.Sessions[0].Items;
Assert.Equal(ImportAction.SkipImported, items[0].Action);
Assert.Equal(ImportAction.SkipInArchive, items[1].Action);
Assert.Equal(lookup.Archive[0].Match.FrameId, items[1].ExistingFrameId);
Assert.Equal(ImportAction.Copy, items[2].Action);
Assert.Equal(await ContentHash.Sha256Async(files[2]), items[2].Sha256);
Assert.Null(items[3].Sha256);
Assert.Equal(8, plan.CopyCount);
Assert.Equal("2026-09-28_18-00-10_0002.JPG", items[1].FileName);
var again = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { Duplicates = DuplicatePolicy.ImportAgain }, lookup);
Assert.Equal(ImportAction.Copy, again.Sessions[0].Items[1].Action);
Assert.Equal(lookup.Archive[0].Match.FrameId, again.Sessions[0].Items[1].ExistingFrameId);
}
[Test]
public async Task ReplanningGivesStableKeysThatTitlesAndEarlierFoldersAttachTo()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 10, Interval);
var destination = context.CreateTempDirectory("archive");
var first = await PlanAsync(card, destination);
var key = first.Sessions[0].SessionKey;
Assert.Equal(key, (await PlanAsync(card, destination)).Sessions[0].SessionKey);
var titled = await PlanAsync(card, destination, new ImportOptions
{
FolderTemplate = "{year}/{date} {title}",
Titles = new Dictionary<string, string> { [key] = "Harbour sunset" },
});
Assert.Equal("2026/2026-09-28 Harbour sunset", titled.Sessions[0].Folder);
Assert.Equal("Harbour sunset", titled.Sessions[0].Title);
var lookup = new FakeLookup();
lookup.SessionFolders[key] = "2026/earlier import";
Assert.Equal("2026/earlier import", (await PlanAsync(card, destination, lookup: lookup)).Sessions[0].Folder);
var taken = new FakeLookup();
taken.TakenFolders.Add("2026/2026-09-28 Canon EOS R5");
Assert.Equal("2026/2026-09-28 Canon EOS R5 (2)", (await PlanAsync(card, destination, lookup: taken)).Sessions[0].Folder);
}
[Test]
public async Task UserMergeAndSplitReshapeSessions()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 10, Interval);
TestPhotos.WriteSeries(card, Start.AddHours(3), 10, Interval, firstSeed: 30, firstNumber: 11);
var destination = context.CreateTempDirectory("archive");
Assert.Equal(2, (await PlanAsync(card, destination)).Sessions.Count);
var merged = await PlanAsync(card, destination, new ImportOptions { MergeAt = new HashSet<string> { "IMG_0011.JPG" } });
Assert.Equal(20, merged.Sessions.Single().Items.Count);
Assert.Equal("2026-09-28_21-00-00_0011.JPG", merged.Sessions[0].Items[10].FileName);
var split = await PlanAsync(card, destination, new ImportOptions { SplitBefore = new HashSet<string> { "IMG_0006.JPG" } });
Assert.SequenceEqual([5, 5, 10], split.Sessions.Select(s => s.Items.Count));
}
[Test]
public async Task APhotoWithoutExifIsPlannedAtItsFileTime()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 8, Interval);
var bare = Path.Combine(card, "BARE.JPG");
File.WriteAllBytes(bare, [0xFF, 0xD8, 0xFF, 0xD9]);
File.SetLastWriteTime(bare, Start.AddSeconds(85));
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
var item = plan.Items.Single(i => i.SourcePath == "BARE.JPG");
Assert.Equal(Start.AddSeconds(85), item.CapturedAt);
// No camera identity: it forms its own body group rather than joining the Canon session.
Assert.SequenceEqual([8, 1], plan.Sessions.Select(s => s.Items.Count));
}
}