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
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.10" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.10" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.10" />
<PackageVersion Include="Microsoft.Kiota.Abstractions" Version="1.22.2" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.8.1" />
<PackageVersion Include="Microsoft.Playwright" Version="1.61.0" />
<PackageVersion Include="Microsoft.TemplateEngine.Authoring.TemplateVerifier" Version="10.0.302" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,7 @@ private static MockMemberModel CreateMethodModel(IMethodSymbol method, ref int m
Constraints = tp.GetGenericConstraints(),
HasReferenceTypeConstraint = tp.HasReferenceTypeConstraint,
HasValueTypeConstraint = tp.HasValueTypeConstraint,
HasAnnotatedNullableUsage = tp.IsUnconstrainedWithNullableUsage(method)
HasAnnotatedNullableUsage = tp.NeedsDefaultConstraintForNullableUsage(method)
}).ToImmutableArray()
),
ExplicitInterfaceName = explicitInterfaceName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,13 @@ public static string GetGenericConstraints(this ITypeParameterSymbol typeParam)
return string.Join(", ", constraints);
}

public static bool IsUnconstrainedWithNullableUsage(this ITypeParameterSymbol typeParam, IMethodSymbol method)
public static bool NeedsDefaultConstraintForNullableUsage(this ITypeParameterSymbol typeParam, IMethodSymbol method)
{
if (!typeParam.IsUnconstrained())
// On overrides and explicit interface implementations, T? is parsed as Nullable<T>
// unless T is known to be a reference/value type or a 'where T : default' clause is
// present. Interface-only constraints (e.g. Kiota's 'where T : IParsable') leave T
// unknown, so they need 'default' too — not just fully unconstrained parameters (#6456).
if (typeParam.IsReferenceType || typeParam.IsValueType)
{
return false;
}
Expand Down
62 changes: 62 additions & 0 deletions tests/TUnit.Mocks.SourceGenerator.Tests/KiotaMockTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using Microsoft.CodeAnalysis;
using Microsoft.Kiota.Abstractions;

namespace TUnit.Mocks.SourceGenerator.Tests;

/// <summary>
/// Regression tests for #6456: mocking Microsoft.Kiota.Abstractions.IRequestAdapter, whose
/// generic methods carry an interface constraint (where ModelType : IParsable). Explicit
/// interface implementations inherit constraints, but T? in them is parsed as Nullable&lt;T&gt;
/// unless a 'where T : default' clause is emitted — which is required whenever T is not known
/// to be a reference or value type, not just when T is fully unconstrained.
/// </summary>
public class KiotaMockTests : SnapshotTestBase
{
private const string Source = """
using Microsoft.Kiota.Abstractions;
using TUnit.Mocks;

[assembly: GenerateMock(typeof(IRequestAdapter))]
""";

private static IEnumerable<MetadataReference> KiotaReferences() =>
[MetadataReference.CreateFromFile(typeof(IRequestAdapter).Assembly.Location)];

[Test]
public void KiotaIRequestAdapter_ConstrainedGenericMethod_EmitsDefaultConstraint()
{
var output = string.Join("\n", RunGenerator(Source, KiotaReferences()));
Comment thread
thomhurst marked this conversation as resolved.

// SendAsync<ModelType> has 'where ModelType : IParsable' and returns Task<ModelType?>;
// its explicit implementation must carry 'where ModelType : default'.
AssertContains(output,
"global::Microsoft.Kiota.Abstractions.IRequestAdapter.SendAsync<ModelType>");
AssertContains(output, "where ModelType : default");
}

[Test]
public void KiotaIRequestAdapter_GeneratedMock_HasNoConstraintErrors()
{
var errors = GetGeneratedCompilationErrors(Source, KiotaReferences());

// The exact errors reported in #6456. Other diagnostics (e.g. CS1520/CS1513 from C# 14
// extension() blocks that the test-pinned Roslyn cannot parse) are infra limitations
// and intentionally not asserted here — see SnapshotTestBase.
foreach (var id in (string[])["CS0539", "CS0535", "CS0453", "CS0314"])
{
var match = errors.FirstOrDefault(e => string.Equals(e.Id, id, StringComparison.Ordinal));
if (match is not null)
{
throw new InvalidOperationException($"Generated code produced {id}: {match}");
}
}
}

private static void AssertContains(string text, string expected)
{
if (!text.Contains(expected, StringComparison.Ordinal))
{
throw new InvalidOperationException($"Expected generated output to contain: {expected}");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.SourceGenerators.Testing" />
<PackageReference Include="Microsoft.Kiota.Abstractions" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" />
<PackageReference Include="Verify" />
<PackageReference Include="Verify.TUnit" />
Expand Down
51 changes: 51 additions & 0 deletions tests/TUnit.Mocks.Tests/Issue6456Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Serialization;
using TUnit.Mocks;

namespace TUnit.Mocks.Tests;

/// <summary>
/// Regression tests for #6456: Microsoft.Kiota.Abstractions.IRequestAdapter could not be mocked
/// because its generic methods carry 'where ModelType : IParsable'. The generated explicit
/// interface implementations omitted the 'where ModelType : default' clause, so the compiler
/// parsed Task&lt;ModelType?&gt; as Task&lt;Nullable&lt;ModelType&gt;&gt; (CS0453/CS0539/CS0535/CS0314).
/// </summary>
public class Issue6456Tests
{
private sealed class TestModel : IParsable
{
public IDictionary<string, Action<IParseNode>> GetFieldDeserializers() =>
new Dictionary<string, Action<IParseNode>>();

public void Serialize(ISerializationWriter writer)
{
}
}

[Test]
public async Task SendNoContentAsync_Can_Be_Mocked_And_Verified()
{
var mock = IRequestAdapter.Mock();
var requestInfo = new RequestInformation();

await mock.Object.SendNoContentAsync(requestInfo);

mock.SendNoContentAsync(Any(), Any(), Any()).WasCalled(Times.Once);
}

[Test]
public async Task SendAsync_With_Constrained_Generic_Returns_Configured_Value()
{
var mock = IRequestAdapter.Mock();
var expected = new TestModel();
mock.SendAsync<TestModel>(Any(), Any(), Any(), Any()).Returns(expected);

var result = await mock.Object.SendAsync(
new RequestInformation(),
static _ => new TestModel(),
errorMapping: null,
CancellationToken.None);

await Assert.That(result).IsSameReferenceAs(expected);
}
}
1 change: 1 addition & 0 deletions tests/TUnit.Mocks.Tests/TUnit.Mocks.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<ItemGroup>
<PackageReference Include="Azure.Data.Tables" />
<PackageReference Include="Azure.Storage.Blobs" />
<PackageReference Include="Microsoft.Kiota.Abstractions" />
<ProjectReference Include="..\..\src\TUnit.Mocks\TUnit.Mocks.csproj" />

</ItemGroup>
Expand Down
Loading