GeezerVison is showing github.com — fix(mocks): bind explicit method type arguments on Mock.Of<IGeneric<X>>() by thomhurst · Pull Request #7406 · thomhurst/TUnit
fix(mocks): bind explicit method type arguments on Mock.Of<IGeneric<X>>()
#7406
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter
Filter by extension
.cs
(6)
.txt
(3)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
fix(mocks): normalize closed signatures without recursive substitution (
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
commit 8741dd581a925831f9901fdf394a8659bd54d989
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -78,9 +78,10 @@ public static EquatableArray<ClosedGenericMethodSetupEmission> ResolveMethodSetu
var emissions = new List<ClosedGenericMethodSetupEmission>();
foreach (var (registration, model) in Pair(registrations, models))
{
if (MockMembersBuilder.GetClosedReceiverGenericMethods(model, registration.TypeArguments).Count > 0)
var methods = MockMembersBuilder.GetClosedReceiverGenericMethods(model, registration.TypeArguments);
if (methods.Count > 0)
{
emissions.Add(new ClosedGenericMethodSetupEmission(model, registration.ClosedTypeFullyQualifiedName, registration.TypeArguments));
emissions.Add(new ClosedGenericMethodSetupEmission(model, registration.ClosedTypeFullyQualifiedName, registration.TypeArguments, new EquatableArray<MockMemberModel>(methods.ToImmutableArray()) ));
}
}
Expand All
@@ -105,14 +106,21 @@ public static string BuildMethodSetups(EquatableArray<ClosedGenericMethodSetupEm
writer.AppendLine("#pragma warning disable");
writer.AppendLine("#nullable enable");
// Keep aliases out of the member-surface namespace, where user types can share
// their names. Global imports preserve the setup surface for every consuming file.
for (var i = 0; i < emissions.Length; i++)
{
writer.AppendLine($"global using {MockImplBuilder.MemberSurfaceNamespace}.ClosedGenericMethodSetups_{i.ToString(CultureInfo.InvariantCulture)};");
}
var index = 0;
foreach (var emission in emissions)
{
var model = emission.Model;
var safeName = MockImplBuilder.GetCompositeSafeName(model);
writer.AppendLine();
using (writer.Block($"namespace {MockImplBuilder.MemberSurfaceNamespace}"))
using (writer.Block($"namespace {MockImplBuilder.MemberSurfaceNamespace}.ClosedGenericMethodSetups_{index.ToString(CultureInfo.InvariantCulture)} "))
{
for (var i = 0; i < model.TypeParameters.Length; i++)
{
Expand All
@@ -125,7 +133,7 @@ public static string BuildMethodSetups(EquatableArray<ClosedGenericMethodSetupEm
using (writer.Block($"extension(global::TUnit.Mocks.Mock<{MockImplBuilder.GetMockableTypeName(model)}> mock)"))
{
var first = true;
foreach (var method in MockMembersBuilder.GetClosedReceiverGenericMethods(model, emission.TypeArguments) )
foreach (var method in emission.Methods )
{
if (!first) writer.AppendLine();
first = false;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -981,10 +981,15 @@ private sealed class ClosedSignatureRewriter : CSharpSyntaxRewriter
{
private readonly Dictionary<string, TypeSyntax> _substitutions = new(System.StringComparer.Ordinal);
private ClosedSignatureRewriter() { }
public ClosedSignatureRewriter(MockTypeModel model, EquatableArray<string> arguments, MockMemberModel method)
{
// Closed arguments contain no model or method parameters. Normalize them separately
// so a canonical method name can never capture a name inside a replacement.
var normalizer = new ClosedSignatureRewriter();
for (var i = 0; i < model.TypeParameters.Length; i++)
_substitutions[model.TypeParameters[i].Name] = SyntaxFactory.ParseTypeName(arguments[i]);
_substitutions[model.TypeParameters[i].Name] = (TypeSyntax)normalizer.Visit( SyntaxFactory.ParseTypeName(arguments[i]))! ;
for (var i = 0; i < method.TypeParameters.Length; i++)
_substitutions[method.TypeParameters[i].Name] = SyntaxFactory.IdentifierName("__MethodType" + i.ToString(CultureInfo.InvariantCulture));
}
Expand All
@@ -994,7 +999,7 @@ public ClosedSignatureRewriter(MockTypeModel model, EquatableArray<string> argum
if (node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax)
return base.VisitIdentifierName(node);
if (_substitutions.TryGetValue(node.Identifier.ValueText, out var replacement))
return Visit( replacement) ;
return replacement;
return node.Identifier.ValueText switch
{
"dynamic" => SyntaxFactory.ParseTypeName("global::System.Object"),
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -35,7 +35,9 @@ internal readonly record struct ClosedGenericFactoryEmission(
/// <param name="Model">The open mock generated for the registration.</param>
/// <param name="ClosedTypeFullyQualifiedName">The closed interface, e.g. <c>global::Ns.IRepository<int></c>.</param>
/// <param name="TypeArguments">Every type argument, in model type-parameter order.</param>
/// <param name="Methods">The collision-checked methods, computed once per registration.</param>
internal sealed record ClosedGenericMethodSetupEmission(
MockTypeModel Model,
string ClosedTypeFullyQualifiedName,
EquatableArray<string> TypeArguments);
EquatableArray<string> TypeArguments,
EquatableArray<MockMemberModel> Methods);
Original file line number
Diff line number
Diff line change
Expand Up
@@ -41,6 +41,58 @@ public struct Point
private const string SetupsFileMarker = "_ClosedMockMemberExtensions_";
[Test]
public async Task Nullable_Containers_Are_Kept_And_Nullable_Model_Elements_Are_Skipped()
{
var setups = GetSetupsSource("""
#nullable enable
namespace TestNamespace
{
public interface INullable<T>
{
U List<U>(System.Collections.Generic.List<T>? value);
U Array<U>(T[]? value);
U Dictionary<U>(System.Collections.Generic.Dictionary<T, U?> value);
U Elements<U>(System.Collections.Generic.IEnumerable<T?> value);
}
public class Usage
{
void M() => _ = TUnit.Mocks.Mock.Of<INullable<int>>();
}
}
""");
await Assert.That(setups).IsNotNull();
await Assert.That(setups!).Contains(" List<U>(");
await Assert.That(setups).Contains(" Array<U>(");
await Assert.That(setups).Contains(" Dictionary<U>(");
await Assert.That(setups).DoesNotContain(" Elements<U>(");
}
[Test]
public async Task Canonical_Method_Type_Parameter_Names_Do_Not_Recurse_Or_Capture()
{
var setups = GetSetupsSource("""
namespace TestNamespace
{
public interface ICanonical<T>
{
U Map<U>(U value);
__MethodType0 Map<__MethodType0>(int key, __MethodType0 value);
U Collapse<U>(T value);
__MethodType0 Collapse<__MethodType0>(int value);
}
public class Usage
{
void M() => _ = TUnit.Mocks.Mock.Of<ICanonical<int>>();
}
}
""");
await Assert.That(setups).IsNotNull();
await Assert.That(setups!).Contains(" Map<U>(");
await Assert.That(setups).Contains(" Map<__MethodType0>(");
await Assert.That(setups).DoesNotContain(" Collapse<");
}
[Test]
public async Task Overloads_That_Collapse_After_Substitution_Are_Omitted()
{
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -28,8 +28,10 @@ file static class ClosedGenericMockFactories
// <auto-generated/>
#pragma warning disable
#nullable enable
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_0;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_1;
namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_0
{
using TContext = int;
Expand Down
Expand Up
@@ -81,7 +83,7 @@ namespace TUnit.Mocks.Generated
}
}
namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_1
{
using TContext = string;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -48,8 +48,14 @@ file static class ClosedGenericMockFactories
// <auto-generated/>
#pragma warning disable
#nullable enable
namespace TUnit.Mocks.Generated
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_0;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_1;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_2;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_3;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_4;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_5;
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_0
{
using T = int;
Expand All
@@ -73,7 +79,7 @@ namespace TUnit.Mocks.Generated
}
}
namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_1
{
using T = int;
Expand All
@@ -97,7 +103,7 @@ namespace TUnit.Mocks.Generated
}
}
namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_2
{
using T = string;
Expand All
@@ -121,7 +127,7 @@ namespace TUnit.Mocks.Generated
}
}
namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_3
{
using T = int;
Expand Down
Expand Up
@@ -160,7 +166,7 @@ namespace TUnit.Mocks.Generated
}
}
namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_4
{
using T = string;
Expand Down
Expand Up
@@ -212,7 +218,7 @@ namespace TUnit.Mocks.Generated
}
}
namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_5
{
using T = int;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -387,8 +387,9 @@ file static class ClosedGenericMockFactories
// <auto-generated/>
#pragma warning disable
#nullable enable
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_0;
namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_0
{
using Int32 = string;
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,21 @@
using TUnit.Mocks;
namespace TUnit.Mocks.Generated
{
// An existing user type must not interfere with the namespace-scoped closed alias.
public sealed class TContext;
}
namespace TUnit.Mocks.Tests
{
public class Issue7302AliasTests
{
[Test]
public async Task User_Type_With_The_Alias_Name_Does_Not_Change_Closed_Setups()
{
var mock = Mock.Of<IMessageInvoker7302<int>>();
mock.RoundTrip<long>(1, 2L).Returns(3L);
await Assert.That(mock.Object.RoundTrip(1, 2L)).IsEqualTo(3L);
}
}
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -25,6 +25,14 @@ public interface IOverloadedInvoker7302<T>
TResult Keep<TResult>(T value);
}
public interface ICanonicalInvoker7302<T>
{
U Map<U>(U value);
__MethodType0 Map<__MethodType0>(int key, __MethodType0 value);
U Collapse<U>(T value);
__MethodType0 Collapse<__MethodType0>(int value);
}
public class Outer7302<TOuter>
{
public interface IInner<TInner>
Expand All
@@ -45,6 +53,16 @@ public struct Point7302
/// </summary>
public class Issue7302Tests
{
[Test]
public async Task Canonical_Method_Type_Parameter_Names_Compile_And_Keep_Distinct_Setups()
{
var mock = Mock.Of<ICanonicalInvoker7302<int>>();
mock.Map<string>(Arg.Any<string>()).Returns("first");
mock.Map<string>(1, Arg.Any<string>()).Returns("second");
await Assert.That(mock.Object.Map("x")).IsEqualTo("first");
await Assert.That(mock.Object.Map(1, "x")).IsEqualTo("second");
}
[Test]
public async Task Closing_Overloads_Does_Not_Break_Compilation_Or_Unrelated_Setups()
{
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.