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
28 changes: 28 additions & 0 deletions Docs/pages/03-create-mocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,34 @@ await That(counter.Mock.ConstructorArgument<string>("label")).IsEqualTo("42 piec

</details>

<details>
<summary>Interface members with a default implementation</summary>

An interface mock implements the public members of the interface, also those with a default implementation, and does not call the default implementation: without a setup, such a member returns the default value like any other member. A non-public member with a default implementation keeps it.

A derived interface can declare an inherited member abstract again, and an interface can inherit two default implementations of the same member, neither of which is more specific than the other. Then there is no default implementation to keep, so the mock implements the member, without calling any of the default implementations:

```csharp
public interface IChocolateStock
{
int Count() => 0;
}

public interface IChocolateShelf : IChocolateStock
{
abstract int IChocolateStock.Count();
}

IChocolateShelf shelf = IChocolateShelf.CreateMock();
shelf.Mock.Setup.Count().Returns(12);

await That(((IChocolateStock)shelf).Count()).IsEqualTo(12);
```

A non-public member is implemented explicitly, like an abstract one, and set up and verified as described in [Non-public interface members](08-advanced-features/01-protected-members.md#non-public-interface-members). When your assembly cannot access it, for example an `internal` member of a referenced assembly that does not grant `InternalsVisibleTo`, the type cannot be mocked and [Mockolate0002](10-analyzers.md#mockolate0002) reports it. The same holds for a mock of several types with [`Implementing<T>()`](#implementing-additional-interfaces) when only the combination of the types leaves a non-public member without a default implementation to keep.

</details>

:::note

A class mock overrides the `virtual` and `abstract` members of the class. Non-virtual members cannot be intercepted
Expand Down
2 changes: 1 addition & 1 deletion Docs/pages/08-advanced-features/01-protected-members.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,4 @@ public async Task CanDispense_ShouldCheckTheStock()
}
```

A non-public member with a default implementation keeps it, because the explicit implementation of the mock could not call the default implementation. An abstract `internal` or `private protected` member of an interface from another assembly cannot be implemented unless that assembly grants your test assembly `InternalsVisibleTo`, so [Mockolate0002](../10-analyzers.md#mockolate0002) reports the interface.
A non-public member with a default implementation keeps it, because the explicit implementation of the mock could not call the default implementation. When a derived interface declares the member abstract again, or the interface inherits two default implementations of which neither is more specific, there is none to keep, and the mock implements the member like an abstract one (see [Interface members with a default implementation](../03-create-mocks.md)). An abstract `internal` or `private protected` member of an interface from another assembly cannot be implemented unless that assembly grants your test assembly `InternalsVisibleTo`, so [Mockolate0002](../10-analyzers.md#mockolate0002) reports the interface.
4 changes: 2 additions & 2 deletions Docs/pages/10-analyzers.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ This rule prevents you from mocking unsupported types:
- `CreateMock(out ConstructorArguments arguments)`: the type must be a sealed class or a record that your assembly can access, with a single accessible constructor with the most parameters, or one marked with `[ActivatorUtilitiesConstructor]`, that sets all `required` members. It must not be abstract, generic or nested in a generic type, obsolete, file-local, in the `System`, `Microsoft` or `Windows` namespaces, or have a member named `CreateMock` or inherit one that hides the generated one.
- `Implementing<T>()`: the type must be an interface.

It also fires when the type has a member that the mock would have to implement (an abstract member, or an interface member without a default implementation), but for which no implementation compiles: a member your assembly cannot access, for example an `internal abstract` or `private protected abstract` member, or a `{ get; internal set; }` property, on a type from a referenced assembly that does not grant `InternalsVisibleTo`, a generic method whose type parameter constraints contradict each other once the type is closed, such as `where U : class, T` with `T` as `int`, or a member with a pointer or function pointer type in its signature, such as `int* GetBuffer()`. There is no valid code a mock could emit for such a member, so the type cannot be mocked at all.
It also fires when the type has a member that the mock would have to implement (an abstract member, an interface member without a default implementation, an interface member that a derived interface declares abstract again, or one with two inherited default implementations of which neither is more specific), but for which no implementation compiles: a member your assembly cannot access, for example an `internal abstract` or `private protected abstract` member, or a `{ get; internal set; }` property, on a type from a referenced assembly that does not grant `InternalsVisibleTo`, a generic method whose type parameter constraints contradict each other once the type is closed, such as `where U : class, T` with `T` as `int`, or a member with a pointer or function pointer type in its signature, such as `int* GetBuffer()`. There is no valid code a mock could emit for such a member, so the type cannot be mocked at all.

<details>
<summary>When a derived type already implements the inaccessible member</summary>
Expand Down Expand Up @@ -88,7 +88,7 @@ override further down that implements the setter makes the type mockable. The mo
A pointer type can only be used in unsafe code, which your test project may not allow, and it cannot be a type argument of a setup. Mockolate therefore leaves every member alone that uses a pointer or function pointer type in its signature, also as an array element or a type argument (`int*[]`, `List<int*[]>`), and every event whose delegate does:

- A `virtual` class member and an interface member with a default implementation keep their implementation. They get no `Setup` or `Verify` members, and the rest of the type is mocked as usual.
- An `abstract` member, or an interface member without a default implementation, makes the rule fire, as does a delegate with such a signature.
- An `abstract` member, or an interface member without a single most specific default implementation, makes the rule fire, as does a delegate with such a signature.
- A constructor with a pointer parameter cannot be called through `CreateMock`. The rule fires when every constructor that the mock could call has one.
- A type with a pointer type as a type argument, such as `IChocolateBuffer<int*[]>`, and an interface that inherits one make the rule fire, because the mock would have to name that type.

Expand Down
110 changes: 89 additions & 21 deletions Source/Mockolate.Analyzers/MockabilityAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,18 @@ private static void AnalyzeImplementing(SyntaxNodeAnalysisContext context,
return;
}

if (FindMemberRequiredByCombination(context.SemanticModel, memberAccess, typeArgument) is { } member)
{
context.ReportDiagnostic(Diagnostic.Create(
Rules.MockabilityRule,
typeArgumentLocation,
typeArgument.ToDisplayString(),
FindPointerType(member) is { } pointerType
? $"together with the other mocked types, the member '{member.ToDisplayString()}' must be implemented, but its signature uses the type '{pointerType.ToDisplayString()}', and pointer types are not supported"
: $"together with the other mocked types, the member '{member.ToDisplayString()}' must be implemented, but it is not public, and a mock of several types cannot implement it"));
return;
}

spellings.Add(new MockedSpelling(typeArgument, typeArgumentLocation));

if (GetImplementingChain(context, memberAccess) is { } chain)
Expand Down Expand Up @@ -682,6 +694,50 @@ private static bool IsImplementedByClassOverride(ITypeSymbol mockedType, ISymbol
{ ContainingType.TypeKind: not TypeKind.Interface, } implementation &&
IsOverriddenByGenerator(implementation, isInterface: false);

/// <summary>
/// The member that the mock of the types in the <c>Implementing&lt;T&gt;()</c> chain up to
/// <paramref name="typeArgument" /> cannot implement, because only adding <paramref name="typeArgument" /> makes it
/// required (see <c>InterfaceImplementations.FindMemberRequiredByCombination</c>), or <see langword="null" />.
/// </summary>
private static ISymbol? FindMemberRequiredByCombination(SemanticModel semanticModel,
MemberAccessExpressionSyntax memberAccess, ITypeSymbol typeArgument)
{
List<ITypeSymbol> types = [typeArgument,];
ExpressionSyntax receiver = memberAccess.Expression;
while (receiver is InvocationExpressionSyntax
{
Expression: MemberAccessExpressionSyntax
{
Name: GenericNameSyntax { Identifier.ValueText: "Implementing", },
} innerAccess,
} innerInvocation)
{
if (semanticModel.GetSymbolInfo(innerInvocation).Symbol is not IMethodSymbol innerMethod ||
AnalyzerHelpers.GetSingleInvocationTypeArgumentOrNull(innerMethod) is not { } innerType)
{
return null;
}

types.Insert(0, innerType);
receiver = innerAccess.Expression;
}

if (semanticModel.GetTypeInfo(memberAccess.Expression).Type is not { } mockedType)
{
return null;
}

types.Insert(0, mockedType);
return InterfaceImplementations.FindMemberRequiredByCombination(types, CannotBeCombined) is { } member &&
InterfaceImplementations.FindMemberRequiredByCombination(types.GetRange(0, types.Count - 1),
CannotBeCombined) is null
? member
: null;

static bool CannotBeCombined(ISymbol member)
=> HasNonPublicPart(member) || FindPointerType(member) is not null;
}

/// <summary>
/// Reports every mocked spelling of a type that is also mocked in another spelling, because the generator
/// emits a mock per spelling and their extensions make each other ambiguous (CS0121).
Expand Down Expand Up @@ -856,25 +912,26 @@ private static (ISymbol Member, ITypeSymbol PointerType)? FindRequiredPointerMem
}

HashSet<string>? filledSlots = null;
InterfaceImplementations? interfaceImplementations = null;
foreach (ISymbol member in EnumerateImplementedTypes(type).SelectMany(implementedType => implementedType.GetMembers()))
{
if (IsAbstractMember(member) &&
FindPointerType(member) is { } pointerType &&
!IsFilled(member))
if (FindPointerType(member) is { } pointerType &&
IsRequired(member))
{
return (member, pointerType);
}
}

return null;

// An abstract explicit implementation declares a member of an inherited interface abstract again.
bool IsRequired(ISymbol member)
=> type.TypeKind == TypeKind.Interface
? (interfaceImplementations ??= new InterfaceImplementations(type)).IsRequired(member)
: IsAbstractMember(member) && !IsFilled(member);

static bool IsAbstractMember(ISymbol member)
=> member.IsAbstract &&
member is IMethodSymbol
{
MethodKind: MethodKind.Ordinary or MethodKind.ExplicitInterfaceImplementation,
} or IPropertySymbol or IEventSymbol;
member is IMethodSymbol { MethodKind: MethodKind.Ordinary, } or IPropertySymbol or IEventSymbol;

// An override can implement a single accessor of a property, which leaves the other one to the mock.
bool IsFilled(ISymbol member)
Expand Down Expand Up @@ -964,12 +1021,12 @@ internal static IMethodSymbol[] GetMockConstructors(INamedTypeSymbol type, IAsse
private static (IMethodSymbol Method, ITypeParameterSymbol TypeParameter, string First, string Second)?
FindUnsatisfiableRequiredMethod(ITypeSymbol type)
{
HashSet<string> filledSlots = CollectFilledSlots(type);
Func<ISymbol, bool> isRequired = CreateIsRequired(type);
foreach (ITypeSymbol implementedType in EnumerateImplementedTypes(type))
{
foreach (IMethodSymbol method in implementedType.GetMembers().OfType<IMethodSymbol>())
{
if (!method.IsAbstract || filledSlots.Contains(GetSignatureKey(method)))
if (!isRequired(method))
{
continue;
}
Expand Down Expand Up @@ -1004,21 +1061,32 @@ private static HashSet<string> CollectFilledSlots(ITypeSymbol type)
return filledSlots;
}

private static (ISymbol Member, ITypeSymbol? InaccessibleType)? FindInaccessibleRequiredMember(ITypeSymbol type,
IAssemblySymbol sourceAssembly)
/// <summary>
/// Whether the mock of <paramref name="type" /> must implement a member: an abstract member of a class that no
/// override fills, or an interface member whose most specific implementation is abstract or not unique.
/// Mirrors <c>IsRequired</c> in <c>Class.cs</c> in the source generator.
/// </summary>
private static Func<ISymbol, bool> CreateIsRequired(ITypeSymbol type)
{
if (type.TypeKind == TypeKind.Interface)
{
return new InterfaceImplementations(type).IsRequired;
}

HashSet<string> filledSlots = CollectFilledSlots(type);
return member => member.IsAbstract && !filledSlots.Contains(GetSignatureKey(member));
}

private static (ISymbol Member, ITypeSymbol? InaccessibleType)? FindInaccessibleRequiredMember(ITypeSymbol type,
IAssemblySymbol sourceAssembly)
{
Func<ISymbol, bool> isRequired = CreateIsRequired(type);
foreach (ITypeSymbol implementedType in EnumerateImplementedTypes(type))
{
foreach (ISymbol member in implementedType.GetMembers())
{
if (filledSlots.Contains(GetSignatureKey(member)))
{
continue;
}

if (FindInaccessibleMember(member, sourceAssembly) is { } inaccessibleMember)
if (isRequired(member) &&
FindInaccessibleMember(member, sourceAssembly) is { } inaccessibleMember)
{
return inaccessibleMember;
}
Expand Down Expand Up @@ -1081,15 +1149,15 @@ private static (ISymbol Member, ITypeSymbol? InaccessibleType)? FindInaccessible
{
switch (member)
{
case IMethodSymbol { MethodKind: MethodKind.Ordinary, IsAbstract: true, } method:
case IMethodSymbol { MethodKind: MethodKind.Ordinary, } method:
return !IsAccessibleFrom(method, sourceAssembly)
? (method, null)
: Combine(method, FindInaccessibleSignatureType(method, sourceAssembly));
case IPropertySymbol { IsAbstract: true, } property:
case IPropertySymbol property:
return FindInaccessibleAccessor(property, sourceAssembly) is { } accessor
? (accessor, null)
: Combine(property, FindInaccessibleSignatureType(property, sourceAssembly));
case IEventSymbol { IsAbstract: true, } @event:
case IEventSymbol @event:
return !IsAccessibleFrom(@event, sourceAssembly)
? (@event, null)
: Combine(@event, FindInaccessibleSignatureType(@event, sourceAssembly));
Expand Down
1 change: 1 addition & 0 deletions Source/Mockolate.Analyzers/Mockolate.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

<ItemGroup>
<Compile Include="..\Mockolate.SourceGenerators\Internals\ConstraintConflicts.cs" Link="ConstraintConflicts.cs"/>
<Compile Include="..\Mockolate.SourceGenerators\Internals\InterfaceImplementations.cs" Link="InterfaceImplementations.cs"/>
<Compile Include="..\Mockolate.SourceGenerators\Internals\MockConstructorSelector.cs" Link="MockConstructorSelector.cs"/>
</ItemGroup>

Expand Down
Loading
Loading