Skip to content
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

added ILoggerTests to ensure NSubstitute can be used to test specific ILogger calls happened. #732

Merged
merged 3 commits into from
Sep 3, 2023
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
13 changes: 12 additions & 1 deletion src/NSubstitute/Core/CallSpecification.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,25 @@ private static Type[] ParameterTypes(MethodInfo info)
return info.GetParameters().Select(p=>p.ParameterType).ToArray();
}

private static bool TypesAreAllEquivalent(Type[] aArgs, Type[] bArgs)
internal static bool TypesAreAllEquivalent(Type[] aArgs, Type[] bArgs)
{
if (aArgs.Length != bArgs.Length) return false;
for (var i = 0; i < aArgs.Length; i++)
{
var first = aArgs[i];
var second = bArgs[i];

if (first.IsGenericType && second.IsGenericType
&& first.GetGenericTypeDefinition() == second.GetGenericTypeDefinition())
{
// both are the same generic type. If their GenericTypeArguments match then they are equivalent
if (!TypesAreAllEquivalent(first.GenericTypeArguments, second.GenericTypeArguments))
{
return false;
}
continue;
}

var areEquivalent = first.IsAssignableFrom(second) || second.IsAssignableFrom(first) ||
first == typeof(Arg.AnyType) || second == typeof(Arg.AnyType);
if (!areEquivalent) return false;
Expand Down
17 changes: 16 additions & 1 deletion src/NSubstitute/Core/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,22 @@ public static bool IsCompatibleWith(this object? instance, Type type)
}

var requiredType = type.IsByRef ? type.GetElementType()! : type;
return instance == null ? TypeCanBeNull(requiredType) : requiredType.IsInstanceOfType(instance);

if (instance == null)
{
return TypeCanBeNull(requiredType);
}

var instanceType = instance.GetType();

if (instanceType.IsGenericType && type.IsGenericType
&& instanceType.GetGenericTypeDefinition() == type.GetGenericTypeDefinition())
{
// both are the same generic type. If their GenericTypeArguments match then they are equivalent
return CallSpecification.TypesAreAllEquivalent(instanceType.GenericTypeArguments, type.GenericTypeArguments);
}

return requiredType.IsInstanceOfType(instance);
}

/// <summary>
Expand Down
109 changes: 109 additions & 0 deletions tests/NSubstitute.Acceptance.Specs/ILoggerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using Microsoft.Extensions.Logging;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;

namespace NSubstitute.Acceptance.Specs;

[TestFixture]
public class ILoggerTests
{
[Test]
public void Received_LogTrace_call_using_AnyType()
{
var logger = Substitute.For<ILogger<ILoggerTests>>();

logger.LogTrace("Vanished without a trace");

logger.Received(1)
.Log(
LogLevel.Trace,
Arg.Any<EventId>(),
Arg.Any<Arg.AnyType>(),
Arg.Any<Exception>(),
Arg.Any<Func<Arg.AnyType, Exception, string>>()
);
}

[Test]
public void Received_LogWarning_call_using_interfaced_types()
{
var logger = Substitute.For<ILogger<ILoggerTests>>();

logger.LogWarning("Warning: Live without warning");

logger.Received(1)
.Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<IReadOnlyList<KeyValuePair<string, object>>>(),
Arg.Any<Exception>(),
Arg.Any<Func<IReadOnlyList<KeyValuePair<string, object>>, Exception, string>>()
);
}

[Test]
public void Received_LogError_call_using_messageTemplate()
{
var logger = Substitute.For<ILogger<ILoggerTests>>();

logger.LogError("Something bad happened!!!");

logger.Received(1)
.Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Is<IReadOnlyList<KeyValuePair<string, object>>>(list => list.Any(i => i.Key == "{OriginalFormat}" && i.Value.Equals("Something bad happened!!!"))),
Arg.Any<Exception>(),
Arg.Any<Func<IReadOnlyList<KeyValuePair<string, object>>, Exception, string>>()
);

logger.DidNotReceive()
.Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Is<IReadOnlyList<KeyValuePair<string, object>>>(list => list.Any(i => i.Key == "{OriginalFormat}" && i.Value.Equals("some other message"))),
Arg.Any<Exception>(),
Arg.Any<Func<IReadOnlyList<KeyValuePair<string, object>>, Exception, string>>()
);
}

[Test]
public void Received_LogInformation_call_using_messageTemplate()
{
var now = DateTimeOffset.UtcNow;
var later = now.AddTicks(1);
var logger = Substitute.For<ILogger<ILoggerTests>>();

logger.LogInformation("I have parameters. {param1} {param2} {param3}", 1979, "apocalypse", now);

logger.Received(1)
.Log(
LogLevel.Information,
Arg.Any<EventId>(),
Arg.Is<IReadOnlyList<KeyValuePair<string, object>>>(list =>
list.Any(i => i.Key == "{OriginalFormat}" && i.Value.Equals("I have parameters. {param1} {param2} {param3}"))
&& list.Any(i => i.Key == "param1" && i.Value.Equals(1979))
&& list.Any(i => i.Key == "param2" && i.Value.Equals("apocalypse"))
&& list.Any(i => i.Key == "param3" && i.Value.Equals(now))
),
Arg.Any<Exception>(),
Arg.Any<Func<IReadOnlyList<KeyValuePair<string, object>>, Exception, string>>()
);

logger.DidNotReceive()
.Log(
LogLevel.Information,
Arg.Any<EventId>(),
Arg.Is<IReadOnlyList<KeyValuePair<string, object>>>(list =>
list.Any(i => i.Key == "{OriginalFormat}" && i.Value.Equals("I have parameters. {param1} {param2} {param3}"))
&& list.Any(i => i.Key == "param1" && i.Value.Equals(1979))
&& list.Any(i => i.Key == "param2" && i.Value.Equals("apocalypse"))
&& list.Any(i => i.Key == "param3" && i.Value.Equals(later)) // this is the only one that will mismatch
),
Arg.Any<Exception>(),
Arg.Any<Func<IReadOnlyList<KeyValuePair<string, object>>, Exception, string>>()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.3.1" />
Expand Down