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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `IDependencyModule` has the new member `InternalApplyGlue`, with a default implementation. The
load of the modules has a last step that adds the collections and the `Func` registrations.
(#132)
- DM0021 also reads `[Mock]` from `VerificationGlue.Mocks`. A VerificationGlue test with that
`[Mock]` and a `[TestExport]` for the same service on one method now gets DM0021.
- `DependencyModules.Testing` depends on `DependencyModules.Runtime` and on
`Microsoft.Extensions.DependencyInjection`: version 8.0.1 for `net8.0` and version 10.0.0 for
`net10.0`. Before, it depended on `Microsoft.Extensions.DependencyInjection.Abstractions` only.
Expand Down
7 changes: 5 additions & 2 deletions docs/design/verificationglue.md
Original file line number Diff line number Diff line change
Expand Up @@ -566,8 +566,11 @@ second report would be a duplicate.
- **DM0016 and DM0019** read assembly-level module attributes. In a VG project, DM0016 is right
unchanged. DM0019 reports only when an `ApplicationModule` was generated, and DM generates one
only from a file named `Program.cs` (`BaseSourceGenerator.CreateSourceValueProvider`,
`ApproveFilter`). MTP writes the entry point of a VG project. I did not check that file's name.
If it were `Program.cs`, `[assembly: SutModule]` in any other file would report DM0019 wrongly.
`ApproveFilter`). MTP writes the entry point of a VG project. Microsoft.Testing.Platform.MSBuild
2.5.3 and 3.0.0-preview name it `MicrosoftTestingPlatformEntryPoint.cs`
(`_TestingPlatformEntryPointSourceName`), which does not end in `Program.cs`. So DM0019 is right
unchanged too. Had it been `Program.cs`, `[assembly: SutModule]` in any other file would have
reported DM0019 wrongly.
- DM's `MockAttribute` remarks say that it throws without a mock-support attribute. The remarks get
a sentence saying that under VerificationGlue it is a VerificationGlue mock.

Expand Down
22 changes: 22 additions & 0 deletions src/DependencyModules.SourceGenerator.Impl/KnownTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,28 @@ private static ITypeDefinition Close(string name, ITypeDefinition argument) =>
}
}

/// <summary>
/// VerificationGlue types, matched by name. No project here references VerificationGlue.
/// </summary>
public static class VerificationGlue
{
public static class Mocks
{
public const string Namespace = "VerificationGlue.Mocks";

/// <summary>
/// VerificationGlue's own <c>[Mock]</c>. Under VerificationGlue it has the same
/// precedence over <c>[TestExport]</c> as DependencyModules' <c>[Mock]</c>, so DM0021
/// reads both.
/// </summary>
public static readonly ITypeDefinition MockAttribute = TypeDefinition.Get(
TypeDefinitionEnum.ClassDefinition,
Namespace,
"MockAttribute"
);
}
}

public static class System
{
public static readonly ITypeDefinition ArgumentOutOfRangeException = TypeDefinition.Get(
Expand Down
24 changes: 19 additions & 5 deletions src/DependencyModules.SourceGenerator/TestAttributeDiagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ namespace DependencyModules.SourceGenerator;
/// everything under it, and one test overriding that for one argument is what having both scopes is
/// for — reporting that would be reporting the feature.
/// </para>
/// <para>
/// <c>[Mock]</c> is either <c>DependencyModules.Testing.Attributes.MockAttribute</c> or
/// <c>VerificationGlue.Mocks.MockAttribute</c>. Under VerificationGlue both win over a
/// <c>[TestExport]</c> on the same method. VerificationGlue reports no diagnostic of its own for
/// this, so this is the only report.
/// </para>
/// </remarks>
internal static class TestAttributeDiagnostics
{
Expand Down Expand Up @@ -95,11 +101,19 @@ System.Threading.CancellationToken cancellationToken

// A keyed mock is registered under its key, so the unkeyed export stays in use.
if (
!Carries(
parameter,
KnownTypes.DependencyModules.Testing.MockAttribute,
context,
cancellationToken
!(
Carries(
parameter,
KnownTypes.DependencyModules.Testing.MockAttribute,
context,
cancellationToken
)
|| Carries(
parameter,
KnownTypes.VerificationGlue.Mocks.MockAttribute,
context,
cancellationToken
)
)
|| Carries(
parameter,
Expand Down
3 changes: 2 additions & 1 deletion src/DependencyModules.Testing/Attributes/MockAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ namespace DependencyModules.Testing.Attributes;
/// Creating the double is delegated to whichever mocking package is in scope, which must implement
/// <see cref="IMockSupportAttribute"/>: <c>[NSubstituteSupport]</c>, <c>[MoqSupport]</c> or
/// <c>[FakeItEasySupport]</c>. Without one this throws rather than silently handing back a real
/// service.
/// service. Under VerificationGlue the parameter is a VerificationGlue mock, the same as one marked
/// with <c>VerificationGlue.Mocks.MockAttribute</c>, and no mock-support attribute is needed.
///
/// A library that separates the double from the object it produces may let the parameter name either.
/// With Moq, <c>[Mock] IFoo</c> gives the object and <c>Mock&lt;IFoo&gt;</c> gives the mock — and on a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,176 @@ public void Conflicting([global::DependencyModules.Testing.Attributes.Mock] IThi
Single(result.GeneratorDiagnostics, d => d.Id == "DM0021");
}

/// <summary>
/// VerificationGlue's <c>[Mock]</c> wins over <c>[TestExport]</c> as DependencyModules' does, so
/// the two spellings get the same report at the same place.
/// </summary>
[VerifyTest]
public void VerificationGlueMock_GetsTheSameReportAsDependencyModulesMock()
{
const string body = """
[TestExport(typeof(IThing), Implementation = typeof(RealThing))]
public void Conflicting([Mock] IThing thing) { }
""";

var dependencyModules = Single(Run(body).GeneratorDiagnostics, d => d.Id == "DM0021");
var verificationGlueResult = RunVerificationGlue(body);
var verificationGlue = Single(
verificationGlueResult.GeneratorDiagnostics,
d => d.Id == "DM0021"
);

Verify(!verificationGlueResult.Errors.Any());
var reportedText = verificationGlue
.Location.SourceTree!.GetText()
.ToString(verificationGlue.Location.SourceSpan);

Verify(dependencyModules.GetMessage() == verificationGlue.GetMessage());
Verify(dependencyModules.Severity == verificationGlue.Severity);
Verify(
System.IO.Path.GetFileName(verificationGlue.Location.GetLineSpan().Path) == "Test.cs"
);
Verify(reportedText == "[Mock] IThing thing");
}

[VerifyTest]
public void VerificationGlueMock_QualifiedSpelling_IsReported()
{
var result = RunVerificationGlue(
"""
[TestExport(typeof(IThing), Implementation = typeof(RealThing))]
public void Conflicting([global::VerificationGlue.Mocks.Mock] IThing thing) { }
"""
);

Verify(!result.Errors.Any());
Single(result.GeneratorDiagnostics, d => d.Id == "DM0021");
}

[VerifyTest]
public void VerificationGlueMock_Keyed_IsNotReported()
{
var result = RunVerificationGlue(
"""
[TestExport(typeof(IThing), Implementation = typeof(RealThing))]
public void Keyed([Mock] [Microsoft.Extensions.DependencyInjection.FromKeyedServices("k")] IThing thing) { }
"""
);

Verify(!result.Errors.Any());
Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021"));
}

[VerifyTest]
public void VerificationGlueMock_NamingAnotherService_IsNotReported()
{
var result = RunVerificationGlue(
"""
[TestExport(typeof(IOther), Implementation = typeof(RealOther))]
public void Unrelated([Mock] IThing thing) { }
"""
);

Verify(!result.Errors.Any());
Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021"));
}

[VerifyTest]
public void VerificationGlueMock_WithTestExportOnTheClass_IsNotReported()
{
var result = GeneratorTestHarness.Run(
$$"""
{{VerificationGluePreamble}}

namespace TestNamespace
{
[TestExport(typeof(IThing), Implementation = typeof(RealThing))]
public class Fixture {
public void Overriding([Mock] IThing thing) { }
}
}
"""
);

Verify(!result.Errors.Any());
Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021"));
}

/// <summary>
/// Matched by namespace and name, so a <c>MockAttribute</c> of another library is not read.
/// </summary>
[VerifyTest]
public void AMockAttributeInAnotherNamespace_IsNotReported()
{
var result = GeneratorTestHarness.Run(
$$"""
using DependencyModules.Testing.Attributes;

namespace Elsewhere
{
[System.AttributeUsage(System.AttributeTargets.Parameter)]
public sealed class MockAttribute : System.Attribute;
}

namespace TestNamespace
{
public interface IThing;

public class RealThing : IThing;

public class Fixture {
[TestExport(typeof(IThing), Implementation = typeof(RealThing))]
public void NotAMock([Elsewhere.Mock] IThing thing) { }
}
}
"""
);

Verify(!result.Errors.Any());
Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021"));
}

/// <summary>
/// A VerificationGlue test file. The stub stands in for <c>VerificationGlue.Mocks</c>, which no
/// project here references. <c>[TestExport]</c> is imported by alias, because importing both
/// namespaces makes <c>[Mock]</c> ambiguous.
/// </summary>
private const string VerificationGluePreamble = """
using VerificationGlue.Mocks;
using TestExportAttribute = DependencyModules.Testing.Attributes.TestExportAttribute;

namespace VerificationGlue.Mocks
{
[System.AttributeUsage(System.AttributeTargets.Parameter)]
public sealed class MockAttribute : System.Attribute;
}

namespace TestNamespace
{
public interface IThing;

public interface IOther;

public class RealThing : IThing;

public class RealOther : IOther;
}
""";

private static GeneratorResult RunVerificationGlue(string body) =>
GeneratorTestHarness.Run(
$$"""
{{VerificationGluePreamble}}

namespace TestNamespace
{
public class Fixture {
{{body}}
}
}
"""
);

private const string Preamble = """
using DependencyModules.Runtime.Attributes;
using DependencyModules.Testing.Attributes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1485,6 +1485,14 @@ namespace DependencyModules.SourceGenerator.Impl
public static CSharpAuthor.ITypeDefinition AsyncEnumerable(CSharpAuthor.ITypeDefinition item) { }
public static CSharpAuthor.ITypeDefinition ValueTask(CSharpAuthor.ITypeDefinition result) { }
}
public static class VerificationGlue
{
public static class Mocks
{
public const string Namespace = "VerificationGlue.Mocks";
public static readonly CSharpAuthor.ITypeDefinition MockAttribute;
}
}
}
public class ModuleAttributeWriter : DependencyModules.SourceGenerator.Impl.Utilities.BaseAttributeWriter<DependencyModules.SourceGenerator.Impl.Models.ModuleEntryPointModel>
{
Expand Down
2 changes: 2 additions & 0 deletions website/reference/diagnostics.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ To correct the problem, set `Realm` on `[Intercept]` to the module that register

A test method has `[TestExport]` for a service type and a `[Mock]` parameter of the same type. The mock replaces the `[TestExport]` registration. The generator gives DM0021 only if the test project references `DependencyModules.SourceGenerator`.

`[Mock]` can be `DependencyModules.Testing.Attributes.MockAttribute` or `VerificationGlue.Mocks.MockAttribute`. The generator gives the same DM0021 for both.

The generator gives no DM0021 for the two exceptions, because the `[TestExport]` registration stays in use:

- The `[Mock]` parameter has `[FromKeyedServices]`.
Expand Down
Loading