Merge branch 'fix/tests-ci': serial culture tests, screenshot diff, playback, installer and PostgreSQL CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 11:10:58 +00:00
commit 2a512a61cc
39 files changed
+1825 -218

No files matched your search

@@ -0,0 +1,61 @@
using System.Globalization;
using Titano.App.Archiving;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Testing;
using static Titano.App.Tests.Archiving.ArchiveLogicTests;
namespace Titano.App.Tests.Archiving;
/// <summary>
/// Archive texts in other languages. 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 ArchiveLanguageTests
{
public ArchiveLanguageTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void MonthColumnsAreInitialsOnlyWhereTheyAreLetters()
{
var numbers = Enumerable.Range(1, 12).Select(m => m.ToString(CultureInfo.InvariantCulture)).ToArray();
try
{
Assert.Equal("J F M A M J J A S O N D", string.Join(' ', ArchiveFigures.MonthLabels()));
Loc.SetCulture(CultureInfo.GetCultureInfo("it"));
Assert.Equal("G F M A M G L A S O N D", string.Join(' ', ArchiveFigures.MonthLabels()));
// Numbered abbreviations ("10月", "Tháng 10") would read "1" for October to December, or "T" for every month.
foreach (var culture in new[] { "ja", "ko", "zh-Hans", "zh-Hant", "vi", "th", "ar", "he" })
{
Loc.SetCulture(CultureInfo.GetCultureInfo(culture));
Assert.SequenceEqual(numbers, ArchiveFigures.MonthLabels(), culture);
}
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
[Test]
public void TreeRowsShowTheirWholeTitleAndTheKeysOfTheReadingDirection()
{
var harbour = Seq("Construction cam · weekly", new DateTime(2026, 9, 28), 3_600, 72_000_000_000);
var tree = ArchiveTree.Build(Main, ArchiveAvailability.Online, [harbour]);
var year = new ArchiveTreeRowViewModel(tree.Root.Children[0], ArchiveAvailability.Online, _ => { });
var sequence = new ArchiveTreeRowViewModel(tree.Root.Children[0].Children[0], ArchiveAvailability.Online, _ => { });
Assert.Equal("Construction cam · weekly · 3,600 photos · 72 GB", sequence.RowToolTip);
Assert.Equal("2026 · 1 sequence · 72 GB · Right arrow opens the year, Left arrow closes it", year.RowToolTip);
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
Assert.Equal(Loc.L("Tooltips.Archive.YearRowRtl", "2026" + Loc.Separator + year.Detail), year.RowToolTip, "the arrow keys of a mirrored tree");
Assert.Contains("‏", year.RowToolTip, "right-to-left marks keep the year and its figures apart");
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
}
@@ -17,11 +17,11 @@ namespace Titano.App.Tests.Archiving;
public sealed class ArchiveLogicTests
{
private static readonly Core.Model.Archive Main = new() { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = "/archive" };
internal static readonly Core.Model.Archive Main = new() { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = "/archive" };
public ArchiveLogicTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
private static Sequence Seq(string title, DateTime? first, int frames = 100, long bytes = 1_000_000, params string[] tags) => new()
internal static Sequence Seq(string title, DateTime? first, int frames = 100, long bytes = 1_000_000, params string[] tags) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Main.Id,
@@ -170,28 +170,6 @@ public sealed class ArchiveLogicTests
Assert.Empty(ArchiveFigures.PhotosPerMonth(Stats() with { ByMonth = [] }, DateTime.Today));
}
[Test]
public void MonthColumnsAreInitialsOnlyWhereTheyAreLetters()
{
var numbers = Enumerable.Range(1, 12).Select(m => m.ToString(CultureInfo.InvariantCulture)).ToArray();
try
{
Assert.Equal("J F M A M J J A S O N D", string.Join(' ', ArchiveFigures.MonthLabels()));
Loc.SetCulture(CultureInfo.GetCultureInfo("it"));
Assert.Equal("G F M A M G L A S O N D", string.Join(' ', ArchiveFigures.MonthLabels()));
// Numbered abbreviations ("10月", "Tháng 10") would read "1" for October to December, or "T" for every month.
foreach (var culture in new[] { "ja", "ko", "zh-Hans", "zh-Hant", "vi", "th", "ar", "he" })
{
Loc.SetCulture(CultureInfo.GetCultureInfo(culture));
Assert.SequenceEqual(numbers, ArchiveFigures.MonthLabels(), culture);
}
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
[Test]
public void TilesAndHealthSummariseTheIndex()
{
@@ -246,27 +224,6 @@ public sealed class ArchiveLogicTests
Assert.Equal(Loc.L("Archive.Error.StalePlan"), ArchiveFailures.Cause(new StaleRenamePlanException(Guid.NewGuid())));
}
[Test]
public void TreeRowsShowTheirWholeTitleAndTheKeysOfTheReadingDirection()
{
var harbour = Seq("Construction cam · weekly", new DateTime(2026, 9, 28), 3_600, 72_000_000_000);
var tree = ArchiveTree.Build(Main, ArchiveAvailability.Online, [harbour]);
var year = new ArchiveTreeRowViewModel(tree.Root.Children[0], ArchiveAvailability.Online, _ => { });
var sequence = new ArchiveTreeRowViewModel(tree.Root.Children[0].Children[0], ArchiveAvailability.Online, _ => { });
Assert.Equal("Construction cam · weekly · 3,600 photos · 72 GB", sequence.RowToolTip);
Assert.Equal("2026 · 1 sequence · 72 GB · Right arrow opens the year, Left arrow closes it", year.RowToolTip);
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
Assert.Equal(Loc.L("Tooltips.Archive.YearRowRtl", "2026" + Loc.Separator + year.Detail), year.RowToolTip, "the arrow keys of a mirrored tree");
Assert.Contains("\u200F", year.RowToolTip, "right-to-left marks keep the year and its figures apart");
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
[Test]
public void RenameTemplatesAreCheckedAndThePlanListedByMode()
{
+2 -21
View File
@@ -8,9 +8,9 @@ namespace Titano.App.Tests.Import;
public sealed class CardPoolTests
{
private static readonly CardDevice CardA = new(@"F:\", "EOS_DIGITAL", 0x3F2A9C11, 128_000_000_000, 31_800_000_000, true, true);
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);
private static readonly CardDevice Usb = new(@"G:\", "BACKUP", 0x99990000, 2_000_000_000_000, 1_800_000_000_000, true, false);
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"));
@@ -77,25 +77,6 @@ public sealed class CardPoolTests
Assert.Equal(@"Folder · D:\Shoots\2026", pool[2].ToolTip);
}
[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 AKnownCardWithoutDcimIsStillACard()
{
@@ -0,0 +1,55 @@
using System.Globalization;
using Titano.App.Import;
using Titano.Core.Localization;
using Titano.Testing;
using static Titano.App.Tests.Import.CardPoolTests;
using static Titano.App.Tests.Import.ImportPlansTests;
namespace Titano.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"));
}
}
}
@@ -11,7 +11,7 @@ public sealed class ImportPlansTests
{
public ImportPlansTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
private static ImportPlan ThreeSessions(long? available = 200_000_000)
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")],
@@ -140,24 +140,6 @@ public sealed class ImportPlansTests
Assert.Equal("Split at IMG_0002.CR2", file.SplitName);
}
[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"));
}
}
[Test]
public void TheNamePreviewShowsTheFirstThreeCopiedFiles()
{
+17 -1
View File
@@ -1,8 +1,24 @@
using System.Globalization;
using Titano.Core.Localization;
using Titano.Testing;
namespace Titano.App.Tests;
internal static class TestMain
{
public static Task<int> Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly);
public static Task<int> Main(string[] args)
{
// The UI language is process-wide: a test that leaves English outside a serial class races with the English
// assertions of the classes running beside it, so it fails at the switch instead of making another one flaky.
// English comes back before the failure, so the classes beside it never see the other language (switching back
// passes this guard).
Loc.CultureChanged += (_, _) =>
{
if (TestContext.Current is not { IsSerial: false } test || Loc.Culture.TwoLetterISOLanguageName == "en") return;
var culture = Loc.Culture.Name;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
throw new AssertionException($"{test.TestName} switched the UI language to '{culture}' outside a [Serial] class");
};
return TestRunner.RunAsync(args, typeof(TestMain).Assembly);
}
}
@@ -0,0 +1,67 @@
using Titano.Core.Imaging;
using Titano.Testing;
using static Titano.Core.Tests.Decoding.FrameWindowTests;
namespace Titano.Core.Tests.Decoding;
/// <summary>
/// <see cref="FrameWindow"/> cancellation (BRIEF §20.4 cancellation gate). Unobserved task exceptions are counted
/// process-wide, so the class is serial: a faulted task another test left behind would otherwise be blamed on it.
/// </summary>
[Serial]
public sealed class FrameWindowIsolationTests(TestContext context)
{
[Test]
[Timeout(10_000)]
public async Task CancellationLeavesNoSpillFileAndNoUnobservedErrors()
{
// Faulted tasks the earlier tests left for the finalizer are reported now, before this test starts counting.
GC.Collect();
GC.WaitForPendingFinalizers();
var unobserved = 0;
void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved);
TaskScheduler.UnobservedTaskException += OnUnobserved;
try
{
var dir = context.CreateTempDirectory();
var source = new Source();
string? spill;
using var cts = new CancellationTokenSource();
var window = new FrameWindow(50, source.Load, new FrameWindowOptions { Behind = 3, Ahead = 2, MemoryBudget = 2 * FrameBytes, SpillDirectory = dir });
try
{
for (var i = 0; i < 6; i++)
{
window.MoveTo(i);
using var a = await window.GetAsync(i);
if (i > 0)
{
using var b = await window.GetAsync(i - 1);
}
}
spill = window.SpillPath;
Assert.NotNull(spill);
Assert.FileExists(spill!);
source.Delay = TimeSpan.FromSeconds(30);
window.MoveTo(20);
var pending = window.GetAsync(20, cts.Token);
cts.CancelAfter(50);
await Assert.ThrowsAsync<OperationCanceledException>(async () => await pending);
}
finally
{
await window.DisposeAsync();
}
Assert.FileMissing(spill!);
Assert.Equal(0, source.Live());
await Assert.ThrowsAsync<OperationCanceledException>(async () => await window.GetAsync(1));
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
TaskScheduler.UnobservedTaskException -= OnUnobserved;
}
Assert.Equal(0, unobserved);
}
}
@@ -3,15 +3,15 @@ using Titano.Testing;
namespace Titano.Core.Tests.Decoding;
/// <summary><see cref="FrameWindow"/>: memory bound independent of sequence length, spill round trip, read-ahead,
/// cancellation and deterministic disposal (BRIEF §8.4, §20.4 memory and cancellation gates).</summary>
/// <summary><see cref="FrameWindow"/>: memory bound independent of sequence length, spill round trip, read-ahead and
/// deterministic disposal (BRIEF §8.4, §20.4 memory gate; the cancellation gate is in <see cref="FrameWindowIsolationTests"/>).</summary>
public sealed class FrameWindowTests(TestContext context)
{
private const int Size = 64;
private const long FrameBytes = Size * Size * 3 * sizeof(float);
internal const long FrameBytes = Size * Size * 3 * sizeof(float);
/// <summary>Synthetic loader whose frames encode their index; records every buffer it hands out.</summary>
private sealed class Source
internal sealed class Source
{
private readonly List<ImageBuffer> _made = [];
public int Loads;
@@ -126,57 +126,6 @@ public sealed class FrameWindowTests(TestContext context)
Assert.Equal(4, source.Loads);
}
[Test]
[Timeout(10_000)]
public async Task CancellationLeavesNoSpillFileAndNoUnobservedErrors()
{
var unobserved = 0;
void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved);
TaskScheduler.UnobservedTaskException += OnUnobserved;
try
{
var dir = context.CreateTempDirectory();
var source = new Source();
string? spill;
using var cts = new CancellationTokenSource();
var window = new FrameWindow(50, source.Load, new FrameWindowOptions { Behind = 3, Ahead = 2, MemoryBudget = 2 * FrameBytes, SpillDirectory = dir });
try
{
for (var i = 0; i < 6; i++)
{
window.MoveTo(i);
using var a = await window.GetAsync(i);
if (i > 0)
{
using var b = await window.GetAsync(i - 1);
}
}
spill = window.SpillPath;
Assert.NotNull(spill);
Assert.FileExists(spill!);
source.Delay = TimeSpan.FromSeconds(30);
window.MoveTo(20);
var pending = window.GetAsync(20, cts.Token);
cts.CancelAfter(50);
await Assert.ThrowsAsync<OperationCanceledException>(async () => await pending);
}
finally
{
await window.DisposeAsync();
}
Assert.FileMissing(spill!);
Assert.Equal(0, source.Live());
await Assert.ThrowsAsync<OperationCanceledException>(async () => await window.GetAsync(1));
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
TaskScheduler.UnobservedTaskException -= OnUnobserved;
}
Assert.Equal(0, unobserved);
}
[Test]
public async Task LoaderFailuresSurfaceAndCanBeRetried()
{
@@ -0,0 +1,62 @@
using System.Globalization;
using Titano.Core.Localization;
using Titano.Testing;
namespace Titano.Core.Tests.Localization;
/// <summary>
/// The guard <see cref="TestMain"/> installs: a test outside a [Serial] class that leaves English fails, and English is
/// back before anything else runs. Serial itself: the fixture it runs switches the language for a moment.
/// </summary>
[Serial]
public sealed class LanguageGuardTests
{
/// <summary>A fixture (assembly discovery leaves nested classes out) that runs beside others and switches to Hebrew.</summary>
public sealed class SwitchesBesideOthers
{
[Test]
public void Body()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
Assert.Fail("the switch went through");
}
}
[Test]
public async Task ATestBesideOthersThatLeavesEnglishFailsAndEnglishIsBackAtOnce()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var cultures = new List<string>();
void Record(object? sender, EventArgs e) => cultures.Add(Loc.Culture.Name);
Loc.CultureChanged += Record;
try
{
var result = await TestRunner.ExecuteAsync(TestRunner.Discover(typeof(SwitchesBesideOthers)).Single());
Assert.Equal(TestOutcome.Failed, result.Outcome);
Assert.Equal(typeof(SwitchesBesideOthers).FullName + ".Body switched the UI language to 'he' outside a [Serial] class", result.Message);
Assert.Equal("en", Loc.Culture.Name);
// The guard runs first and switches back inside the change, so later listeners only ever hear of English.
Assert.SequenceEqual(new[] { "en" }, cultures);
}
finally
{
Loc.CultureChanged -= Record;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
[Test]
public void ASerialTestMaySwitchTheLanguage()
{
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
Assert.Equal("he", Loc.Culture.Name);
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
}
+17 -1
View File
@@ -1,8 +1,24 @@
using System.Globalization;
using Titano.Core.Localization;
using Titano.Testing;
namespace Titano.Core.Tests;
internal static class TestMain
{
public static Task<int> Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly);
public static Task<int> Main(string[] args)
{
// The UI language is process-wide: a test that leaves English outside a serial class races with the English
// assertions of the classes running beside it, so it fails at the switch instead of making another one flaky.
// English comes back before the failure, so the classes beside it never see the other language (switching back
// passes this guard).
Loc.CultureChanged += (_, _) =>
{
if (TestContext.Current is not { IsSerial: false } test || Loc.Culture.TwoLetterISOLanguageName == "en") return;
var culture = Loc.Culture.Name;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
throw new AssertionException($"{test.TestName} switched the UI language to '{culture}' outside a [Serial] class");
};
return TestRunner.RunAsync(args, typeof(TestMain).Assembly);
}
}
@@ -16,6 +16,9 @@ public sealed class RenderIsolationTests
[Test]
public async Task FailuresLeaveNoUnobservedTaskExceptions()
{
// Faulted tasks the earlier tests left for the finalizer are reported now, before this test starts counting.
GC.Collect();
GC.WaitForPendingFinalizers();
var unobserved = 0;
void Handler(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved);
TaskScheduler.UnobservedTaskException += Handler;
@@ -65,6 +65,61 @@ public sealed class MediaFoundationEncoderTests(TestContext context)
Assert.Count(1, Directory.GetFiles(dir)); // no temporary file left behind
}
/// <summary>
/// BRIEF §20.2: what the encoder writes plays in Windows. MediaPlayer (Windows Media Player's pipeline) opens it at
/// the encoded size and length. Where Windows Media Player is missing or unusable (Windows Server, "N" editions) the
/// test is skipped with that reason, and <see cref="SourceReaderDecodesTheSoftwareH264Output"/> is the check.
/// </summary>
[Test]
[WindowsOnly]
[Timeout(120_000)]
public void MediaPlayerOpensTheSoftwareH264Output()
{
RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false);
RequireMediaPlayer();
var opened = OpenWithMediaPlayer(Encoded("playback.mp4", VideoCodec.H264, 8, hardware: false));
context.Log($"MediaPlayer: {opened}");
Assert.Equal(1280, opened.Width);
Assert.Equal(720, opened.Height);
Assert.Approximately(2.0, opened.Duration.TotalSeconds, 0.05);
}
/// <summary>
/// BRIEF §20.2: a Media Foundation source reader decodes the encoder's first frame to the picture that was encoded.
/// It needs no Windows Media Player, so it runs on every Windows with Media Foundation, Server editions included.
/// </summary>
[Test]
[WindowsOnly]
[Timeout(60_000)]
public void SourceReaderDecodesTheSoftwareH264Output()
{
RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false);
var frame = Mp4Playback.DecodeFirstFrame(Encoded("decode.mp4", VideoCodec.H264, 8, hardware: false));
context.Log($"source reader: {frame.Width}×{frame.Height}, {frame.Duration}, luma square {frame.LumaAt(100, 360)}, corner {frame.LumaAt(4, 4)}");
Assert.Equal(1280, frame.Width);
Assert.Equal(720, frame.Height);
Assert.Approximately(2.0, frame.Duration.TotalSeconds, 0.05);
// Frame 0 as WriteFrames drew it: the white square centred at (100, 360) on a dark blue corner.
Assert.Greater(frame.LumaAt(100, 360), 200);
Assert.Less(frame.LumaAt(4, 4), 60);
}
/// <summary>The hardware HEVC Main10 output opens in MediaPlayer at its size and length, where Windows can decode HEVC.</summary>
[Test]
[WindowsOnly]
[Timeout(120_000)]
public void MediaPlayerOpensTheHardwareHevcMain10Output()
{
RequireEncoder(VideoCodec.Hevc, hardware: true, tenBit: true);
RequireMediaPlayer();
if (!Mp4Playback.HasDecoder(VideoCodec.Hevc)) TestContext.Skip("No HEVC decoder on this machine (HEVC Video Extensions)");
var opened = OpenWithMediaPlayer(Encoded("main10.mp4", VideoCodec.Hevc, 10, hardware: true));
context.Log($"MediaPlayer: {opened}");
Assert.Equal(1280, opened.Width);
Assert.Equal(720, opened.Height);
Assert.Approximately(2.0, opened.Duration.TotalSeconds, 0.05);
}
[Test]
[WindowsOnly]
[Timeout(60_000)]
@@ -139,6 +194,42 @@ public sealed class MediaFoundationEncoderTests(TestContext context)
}
}
/// <summary>Two seconds of <see cref="WriteFrames"/> (60 frames at 30 fps, 1280×720) in a new temporary file.</summary>
private string Encoded(string name, VideoCodec codec, int bitDepth, bool hardware)
{
var settings = Settings(Path.Combine(context.CreateTempDirectory(), name), codec, bitDepth) with { PreferHardware = hardware };
using (var session = new MediaFoundationEncoderProvider().Open(settings))
{
Assert.Equal(hardware, session.IsHardware);
context.Log("encoder: " + session.EncoderName);
WriteFrames(session, 60, bitDepth);
session.Complete();
}
return settings.OutputPath;
}
/// <summary>
/// <see cref="Mp4Playback.OpenWithMediaPlayer"/>, skipped when WPF finds Windows Media Player present but unusable
/// (its <see cref="NotSupportedException"/>, "version 10 or later is required").
/// </summary>
private static Mp4Playback.Opened OpenWithMediaPlayer(string path)
{
try
{
return Mp4Playback.OpenWithMediaPlayer(path, TimeSpan.FromSeconds(60));
}
catch (NotSupportedException ex)
{
TestContext.Skip("Windows Media Player cannot be used: " + ex.Message);
throw;
}
}
private static void RequireMediaPlayer()
{
if (!Mp4Playback.HasMediaPlayer) TestContext.Skip("Windows Media Player is not installed (Windows Server, \"N\" editions); the source reader test checks playback");
}
private static void RequireMediaFoundation()
{
if (!MediaFoundationRuntime.IsAvailable) TestContext.Skip("Media Foundation is not installed (Windows N or Server without Media Foundation)");
@@ -0,0 +1,289 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.Core.Video;
using Titano.Core.Windows.Interop;
using Titano.Core.Windows.MediaFoundation;
namespace Titano.Core.Windows.Tests.MediaFoundation;
/// <summary>
/// How Windows plays a written MP4 back (BRIEF §20.2): WPF's <see cref="MediaPlayer"/>, which runs on Windows Media
/// Player's pipeline, and a Media Foundation source reader that decodes the first frame, which also works where Windows
/// Media Player is not installed (Windows Server, "N" editions).
/// </summary>
internal static partial class Mp4Playback
{
/// <summary>What a player reports once the file is open.</summary>
public sealed record Opened(int Width, int Height, TimeSpan Duration);
/// <summary>The first decoded frame: its size, the file's duration and the luma plane (8 bits, top-down, no padding).</summary>
public sealed record FirstFrame(int Width, int Height, TimeSpan Duration, byte[] Luma)
{
public byte LumaAt(int x, int y) => Luma[y * Width + x];
}
/// <summary>True when <see cref="MediaPlayer"/> can work: it needs Windows Media Player (wmp.dll).</summary>
public static bool HasMediaPlayer
{
get
{
if (!NativeLibrary.TryLoad("wmp.dll", out var handle)) return false;
NativeLibrary.Free(handle);
return true;
}
}
/// <summary>
/// True when Media Foundation has a decoder for <paramref name="codec"/>: always for H.264, only with the HEVC Video
/// Extensions for HEVC, which MediaPlayer needs as much as the source reader does.
/// </summary>
public static unsafe bool HasDecoder(VideoCodec codec)
{
using var runtime = MediaFoundationRuntime.Acquire();
var input = new MftRegisterTypeInfo { MajorType = MfGuids.MediaTypeVideo, Subtype = MediaFoundationEncoders.Subtype(codec) };
const uint flags = MfNative.EnumHardware | MfNative.EnumAsync | MfNative.EnumSync | MfNative.EnumSortAndFilter;
if (MfNative.MFTEnumEx(VideoDecoderCategory, flags, &input, null, out var array, out var count) < 0) return false;
try
{
for (var i = 0; i < count; i++) Marshal.Release(Marshal.ReadIntPtr(array, i * IntPtr.Size));
}
finally
{
Marshal.FreeCoTaskMem(array);
}
return count > 0;
}
/// <summary>
/// Opens <paramref name="path"/> with <see cref="MediaPlayer"/> on its own dispatcher thread and returns what it
/// reports at <see cref="MediaPlayer.MediaOpened"/>. Throws, on the calling thread, when it raises
/// <see cref="MediaPlayer.MediaFailed"/>, when neither event comes within <paramref name="timeout"/>, and with WPF's
/// own exception when the player cannot be made or opened at all (a <see cref="NotSupportedException"/> where Windows
/// Media Player 10 or later is not usable): nothing escapes the dispatcher thread, where it would end the test program.
/// </summary>
public static Opened OpenWithMediaPlayer(string path, TimeSpan timeout)
{
Opened? opened = null;
Exception? failure = null;
var thread = new Thread(() =>
{
var dispatcher = Dispatcher.CurrentDispatcher;
MediaPlayer? player = null;
DispatcherTimer? deadline = null;
var finished = false;
// The first outcome counts; the player is closed and the dispatcher stopped once.
void Finish(Opened? result, Exception? error)
{
if (finished) return;
finished = true;
(opened, failure) = (result, error);
deadline?.Stop();
try
{
player?.Close();
}
catch (Exception ex)
{
failure ??= ex;
}
dispatcher.InvokeShutdown();
}
try
{
player = new MediaPlayer();
player.MediaOpened += (_, _) =>
{
// A handler that threw would leave Dispatcher.Run with the player still open.
try
{
Finish(new Opened(player.NaturalVideoWidth, player.NaturalVideoHeight,
player.NaturalDuration.HasTimeSpan ? player.NaturalDuration.TimeSpan : TimeSpan.Zero), null);
}
catch (Exception ex)
{
Finish(null, ex);
}
};
player.MediaFailed += (_, e) =>
Finish(null, new InvalidDataException($"MediaPlayer could not open '{path}': {e.ErrorException?.Message}", e.ErrorException));
// This constructor starts the timer.
deadline = new DispatcherTimer(timeout, DispatcherPriority.Normal, (_, _) =>
Finish(null, new TimeoutException($"MediaPlayer neither opened nor failed on '{path}' within {timeout.TotalSeconds:0} s")), dispatcher);
player.Open(new Uri(path, UriKind.Absolute));
Dispatcher.Run();
}
catch (Exception ex)
{
if (finished) failure ??= ex;
else Finish(null, ex);
}
})
{
IsBackground = true,
Name = "MediaPlayer check",
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
// Rethrown with the dispatcher thread's stack trace and its own type: a NotSupportedException stays one.
if (failure is not null) ExceptionDispatchInfo.Throw(failure);
return opened ?? throw new InvalidOperationException("MediaPlayer stopped without a result");
}
/// <summary>Decodes the first video frame of <paramref name="path"/> to NV12 with a Media Foundation source reader.</summary>
public static unsafe FirstFrame DecodeFirstFrame(string path)
{
using var runtime = MediaFoundationRuntime.Acquire();
ComObjects.Check(MFCreateSourceReaderFromURL(path, 0, out var readerPointer), "MFCreateSourceReaderFromURL");
var reader = ComObjects.Attach<IMFSourceReader>(readerPointer);
try
{
var duration = TimeSpan.Zero;
var variant = stackalloc byte[PropVariantSize];
new Span<byte>(variant, PropVariantSize).Clear();
if (reader.GetPresentationAttribute(MediaSource, PresentationDuration, (nint)variant) >= 0)
{
if (*(ushort*)variant == VtUi8) duration = TimeSpan.FromTicks((long)*(ulong*)(variant + 8));
PropVariantClear((nint)variant);
}
// The reader inserts the H.264/HEVC decoder itself once NV12 is asked for.
ComObjects.Check(MfNative.MFCreateMediaType(out var typePointer), "MFCreateMediaType");
var type = ComObjects.Attach<IMFMediaType>(typePointer);
try
{
ComObjects.Check(type.SetGUID(MfGuids.MajorType, MfGuids.MediaTypeVideo), "MF_MT_MAJOR_TYPE");
ComObjects.Check(type.SetGUID(MfGuids.Subtype, MfGuids.FormatNv12), "MF_MT_SUBTYPE");
var native = ComObjects.GetPointer(type);
try
{
ComObjects.Check(reader.SetCurrentMediaType(FirstVideoStream, 0, native), "SetCurrentMediaType(NV12)");
}
finally
{
Marshal.Release(native);
}
}
finally
{
ComObjects.Release(type);
}
var sample = ReadFirstSample(reader);
try
{
ComObjects.Check(reader.GetCurrentMediaType(FirstVideoStream, out var currentPointer), "GetCurrentMediaType");
var current = ComObjects.Attach<IMFMediaType>(currentPointer);
ulong size;
try
{
ComObjects.Check(current.GetUINT64(MfGuids.FrameSize, out size), "MF_MT_FRAME_SIZE");
}
finally
{
ComObjects.Release(current);
}
var (width, height) = ((int)(size >> 32), (int)(size & 0xFFFF_FFFF));
return new FirstFrame(width, height, duration, CopyLuma(sample, width, height));
}
finally
{
ComObjects.Release(sample);
}
}
finally
{
ComObjects.Release(reader);
}
}
/// <summary>Reads until the first video sample; stream ticks and format changes come without one.</summary>
private static IMFSample ReadFirstSample(IMFSourceReader reader)
{
for (var attempt = 0; attempt < 100; attempt++)
{
ComObjects.Check(reader.ReadSample(FirstVideoStream, 0, out _, out var flags, out _, out var samplePointer), "ReadSample");
if (samplePointer != 0) return ComObjects.Attach<IMFSample>(samplePointer);
if ((flags & (ReaderError | ReaderEndOfStream)) != 0) throw new InvalidDataException($"The source reader returned no frame (flags 0x{flags:X})");
}
throw new InvalidDataException("The source reader returned no frame in 100 reads");
}
/// <summary>Copies the Y plane out of the sample's buffer, honouring the decoder's row pitch.</summary>
private static unsafe byte[] CopyLuma(IMFSample sample, int width, int height)
{
ComObjects.Check(sample.ConvertToContiguousBuffer(out var bufferPointer), "ConvertToContiguousBuffer");
var buffer = ComObjects.Attach<IMFMediaBuffer>(bufferPointer);
try
{
var luma = new byte[width * height];
if (buffer is IMF2DBuffer twoD && twoD.Lock2D(out var scanline0, out var pitch) >= 0)
{
try
{
for (var y = 0; y < height; y++) new ReadOnlySpan<byte>((byte*)scanline0 + (long)y * pitch, width).CopyTo(luma.AsSpan(y * width));
}
finally
{
twoD.Unlock2D();
}
return luma;
}
ComObjects.Check(buffer.Lock(out var data, out _, out var length), "IMFMediaBuffer.Lock");
try
{
// A contiguous NV12 frame: the Y rows, then half as many interleaved chroma rows, all of one pitch.
var stride = (int)(length / (uint)(height + height / 2));
if (stride < width) throw new InvalidDataException($"An NV12 buffer of {length} bytes is too small for {width}×{height}");
for (var y = 0; y < height; y++) new ReadOnlySpan<byte>((byte*)data + (long)y * stride, width).CopyTo(luma.AsSpan(y * width));
return luma;
}
finally
{
buffer.Unlock();
}
}
finally
{
ComObjects.Release(buffer);
}
}
private const uint FirstVideoStream = 0xFFFF_FFFC; // MF_SOURCE_READER_FIRST_VIDEO_STREAM
private const uint MediaSource = 0xFFFF_FFFF; // MF_SOURCE_READER_MEDIASOURCE
private const uint ReaderError = 0x1, ReaderEndOfStream = 0x2; // MF_SOURCE_READERF_ERROR, _ENDOFSTREAM
private const ushort VtUi8 = 21;
private const int PropVariantSize = 24; // PROPVARIANT on 64-bit Windows
/// <summary>MFT_CATEGORY_VIDEO_DECODER.</summary>
private static readonly Guid VideoDecoderCategory = new("d6c02d4b-6833-45b4-971a-05a4b04bab91");
/// <summary>MF_PD_DURATION: the presentation's length in 100 ns units.</summary>
private static readonly Guid PresentationDuration = new("6c990d33-bb8e-477a-8598-0d5d96fcd88a");
[LibraryImport("mfreadwrite.dll", StringMarshalling = StringMarshalling.Utf16)]
private static partial int MFCreateSourceReaderFromURL(string url, nint attributes, out nint reader);
[LibraryImport("ole32.dll")]
private static partial int PropVariantClear(nint variant);
}
/// <summary>IMFSourceReader (mfreadwrite.h) in vtable order.</summary>
[GeneratedComInterface]
[Guid("70ae66f2-c809-4e4f-8915-bdcb406b7993")]
internal partial interface IMFSourceReader
{
[PreserveSig] int GetStreamSelection(uint streamIndex, out int selected);
[PreserveSig] int SetStreamSelection(uint streamIndex, int selected);
[PreserveSig] int GetNativeMediaType(uint streamIndex, uint mediaTypeIndex, out nint mediaType);
[PreserveSig] int GetCurrentMediaType(uint streamIndex, out nint mediaType);
[PreserveSig] int SetCurrentMediaType(uint streamIndex, nint reserved, nint mediaType);
[PreserveSig] int SetCurrentPosition(in Guid timeFormat, nint position);
[PreserveSig] int ReadSample(uint streamIndex, uint controlFlags, out uint actualStreamIndex, out uint streamFlags, out long timestamp, out nint sample);
[PreserveSig] int Flush(uint streamIndex);
[PreserveSig] int GetServiceForStream(uint streamIndex, in Guid service, in Guid iid, out nint instance);
[PreserveSig] int GetPresentationAttribute(uint streamIndex, in Guid attribute, nint value);
}
@@ -4,6 +4,10 @@
<TargetFramework>net10.0-windows</TargetFramework>
<RootNamespace>Titano.Core.Windows.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<!-- WPF's MediaPlayer for the playback check (BRIEF §20.2); not UseWPF, which would also change the implicit usings. -->
<FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Titano.Testing\Titano.Testing.csproj" />
<ProjectReference Include="..\..\src\Titano.Core.Windows\Titano.Core.Windows.csproj" />
@@ -29,6 +29,11 @@ internal static class PgTestServer
public static string Optional(string variable) =>
Environment.GetEnvironmentVariable(variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{variable} not set");
/// <summary>Set to 1 where the server was set up with TLS (CI): a server that refuses TLS then fails the TLS tests.</summary>
public const string TlsVariable = "TITANO_TEST_PG_TLS";
public static bool TlsExpected => Environment.GetEnvironmentVariable(TlsVariable) is "1" or "true";
public static async Task<string> CreateSchemaAsync(CancellationToken cancellationToken)
{
var name = "titano_t_" + Guid.NewGuid().ToString("N")[..16];
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security.Authentication;
using Titano.Data.Postgres;
using Titano.Data.Tests.Infrastructure;
@@ -6,7 +7,11 @@ using Titano.Testing;
namespace Titano.Data.Tests.Postgres;
/// <summary>Protocol-level tests against a live server (TITANO_TEST_PG; optional TITANO_TEST_PG_MD5/_CLEARTEXT/_TRUST).</summary>
/// <summary>
/// Protocol-level tests against a live server (TITANO_TEST_PG). Optional: TITANO_TEST_PG_MD5/_CLEARTEXT/_TRUST (roles
/// of the other authentication methods), TITANO_TEST_PG_TLS=1 (the server offers TLS) and TITANO_TEST_PG_ROOT_CERT (the
/// PEM its certificate chains to). CI sets them all up (.github/scripts/postgres-ci-setup.sh).
/// </summary>
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PgWireTests(TestContext context) : DatabaseTest(context)
{
@@ -15,6 +20,14 @@ public sealed class PgWireTests(TestContext context) : DatabaseTest(context)
private async Task<PostgresDatabase> OpenAsync(string? extra = null) =>
(PostgresDatabase)Own(DatabaseFactory.Open(await NewOptionsAsync(extraPostgres: extra)));
/// <summary>A server without TLS skips the TLS tests, unless it was set up with TLS (<see cref="PgTestServer.TlsVariable"/>).</summary>
[DoesNotReturn]
private static void WithoutTls(DatabaseConnectionException refusal)
{
if (PgTestServer.TlsExpected) Assert.Fail($"{PgTestServer.TlsVariable} says the server offers TLS, but it refused: {refusal.Message}");
TestContext.Skip("server has no TLS");
}
private async Task<string> AuthenticateAsync(string connectionString)
{
var database = Own(new PostgresDatabase(PostgresSettings.Parse(connectionString)));
@@ -61,7 +74,7 @@ public sealed class PgWireTests(TestContext context) : DatabaseTest(context)
}
catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal))
{
TestContext.Skip("server has no TLS");
WithoutTls(ex);
return;
}
await using var session = await database.OpenAsync(Ct);
@@ -83,13 +96,22 @@ public sealed class PgWireTests(TestContext context) : DatabaseTest(context)
}
catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal))
{
TestContext.Skip("server has no TLS");
WithoutTls(ex);
}
catch (AuthenticationException)
{
}
}
[Test]
public async Task VerifyFullAcceptsACertificateThatChainsToTheConfiguredRoot()
{
var root = PgTestServer.Optional("TITANO_TEST_PG_ROOT_CERT");
var database = await OpenAsync($"SslMode=VerifyFull;Root Certificate={root}");
await using var session = await database.OpenAsync(Ct);
Assert.True(await session.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
}
[Test]
public async Task DecodesEveryMappedResultType()
{
+16 -1
View File
@@ -9,18 +9,33 @@ namespace Titano.Testing;
/// </summary>
public sealed class TestContext : IDisposable
{
private static readonly AsyncLocal<TestContext?> CurrentTest = new();
private readonly ConcurrentQueue<string> _log = new();
private readonly List<string> _tempDirectories = [];
private readonly Lock _gate = new();
internal TestContext(string testName, CancellationToken cancellation)
internal TestContext(string testName, bool isSerial, CancellationToken cancellation)
{
TestName = testName;
IsSerial = isSerial;
Cancellation = cancellation;
}
/// <summary>
/// The test running on this flow of execution (its constructor, body and the tasks it starts); null outside tests.
/// Lets a test program guard process-wide state, which only a serial test may change.
/// </summary>
public static TestContext? Current
{
get => CurrentTest.Value;
internal set => CurrentTest.Value = value;
}
public string TestName { get; }
/// <summary>True when the test's class is <see cref="SerialAttribute"/>: no other test runs beside it.</summary>
public bool IsSerial { get; }
/// <summary>Signalled when the test times out or the run is aborted.</summary>
public CancellationToken Cancellation { get; }
+44 -24
View File
@@ -100,30 +100,41 @@ public static class TestRunner
}
foreach (var type in types.Where(t => t is { IsClass: true, IsPublic: true } && !t.IsAbstract).OrderBy(t => t.FullName, StringComparer.Ordinal))
list.AddRange(Discover(type));
return list;
}
/// <summary>
/// The tests of one class, in declaration order. Assembly discovery takes top-level classes only, so a class nested
/// in a test class is a fixture that runs only when a test hands it to <see cref="ExecuteAsync"/>.
/// </summary>
public static IReadOnlyList<TestCase> Discover(Type type)
{
var list = new List<TestCase>();
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).OrderBy(m => m.MetadataToken))
{
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).OrderBy(m => m.MetadataToken))
if (method.GetCustomAttribute<TestAttribute>() is not null)
{
if (method.GetCustomAttribute<TestAttribute>() is not null)
{
list.Add(new TestCase(type, method, null, null));
}
else if (method.GetCustomAttribute<TheoryAttribute>() is not null)
{
foreach (var c in method.GetCustomAttributes<CaseAttribute>())
list.Add(new TestCase(type, method, c.Arguments, c.Name));
}
list.Add(new TestCase(type, method, null, null));
}
else if (method.GetCustomAttribute<TheoryAttribute>() is not null)
{
foreach (var c in method.GetCustomAttributes<CaseAttribute>())
list.Add(new TestCase(type, method, c.Arguments, c.Name));
}
}
return list;
}
private static async Task<TestResult> ExecuteAsync(TestCase test)
/// <summary>Runs one test (constructor, body, disposal) under its timeout and returns its outcome.</summary>
public static async Task<TestResult> ExecuteAsync(TestCase test)
{
ArgumentNullException.ThrowIfNull(test);
if (test.StaticSkipReason is { } reason)
return new TestResult(test, TestOutcome.Skipped, TimeSpan.Zero, reason, null, string.Empty);
using var cts = new CancellationTokenSource();
using var context = new TestContext(test.FullName, cts.Token);
using var context = new TestContext(test.FullName, test.Serial, cts.Token);
var sw = Stopwatch.StartNew();
try
{
@@ -152,29 +163,21 @@ public static class TestRunner
private static async Task InvokeAsync(TestCase test, TestContext context)
{
TestContext.Current = context;
object? instance = null;
try
{
if (!test.Method.IsStatic)
{
var ctor = test.Type.GetConstructor([typeof(TestContext)]);
instance = ctor is not null
instance = Unwrapped(() => ctor is not null
? ctor.Invoke([context])
: Activator.CreateInstance(test.Type);
: Activator.CreateInstance(test.Type));
}
var parameters = test.Method.GetParameters();
var args = BuildArguments(test, parameters, context);
object? returned;
try
{
returned = test.Method.Invoke(instance, args);
}
catch (TargetInvocationException tie) when (tie.InnerException is not null)
{
ExceptionDispatchInfo.Capture(tie.InnerException).Throw();
throw;
}
var returned = Unwrapped(() => test.Method.Invoke(instance, args));
switch (returned)
{
@@ -200,6 +203,23 @@ public static class TestRunner
}
}
/// <summary>
/// Makes a reflection call and rethrows what the constructor or method threw, so a skip stays a skip and a failure
/// carries its own message and stack trace instead of "Exception has been thrown by the target of an invocation".
/// </summary>
private static object? Unwrapped(Func<object?> call)
{
try
{
return call();
}
catch (TargetInvocationException tie) when (tie.InnerException is not null)
{
ExceptionDispatchInfo.Capture(tie.InnerException).Throw();
throw;
}
}
private static object?[] BuildArguments(TestCase test, ParameterInfo[] parameters, TestContext context)
{
var supplied = test.Arguments ?? [];
@@ -0,0 +1,188 @@
using Titano.Core.Codecs.Png;
using Titano.Testing;
using Titano.Tools.Commands;
using static Titano.Tools.Commands.ScreenshotsCommand;
namespace Titano.Tools.Tests;
/// <summary>
/// The screenshot diff fails on changed screens and tolerates noise (BRIEF §20.2); a screen without a baseline fails
/// once any baseline exists, and a run before the first baselines says that it compared nothing.
/// </summary>
public sealed class ScreenshotsCommandTests(TestContext context)
{
private const int Size = 100;
/// <summary>A 100×100 RGB screen: a dark background with a light panel, then <paramref name="change"/> applied.</summary>
private static void WriteScreen(string folder, string name, Action<byte[]>? change = null, int width = Size, int height = Size)
{
var pixels = new byte[width * height * 3];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var v = (byte)(x is >= 20 and < 80 && y is >= 30 and < 60 ? 230 : 32);
pixels[(y * width + x) * 3] = pixels[(y * width + x) * 3 + 1] = pixels[(y * width + x) * 3 + 2] = v;
}
}
change?.Invoke(pixels);
File.WriteAllBytes(Path.Combine(folder, name), PngEncoder.Encode(pixels, width, height, PngColorType.Rgb));
}
/// <summary>Adds <paramref name="delta"/> to the red channel of the first <paramref name="count"/> pixels.</summary>
private static Action<byte[]> Shift(int count, int delta) => pixels =>
{
for (var i = 0; i < count; i++) pixels[i * 3] = (byte)(pixels[i * 3] + delta);
};
private (string Captured, string Baseline, string Output) Folders()
{
var root = context.CreateTempDirectory();
var folders = (Path.Combine(root, "screenshots"), Path.Combine(root, "baselines"), Path.Combine(root, "diff"));
Directory.CreateDirectory(folders.Item1);
Directory.CreateDirectory(folders.Item2);
return folders;
}
private static DiffReport Run(string captured, string baseline, string output, StringWriter log, int tolerance = DefaultTolerance, double maxDiff = DefaultMaxDiff) =>
ScreenshotsCommand.Diff(new DiffOptions(captured, baseline, output, tolerance, maxDiff), log, annotate: true, stepSummary: null);
[Test]
public void ChangedScreensFailAndNoiseWithinTheToleranceDoesNot()
{
var (captured, baseline, output) = Folders();
foreach (var name in new[] { "library-dark.png", "jobs-dark.png", "about-dark.png", "server-dark.png" }) WriteScreen(baseline, name);
WriteScreen(captured, "library-dark.png");
// Every pixel a little off: anti-aliasing noise below the per-channel tolerance.
WriteScreen(captured, "jobs-dark.png", Shift(Size * Size, DefaultTolerance));
// Four pixels clearly off: 0.04 % of the screen, under the 0.05 % allowed.
WriteScreen(captured, "about-dark.png", Shift(4, 100));
// A whole row moved: 1 % of the screen.
WriteScreen(captured, "server-dark.png", Shift(Size, 100));
using var log = new StringWriter();
var report = Run(captured, baseline, output, log);
Assert.True(report.Fails);
Assert.SequenceEqual(new[] { Verdict.Within, Verdict.Same, Verdict.Same, Verdict.Changed }, report.Screens.Select(s => s.Verdict));
Assert.SequenceEqual(new[] { "about-dark.png", "jobs-dark.png", "library-dark.png", "server-dark.png" }, report.Screens.Select(s => s.Name));
Assert.Equal(Size, report.Screens[3].Differing);
Assert.FileExists(Path.Combine(output, "server-dark-diff.png"));
Assert.FileExists(Path.Combine(output, "about-dark-diff.png"));
Assert.FileMissing(Path.Combine(output, "library-dark-diff.png"));
Assert.Contains("::error title=Screenshot changed::server-dark.png: 1 %25 of the pixels differ (100; limit 0.05 %25)", log.ToString());
Assert.Contains("| server-dark.png | changed | 1 % of the pixels differ (100; limit 0.05 %) |", File.ReadAllText(Path.Combine(output, "summary.md")));
}
[Test]
public void TheDiffImageShowsTheDifferingPixelsInMagentaOverTheFadedBaseline()
{
var (captured, baseline, output) = Folders();
WriteScreen(baseline, "a.png");
WriteScreen(captured, "a.png", Shift(Size, 100));
using var log = new StringWriter();
Run(captured, baseline, output, log);
var diff = ScreenshotsCommand.Read(Path.Combine(output, "a-diff.png"));
Assert.Equal(Size, diff.Width);
Assert.SequenceEqual(new byte[] { 255, 0, 255, 255 }, diff.Pixels[..4], "a differing pixel");
var panel = ((40 * Size) + 50) * 4;
var background = ((90 * Size) + 50) * 4;
Assert.Greater(diff.Pixels[panel], diff.Pixels[background], "the baseline's light panel stays lighter than its background");
Assert.InRange(diff.Pixels[background], 112, 207);
}
[Test]
public void BeforeTheFirstBaselinesTheRunWarnsThatItComparedNothing()
{
var (captured, baseline, output) = Folders();
WriteScreen(captured, "welcome-dark.png");
WriteScreen(captured, "about-dark.png");
// A README is not a baseline: the folder as committed before the first screens are accepted.
File.WriteAllText(Path.Combine(baseline, "README.md"), "# Screenshot baselines");
foreach (var folder in new[] { baseline, Path.Combine(baseline, "not-there") })
{
using var log = new StringWriter();
var report = Run(captured, folder, output, log);
Assert.False(report.Fails);
Assert.False(report.Armed);
Assert.True(report.Screens.All(s => s.Verdict == Verdict.New));
Assert.Contains("::warning title=No screenshot baselines::The baseline folder holds no PNG: nothing was compared, and no visual change can fail " +
"this step until baselines are committed. 2 screenshot(s) without a baseline (about-dark.png, welcome-dark.png);", log.ToString());
Assert.False(log.ToString().Contains("::error", StringComparison.Ordinal));
Assert.Contains("0 compared", log.ToString());
Assert.Contains("**The baseline folder holds no PNG: nothing was compared", File.ReadAllText(Path.Combine(output, "summary.md")));
}
}
[Test]
public void OnceAnyBaselineExistsAScreenWithoutOneFails()
{
var (captured, baseline, output) = Folders();
WriteScreen(baseline, "library-dark.png");
WriteScreen(captured, "library-dark.png");
// A screen added after the baselines were committed, whose baseline nobody accepted.
WriteScreen(captured, "library-new-dark.png");
using var log = new StringWriter();
var report = Run(captured, baseline, output, log);
Assert.True(report.Armed);
Assert.True(report.Fails);
Assert.SequenceEqual(new[] { Verdict.Same, Verdict.Unbased }, report.Screens.Select(s => s.Verdict));
Assert.Contains("::error title=Screenshot without baseline::library-new-dark.png: no baseline, while other screens have one (screenshots accept adds it)", log.ToString());
Assert.False(log.ToString().Contains("::warning", StringComparison.Ordinal), "the not-compared warning belongs to a run before the first baselines");
Assert.Contains("1 compared: 1 within tolerance, 0 changed; 1 without a baseline; 0 missing.", log.ToString());
Assert.False(File.ReadAllText(Path.Combine(output, "summary.md")).Contains("holds no PNG", StringComparison.Ordinal));
}
[Test]
public void AResizedScreenAndABaselineWithoutItsScreenFail()
{
var (captured, baseline, output) = Folders();
WriteScreen(baseline, "settings-dark.png");
WriteScreen(baseline, "setup-failed-dark.png");
WriteScreen(captured, "settings-dark.png", width: Size + 1);
using var log = new StringWriter();
var report = Run(captured, baseline, output, log);
Assert.SequenceEqual(new[] { Verdict.Resized, Verdict.Missing }, report.Screens.Select(s => s.Verdict));
Assert.True(report.Screens.All(s => s.Fails));
Assert.Contains("settings-dark.png: 101×100, baseline 100×100", log.ToString());
}
[Test]
public void ThePerChannelToleranceIsInclusive()
{
var expected = new Picture(2, 1, [10, 10, 10, 255, 10, 10, 10, 255]);
var actual = new Picture(2, 1, [18, 10, 10, 255, 10, 10, 10, 247]);
Assert.Equal(0L, ScreenshotsCommand.Compare(expected, actual, tolerance: 8).Differing);
Assert.Equal(2L, ScreenshotsCommand.Compare(expected, actual, tolerance: 7).Differing, "alpha counts like a colour");
}
[Test]
public void TheCommandExitsWithOneOnAChangeAndAcceptCopiesTheBaselines()
{
var (captured, baseline, output) = Folders();
WriteScreen(baseline, "a.png");
WriteScreen(captured, "a.png", Shift(Size * 2, 120));
WriteScreen(captured, "b.png");
using var log = new StringWriter();
int Run(params string[] args) => ScreenshotsCommand.Run(args, _ => null, log);
Assert.Equal(1, Run("diff", captured, "--baseline", baseline, "--out", output, "--tolerance", "8", "--max-diff", "0.001"));
// a.png is now within the limit, but b.png still has no baseline beside a.png's.
Assert.Equal(1, Run("diff", captured, "--baseline", baseline, "--out", output, "--max-diff", "0.05"));
Assert.FileExists(Path.Combine(output, "a-diff.png"));
File.Copy(Path.Combine(captured, "b.png"), Path.Combine(baseline, "b.png"));
Assert.Equal(0, Run("diff", captured, "--baseline", baseline, "--out", output, "--max-diff", "0.05"));
Assert.Equal(0, Run("accept", captured, "--baseline", baseline));
Assert.FileExists(Path.Combine(baseline, "b.png"));
Assert.Equal(0, Run("diff", captured, "--baseline", baseline, "--out", output));
// The diff of the earlier run is removed with the change it showed.
Assert.FileMissing(Path.Combine(output, "a-diff.png"));
Assert.False(log.ToString().Contains("::", StringComparison.Ordinal), "no workflow commands outside GitHub Actions");
Assert.Throws<ToolException>(() => Run("diff", captured, "--baseline", baseline, "--tolerance", "300"));
Assert.Throws<ToolException>(() => Run("compare", captured));
}
}
+102
View File
@@ -0,0 +1,102 @@
using Titano.Testing;
namespace Titano.Tools.Tests;
/// <summary>
/// The in-house runner reports what a test class did, not how reflection called it (BRIEF §20.1). The nested classes
/// are fixtures: assembly discovery leaves them out, and each test hands one to the runner.
/// </summary>
public sealed class TestRunnerTests(TestContext context)
{
public sealed class SkippingConstructor
{
public SkippingConstructor() => TestContext.Skip("no server configured");
[Test]
public void Body() => Assert.Fail("the body ran after the constructor skipped");
}
public sealed class FailingConstructor
{
public FailingConstructor(TestContext context) => Assert.Fail($"{context.TestName} could not start its fixture");
[Test]
public void Body() => Assert.Fail("the body ran after the constructor failed");
}
public sealed class ThrowingFieldInitializer
{
private readonly string _root = Environment.GetEnvironmentVariable("TITANO_NO_SUCH_VARIABLE") ?? throw new InvalidOperationException("no root folder");
[Test]
public void Body() => Assert.Fail("the body ran with " + _root);
}
public sealed class BesideOthers
{
[Test]
public async Task SeesItsOwnContext(TestContext context)
{
Assert.Same(context, TestContext.Current);
Assert.False(context.IsSerial);
await Task.Yield();
Assert.Same(context, await Task.Run(() => TestContext.Current));
}
}
[Serial]
public sealed class Alone
{
[Test]
public void KnowsItRunsAlone(TestContext context) => Assert.True(context.IsSerial && TestContext.Current == context);
}
private static async Task<TestResult> RunAsync<T>()
{
var test = TestRunner.Discover(typeof(T)).Single();
return await TestRunner.ExecuteAsync(test);
}
[Test]
public void NestedFixturesAreNotDiscoveredWithTheAssembly()
{
var names = TestRunner.Discover(typeof(TestRunnerTests).Assembly).Select(t => t.FullName).ToList();
Assert.Contains(typeof(TestRunnerTests).FullName + "." + nameof(NestedFixturesAreNotDiscoveredWithTheAssembly), names);
Assert.False(names.Any(n => n.Contains('+', StringComparison.Ordinal)), "a nested class would run as a real test");
}
[Test]
public async Task ASkipInTheConstructorSkipsTheTest()
{
var result = await RunAsync<SkippingConstructor>();
Assert.Equal(TestOutcome.Skipped, result.Outcome);
Assert.Equal("no server configured", result.Message);
}
[Test]
public async Task AFailureInTheConstructorKeepsItsMessage()
{
var result = await RunAsync<FailingConstructor>();
Assert.Equal(TestOutcome.Failed, result.Outcome);
Assert.Equal(typeof(FailingConstructor).FullName + ".Body could not start its fixture", result.Message);
Assert.Contains(nameof(FailingConstructor), result.StackTrace);
}
[Test]
public async Task AnExceptionInAFieldInitializerIsReportedAsItself()
{
var result = await RunAsync<ThrowingFieldInitializer>();
Assert.Equal(TestOutcome.Failed, result.Outcome);
Assert.Equal("System.InvalidOperationException: no root folder", result.Message);
}
[Test]
public async Task TheCurrentContextFollowsEachTestAndItsTasks()
{
var parallel = await RunAsync<BesideOthers>();
Assert.Equal(TestOutcome.Passed, parallel.Outcome, parallel.Message);
var alone = await RunAsync<Alone>();
Assert.Equal(TestOutcome.Passed, alone.Outcome, alone.Message);
Assert.Same(context, TestContext.Current);
}
}
+52
View File
@@ -0,0 +1,52 @@
# Screenshot baselines
The approved look of every screen, one PNG per `--capture` screenshot (`<screen>-<theme>.png`, as `Titano.exe`,
`Titano.Uploader.exe` and `Titano.Setup.exe --capture <dir>` write them). CI compares each new screenshot with the
file of the same name here (BRIEF §20.2, visual regression with a pixel-diff tolerance):
```
dotnet run --project src/Titano.Tools -- screenshots diff out/screenshots --out out/screenshot-diff
```
- A pixel differs when one of its channels moves by more than `--tolerance` (default 8 of 255); a screen fails when
more than `--max-diff` of its pixels differ (default 0.0005, that is 0.05 %), when its size changed, or when a
baseline here has no screenshot any more.
- A screenshot without a baseline fails as soon as this folder holds any PNG: a pull request that adds a screen adds its
baselines too.
- While this folder holds no PNG nothing is compared: the step passes, with a warning and a bold line in the job summary
saying that no visual change can fail it.
- `out/screenshot-diff` gets `<screen>-diff.png` for every screen with differing pixels (the baseline faded to grey, the
differences magenta) and `summary.md`; CI uploads them as the `screenshot-diff` artifact and adds the summary to the
job page.
## The pictures are reproducible
The capture runs on sample data whose clock stands at `SampleData.Now` (2026-10-02 10:18 UTC), in English with English
formats and with animations off, so the same code draws the same pixels on any day. Two things still come from the
machine:
- the time zone: times are shown in local time, and the baselines are made on the CI runner (`windows-latest`, UTC);
- a few measured values: the server's response time and the time and duration of the last sync comparison. They change
a few dozen pixels, well inside the allowed fraction.
## Adding or updating baselines
Take them from CI, never from a local run (fonts, scaling and the time zone differ). Every same-repository pull request
pushes its screenshots to the `ci-screenshots` branch (one commit, the PNGs at its root). After checking them:
```
git fetch origin ci-screenshots
git worktree add ../ci-screenshots origin/ci-screenshots
dotnet run --project src/Titano.Tools -- screenshots accept ../ci-screenshots
git worktree remove ../ci-screenshots
```
`screenshots accept <dir>` copies every PNG of `<dir>` here. Commit only the screens whose change is intended, and delete
the baseline of a screen that no longer exists.
## The first baselines
None is committed yet. Screenshots captured before the capture was made reproducible cannot serve: their times and
dates follow the moment they were taken (a job finished at "12:18 AM", sample sequences dated from that day). The first
baselines are accepted, all at once, from the `ci-screenshots` commit of the first green `windows-latest` run whose
code captures at `SampleData.Now`; from that commit on, every screen is gated.