using System.Text; using AIStudio.Tools.DocumentSegments; using AIStudio.Tools.DocumentSegments.Html; using Microsoft.Extensions.Logging.Abstractions; namespace AIStudio.Tests.Tools.DocumentSegments.Html; /// /// Checks which parts of a web page a model works on, and that everything else stays as it is. /// [TestFixture] public sealed class HtmlSegmentFormatTests { private const string PARAGRAPH = "Read the <1>manual first.<2/> Then run <3/> & check the <4>output."; // // The line endings of this file depend on the checkout, so the page gets the ones of web pages on Linux and macOS: // private static readonly string PAGE = """ Mission to Mars

Getting started

Read the manual first.
Then run dotnet build & check the output.

The red planet
Text of its own

A paragraph

preformatted stays
""".ReplaceLineEndings("\n"); private readonly HtmlSegmentFormat format = new(); private string testFolder = string.Empty; private string source = string.Empty; private string target = string.Empty; [SetUp] public void CreatePage() { this.testFolder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName; this.source = Path.Join(this.testFolder, "source.html"); this.target = Path.Join(this.testFolder, "target.html"); File.WriteAllText(this.source, PAGE, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } [TearDown] public void RemoveFolder() => Directory.Delete(this.testFolder, true); [Test] public async Task TheWordsGoToTheModelAndTheMarkupBecomesTags() { var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList(); using (Assert.EnterMultipleScope()) { Assert.That(keys, Does.Contain("Mission to Mars"), "The title of the page is read."); Assert.That(keys, Does.Contain("Why we fly to Mars"), "The description of the page is read."); Assert.That(keys, Does.Contain("Getting started")); Assert.That(keys, Does.Contain(PARAGRAPH), "Links and emphasis are pairs, line breaks and code tags of their own, entities decoded, and white space collapsed."); Assert.That(keys, Does.Contain("The manual"), "The tooltip of the link is read."); Assert.That(keys, Does.Contain("The red planet"), "The alternative text of the picture is read."); Assert.That(keys, Is.SupersetOf(new[] { "Install the tools", "Open the app", "Text of its own", "A paragraph" })); Assert.That(keys, Has.None.Contains("stays"), "Preformatted text and scripts stay out."); Assert.That(keys, Has.None.Contains("color"), "Styles stay out."); } } [Test] public async Task WritingTheSourceBackChangesNothing() { var result = await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key), string.Empty, NullLogger.Instance, CancellationToken.None); using (Assert.EnterMultipleScope()) { Assert.That(result.Outcome, Is.EqualTo(SegmentWriteOutcome.WRITTEN)); Assert.That(File.ReadAllText(this.target), Is.EqualTo(PAGE)); } } [Test] public async Task NewWordsKeepTheirMarkup() { var result = await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), "de-DE", NullLogger.Instance, CancellationToken.None); var written = File.ReadAllText(this.target); using (Assert.EnterMultipleScope()) { Assert.That(result.SimplifiedCount, Is.Zero); Assert.That(written, Does.Contain(""), "The page names its new language."); Assert.That(written, Does.Contain("MISSION TO MARS")); Assert.That(written, Does.Contain("")); Assert.That(written, Does.Contain("")); Assert.That(written, Does.Contain("

GETTING STARTED

")); Assert.That(written, Does.Contain("

READ THE MANUAL FIRST.
THEN RUN dotnet build & CHECK THE OUTPUT.

"), "The address and the code stay, the tooltip is new, and the ampersand stays an entity."); Assert.That(written, Does.Contain("\"THE")); Assert.That(written, Does.Contain("
  • INSTALL THE TOOLS
  • ")); Assert.That(written, Does.Contain("
    TEXT OF ITS OWN

    A PARAGRAPH

    ")); Assert.That(written, Does.Contain("
    preformatted stays
    ")); Assert.That(written, Does.Contain("")); } } [Test] public async Task NewWordsCannotBreakTheMarkup() { var results = await this.ResultsAsync(key => key switch { "Getting started" => "Erste & mehr", "The red planet" => "Der \"rote\" Planet", _ => key, }); await this.format.WriteAsync(this.source, this.target, results, string.Empty, NullLogger.Instance, CancellationToken.None); var written = File.ReadAllText(this.target); using (Assert.EnterMultipleScope()) { Assert.That(written, Does.Contain("

    Erste <Schritte> & mehr

    ")); Assert.That(written, Does.Contain("alt=\"Der "rote" Planet\"")); } } [Test] public async Task APageWithoutLanguageGetsOne() { File.WriteAllText(this.source, "

    Hello

    ", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(_ => "Hallo"), "de-DE", NullLogger.Instance, CancellationToken.None); Assert.That(File.ReadAllText(this.target), Is.EqualTo("

    Hallo

    ")); } [Test] public async Task AChangedSourceWritesNothing() { var result = await this.format.WriteAsync(this.source, this.target, new SegmentResults(new Dictionary()), "de-DE", NullLogger.Instance, CancellationToken.None); using (Assert.EnterMultipleScope()) { Assert.That(result.Outcome, Is.EqualTo(SegmentWriteOutcome.SOURCE_CHANGED)); Assert.That(File.Exists(this.target), Is.False); } } [Test] public async Task AnAttributeWithoutQuotesGetsThemForNewWords() { File.WriteAllText(this.source, "

    The planet Mars is red.

    ", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); var results = await this.ResultsAsync(key => key == "Mars" ? "Der rote Planet" : key); await this.format.WriteAsync(this.source, this.target, results, string.Empty, NullLogger.Instance, CancellationToken.None); var written = await File.ReadAllTextAsync(this.target); using (Assert.EnterMultipleScope()) { Assert.That(written, Does.Contain("\"Der")); Assert.That(HtmlSegmentReader.Parse(written).DocumentNode.Descendants("img").Single().GetAttributeValue("alt", string.Empty), Is.EqualTo("Der rote Planet"), "The new words stay one value."); } } [Test] public async Task NewWordsOfAnAttributeWithoutQuotesGetQuotesOnce() { File.WriteAllText(this.source, "

    The planet Mars is red.

    ", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); // The model added a pair, which the attribute does not have, so its words come in three runs: var results = await this.ResultsAsync(key => key == "Mars" ? "Der <1>rote Planet" : key); await this.format.WriteAsync(this.source, this.target, results, string.Empty, NullLogger.Instance, CancellationToken.None); var written = await File.ReadAllTextAsync(this.target); Assert.That(written, Does.Contain("\"Der"), "The quotes enclose the whole value, not each run of words."); } [Test] public async Task ElementsNestedTooDeepStayAsTheyAre() { var page =$"

    Intro text.

    {Nested("div", 300, "Deep block")}

    Before {Nested("span", 300, "deep words")} after.

    Outro text.

    "; File.WriteAllText(this.source, page, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList(); await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None); var written = await File.ReadAllTextAsync(this.target); using (Assert.EnterMultipleScope()) { Assert.That(keys, Is.EqualTo(new[] { "Intro text.", "Outro text." }), "A block nested too deep, and a run with words nested too deep, stay as they are."); Assert.That(written, Is.EqualTo(page.Replace("Intro text.", "INTRO TEXT.").Replace("Outro text.", "OUTRO TEXT."))); } } [Test] public void APageNestedFarTooDeepIsRefusedRatherThanEndingTheApp() { // Thousands of elements without their end tags, as a broken generator may write them: File.WriteAllText(this.source, "

    " + string.Concat(Enumerable.Repeat("", 20_000)) + "Words

    ", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); Assert.That(async () => await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None), Throws.Exception); } [Test] public async Task BlocksWithinALinkAreRead() { // A card, as many pages show them: a link around a heading and a paragraph: File.WriteAllText(this.source, "

    Mars

    The red planet.

    ", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList(); Assert.That(keys, Is.EqualTo(new[] { "Mars", "The red planet." })); } [Test] public async Task NewWordsKeepTheByteOrderMarkTheLineEndingsAndEveryScript() { const string WORDS = "Grüße: ä ß € é ø ş ł ж 日本 한 a\u0308"; var page = $"

    {WORDS}

    \r\n

    Second line.

    \r\n"; File.WriteAllText(this.source, page, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)); await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key + " ✓"), string.Empty, NullLogger.Instance, CancellationToken.None); var bytes = await File.ReadAllBytesAsync(this.target); var written = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true).GetString(bytes, 3, bytes.Length - 3); using (Assert.EnterMultipleScope()) { Assert.That(bytes.Take(3), Is.EqualTo(new byte[] { 0xEF, 0xBB, 0xBF }), "The byte order mark stays."); Assert.That(written, Is.EqualTo($"

    {WORDS} ✓

    \r\n

    Second line. ✓

    \r\n"), "The line endings stay, and every character comes back as it was."); } } /// /// Words within elements nested in each other. /// private static string Nested(string element, int depth, string words) => string.Concat(Enumerable.Repeat($"<{element}>", depth)) + words + string.Concat(Enumerable.Repeat($"", depth)); private async Task ResultsAsync(Func transform) { var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None); return new SegmentResults(segments .Where(segment => segment.HasWords) .DistinctBy(segment => segment.Key) .ToDictionary(segment => segment.Key, segment => SegmentOutcome.Transformed(transform(segment.Key)))); } }