Skip to content

Commit

Permalink
Add unit tests for ExcludeMatchDates (#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
axunonb authored Jan 28, 2024
1 parent 2103e81 commit 4fdb7d6
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
using Microsoft.Extensions.Logging.Abstractions;
using NUnit.Framework;
using SD.LLBLGen.Pro.ORMSupportClasses;
using TournamentManager.DAL.EntityClasses;
using TournamentManager.DAL.HelperClasses;
using TournamentManager.Data;
using TournamentManager.Plan;
using TournamentManager.Tests.TestComponents;
using Moq;
using TournamentManager.DAL.TypedViewClasses;
using TournamentManager.MultiTenancy;
using TournamentManager.Importers.ExcludeDates;

namespace TournamentManager.Tests.Plan;

[TestFixture]
internal class ExcludeMatchDatesTests
{
private ITenantContext _tenantContext = new TenantContext();
private readonly EntityCollection<ExcludeMatchDateEntity> _excludeMatchDays = new();

[Test]
public async Task Generate_Schedule_Should_Succeed()
{
var excludeMatchDates = GetExcludeMatchDatesInstance();
await excludeMatchDates.GenerateExcludeDates(new ExcludeMatchDatesTestImporter(), 1, true, CancellationToken.None);

Assert.Multiple(() =>
{
Assert.That(_excludeMatchDays, Has.Count.EqualTo(1));
Assert.That(_excludeMatchDays[0].DateFrom, Is.EqualTo(new DateTime(2024, 1, 1)));
Assert.That(_excludeMatchDays[0].DateTo, Is.EqualTo(new DateTime(2024, 1, 1).AddDays(1).AddMinutes(-1)));
Assert.That(_excludeMatchDays[0].Reason, Is.EqualTo("Any Reason"));
});
}

private ExcludeMatchDates GetExcludeMatchDatesInstance()
{
var tenantContextMock = TestMocks.GetTenantContextMock();
var appDbMock = TestMocks.GetAppDbMock();

#region ** RoundRepository mocks setup **

var roundRepoMock = TestMocks.GetRepo<RoundRepository>();
roundRepoMock.Setup(rep =>
rep.GetRoundLegPeriodAsync(It.IsAny<PredicateExpression>(), It.IsAny<CancellationToken>()))
.Returns((IPredicateExpression filter, CancellationToken cancellationToken) =>
{
var roundLegRow = new List<RoundLegPeriodRow> {
new() {
StartDateTime = new DateTime(2024, 1, 1),
EndDateTime = new DateTime(2024, 6, 30)
}
};

return Task.FromResult(roundLegRow);
});
appDbMock.Setup(a => a.RoundRepository).Returns(roundRepoMock.Object);

#endregion

#region ** GenericRepository mocks setup **

var genericRepoMock = TestMocks.GetRepo<GenericRepository>();
genericRepoMock.Setup(rep =>
rep.SaveEntitiesAsync(It.IsAny<EntityCollection<ExcludeMatchDateEntity>>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Callback(() => { })
.Returns((EntityCollection<ExcludeMatchDateEntity> dates, bool refetchAfterSave, bool recursion, CancellationToken cancellationToken) =>
{
foreach (var emd in dates)
{
emd.IsDirty = false;
emd.IsNew = false;
}
_excludeMatchDays.AddRange(dates);
return Task.CompletedTask;
});
genericRepoMock.Setup(rep =>
rep.DeleteEntitiesDirectlyAsync(It.IsAny<Type>(), It.IsAny<IRelationPredicateBucket>(), It.IsAny<CancellationToken>()))
.Callback(() => { })
.Returns((Type type, IRelationPredicateBucket bucket, CancellationToken cancellationToken) =>
{
if (type == typeof(ExcludeMatchDateEntity))
{
var count = _excludeMatchDays.Count;
_excludeMatchDays.Clear();
return Task.FromResult(count);
}
throw new ArgumentException("Type not supported");
});
appDbMock.Setup(a => a.GenericRepository).Returns(genericRepoMock.Object);

#endregion

#region ** ExcludedMatchDateRepository mocks setup **

var excludedMatchDatesMock = TestMocks.GetRepo<ExcludedMatchDateRepository>();
excludedMatchDatesMock.Setup(rep =>
rep.GetExcludedMatchDatesAsync(It.IsAny<long>(), It.IsAny<CancellationToken>()))
.Returns((long tournamentId, CancellationToken cancellationToken) =>
{
var excludedMatchDates = new EntityCollection<ExcludeMatchDateEntity>();
return Task.FromResult(excludedMatchDates);
});
appDbMock.Setup(a => a.ExcludedMatchDateRepository).Returns(excludedMatchDatesMock.Object);

#endregion

// Build complete TenantContext mock
var dbContextMock = TestMocks.GetDbContextMock();
dbContextMock.SetupAppDb(appDbMock);
tenantContextMock.SetupDbContext(dbContextMock);

// Create ExcludeMatchDates instance
var logger = NullLogger<ExcludeMatchDates>.Instance;
_tenantContext = tenantContextMock.Object;

var excludeMatchDates = new ExcludeMatchDates(_tenantContext, logger);
return excludeMatchDates;
}
}

internal class ExcludeMatchDatesTestImporter : IExcludeDateImporter
{
public IEnumerable<ExcludeDateRecord> Import(DateTimePeriod dateLimits)
{
yield return new ExcludeDateRecord
{
Period = new DateTimePeriod(dateLimits.Start, dateLimits.Start?.AddDays(1).AddMinutes(-1)),
Reason = "Any Reason"
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private MatchScheduler GetMatchSchedulerInstance()

var genericRepoMock = TestMocks.GetRepo<GenericRepository>();
genericRepoMock.Setup(rep =>
rep.SaveEntitiesAsync(It.IsAny<EntityCollection<MatchEntity>>(), true, false,It.IsAny<CancellationToken>()))
rep.SaveEntitiesAsync(It.IsAny<EntityCollection<MatchEntity>>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Returns((EntityCollection<MatchEntity> matches, bool refetchAfterSave, bool recursion, CancellationToken cancellationToken) =>
{
// DO NOT add matches to tournamentMatches, because
Expand Down
6 changes: 3 additions & 3 deletions TournamentManager/TournamentManager/DateTimePeriod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public bool Contains(DateTime testDateTime)
/// <returns>Returns true, if the <see cref="DateTimePeriod"/> overlaps with another <see cref="DateTimePeriod"/>. If one of the start or end values is null, false is returned.</returns>
public bool Overlaps(DateTimePeriod testPeriod)
{
if (!(_start.HasValue && _end.HasValue && testPeriod.Start.HasValue && testPeriod.End.HasValue)) return false;
if (!(_start.HasValue && _end.HasValue && testPeriod is { Start: not null, End: not null })) return false;
// https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
return _start <= testPeriod.End && testPeriod.Start <= _end;
}
Expand All @@ -177,9 +177,9 @@ public bool Overlaps(DateTimePeriod testPeriod)
/// Returns null, if Start and/or End are null.
/// </summary>
/// <returns>Gets the duration as the <see cref="TimeSpan"/> of End minus Date. Returns null, if Start and/or End are null.</returns>
public TimeSpan? Duration(bool nullable)
public TimeSpan? Duration(bool nullIfUndefined)
{
if (!(Start.HasValue && End.HasValue && nullable)) return null;
if (!(Start.HasValue && End.HasValue && nullIfUndefined)) return null;

return Duration();
}
Expand Down

0 comments on commit 4fdb7d6

Please sign in to comment.