Skip to content

Commit

Permalink
Fix some verifications and mock setups
Browse files Browse the repository at this point in the history
  • Loading branch information
kdankert committed Feb 26, 2024
1 parent 8a3f40e commit 425eb79
Show file tree
Hide file tree
Showing 11 changed files with 59 additions and 24 deletions.
3 changes: 2 additions & 1 deletion src/EvoSC.Testing/Mocking.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,10 @@ public static (TController Controller, ControllerContextMock<TContext> ContextMo
/// <returns></returns>
public static IContextService NewContextServiceMock(IControllerContext context, IOnlinePlayer? actor)
{
var auditEvent = context.AuditEvent;
var mock = Substitute.For<IContextService>();

mock.Audit().Returns(context.AuditEvent);
mock.Audit().Returns(auditEvent);
mock.GetContext().Returns(context);

if (actor != null)
Expand Down
27 changes: 26 additions & 1 deletion src/EvoSC.Testing/Verifications.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace EvoSC.Testing;

public static class Verifications
{

/// <summary>
/// Helper method for verifying that a logging call was made.
/// </summary>
Expand All @@ -15,7 +16,31 @@ public static class Verifications
/// <param name="msg">Message which was logged.</param>
/// <param name="times">How many times this log was called.</param>
/// <typeparam name="T">The type which this logger is assigned to.</typeparam>
public static void Verify<T>(ILogger<T> loggerMock, LogLevel logLevel, Exception? exception, string? msg, int times)
public static void Verify<T>(this ILogger<T> loggerMock, LogLevel logLevel, Exception? exception, string? msg, Quantity times)
{
if (exception == null)
{
loggerMock.Received(times).Log(
logLevel,
Arg.Any<EventId>(),
Arg.Is<object>(o => msg == null || (
o.ToString()!.StartsWith(msg, StringComparison.Ordinal)
&& o.GetType().Name.Equals("FormattedLogValues", StringComparison.Ordinal)
)),
Arg.Any<Exception>(),
Arg.Any<Func<object, Exception?, string>>());
}
else
{
loggerMock.Received(times).Log(
logLevel,
Arg.Any<EventId>(),
Arg.Is<object>(o => msg == null || (
o.ToString()!.StartsWith(msg, StringComparison.Ordinal)
&& o.GetType().Name.Equals("FormattedLogValues", StringComparison.Ordinal)
)),
exception,
Arg.Any<Func<object, Exception?, string>>());
}
}
}
3 changes: 2 additions & 1 deletion tests/EvoSC.Common.Tests/Services/MapServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
using GbxRemoteNet.Structs;
using Microsoft.Extensions.Logging;
using NSubstitute;
using NSubstitute.ClearExtensions;
using Xunit;

namespace EvoSC.Common.Tests.Services;
Expand Down Expand Up @@ -367,9 +368,9 @@ public async Task Add_Current_Map_List_Adds_Maplist()
UpdatedAt = new DateTime(),
LastVisit = new DateTime()
};

_server.Remote.GetMapListAsync(Arg.Any<int>(), Arg.Any<int>())
.Returns(Task.FromResult(new[] { tmMapInfo }));
_mapRepository.GetMapByUidAsync(tmMapInfo.UId).Returns((IMap?) null);
_playerService.GetOrCreatePlayerAsync(Arg.Any<string>())
.Returns(Task.FromResult((IPlayer)player));

Expand Down
7 changes: 4 additions & 3 deletions tests/Modules/FastestCp.Tests/FastestCpServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ public async Task Should_Register_Time_And_Update_Widget()
{
AccountId = "AccountId1", Id = 1, NickName = "NickName1", UbisoftName = "Ubisoft1"
});
object? actualData = null;
await _manialinkManagerMock.SendPersistentManialinkAsync(Arg.Any<string>(), Arg.Do<object>(x => actualData = x));

await _fastestCpService.RegisterCpTimeAsync(new WayPointEventArgs
{
Expand All @@ -54,9 +56,8 @@ await _fastestCpService.RegisterCpTimeAsync(new WayPointEventArgs
IsEndLap = false,
IsEndRace = false
});

object? actualData = null;
await _manialinkManagerMock.Received(1).SendPersistentManialinkAsync("FastestCpModule.FastestCp", Arg.Do<object>(x => actualData = x));

await _manialinkManagerMock.Received(1).SendPersistentManialinkAsync("FastestCpModule.FastestCp", Arg.Any<object>());
Assert.Equivalent(
new { times = new List<PlayerCpTime?> { new("NickName1", 0, TimeSpan.FromMilliseconds(10)) } },
actualData);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public async Task Map_Is_Removed()
AuditEventBuilder.Received(1).WithEventName(AuditEvents.MapRemoved);
await _server.Client.Received(1).SuccessMessageAsync(Arg.Any<string>(), _actor);
await _server.Client.DidNotReceive().ErrorMessageAsync(Arg.Any<string>(), _actor);
_logger.Received(1).Log(LogLevel.Debug, null, Arg.Any<string?>());
_logger.Verify(LogLevel.Debug, null, null, Quantity.Exactly(1));
}

[Fact]
Expand Down
18 changes: 13 additions & 5 deletions tests/Modules/MotdModule.Tests/HttpServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.Extensions.Logging;
using MockHttpClient;
using NSubstitute;
using NSubstitute.ReceivedExtensions;

namespace MotdModule.Tests;

Expand Down Expand Up @@ -67,14 +68,21 @@ public async Task GetAsync_Returns_Correct_Format(string url, HttpResponseMessag
if (throwException)
{
Assert.Empty(result);
_logger.Received(1).Log(LogLevel.Error, null, Arg.Any<string?>());
_logger.Verify(LogLevel.Error, null, null, Quantity.Exactly(1));
}
else
{
var data = expectedResponse.Data.FirstOrDefault()!;
Assert.Equal(data.Message, result);
Assert.IsType<int>(data.Id);
Assert.NotEmpty(data.Server);
if (expectedResponse.Data is null)
{
Assert.Empty(result);
}
else
{
var data = expectedResponse.Data.FirstOrDefault()!;
Assert.Equal(data.Message, result);
Assert.IsType<int>(data.Id);
Assert.NotEmpty(data.Server);
}
}
}

Expand Down
3 changes: 1 addition & 2 deletions tests/Modules/MotdModule.Tests/MotdCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using EvoSC.Testing;
using EvoSC.Testing.Controllers;
using NSubstitute;
using NSubstitute.ReceivedExtensions;

namespace MotdModule.Tests;

Expand All @@ -28,7 +27,7 @@ public MotdCommandTests()
public void SetMotdLocal_Sets_Motd_Source_To_Local(string isLocal)
{
Controller.SetMotdLocal(isLocal);
_motdService.Received().SetMotdSource(bool.Parse(isLocal), null);
_motdService.Received().SetMotdSource(bool.Parse(isLocal), Arg.Any<IPlayer>());
}

[Fact]
Expand Down
6 changes: 3 additions & 3 deletions tests/Modules/MotdModule.Tests/MotdServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public class MotdServiceTests
private readonly IPlayerManagerService _playerManager = Substitute.For<IPlayerManagerService>();
private readonly IContextService _context;

private const int Max = 100;

private readonly ControllerContextMock<ICommandInteractionContext> _commandContext =
Mocking.NewControllerContextMock<ICommandInteractionContext>();

Expand Down Expand Up @@ -106,7 +108,7 @@ public async Task SetInterval_Timer_Fires_Given_Amount_Of_Times(int times)
SetupController();
_motdService!.SetInterval(100, _player);
await Task.Delay(150 * times);
await _httpService.Received(int.MaxValue).GetAsync(Arg.Any<string>());
await _httpService.Received(Quantity.Within(times, Max)).GetAsync(Arg.Any<string>());
}

[Fact]
Expand Down Expand Up @@ -174,8 +176,6 @@ public async Task GetMotd_Gets_Correct_Text()
{
_httpService.GetAsync(Arg.Any<string>())
.Returns(Task.FromResult("test"));
await _maniaLinkManager.SendManialinkAsync(_player, "MotdModule.MotdTemplate",
new { isChecked = false, text = "test" });

SetupMocks();
SetupController();
Expand Down
10 changes: 5 additions & 5 deletions tests/Modules/Player.Tests/PlayerServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public async Task Player_Is_UnMuted_And_Audited()

mock.Audit.Received(1).Success();
await mock.Server.Remote.Received(1).UnIgnoreAsync(PlayerLogin);
await mock.Server.Client.Received(1).WarningMessageAsync(Arg.Any<string>(), mock.Player);
await mock.Server.Client.Received(1).InfoMessageAsync(Arg.Any<string>(), mock.Player);
await mock.Server.Client.Received(1).SuccessMessageAsync(Arg.Any<string>(), mock.Actor);
}

Expand Down Expand Up @@ -221,7 +221,7 @@ public async Task Player_Banning_Failed_Still_Blacklists_And_Logs_Trace()


await mock.Server.Remote.Received(1).BanAsync(PlayerLogin);
mock.Logger.Received(1).Log(LogLevel.Trace, null);
mock.Logger.Verify(LogLevel.Trace, null, null, Quantity.Exactly(1));
await mock.Server.Remote.Received(1).BlackListAsync(PlayerLogin);
await mock.Server.Client.Received(1).SuccessMessageAsync(Arg.Any<string>(), mock.Actor);
mock.Audit.Received(1).Success();
Expand All @@ -238,7 +238,7 @@ public async Task Player_Is_Unbanned_And_Audited()

await mock.Server.Remote.Received(1).UnBanAsync(PlayerLogin);
await mock.Server.Remote.Received(1).UnBlackListAsync(PlayerLogin);
await mock.Server.Client.Received(1).SuccessMessageAsync(Arg.Any<string>(), _actor);
await mock.Server.Client.Received(2).SuccessMessageAsync(Arg.Any<string>(), _actor);
mock.Audit.Received(2).Success();
}

Expand All @@ -256,7 +256,7 @@ public async Task Player_Unban_Failed_Is_Logged_And_Still_Unblacklisted()
await mock.Server.Remote.Received(1).UnBlackListAsync(PlayerLogin);
await mock.Server.Client.Received(1).ErrorMessageAsync(Arg.Any<string>(), _actor);
mock.Audit.Received(1).Success();
mock.Logger.Received(1).Log(LogLevel.Error, ex, null);
mock.Logger.Verify(LogLevel.Error, ex, null, Quantity.Exactly(1));
}

[Fact]
Expand All @@ -273,6 +273,6 @@ public async Task Player_Unblacklist_Failed_Sends_ErrorMsg_And_ErrorLog()
await mock.Server.Remote.Received(1).UnBlackListAsync(PlayerLogin);
await mock.Server.Client.Received(1).ErrorMessageAsync(Arg.Any<string>(), _actor);
mock.Audit.Received(1).Success();
mock.Logger.Received(1).Log(LogLevel.Error, ex, null);
mock.Logger.Verify(LogLevel.Error, ex, null, Quantity.Exactly(1));
}
}
2 changes: 1 addition & 1 deletion tests/Modules/SetName.Tests/SetNameControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public async Task Invalid_Entry_Model_Shows_Manialink_Again()
await Controller.EditNameAsync(entry);

await _setNameService.DidNotReceive().SetNicknameAsync(_actor, entry.Nickname);
await ManialinkManager.DidNotReceive().SendManialinkAsync(_actor, "SetName.EditName", Arg.Any<ExpandoObject>());
await ManialinkManager.DidNotReceive().SendManialinkAsync(_actor, "SetName.EditName", Arg.Any<object>());
}

[Fact]
Expand Down
2 changes: 1 addition & 1 deletion tests/Modules/SetName.Tests/SetNameServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public async Task Name_Is_Set_And_Updated_In_Caches()

await service.SetNicknameAsync(player, "NewName");

await playerRepository.Received(1).UpdateNicknameAsync(player, "New Name");
await playerRepository.Received(1).UpdateNicknameAsync(player, "NewName");
await playerCache.Received(1).UpdatePlayerAsync(player);
await eventManager.Received(1).RaiseAsync(SetNameEvents.NicknameUpdated, Arg.Any<NicknameUpdatedEventArgs>());
}
Expand Down

0 comments on commit 425eb79

Please sign in to comment.