Skip to content
Open
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
80 changes: 80 additions & 0 deletions TruePath.PathIoGenerator.Tests/CancellationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// SPDX-FileCopyrightText: 2026 TruePath contributors <https://github.com/ForNeVeR/TruePath>
//
// SPDX-License-Identifier: MIT

using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Xunit;

namespace TruePath.PathIoGenerator.Tests;

public sealed class CancellationTests
{
[Fact]
public void CancellationDuringDocumentationReadStopsTheRunAndAllowsRetry()
{
using var cancellation = new CancellationTokenSource();
var reads = 0;
var docs = new CallbackText("System.Runtime.xml", token =>
{
if (++reads == 1)
{
Assert.Equal(cancellation.Token, token);
cancellation.Cancel();
}
}, "<doc><members></members></doc>");
var compilation = TestHelper.CreateCompilation(TestHelper.DefaultSources);
GeneratorDriver driver = CSharpGeneratorDriver.Create(
new[] { new PathIoSourceGenerator().AsSourceGenerator() }, new[] { docs });

Assert.Throws<OperationCanceledException>(() => driver.RunGenerators(compilation, cancellation.Token));

driver = driver.RunGenerators(compilation, TestContext.Current.CancellationToken);
Assert.NotEmpty(driver.GetRunResult().GeneratedTrees);
Assert.Empty(driver.GetRunResult().Diagnostics);
}

[Fact]
public void CancellationDuringExclusionReadStopsTheRun()
{
using var cancellation = new CancellationTokenSource();
var exclusions = new CallbackText("path-io-exclusions.txt", token =>
{
Assert.Equal(cancellation.Token, token);
cancellation.Cancel();
});
var compilation = TestHelper.CreateCompilation(TestHelper.DefaultSources);
GeneratorDriver driver = CSharpGeneratorDriver.Create(
new[] { new PathIoSourceGenerator().AsSourceGenerator() }, new[] { exclusions });

Assert.Throws<OperationCanceledException>(() => driver.RunGenerators(compilation, cancellation.Token));
}

[Fact]
public void CoreOperationsHonorAnAlreadyCancelledToken()
{
var token = new CancellationToken(canceled: true);
var compilation = TestHelper.CreateCompilation(TestHelper.DefaultSources);
var markedType = compilation.GetTypeByMetadataName("TruePath.SystemIo.PathIo")!;

Assert.Throws<OperationCanceledException>(() => BclDocIndex.Build(ImmutableArray<AdditionalText>.Empty, token));
Assert.Throws<OperationCanceledException>(() => Exclusions.Parse(ImmutableArray<string>.Empty, token));
Assert.Throws<OperationCanceledException>(() => PathIoGeneratorCore.CollectUserDefinedMembersInfo(compilation, markedType, token));
Assert.Throws<OperationCanceledException>(() => PathIoGeneratorCore.Generate(
compilation, "TruePath.SystemIo.PathIo", false, UserDefinedMembersInfo.Empty,
ImmutableHashSet<string>.Empty, BclDocIndex.Build(ImmutableArray<AdditionalText>.Empty, TestContext.Current.CancellationToken), token));
}

private sealed class CallbackText(string path, Action<CancellationToken> callback, string text = "") : AdditionalText
{
public override string Path => path;

public override SourceText GetText(CancellationToken cancellationToken = default)
{
callback(cancellationToken);
return SourceText.From(text);
}
}
}
122 changes: 122 additions & 0 deletions TruePath.PathIoGenerator.Tests/DocumentationIndexTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// SPDX-FileCopyrightText: 2026 TruePath contributors <https://github.com/ForNeVeR/TruePath>
//
// SPDX-License-Identifier: MIT

using System.Collections.Immutable;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Xunit;

namespace TruePath.PathIoGenerator.Tests;

public sealed class DocumentationIndexTests
{
private const string Id = "M:System.IO.File.ReadAllText(System.String)";

[Theory]
[InlineData("\n")]
[InlineData("\r\n")]
[InlineData("\r")]
[InlineData("\u0085")]
[InlineData("\u2028")]
[InlineData("\u2029")]
public void ReadsRelevantMembersWithAnyLineEndingsAndTrailingWhitespace(string newline)
{
var text = string.Join(newline, new[]
{
"<doc><members>",
" <member name=\"M:System.String.Unrelated\"><invalid unrelated XML",
$"\t<member name=\"{Id}\">",
" <summary>first", "second</summary>", " </member> \t",
"</members></doc>"
});
var index = Build(new InMemoryAdditionalText("System.Runtime.xml", text));

Assert.True(index.TryGetMethodMember(Id, out var member));
Assert.Equal("first\nsecond", member.Element("summary")!.Value);
Assert.False(index.TryGetMethodMember("M:System.String.Unrelated", out _));
}

[Theory]
[InlineData(61)]
[InlineData(128)]
public void ReadsMembersWhoseOpeningTagCrossesOrFollowsThePrefixBuffer(int indentation)
{
var index = Build(new InMemoryAdditionalText("System.Runtime.xml", new string(' ', indentation)
+ $"<member name=\"{Id}\"><summary>valid</summary></member>"));

Assert.True(index.TryGetMethodMember(Id, out var member));
Assert.Equal("valid", member.Element("summary")!.Value);
}

[Fact]
public void ReadsSingleLineMembersAndSkipsMalformedMembers()
{
// Only netstandard.xml is parsed leniently, so this is the file where a malformed member is skipped.
var index = Build(new InMemoryAdditionalText("netstandard.xml", $"""
<doc><members>
<member name="M:System.IO.File.Broken"><summary></member>
<member name="{Id}"><summary>valid</summary></member>
<member name="M:System.IO.FileStream.Unrelated"><summary>ignored</summary></member>
<member name="M:System.IO.Directory.Delete(System.String)"><summary>directory</summary></member>
</members></doc>
"""));

Assert.False(index.TryGetMethodMember("M:System.IO.File.Broken", out _));
Assert.False(index.TryGetMethodMember("M:System.IO.FileStream.Unrelated", out _));
Assert.True(index.TryGetMethodMember(Id, out _));
Assert.True(index.TryGetMethodMember("M:System.IO.Directory.Delete(System.String)", out _));
}

[Fact]
public void FrameworkDocumentationWinsOverStandardDocumentation()
{
// A malformed framework member is a hard parse error now, so the merge only ever sees valid members; the
// framework-specific file must still take precedence over the standard one.
var index = Build(
new InMemoryAdditionalText("System.Runtime.xml", $"<member name=\"{Id}\"><summary>framework</summary></member>"),
new InMemoryAdditionalText("netstandard.xml", $"<member name=\"{Id}\"><summary>standard</summary></member>"));

Assert.True(index.TryGetMethodMember(Id, out var member));
Assert.Equal("framework", member.Element("summary")!.Value);
}

[Fact]
public void PublicLookupCannotMutateTheCachedMember()
{
var index = Build(new InMemoryAdditionalText("System.Runtime.xml",
$"<member name=\"{Id}\"><summary>original</summary></member>"));
Assert.True(index.TryGetMethodMember(Id, out var first));
first.ReplaceAll(new XElement("summary", "changed"));

Assert.True(index.TryGetMethodMember(Id, out var second));
Assert.Equal("original", second.Element("summary")!.Value);
}

[Fact]
public void FormattingPreservesIndependentFragmentsEscapingAndNamespaces()
{
var member = XElement.Parse("""
<member>
<summary>A &amp; B <paramref name="sourceFileName" /></summary>
<param name="sourceFileName">Path &lt;value&gt;</param>
<returns><d:item xmlns:d="urn:docs">result</d:item></returns>
<remarks><d:item xmlns:d="urn:docs">details</d:item></remarks>
</member>
""");

var lines = DocFormatting.ToDocLines(member, ImmutableArray.Create("sourceFile"), TestContext.Current.CancellationToken);

Assert.Equal(new[]
{
"<summary>A &amp; B <paramref name=\"sourceFile\"/></summary>",
"<param name=\"sourceFile\">Path &lt;value&gt;</param>",
"<returns><d:item xmlns:d=\"urn:docs\">result</d:item></returns>",
"<remarks><d:item xmlns:d=\"urn:docs\">details</d:item></remarks>"
}, lines);
Assert.Equal("sourceFileName", member.Element("param")!.Attribute("name")!.Value);
}

private static BclDocIndex Build(params AdditionalText[] files) =>
BclDocIndex.Build(files.ToImmutableArray(), TestContext.Current.CancellationToken);
}
Loading
Loading