Merge branch 'phase/73-lesson-marks'

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Leonid Pershin
2026-08-21 12:00:53 +03:00
co-authored by Cursor
17 changed files with 703 additions and 22 deletions
+65
View File
@@ -0,0 +1,65 @@
using HSchool.Content;
namespace HSchool.Ai.Tests;
public class LessonMarkTests
{
private static readonly BehaviorDef Rules = new()
{
DefName = "Behavior",
LessonMarkThresholds = BehaviorDef.DefaultLessonMarkThresholds,
LessonMarkMax = 40,
LessonMarkWhenNoTeacher = 2,
};
[Fact]
public void StrongTeacher_MarkIsAtLeastEmptyRoomMark()
{
var strongQuality = LessonLearning.Quality(
hunger: 1f,
traitOffset: 0,
teacherSkill: 100f,
warmth: 1f,
textbookFactor: 1f);
var strong = LessonLearning.Mark(strongQuality, Rules);
var emptyRoom = Rules.LessonMarkWhenNoTeacher!.Value;
Assert.True(strong >= emptyRoom);
Assert.Equal(5, strong);
Assert.Equal(2, emptyRoom);
}
[Fact]
public void SameInputs_SameMark()
{
var first = LessonLearning.Mark(
LessonLearning.Quality(0.8f, 4, 70f, 0.9f, 0.5f),
Rules);
var second = LessonLearning.Mark(
LessonLearning.Quality(0.8f, 4, 70f, 0.9f, 0.5f),
Rules);
Assert.Equal(first, second);
Assert.InRange(first, 2, 5);
}
[Fact]
public void ZeroMultiplier_YieldsLowestMark()
{
var mark = LessonLearning.Mark(
LessonLearning.Quality(1f, 0, 100f, 1f, textbookFactor: 0f),
Rules);
Assert.Equal(2, mark);
}
[Theory]
[InlineData(0.85f, 5)]
[InlineData(0.6f, 4)]
[InlineData(0.35f, 3)]
[InlineData(0.34f, 2)]
public void Thresholds_MapQualityToMark(float quality, int expected)
{
Assert.Equal(expected, LessonLearning.Mark(quality, Rules));
}
}
@@ -0,0 +1,41 @@
using System.Net;
using System.Net.Http.Json;
namespace HSchool.AppHost.Tests;
[Collection(AppHostCollection.Name)]
public class LessonMarkApiTests(AppHostFixture fixture)
{
private static readonly DateTime Start = new(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc);
[Fact]
public async Task PostMark_IsNotAccepted()
{
using var client = fixture.App.CreateHttpClient("server");
await SchoolApiTests.ResetAsync(client);
var school = await SchoolApiTests.CreateAsync(client, "Оценка API", Start, seed: 73);
var page = await client.GetFromJsonAsync<PeoplePage>(
$"/api/schools/{school.Id}/people?role=student&pageSize=1",
TestContext.Current.CancellationToken);
Assert.NotNull(page);
Assert.NotEmpty(page.People);
var personId = page.People[0].Id;
using var response = await client.PostAsJsonAsync(
$"/api/schools/{school.Id}/people/{personId}/marks",
new { subject = "Mathematics", value = 5, period = 1 },
TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
using var put = await client.PutAsJsonAsync(
$"/api/schools/{school.Id}/people/{personId}/marks",
new { subject = "Mathematics", value = 5, period = 1 },
TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NotFound, put.StatusCode);
}
private sealed record PeoplePage(IReadOnlyList<PersonRow> People);
private sealed record PersonRow(string Id);
}
@@ -0,0 +1,43 @@
using HSchool.Content;
namespace HSchool.Content.Tests;
public class LessonMarkBehaviorTests
{
private readonly CatalogLoader _loader = new();
[Fact]
public void MissingLessonMarkFields_UseVanillaDefaults()
{
var catalog = _loader.Load(
[CatalogLoader.CorePackId],
[
PackDocuments.Def(
CatalogLoader.CorePackId,
"behavior",
"rules",
"""{ "defName": "Behavior", "needThreshold": 0.35, "lessonSkillPerHour": 0.05, "commuteSlackMin": 0, "commuteSlackMax": 6, "switchMargin": 0.15 }"""),
]);
Assert.NotNull(catalog.BehaviorRules);
Assert.Equal(40, catalog.BehaviorRules.LessonMarkMax);
Assert.Equal(2, catalog.BehaviorRules.LessonMarkWhenNoTeacher);
Assert.Equal(BehaviorDef.DefaultLessonMarkThresholds, catalog.BehaviorRules.LessonMarkThresholds);
}
[Fact]
public void AscendingThresholds_FailTheCatalog()
{
var error = Assert.Throws<ContentLoadException>(() => _loader.Load(
[CatalogLoader.CorePackId],
[
PackDocuments.Def(
CatalogLoader.CorePackId,
"behavior",
"rules",
"""{ "defName": "Behavior", "lessonMarkThresholds": [0.3, 0.6, 0.9] }"""),
]));
Assert.Contains("descending", error.Message, StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,100 @@
using HSchool.Content;
namespace HSchool.People.Tests;
public class LessonMarkMemoryTests
{
[Fact]
public void OverCeiling_DropsTheOldest()
{
var person = Blank("a");
var rules = Rules(max: 2);
var t0 = new DateTime(2012, 4, 3, 10, 0, 0, DateTimeKind.Utc);
Assert.True(LessonMarkMemory.Record(person, "Mathematics", 5, t0, period: 1, rules));
Assert.True(LessonMarkMemory.Record(person, "Literature", 4, t0.AddMinutes(1), period: 2, rules));
Assert.True(LessonMarkMemory.Record(person, "History", 3, t0.AddMinutes(2), period: 3, rules));
Assert.Equal(2, person.LessonMarks!.Count);
Assert.Equal("Literature", person.LessonMarks[0].Subject);
Assert.Equal("History", person.LessonMarks[1].Subject);
}
[Fact]
public void RosterJson_RoundTripsLessonMarks_AndOmitsEmpty()
{
var roster = Fixtures.Generate(Fixtures.Classrooms(4));
var pupil = roster.People.First(person => person.IsStudent && !person.IsParent);
var time = new DateTime(2012, 4, 3, 11, 20, 0, DateTimeKind.Utc);
LessonMarkMemory.Record(pupil, "Mathematics", 4, time, period: 1, Rules(max: 40));
var json = RosterJson.Serialize(RosterDocument.From(1, roster));
Assert.Contains("\"lessonMarks\"", json, StringComparison.Ordinal);
Assert.Contains("\"value\": 4", json, StringComparison.Ordinal);
Assert.Contains("\"subject\": \"Mathematics\"", json, StringComparison.Ordinal);
var without = roster.People.First(person => person.LessonMarks is null || person.LessonMarks.Count == 0);
var withoutSlice = PersonJsonSlice(json, without.Id);
Assert.DoesNotContain("\"lessonMarks\"", withoutSlice, StringComparison.Ordinal);
var loaded = RosterJson.Parse(json).ToRoster();
var loadedPupil = loaded.People.First(person => person.Id.Equals(pupil.Id, StringComparison.Ordinal));
Assert.NotNull(loadedPupil.LessonMarks);
Assert.Single(loadedPupil.LessonMarks!);
Assert.Equal(4, loadedPupil.LessonMarks[0].Value);
Assert.Equal("Mathematics", loadedPupil.LessonMarks[0].Subject);
Assert.Equal(1, loadedPupil.LessonMarks[0].Period);
Assert.Equal(time, loadedPupil.LessonMarks[0].Time);
}
private static string PersonJsonSlice(string json, string personId)
{
var marker = $"\"id\": \"{personId}\"";
var start = json.IndexOf(marker, StringComparison.Ordinal);
Assert.True(start >= 0);
var end = json.IndexOf("},", start, StringComparison.Ordinal);
if (end < 0)
{
end = json.Length;
}
return json[start..end];
}
private static BehaviorDef Rules(int max) => new()
{
DefName = "Behavior",
LessonMarkMax = max,
LessonMarkThresholds = BehaviorDef.DefaultLessonMarkThresholds,
LessonMarkWhenNoTeacher = 2,
};
private static Person Blank(string id)
{
var cases = new CaseTable
{
Nom = id,
Gen = id,
Dat = id,
Acc = id,
Ins = id,
Pre = id,
};
return new Person
{
Id = id,
FamilyId = "f",
Female = false,
BirthDate = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc),
Name = new PersonName(id, id, id, cases, cases, cases),
IsStudent = true,
IsStaff = false,
IsParent = false,
Numbers = new Dictionary<string, int>(StringComparer.Ordinal),
Choices = new Dictionary<string, string>(StringComparer.Ordinal),
Skills = new Dictionary<string, int>(StringComparer.Ordinal),
Traits = [],
Needs = new Dictionary<string, float>(StringComparer.Ordinal),
Opinions = new Dictionary<string, int>(StringComparer.Ordinal),
};
}
}
@@ -0,0 +1,14 @@
using HSchool.Protocol;
namespace HSchool.Protocol.Tests;
public class LessonMarkProtocolTests
{
[Fact]
public void Wire_HasNoClientSetMarkMessage()
{
var names = Enum.GetNames<MessageType>();
Assert.DoesNotContain(names, name => name.Contains("Mark", StringComparison.OrdinalIgnoreCase));
Assert.DoesNotContain(names, name => name.Contains("Grade", StringComparison.OrdinalIgnoreCase));
}
}
@@ -0,0 +1,175 @@
using Arch.Core;
using HSchool.Ai;
using HSchool.Content;
using HSchool.People;
using HSchool.Schedule;
namespace HSchool.Simulation.Tests;
public class LessonMarkSimulationTests
{
private static readonly DateTime TuesdayMorning = new(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc);
private static readonly DateTime LessonStart = new(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc);
[Fact]
public void StrongTeacher_MarkIsAtLeastEmptyRoom()
{
var (withTeacher, room, pupilId, teacherId) = StaffedMath();
using (withTeacher)
{
AdvanceTo(withTeacher, LessonStart);
SetPlace(withTeacher, pupilId, room);
SetPlace(withTeacher, teacherId, room);
PlaceTextbook(withTeacher, pupilId, "Mathematics", ItemLocations.Bag);
LessonLearningSystem.Apply(withTeacher, 45);
var strong = MarkOf(withTeacher, pupilId);
Assert.NotNull(strong);
Assert.InRange(strong!.Value, 2, 5);
var (empty, emptyRoom, emptyPupil, emptyTeacher) = StaffedMath();
using (empty)
{
AdvanceTo(empty, LessonStart);
SetPlace(empty, emptyPupil, emptyRoom);
SetPlace(empty, emptyTeacher, "restroom-1");
LessonLearningSystem.Apply(empty, 45);
var absent = MarkOf(empty, emptyPupil);
Assert.NotNull(absent);
Assert.Equal(2, absent!.Value);
Assert.True(strong.Value >= absent.Value);
}
}
}
[Fact]
public void OneSlot_DoesNotWriteEveryMinute()
{
var (school, room, pupilId, teacherId) = StaffedMath();
using (school)
{
AdvanceTo(school, LessonStart);
SetPlace(school, pupilId, room);
SetPlace(school, teacherId, room);
PlaceTextbook(school, pupilId, "Mathematics", ItemLocations.Bag);
LessonLearningSystem.Apply(school, 5);
LessonLearningSystem.Apply(school, 5);
LessonLearningSystem.Apply(school, 5);
var marks = school.Roster!.People.First(row => row.Id == pupilId).LessonMarks;
Assert.NotNull(marks);
Assert.Single(marks!);
}
}
[Fact]
public void NoTeacher_WritesConfiguredMark()
{
var (school, room, pupilId, teacherId) = StaffedMath();
using (school)
{
Assert.Equal(2, school.Catalog!.BehaviorRules!.LessonMarkWhenNoTeacher);
AdvanceTo(school, LessonStart);
SetPlace(school, pupilId, room);
SetPlace(school, teacherId, "restroom-1");
LessonLearningSystem.Apply(school, 45);
var mark = MarkOf(school, pupilId);
Assert.NotNull(mark);
Assert.Equal(2, mark!.Value);
Assert.Equal("Mathematics", mark.Subject);
}
}
private static LessonMarkRecord? MarkOf(School school, string pupilId) =>
school.Roster!.People.First(row => row.Id == pupilId).LessonMarks?.LastOrDefault();
private static (School School, string Homeroom, string PupilId, string TeacherId) StaffedMath(
string? teacherId = null)
{
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 hired = Staffing.Hire(catalog, map, roster, pool, pool.Applicants[0].Person.Id, Staffing.TeacherPosition, 1_000_000f);
Assert.Equal(StaffingError.None, hired.Error);
roster = hired.Roster;
pool = hired.Pool;
var hiredId = roster.People.First(person => person.IsStaff).Id;
var schoolClass = roster.Classes.First(row =>
row.RoomId is "classroom-101" or "classroom-102" or "classroom-103" or "classroom-104");
var school = School.Create(1, "Оценка", TuesdayMorning, catalog, map);
school.InstallPeople(roster, seed: 1, "Russia", pool);
school.SetTimetable(new Timetable(
[new LessonPlacement(schoolClass.Id, "Mathematics", teacherId ?? hiredId, schoolClass.RoomId, Day: 1, Period: 1)],
[]));
school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
var pupil = schoolClass.PupilIds
.Select(id => school.Roster!.People.First(person => person.Id == id))
.First(person => !person.Traits.Contains("Lazy"));
return (school, schoolClass.RoomId, pupil.Id, hiredId);
}
private static void PlaceTextbook(School school, string personId, string subject, string location)
{
var person = school.Roster!.People.First(row => row.Id.Equals(personId, StringComparison.Ordinal));
if (person.Items is not IList<InventoryItem> items || items.IsReadOnly)
{
throw new InvalidOperationException($"Cannot mutate items for {personId}.");
}
for (var i = items.Count - 1; i >= 0; i--)
{
if (items[i].Subject is not null)
{
items.RemoveAt(i);
}
}
items.Add(new InventoryItem("Textbook", Color: null, Condition: 1f, location, subject));
}
private static void AdvanceTo(School school, DateTime until)
{
while (school.Clock.Time < until)
{
school.Tick(0.2d, 5d);
}
}
private static void SetPlace(School school, string personId, string node, string[]? path = null, float remaining = 0f)
{
var query = new QueryDescription().WithAll<PersonIdentity, Presence>();
school.World.Query(
in query,
(ref PersonIdentity identity, ref Presence presence) =>
{
if (identity.Id.Equals(personId, StringComparison.Ordinal))
{
presence = new Presence(node, remaining, node, HeadingHome: false, path ?? []);
}
});
}
private static (DefCatalog Catalog, MapLayout Map) Vanilla()
{
var root = Path.Combine(AppContext.BaseDirectory, "vanilla");
var documents = new List<ContentDocument>();
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);
}
}