using HSchool.Ai; using HSchool.Content; using HSchool.People; using HSchool.Schedule; namespace HSchool.Simulation.Tests; public class PresenceTests { private static readonly DateTime TuesdayMorning = new(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc); private static readonly float Cap = 100_000f; [Fact] public void SundayAndHoliday_LeaveTheCampusEmpty() { var (catalog, map) = Vanilla(); var sunday = new DateTime(2012, 4, 8, 10, 0, 0, DateTimeKind.Utc); using var onSunday = Open(catalog, map, sunday, seed: 1); onSunday.Tick(0.2d, 5d); Assert.True(onSunday.IsCampusEmpty()); Assert.All(onSunday.CapturePresence(), row => Assert.Null(row.NodeId)); var holiday = new DateTime(2012, 6, 1, 10, 0, 0, DateTimeKind.Utc); using var onHoliday = Open(catalog, map, holiday, seed: 1); onHoliday.Tick(0.2d, 5d); Assert.True(onHoliday.IsCampusEmpty()); } [Fact] public void ClassWithoutLessons_StaysAway_TeacherWithAnotherClassComes() { var (catalog, map) = Vanilla(); var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Russia", TuesdayMorning); var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Russia", TuesdayMorning); var idle = roster.Classes[0]; var busy = roster.Classes[1]; var hired = Staffing.Hire(catalog, map, roster, pool, pool.Applicants[0].Person.Id, Staffing.TeacherPosition, Cap); Assert.Equal(StaffingError.None, hired.Error); using var school = School.Create(1, "Два класса", TuesdayMorning, catalog, map); school.InstallPeople(hired.Roster, seed: 1, "Russia", hired.Pool); school.SetTimetable(new Timetable( [new LessonPlacement(busy.Id, "Mathematics", hired.Roster.People.First(person => person.IsStaff).Id, busy.RoomId, Day: 1, Period: 1)], [])); school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000); AdvanceTo(school, new DateTime(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc)); var teacherId = school.Roster!.People.First(person => person.IsStaff).Id; var idlePupil = idle.PupilIds[0]; var byId = school.CapturePresence().ToDictionary(row => row.PersonId, StringComparer.Ordinal); Assert.Null(byId[idlePupil].NodeId); Assert.NotNull(byId[teacherId].NodeId); } [Fact] public void FirstLesson_PutsThePupilInTheirHomeroom() { var (school, homeroom, pupilId) = StaffedFirstFloorClass(); using (school) { AdvanceTo(school, new DateTime(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc)); var row = school.CapturePresence().Single(item => item.PersonId == pupilId); Assert.Equal(homeroom, row.NodeId); Assert.Empty(row.Path); } } [Fact] public void PhysicalEducationAfterAClassroomLesson_ReachesTheGymOnTheBreak() { var (catalog, map) = Vanilla(); var walks = WalkGraph.Build(catalog, map); Assert.Equal(6f, walks.Minutes("classroom-101", "gym-hall")); Assert.True(walks.Minutes("classroom-101", "gym-hall") < catalog.DayFrame!.BreakMinutes); var (school, _, pupilId) = StaffedFirstFloorClass(); using (school) { AdvanceTo(school, new DateTime(2012, 4, 3, 9, 25, 0, DateTimeKind.Utc)); var row = school.CapturePresence().Single(item => item.PersonId == pupilId); Assert.Equal("gym-hall", row.NodeId); Assert.Empty(row.Path); } } [Fact] public void SameSeedAndMap_YieldTheSamePlaces() { var (catalog, map) = Vanilla(); using var a = OpenStaffed(catalog, map, seed: 9); using var b = OpenStaffed(catalog, map, seed: 9); var until = new DateTime(2012, 4, 3, 9, 20, 0, DateTimeKind.Utc); AdvanceTo(a, until); AdvanceTo(b, until); Assert.Equal(Fingerprint(a.CapturePresence()), Fingerprint(b.CapturePresence())); } [Fact] public void SaveAndLoadMidBreak_DoesNotTeleport() { var (catalog, map) = Vanilla(); using var live = OpenStaffed(catalog, map, seed: 4); AdvanceTo(live, new DateTime(2012, 4, 3, 9, 18, 0, DateTimeKind.Utc)); var snapshot = live.CapturePresence(); Assert.Contains(snapshot, row => row.NodeId is not null && (row.Path.Count > 0 || row.RemainingMinutes > 0)); using var loaded = School.Load(2, "Сейв", live.Clock.Time, running: true, speedIndex: 0, catalog, map); loaded.InstallPeople(live.Roster!, seed: 4, "Russia", live.Applicants); loaded.SetTimetable(live.Timetable!); loaded.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000); loaded.RestorePresence(snapshot); Assert.Equal(Fingerprint(snapshot), Fingerprint(loaded.CapturePresence())); } [Fact] public void SkipEmpty_FromSaturdayLandsOnMondaySix() { using var school = OpenEmpty(new DateTime(2012, 4, 7, 10, 0, 0, DateTimeKind.Utc)); var result = school.TrySkipEmpty(); Assert.True(result.Succeeded); Assert.Equal(new DateTime(2012, 4, 9, 6, 0, 0, DateTimeKind.Utc), school.Clock.Time); } [Fact] public void SkipEmpty_FromTuesdayNightLandsOnThatMorning() { using var school = OpenEmpty(new DateTime(2012, 4, 3, 3, 0, 0, DateTimeKind.Utc)); var result = school.TrySkipEmpty(); Assert.True(result.Succeeded); Assert.Equal(new DateTime(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc), school.Clock.Time); } [Fact] public void SkipEmpty_FromTuesdayEveningLandsOnWednesday() { using var school = OpenEmpty(new DateTime(2012, 4, 3, 22, 0, 0, DateTimeKind.Utc)); var result = school.TrySkipEmpty(); Assert.True(result.Succeeded); Assert.Equal(new DateTime(2012, 4, 4, 6, 0, 0, DateTimeKind.Utc), school.Clock.Time); } [Fact] public void SkipEmpty_InTheWorkWindow_IsRejectedEvenWhenEmpty() { using var school = OpenEmpty(new DateTime(2012, 4, 3, 7, 0, 0, DateTimeKind.Utc)); Assert.True(school.IsCampusEmpty()); var result = school.TrySkipEmpty(); Assert.False(result.Succeeded); Assert.Equal(SkipEmptyError.InWorkWindow, result.Error); Assert.Equal(new DateTime(2012, 4, 3, 7, 0, 0, DateTimeKind.Utc), school.Clock.Time); } [Fact] public void SkipEmpty_SchoolWithoutTeachers_StillHasAWorkDay() { using var school = OpenEmpty(new DateTime(2012, 4, 3, 10, 0, 0, DateTimeKind.Utc)); Assert.Equal(0, school.Roster!.People.Count(person => person.IsStaff)); var result = school.TrySkipEmpty(); Assert.False(result.Succeeded); Assert.Equal(SkipEmptyError.InWorkWindow, result.Error); } [Fact] public void SkipEmpty_OverSummer_RunsFirstSeptemberIntake() { var start = new DateTime(2012, 6, 1, 22, 0, 0, DateTimeKind.Utc); using var school = OpenEmpty(start); var before = school.Roster!; var oldest = before.Classes.Max(row => row.Year); var graduated = before.Classes .Where(row => row.Year == oldest) .SelectMany(row => row.PupilIds) .ToHashSet(StringComparer.Ordinal); var result = school.TrySkipEmpty(); Assert.True(result.Succeeded); Assert.True(result.PeopleChanged); Assert.Equal(new DateTime(2012, 9, 3, 6, 0, 0, DateTimeKind.Utc), school.Clock.Time); Assert.Contains(school.Roster!.Classes, row => row.Year == 1); Assert.DoesNotContain(school.Roster.People, person => graduated.Contains(person.Id)); Assert.Equal(before.People.Count(person => person.IsStudent), school.Roster.People.Count(person => person.IsStudent)); } [Fact] public void SkipEmpty_Week_MatchesALivedWeek() { var start = new DateTime(2012, 4, 6, 22, 0, 0, DateTimeKind.Utc); var until = new DateTime(2012, 4, 9, 6, 0, 0, DateTimeKind.Utc); using var skipped = OpenEmpty(start); using var lived = OpenEmpty(start); Assert.True(skipped.TrySkipEmpty().Succeeded); while (lived.Clock.Time < until) { lived.Tick(0.2d, 5d); } Assert.Equal(until, skipped.Clock.Time); Assert.Equal(until, lived.Clock.Time); Assert.Equal(skipped.Applicants!.Week, lived.Applicants!.Week); Assert.Equal( skipped.Applicants.Applicants.Select(row => row.Person.Id), lived.Applicants.Applicants.Select(row => row.Person.Id)); Assert.Equal( skipped.Roster!.People.Select(person => person.Id).Order(StringComparer.Ordinal), lived.Roster!.People.Select(person => person.Id).Order(StringComparer.Ordinal)); Assert.True(skipped.IsCampusEmpty()); Assert.True(lived.IsCampusEmpty()); Assert.Equal(Fingerprint(skipped.CapturePresence()), Fingerprint(lived.CapturePresence())); } [Fact] public void HireAndAssignMath_DuringLessonThree_PutsSomeoneOnCampus() { var start = new DateTime(2012, 4, 3, 10, 20, 0, DateTimeKind.Utc); using var school = OpenEmpty(start); school.Tick(0.2d, 5d); Assert.True(school.IsCampusEmpty()); var catalog = school.Catalog!; var map = school.Map!; var hired = Staffing.Hire( catalog, map, school.Roster!, school.Applicants!, school.Applicants!.Applicants[0].Person.Id, Staffing.TeacherPosition, Cap); Assert.Equal(StaffingError.None, hired.Error); school.ApplyStaffing(hired.Roster, hired.Pool); var assigned = Staffing.AssignSubject(catalog, hired.Roster, hired.Pool, hired.Roster.People.Single(person => person.IsStaff).Id, "Mathematics", Cap); Assert.Equal(StaffingError.None, assigned.Error); school.ApplyStaffing(assigned.Roster, assigned.Pool); school.SetTimetable(SchoolTimetables.Build(catalog, map, assigned.Roster, null, weekDays: 5)); for (var i = 0; i < 20; i++) { school.Tick(0.2d, 5d); } Assert.Contains(school.CapturePresence(), row => row.NodeId is not null); } [Fact] public void Simulation_DoesNotReferenceSockets() { var names = typeof(School).Assembly.GetReferencedAssemblies().Select(assembly => assembly.Name!); Assert.DoesNotContain(names, name => name.Contains("Sockets", StringComparison.OrdinalIgnoreCase)); Assert.DoesNotContain(names, name => name.Contains("AspNet", StringComparison.OrdinalIgnoreCase)); } private static (School School, string Homeroom, string PupilId) StaffedFirstFloorClass() { var (catalog, map) = Vanilla(); var school = OpenStaffed(catalog, map, seed: 1); var homeroomClass = school.Roster!.Classes.First(row => row.RoomId is "classroom-101" or "classroom-102" or "classroom-103" or "classroom-104"); var pupil = homeroomClass.PupilIds .Select(id => school.Roster.People.First(person => person.Id == id)) .First(person => !person.Traits.Contains("Lazy")); return (school, homeroomClass.RoomId, pupil.Id); } private static School OpenStaffed(DefCatalog catalog, MapLayout map, int seed) { var roster = RosterGenerator.Generate(catalog, map, seed, "Russia", TuesdayMorning); var pool = ApplicantPool.Create(catalog, roster, seed, "Russia", TuesdayMorning); var schoolClass = roster.Classes.First(row => row.RoomId is "classroom-101" or "classroom-102" or "classroom-103" or "classroom-104"); var school = School.Create(seed, "Присутствие", TuesdayMorning, catalog, map); school.InstallPeople(roster, seed, "Russia", pool); school.SetTimetable(new Timetable( [ new LessonPlacement(schoolClass.Id, "Mathematics", "t1", schoolClass.RoomId, Day: 1, Period: 1), new LessonPlacement(schoolClass.Id, "PhysicalEducation", "t2", "gym-hall", Day: 1, Period: 2), ], [])); school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000); return school; } private static School Open(DefCatalog catalog, MapLayout map, DateTime start, int seed) { var roster = RosterGenerator.Generate(catalog, map, seed, "Russia", start); var pool = ApplicantPool.Create(catalog, roster, seed, "Russia", start); var schoolClass = roster.Classes[0]; var school = School.Create(seed, "Присутствие", start, catalog, map); school.InstallPeople(roster, seed, "Russia", pool); school.SetTimetable(new Timetable( [new LessonPlacement(schoolClass.Id, "Mathematics", "t1", schoolClass.RoomId, Day: 0, Period: 1)], [])); school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000); return school; } private static School OpenEmpty(DateTime start) { var (catalog, map) = Vanilla(); var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Russia", start); var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Russia", start); var school = School.Create(1, "Пустая", start, catalog, map); school.InstallPeople(roster, seed: 1, "Russia", pool); school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000); return school; } private static void AdvanceTo(School school, DateTime until) { while (school.Clock.Time < until) { school.Tick(0.2d, 5d); } } private static string Fingerprint(IReadOnlyList rows) => string.Join( "|", rows.OrderBy(row => row.PersonId, StringComparer.Ordinal) .Select(row => $"{row.PersonId}:{row.NodeId ?? "-"}:{row.RemainingMinutes:0.###}:{row.DestinationId ?? "-"}:{(row.HeadingHome ? "1" : "0")}:{string.Join(",", row.Path)}")); private static (DefCatalog Catalog, MapLayout Map) Vanilla() { var root = Path.Combine(AppContext.BaseDirectory, "vanilla"); var documents = new List(); foreach (var path in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories)) { if (!path.EndsWith(".jsonc", StringComparison.OrdinalIgnoreCase) && !path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) { continue; } var relative = Path.GetRelativePath(root, path).Replace('\\', '/'); documents.Add(new ContentDocument(CatalogLoader.CorePackId, relative, File.ReadAllText(path))); } var catalog = new CatalogLoader().Load([CatalogLoader.CorePackId], documents); var map = CatalogLoader.LastDefaultMap([CatalogLoader.CorePackId], documents); Assert.NotNull(map); return (catalog, map); } }