Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Docs/pages/01-automated/01-moq.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ dispenser.Mock.Verify.Dispense("Dark", It.IsAny<int>()).Once();

</ApplyFix>

Strict mocks get a [behavior](../../04-create-mocks.md#customizing-mock-behavior) that throws when no setup matches. Properties, raising events and verifying subscriptions are migrated as well:
Strict mocks get a [behavior](../../04-create-mocks.md#customizing-mock-behavior) that throws when no setup matches, written as `Mockolate.MockBehavior` because Moq has a `MockBehavior` as well. Properties, raising events and verifying subscriptions are migrated as well:

<ApplyFix id="MockolateM001" migrateTo="Mockolate">

Expand All @@ -46,7 +46,7 @@ dispenser.VerifyAdd(m => m.ChocolateDispensed += It.IsAny<ChocolateDispensedDele
```

```csharp title="After (Mockolate)"
IChocolateDispenser dispenser = IChocolateDispenser.CreateMock(MockBehavior.Default.ThrowingWhenNotSetup());
IChocolateDispenser dispenser = IChocolateDispenser.CreateMock(Mockolate.MockBehavior.Default.ThrowingWhenNotSetup());
dispenser.Mock.Setup.TotalDispensed.InitializeWith(10);
dispenser.Mock.Raise.ChocolateDispensed("Dark", 2);
dispenser.Mock.Verify.ChocolateDispensed.Subscribed().Once();
Expand Down
92 changes: 92 additions & 0 deletions Tests/Mockolate.Migration.Tests/Docs/ApplyFixBox.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RegexMatch = System.Text.RegularExpressions.Match;

namespace Mockolate.Migration.Tests.Docs;

/// <summary>
/// An <c>&lt;ApplyFix id="…"&gt;</c> box of a documentation page that starts at the one-based
/// <paramref name="Line" />, with the code of its <c>```csharp</c> blocks.
/// </summary>
/// <remarks>
/// The docs site shows the first block as the code before the migration and the second block, behind a "Migrate"
/// button, as the code after it.
/// </remarks>
public sealed partial record ApplyFixBox(string Page, int Line, string Id, IReadOnlyList<string> Blocks)
{
/// <summary>
/// Extracts the <c>ApplyFix</c> boxes from the <paramref name="lines" /> of the <paramref name="page" />, without
/// the Docusaurus highlight comment lines of their blocks.
/// </summary>
public static List<ApplyFixBox> Extract(string page, string[] lines)
{
List<ApplyFixBox> boxes = [];
ApplyFixBox? box = null;
int i = 0;
while (i < lines.Length)
{
string line = lines[i++];
RegexMatch opening =Opening().Match(line);
if (opening.Success)
{
box = new ApplyFixBox(page, i, opening.Groups["id"].Value, []);
}
else if (box is not null && Closing().IsMatch(line))
{
boxes.Add(box);
box = null;
}
else if (Fence().Match(line) is { Success: true, } fence)
{
string? code = ReadBlock(lines, ref i, fence);
if (box is not null && code is not null)
{
box = box with { Blocks = [..box.Blocks, code,], };
}
}
}

return boxes;
}

/// <inheritdoc />
public override string ToString()
=> $"{Page}:{Line}";

private static string? ReadBlock(string[] lines, ref int i, RegexMatch fence)
{
string marker = fence.Groups["fence"].Value;
int start = i;
while (i < lines.Length && !IsClosing(lines[i], marker))
{
i++;
}

int end = i++;
if (!fence.Groups["info"].Value.TrimStart().StartsWith("csharp", StringComparison.Ordinal))
{
return null;
}

return string.Join("\n", lines[start..end].Where(line => !Highlight().IsMatch(line)));
}

private static bool IsClosing(string line, string fence)
{
string trimmed = line.Trim();
return trimmed.Length >= fence.Length && trimmed.All(c => c == fence[0]);
}

[GeneratedRegex("""^\s*<ApplyFix\b[^>]*\bid="(?<id>[^"]+)"[^>]*>\s*$""")]
private static partial Regex Opening();

[GeneratedRegex(@"^\s*</ApplyFix>\s*$")]
private static partial Regex Closing();

[GeneratedRegex(@"^\s*(?<fence>`{3,}|~{3,})(?<info>.*)$")]
private static partial Regex Fence();

[GeneratedRegex(@"^\s*//\s*highlight-(next-line|start|end)\s*$")]
private static partial Regex Highlight();
}
106 changes: 106 additions & 0 deletions Tests/Mockolate.Migration.Tests/Docs/ApplyFixTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Mockolate.Migration.Tests.Docs;

public sealed class ApplyFixTests
{
private static readonly string PagesDirectory = GetPagesDirectory();

public static IEnumerable<ApplyFixBox> Boxes()
=> Directory.EnumerateFiles(PagesDirectory, "*.md*", SearchOption.AllDirectories)
.Order(StringComparer.Ordinal)
.SelectMany(path => ApplyFixBox.Extract(
$"Docs/pages/{Path.GetRelativePath(PagesDirectory, path).Replace('\\', '/')}",
File.ReadAllLines(path)));

[Test]
[MethodDataSource(nameof(Boxes))]
public async Task ApplyFix_ShouldShowTheResultOfTheCodeFix(ApplyFixBox box)
{
Fail.Unless(box.Blocks.Count == 2,
$"The ApplyFix box at {box} must contain two csharp blocks, but contains {box.Blocks.Count}.");

CodeFixRunner.Result result = await CodeFixRunner.ApplyAsync(box.Id, box.Blocks[0], box.Blocks[1]);

Fail.Unless(result.Errors.Count == 0,
$"The code fix could not migrate the code of the ApplyFix box at {box}:\n{string.Join("\n", result.Errors)}");
Fail.Unless(result.Actual == result.Expected,
$"The code after the migration in the ApplyFix box at {box} differs from the result of the code fix.\n" +
$"Expected (page):\n{result.Expected}\n\nActual (code fix):\n{result.Actual}");
}

[Test]
public async Task Boxes_ShouldFindTheApplyFixBoxesOfAllPages()
{
int count = Boxes().Count();

await That(count).IsGreaterThanOrEqualTo(4)
.Because("the check must not pass because it no longer finds the ApplyFix boxes");
}

[Test]
public async Task Extract_ShouldFindBothBlocksOfABox()
{
string[] lines =
[
"```csharp",
"int outside = 0;",
"```",
"<ApplyFix id=\"MockolateM001\" migrateTo=\"Mockolate\">",
"",
"```csharp title=\"Before (Moq)\"",
"int before = 1;",
"```",
"",
"```csharp title=\"After (Mockolate)\"",
"int after = 2;",
"```",
"",
"</ApplyFix>",
];

List<ApplyFixBox> boxes = ApplyFixBox.Extract("page.md", lines);

await That(boxes).HasSingle().Which.Satisfies(box => box.Page == "page.md" && box.Line == 4 && box.Id == "MockolateM001");
await That(boxes[0].Blocks).IsEqualTo(["int before = 1;", "int after = 2;",])
.Because("blocks outside of an ApplyFix box are not part of it");
}

[Test]
public async Task Extract_ShouldRemoveTheHighlightCommentLines()
{
string[] lines =
[
"<ApplyFix id=\"MockolateM002\" migrateTo=\"Mockolate\">",
"```csharp",
"// highlight-next-line",
"int a = 1;",
" // highlight-start",
"int b = 2;",
"// highlight-end",
"// a comment",
"```",
"</ApplyFix>",
];

List<ApplyFixBox> boxes = ApplyFixBox.Extract("page.md", lines);

await That(boxes).HasSingle().Which.Satisfies(box => box.Blocks.Count == 1);
await That(boxes[0].Blocks[0]).IsEqualTo("int a = 1;\nint b = 2;\n// a comment");
}

private static string GetPagesDirectory()
{
DirectoryInfo? directory = new(AppContext.BaseDirectory);
while (directory is not null && !Directory.Exists(Path.Combine(directory.FullName, "Docs", "pages")))
{
directory = directory.Parent;
}

return directory is null
? throw new DirectoryNotFoundException($"No Docs/pages above {AppContext.BaseDirectory}")
: Path.Combine(directory.FullName, "Docs", "pages");
}
}
Loading
Loading