using System.Text; using AIStudio.Tools.DocumentSegments; using Microsoft.Extensions.Logging.Abstractions; namespace AIStudio.Tests.Tools.DocumentSegments; /// /// Checks which parts of a Markdown file a model works on, and that everything else stays as it is. /// [TestFixture] public sealed class MarkdownSegmentFormatTests { // // The line endings of this file depend on the checkout, so the document gets the ones of Markdown files on Linux and macOS: // private static readonly string DOCUMENT = """ --- title: Hello --- # Getting started Read the [manual](https://example.org/manual "Manual") first. Then run `dotnet build` and **check** the output. - Install the *tools* - Open > Quoted text > on two lines. | Name | Value | |------|-------| | Speed | 42 | ```bash echo "code stays" ```
HTML stays
Line one\ line two """.ReplaceLineEndings("\n"); private readonly MarkdownSegmentFormat format = new(); private string testFolder = string.Empty; [SetUp] public void CreateFolder() => this.testFolder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName; [TearDown] public void RemoveFolder() => Directory.Delete(this.testFolder, true); [Test] public void TheWordsGoToTheModelAndTheMarkupBecomesTags() { var keys = MarkdownSegmentFormat.SegmentsOf(DOCUMENT).Select(segment => segment.Segment.Key).ToList(); using (Assert.EnterMultipleScope()) { Assert.That(keys, Does.Contain("Getting started")); Assert.That(keys, Does.Contain("Read the <1>manual first. Then run <2/> and <3>check the output."), "Links and emphasis become pairs, code a tag of its own, and the soft line break a space."); Assert.That(keys, Does.Contain("Install the <1>tools")); Assert.That(keys, Does.Contain("Open <1/>"), "An autolink is an address, not words."); Assert.That(keys, Does.Contain("Quoted text on two lines."), "The quote mark of the second line belongs to the line break."); Assert.That(keys, Is.SupersetOf(new[] { "Name", "Value", "Speed" })); Assert.That(keys, Has.None.EqualTo("42"), "A cell without letters stays as it is, as in web pages and LaTeX."); Assert.That(keys, Does.Contain("Line one<1/>line two"), "A hard line break is a tag of its own."); Assert.That(keys, Has.None.Contains("title"), "The front matter stays out."); Assert.That(keys, Has.None.Contains("code stays"), "Code blocks stay out."); Assert.That(keys, Has.None.Contains("HTML stays"), "HTML blocks stay out."); } } [Test] public async Task WritingTheSourceBackChangesNothing() { var source = await this.WriteSourceAsync(DOCUMENT); var target = Path.Join(this.testFolder, "target.md"); var result = await this.format.WriteAsync(source, target, await this.ResultsAsync(source, text => text), string.Empty, NullLogger.Instance, CancellationToken.None); using (Assert.EnterMultipleScope()) { Assert.That(result.Outcome, Is.EqualTo(SegmentWriteOutcome.WRITTEN)); Assert.That(File.ReadAllText(target), Is.EqualTo(DOCUMENT)); } } [Test] public async Task NewWordsKeepTheirMarkup() { var source = await this.WriteSourceAsync(DOCUMENT); var target = Path.Join(this.testFolder, "target.md"); var result = await this.format.WriteAsync(source, target, await this.ResultsAsync(source, text => text.ToUpperInvariant()), "de-DE", NullLogger.Instance, CancellationToken.None); var written = File.ReadAllText(target); using (Assert.EnterMultipleScope()) { Assert.That(result.SimplifiedCount, Is.Zero); Assert.That(written, Does.StartWith("---\ntitle: Hello\n---"), "The front matter stays as it is."); Assert.That(written, Does.Contain("# GETTING STARTED")); Assert.That(written, Does.Contain("READ THE [MANUAL](https://example.org/manual \"Manual\") FIRST. THEN RUN `dotnet build` AND **CHECK** THE OUTPUT.")); Assert.That(written, Does.Contain("- INSTALL THE *TOOLS*")); Assert.That(written, Does.Contain("- OPEN ")); Assert.That(written, Does.Contain("> QUOTED TEXT ON TWO LINES.")); Assert.That(written, Does.Contain("| NAME | VALUE |")); Assert.That(written, Does.Contain("| SPEED | 42 |")); Assert.That(written, Does.Contain("echo \"code stays\"")); Assert.That(written, Does.Contain("
HTML stays
")); Assert.That(written, Does.EndWith("LINE ONE\\\nLINE TWO"), "The hard line break stays with its backslash."); } } [Test] public async Task WordsWhoseTagsDoNotFitKeepTheMarkupWithoutWords() { const string DOCUMENT_WITH_CODE = "Run `dotnet build` and **check** the output."; var source = await this.WriteSourceAsync(DOCUMENT_WITH_CODE); var target = Path.Join(this.testFolder, "target.md"); var results = new SegmentResults(new Dictionary { ["Run <1/> and <2>check the output."] = SegmentOutcome.Transformed("Führe es aus und prüfe die Ausgabe."), }); var result = await this.format.WriteAsync(source, target, results, "de-DE", NullLogger.Instance, CancellationToken.None); using (Assert.EnterMultipleScope()) { Assert.That(result.SimplifiedCount, Is.EqualTo(1)); Assert.That(File.ReadAllText(target), Is.EqualTo("Führe es aus und prüfe die Ausgabe. `dotnet build`"), "The code the model dropped follows the words rather than getting lost."); } } [Test] public async Task AChangedSourceWritesNothing() { var source = await this.WriteSourceAsync(DOCUMENT); var target = Path.Join(this.testFolder, "target.md"); var result = await this.format.WriteAsync(source, 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(target), Is.False); } } [Test] public async Task TheEncodingAndTheLineEndingsStay() { const string WINDOWS_DOCUMENT = "# Title\r\n\r\nSome text\r\nmore text.\r\n"; var source = Path.Join(this.testFolder, "source.md"); await File.WriteAllTextAsync(source, WINDOWS_DOCUMENT, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)); var target = Path.Join(this.testFolder, "target.md"); await this.format.WriteAsync(source, target, await this.ResultsAsync(source, text => text.ToUpperInvariant()), "de-DE", NullLogger.Instance, CancellationToken.None); var bytes = await File.ReadAllBytesAsync(target); using (Assert.EnterMultipleScope()) { Assert.That(bytes.Take(3), Is.EqualTo(new byte[] { 0xEF, 0xBB, 0xBF }), "The byte order mark stays."); Assert.That(Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3), Is.EqualTo("# TITLE\r\n\r\nSOME TEXT MORE TEXT.\r\n")); } } [Test] public async Task NewWordsWhichLookLikeMarkdownStayWords() { var source = await this.WriteSourceAsync("January 1 is a holiday.\n\n| Term | Meaning |\n|------|---------|\n| a | b |\n"); var target = Path.Join(this.testFolder, "target.md"); var results = await this.ResultsAsync(source, key => key switch { "January 1 is a holiday." => "1. Januar ist ein Feiertag.", "a" => "x | y", "b" => "5 * 3 [Beispiel]", _ => key, }); await this.format.WriteAsync(source, target, results, "de-DE", NullLogger.Instance, CancellationToken.None); var written = await File.ReadAllTextAsync(target); using (Assert.EnterMultipleScope()) { Assert.That(written, Does.StartWith("1\\. Januar ist ein Feiertag."), "Words at the start of a line which read as a list get an escape."); Assert.That(written, Does.Contain("| x \\| y | 5 \\* 3 \\[Beispiel\\] |"), "Characters of markup get an escape, a | in a cell above all."); Assert.That(MarkdownSegmentFormat.SegmentsOf(written).Select(segment => segment.Segment.Key), Is.EqualTo(new[] { "1. Januar ist ein Feiertag.", "Term", "Meaning", "x | y", "5 * 3 [Beispiel]" }), "The new words stay words: no list, no further column, no link."); } } [Test] public async Task EscapesAndEntitiesReachTheModelAsTheyRead() { var source = await this.WriteSourceAsync("Fish & Chips cost 5 \\* 3 \\| 2 © us.\n"); var keys = (await this.format.ReadAsync(source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList(); Assert.That(keys, Is.EqualTo(new[] { "Fish & Chips cost 5 * 3 | 2 © us." })); } [Test] public async Task ReferenceLinksKeepTheirDefinitions() { var source = await this.WriteSourceAsync("See [Markdig] and the [guide][] or the [manual][docs].\n\n[Markdig]: https://github.com/xoofx/markdig\n[guide]: https://example.org/guide\n[docs]: https://example.org/docs\n"); var target = Path.Join(this.testFolder, "target.md"); var results = await this.ResultsAsync(source, key => key == "See <1>Markdig and the <2>guide or the <3>manual." ? "Siehe <1>die Bibliothek und die <2>Anleitung oder das <3>Handbuch." : key); await this.format.WriteAsync(source, target, results, "de-DE", NullLogger.Instance, CancellationToken.None); var written = await File.ReadAllTextAsync(target); using (Assert.EnterMultipleScope()) { Assert.That(written, Does.StartWith("Siehe [die Bibliothek][Markdig] und die [Anleitung][guide] oder das [Handbuch][docs]."), "New words would name no definition, so the label of the source does."); Assert.That(MarkdownSegmentFormat.SegmentsOf(written).Select(segment => segment.Segment.Key), Is.EqualTo(new[] { "Siehe <1>die Bibliothek und die <2>Anleitung oder das <3>Handbuch." }), "All three stay links."); } } [Test] public async Task NewWordsWhichLookLikeMarkdownOfTheExtensionsStayWords() { var source = await this.WriteSourceAsync("First.\n\nSecond.\n\nThird.\n"); var target = Path.Join(this.testFolder, "target.md"); var newWords = new Dictionary { ["First."] = "A. Müller schrieb das.", ["Second."] = "IV. Ergebnisse", ["Third."] = "C++ und ==markiert== und \"\"zitiert\"\"", }; var results = await this.ResultsAsync(source, key => newWords[key]); await this.format.WriteAsync(source, target, results, "de-DE", NullLogger.Instance, CancellationToken.None); var written = await File.ReadAllTextAsync(target); Assert.That(MarkdownSegmentFormat.SegmentsOf(written).Select(segment => segment.Segment.Key), Is.EqualTo(newWords.Values), "No numbered list with a letter or a Roman numeral, no marked words, and no citation."); } [Test] public async Task WhiteSpaceAtTheEdgesOfAPairGoesOutsideOfItsMarkup() { var source = await this.WriteSourceAsync("Some **bold** words.\n"); var target = Path.Join(this.testFolder, "target.md"); var results = await this.ResultsAsync(source, _ => "Einige<1> fette Wörter."); await this.format.WriteAsync(source, target, results, "de-DE", NullLogger.Instance, CancellationToken.None); var written = await File.ReadAllTextAsync(target); using (Assert.EnterMultipleScope()) { Assert.That(written, Is.EqualTo("Einige **fette** Wörter.\n"), "Markdown shows no emphasis whose markup touches white space on its inner side."); Assert.That(MarkdownSegmentFormat.SegmentsOf(written).Single().Segment.Key, Is.EqualTo("Einige <1>fette Wörter.")); } } [Test] public async Task ALineBreakWhichTheModelDroppedStaysOut() { var source = await this.WriteSourceAsync("Line one\\\nline two\n"); var target = Path.Join(this.testFolder, "target.md"); var results = await this.ResultsAsync(source, _ => "Zeile eins und zwei"); await this.format.WriteAsync(source, target, results, "de-DE", NullLogger.Instance, CancellationToken.None); var written = await File.ReadAllTextAsync(target); Assert.That(written, Is.EqualTo("Zeile eins und zwei\n"), "After the words, the backslash of the line break would show."); } [Test] public async Task WordsWhichReadAsATagStayAsTheyAre() { var source = await this.WriteSourceAsync("Press <1> to continue.\n\nPress <1 /> as well.\n\nOther words.\n"); var keys = (await this.format.ReadAsync(source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList(); Assert.That(keys, Is.EqualTo(new[] { "Other words." }), "A model could not tell such words apart from tags, even when they come from two entities and the words between them."); } private async Task WriteSourceAsync(string text) { var path = Path.Join(this.testFolder, "source.md"); await File.WriteAllTextAsync(path, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); return path; } private async Task ResultsAsync(string path, Func transform) { var segments = await this.format.ReadAsync(path, 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)))); } }