using AIStudio.Tools;
namespace AIStudio.TrimSmokeTest;
///
/// Lets HTMLParser convert what its tests convert, because ReverseMarkdown is marked as trimmable since version 6.1.
///
///
/// The trimmer therefore removes every part of ReverseMarkdown which nothing but reflection reaches, and
/// Trimming.props suppresses the warnings which would name such a part. The converter of HTMLParser takes only the
/// built-in readers and writers, which need no reflection, and a preprocessing step of our own. The HTML and the
/// expected Markdown are those of HTMLParserConversionTests in app/Tests/Tools, which run untrimmed.
///
public static class MarkdownChecks
{
private const string TEASER_HTML =
"""
Code in a link: line one
line two
""";
private const string TEASER_MARKDOWN =
"""
- [Probe lands on the asteroid 22 minutes ago Example News](https://example.org/news/1)
- [Second headline A summary of it.](https://example.org/news/2)
- [Plain link text](https://example.org/news/3)
Code in a link: [](https://example.org/code)
```
line one
line two
```
""";
private const string CONFIGURATION_HTML =
"""
Heading & more
Text with an unknown tag, and a https://example.org link.
- First
- Second
""";
private const string CONFIGURATION_MARKDOWN =
"""
## Heading & more
Text with an unknown tag, and a https://example.org link.
1. First
- Nested
2. Second
| Name | Value |
| --- | --- |
| A < B | 1 |
""";
///
/// Returns a description of every conversion which fails or gives other Markdown than untrimmed.
///
/// One line per failure, naming the conversion and what went wrong.
public static IReadOnlyList FindFailures()
{
var failures = new List();
Expect(failures, "a teaser wrapped in a link", TEASER_HTML, TEASER_MARKDOWN);
Expect(failures, "headings, lists, a table, and links", CONFIGURATION_HTML, CONFIGURATION_MARKDOWN);
return failures;
}
///
/// Converts HTML and compares the Markdown with the expected one.
///
/// Where to add a failure.
/// What the HTML holds, completing "HTMLParser could not convert ...".
/// The HTML to convert.
/// The Markdown the conversion gives untrimmed.
private static void Expect(List failures, string what, string html, string expected)
{
string markdown;
try
{
markdown = HTMLParser.ParseToMarkdown(html).ReplaceLineEndings("\n");
}
catch (Exception exception)
{
//
// A member the trimmer removed surfaces as the innermost exception, e.g., below a TypeInitializationException:
//
var cause = exception.GetBaseException();
failures.Add($"HTMLParser could not convert {what}: {cause.GetType().Name}: {cause.Message}");
return;
}
if (markdown != expected.ReplaceLineEndings("\n"))
failures.Add($"HTMLParser converted {what} into '{markdown}' instead of '{expected.ReplaceLineEndings("\n")}'.");
}
}