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
141 changes: 141 additions & 0 deletions MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
using Bunit;
using MW_GC.EventManager.Shared.Entities;
using MW_GC.EventManager.Shared.Models;
using MW_GC.EventManager.Web.Pages;
using MW_GC.EventManager.Web.Services;
using static MW_GC.EventManager.Web.Tests.PageActions;

namespace MW_GC.EventManager.Web.Tests;

// #100, #204: the repeat marker in the Events list, and every Web reader of an Event's Selections with an Occurrence
// that has none yet (ADR 0002). "Weekly night" is an Occurrence (SeriesId set, no Selections); "Game night" is a
// standalone Event with one Selection, its Winner.
[TestClass]
public sealed class EmptyOccurrenceTests : IDisposable
{
private readonly StubApiHandler api = new();
private readonly PageHarness harness;
private readonly GameEntity kart = new() { Name = "Kart" };
private readonly ActivityEntity grandPrix;
private readonly EventEntity night;
private readonly EventEntity weekly;

public EmptyOccurrenceTests()
{
grandPrix = new ActivityEntity { Name = "Grand Prix", GameId = kart.Id };
night = new EventEntity { Name = "Game night", Date = new DateTimeOffset(2026, 10, 9, 19, 0, 0, TimeSpan.Zero), Selections = [Pick(kart, grandPrix)], WinnerActivityId = grandPrix.Id };
weekly = new EventEntity { Name = "Weekly night", Date = new DateTimeOffset(2026, 10, 2, 19, 0, 0, TimeSpan.Zero), SeriesId = Guid.NewGuid(), OccurrenceKey = new DateTimeOffset(2026, 10, 2, 19, 0, 0, TimeSpan.Zero) };
api.Json(HttpMethod.Get, "/api/events", new[] { night, weekly })
.Json(HttpMethod.Get, "/api/games", new[] { kart })
.Json(HttpMethod.Get, "/api/activities", new[] { grandPrix })
.Json(HttpMethod.Get, "/api/themes", Array.Empty<ThemeEntity>())
.Json(HttpMethod.Get, "/api/holidays", Array.Empty<HolidayEntity>())
.Json(HttpMethod.Get, $"/api/events/{weekly.Id}/metrics", new { id = weekly.Id })
.Json(HttpMethod.Get, $"/api/events/{weekly.Id}/likes", new { count = 0 });
harness = new PageHarness(api);
}

public void Dispose() => harness.Dispose();

// The marker has an accessible name on the Occurrence's row and is missing from the standalone Event's row; the
// empty Occurrence shows 0 Selections and no Winner, and the grid keeps its five columns.
[TestMethod]
public void TheList_MarksTheOccurrenceOnly_AndShowsZeroSelectionsAndNoWinner()
{
var page = Loaded();

var occurrence = Row(page, "Weekly night");
var marker = Assert.ContainsSingle(occurrence.QuerySelectorAll(".repeat-marker"));
Assert.AreEqual("Repeats", marker.GetAttribute("aria-label"));
Assert.AreEqual("img", marker.GetAttribute("role"));
Assert.IsEmpty(Row(page, "Game night").QuerySelectorAll(".repeat-marker"));

var cells = occurrence.QuerySelectorAll("td").Select(c => Normalize(c.TextContent)).ToList();
Assert.HasCount(5, cells);
Assert.AreEqual("Weekly night", cells[0]);
Assert.AreEqual("0", cells[2]);
Assert.AreEqual("None", cells[3]);
Assert.AreEqual("minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) 120px",
page.Find("table").GetAttribute("style")!.Split("grid-template-columns:")[1].Split(';')[0].Trim());
}

// Details of an empty Occurrence opens with no error and no Selection card, so no Select Winner either.
[TestMethod]
public async Task Details_OfAnEmptyOccurrence_OpensWithoutError_AndOffersNoWinner()
{
var page = Loaded();

await RowButton(page, "Weekly night", "Details").ClickAsync(new());

Assert.IsTrue(page.HasFormDialog());
Assert.AreEqual("Weekly night", page.FormDialog().GetAttribute("aria-label"));
Assert.IsEmpty(page.FormDialog().Alerts());
Assert.IsFalse(page.FormDialog().QuerySelectorAll("fluent-button").Any(b => b.TextContent.Trim() == "Select Winner"));
Assert.IsFalse(harness.UnhandledException.IsCompleted);
}

// Edit of an empty Occurrence opens with no slot and no error and no Repeat section; rolling it is the next card.
[TestMethod]
public async Task Edit_OfAnEmptyOccurrence_OpensWithoutError()
{
var page = Loaded();

await RowButton(page, "Weekly night", "Edit").ClickAsync(new());

Assert.AreEqual("Edit Event", page.DialogTitle());
Assert.IsEmpty(page.FormDialog().Alerts());
Assert.IsEmpty(page.FormDialog().QuerySelectorAll("fluent-button[aria-label^='Re-roll slot']"));
Assert.IsNull(page.FormDialog().QuerySelector(".repeat-section"));
Assert.IsFalse(harness.UnhandledException.IsCompleted);
}

// Stats, the Activity performance panel and Play stats all run PlayStats.Compute: an empty past Occurrence offered
// nothing, so it adds no Offered, no win and no Likes to any row, and no rate is a division by zero.
[TestMethod]
public void PlayStats_CountsNothingForAnEmptyOccurrence()
{
var metrics = new[] { new EventMetricsWithLikes(weekly.Id, 9, null, null, null, 4) };
var stats = new PlayStats(new FixedClock(new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero)));

var withIt = stats.Compute([night, weekly], [kart], [grandPrix], metrics);
var onlyIt = stats.Compute([weekly], [kart], [grandPrix], metrics);

var row = Assert.ContainsSingle(withIt.Activities);
Assert.AreEqual((1, 1, night.Date), (row.Offered, row.Wins, row.LastOffered));
Assert.AreEqual(new ActivityPerformance(1m, 0m, null), row.Performance);
var unused = Assert.ContainsSingle(onlyIt.Activities);
Assert.AreEqual((0, 0, (DateTimeOffset?)null), (unused.Offered, unused.Wins, unused.LastOffered));
Assert.AreEqual(new ActivityPerformance(null, null, null), unused.Performance);
Assert.AreEqual(0, Assert.ContainsSingle(onlyIt.Games).Offered);
}

// The Stats page renders with an empty Occurrence in the list: no "NaN", the Activity's numbers from the one Event.
[TestMethod]
public void TheStatsPage_RendersWithAnEmptyOccurrence()
{
api.Json(HttpMethod.Get, "/api/event-metrics", Array.Empty<EventMetricsWithLikes>());
var page = harness.Render<Stats>();

page.WaitForAssertion(() => Assert.HasCount(2, page.FindAll("tbody tr.fluent-data-grid-row")));
Assert.DoesNotContain("NaN", page.Markup);
Assert.AreEqual("1", page.Find("table.stats-activities .stats-offered").TextContent.Trim());
Assert.IsEmpty(page.PageAlerts());
}

// ---- helpers -------------------------------------------------------------------------------

private IRenderedComponent<Events> Loaded()
{
var page = harness.Render<Events>();
page.WaitForRows(2);
return page;
}

private static AngleSharp.Dom.IElement Row(IRenderedComponent<Events> page, string name) =>
page.FindAll("tbody tr.fluent-data-grid-row").Single(r => r.TextContent.Contains(name));

private sealed class FixedClock(DateTimeOffset now) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => now;
}
}
1 change: 1 addition & 0 deletions MW-GC.EventManager.Web.Tests/PageHarness.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public PageHarness(StubApiHandler api)
_context.Services.AddLibraryClients();
_context.Services.AddSingleton(new ActivityService(http));
_context.Services.AddSingleton(new EventService(http));
_context.Services.AddSingleton(new SeriesService(http));
_context.Services.AddSingleton(new EventMetricsClient(http));
_context.Services.AddSingleton(new CommentClient(http));
_context.Services.AddScoped<FocusReturn>();
Expand Down
164 changes: 164 additions & 0 deletions MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
using MW_GC.EventManager.Shared.Series;
using MW_GC.EventManager.Web.Shared.Events;

namespace MW_GC.EventManager.Web.Tests;

// #100, #204: the Repeat section's pure model. Every expected value is written out by hand: 10 December 2026 is a
// Thursday in the second week of its month, 31 December 2026 a Thursday in its last, and Thanksgiving 2026 is 26
// November (the fourth Thursday).
[TestClass]
public sealed class RepeatChoiceTests
{
private static readonly TimeSpan Chicago = TimeSpan.FromHours(-6);
private static readonly DateTimeOffset SecondThursday = new(2026, 12, 10, 19, 0, 0, Chicago);

[TestMethod]
public void ANewChoice_IsOff_AndWeekly_WithNoEnd()
{
var choice = new RepeatChoice();

Assert.IsFalse(choice.IsOn);
Assert.AreEqual(RecurrenceKind.Weekly, choice.Kind);
Assert.IsNull(choice.EndDate);
Assert.IsNull(choice.EndFor(SecondThursday));
Assert.IsNull(choice.ScheduleFor(SecondThursday).End);
}

[TestMethod]
public void TheRulesAreOffered_InTheseWords_WeeklyFirst()
{
CollectionAssert.AreEqual(
new[] { "Weekly", "Every other week", "Monthly on the nth weekday", "Monthly on the same date", "Yearly on the same date", "Yearly on a holiday" },
RepeatChoice.Rules.Select(r => r.Name).ToArray());
CollectionAssert.AreEqual(new[] { "First", "Second", "Third", "Fourth", "Last" }, RepeatChoice.Weeks.Select(w => w.Name).ToArray());
}

[TestMethod]
[DataRow(RecurrenceKind.Weekly)]
[DataRow(RecurrenceKind.BiWeekly)]
[DataRow(RecurrenceKind.MonthlyNthWeekday)]
[DataRow(RecurrenceKind.MonthlySameDate)]
[DataRow(RecurrenceKind.AnnualSameDate)]
[DataRow(RecurrenceKind.AnnualHoliday)]
public void EachRule_MakesItsExactRecurrenceRule(RecurrenceKind kind)
{
var choice = new RepeatChoice { IsOn = true, Kind = kind };

var expected = kind switch
{
RecurrenceKind.Weekly => new RecurrenceRule(RecurrenceKind.Weekly),
RecurrenceKind.BiWeekly => new RecurrenceRule(RecurrenceKind.BiWeekly),
RecurrenceKind.MonthlyNthWeekday => new RecurrenceRule(RecurrenceKind.MonthlyNthWeekday, WeekOfMonth.Second, DayOfWeek.Thursday),
RecurrenceKind.MonthlySameDate => new RecurrenceRule(RecurrenceKind.MonthlySameDate),
RecurrenceKind.AnnualSameDate => new RecurrenceRule(RecurrenceKind.AnnualSameDate),
_ => new RecurrenceRule(RecurrenceKind.AnnualHoliday, Preset: HolidayPreset.NewYearsDay),
};
Assert.AreEqual(expected, choice.ScheduleFor(SecondThursday).Rule);
}

// A Thursday in the second week gives Second and Thursday.
[TestMethod]
public void TheNthWeekday_DefaultsToThePickedDatesWeekAndWeekday()
{
var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.MonthlyNthWeekday };

Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Second, DayOfWeek.Thursday), choice.ScheduleFor(SecondThursday).Rule);
}

[TestMethod]
[DataRow(1, WeekOfMonth.First)]
[DataRow(7, WeekOfMonth.First)]
[DataRow(8, WeekOfMonth.Second)]
[DataRow(14, WeekOfMonth.Second)]
[DataRow(15, WeekOfMonth.Third)]
[DataRow(21, WeekOfMonth.Third)]
[DataRow(22, WeekOfMonth.Fourth)]
[DataRow(28, WeekOfMonth.Fourth)]
[DataRow(29, WeekOfMonth.Last)]
[DataRow(31, WeekOfMonth.Last)]
public void TheDefaultWeek_FollowsTheDay(int day, WeekOfMonth week) =>
Assert.AreEqual(week, RepeatChoice.DefaultWeek(new DateOnly(2026, 12, day)));

// A date in the last week (a fifth Thursday) is Last, never a Fourth one week too early.
[TestMethod]
public void ADateInTheLastWeek_GivesLast()
{
var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.MonthlyNthWeekday };

Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Last, DayOfWeek.Thursday),
choice.ScheduleFor(new DateTimeOffset(2026, 12, 31, 19, 0, 0, Chicago)).Rule);
}

[TestMethod]
public void AChosenWeekAndWeekday_WinOverTheDate()
{
var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.MonthlyNthWeekday, ChosenWeek = WeekOfMonth.Last, ChosenWeekday = DayOfWeek.Friday };

Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Last, DayOfWeek.Friday), choice.ScheduleFor(SecondThursday).Rule);
}

// 23:30 on Thursday at UTC-06:00 is already Friday in UTC: the weekday is read at the start's own offset.
[TestMethod]
public void TheWeekday_IsReadAtTheStartsOwnOffset()
{
var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.MonthlyNthWeekday };
var late = new DateTimeOffset(2026, 12, 10, 23, 30, 0, Chicago);

Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Second, DayOfWeek.Thursday), choice.ScheduleFor(late).Rule);
}

[TestMethod]
public void TheHoliday_DefaultsToTheOneOnThePickedDate_AndAChosenOneWins()
{
var thanksgiving = new DateTimeOffset(2026, 11, 26, 18, 0, 0, Chicago);
var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.AnnualHoliday };

Assert.AreEqual(RecurrenceRule.AnnualHoliday(HolidayPreset.Thanksgiving), choice.ScheduleFor(thanksgiving).Rule);
choice.ChosenHoliday = HolidayPreset.EasterSunday;
Assert.AreEqual(RecurrenceRule.AnnualHoliday(HolidayPreset.EasterSunday), choice.ScheduleFor(thanksgiving).Rule);
}

// One table of names: every preset has exactly one readable name, and the names are distinct.
[TestMethod]
public void EveryHolidayPreset_HasOneReadableName()
{
foreach (var preset in Enum.GetValues<HolidayPreset>())
{
var name = Assert.ContainsSingle(RepeatChoice.Holidays.Where(h => h.Value == preset)).Name;
Assert.IsFalse(string.IsNullOrWhiteSpace(name), preset.ToString());
}
Assert.HasCount(Enum.GetValues<HolidayPreset>().Length, RepeatChoice.Holidays);
Assert.HasCount(RepeatChoice.Holidays.Count, RepeatChoice.Holidays.Select(h => h.Name).Distinct());
Assert.AreEqual("Thanksgiving", RepeatChoice.HolidayName(HolidayPreset.Thanksgiving));
Assert.AreEqual("Martin Luther King Jr. Day", RepeatChoice.HolidayName(HolidayPreset.MartinLutherKingJrDay));
Assert.AreEqual("St. Patrick's Day", RepeatChoice.HolidayName(HolidayPreset.StPatricksDay));
}

// The start is sent exactly as given, its offset kept, and the end is the end date at the start's time and offset.
[TestMethod]
public void TheSchedule_KeepsTheStartsOffset_AndPutsTheEndAtItsTimeAndOffset()
{
var choice = new RepeatChoice { IsOn = true, EndDate = new DateOnly(2027, 3, 4) };

var schedule = choice.ScheduleFor(SecondThursday);

Assert.AreEqual(SecondThursday, schedule.First);
Assert.AreEqual(Chicago, schedule.First.Offset);
Assert.AreEqual(new DateTimeOffset(2027, 3, 4, 19, 0, 0, Chicago), schedule.End);
Assert.AreEqual(Chicago, schedule.End!.Value.Offset);
}

[TestMethod]
[DataRow(2026, 12, 9, true)]
[DataRow(2026, 12, 10, true)]
[DataRow(2026, 12, 11, false)]
public void AnEndNotAfterTheStart_GivesTheApisWording(int year, int month, int day, bool refused)
{
var choice = new RepeatChoice { IsOn = true, EndDate = new DateOnly(year, month, day) };

Assert.AreEqual(refused ? "End must be after the start." : null, choice.EndProblem(SecondThursday));
}

[TestMethod]
public void NoEnd_IsNoProblem() => Assert.IsNull(new RepeatChoice { IsOn = true }.EndProblem(SecondThursday));
}
Loading
Loading