Merge main into phase/39-school-owners.

Keep school owners and phase 41 opinions/portraits together; ResetAsync wipes all saves so shared AppHost tests stay isolated.
This commit is contained in:
Leonid Pershin
2026-08-20 08:36:13 +03:00
44 changed files with 1388 additions and 85 deletions
+51 -2
View File
@@ -177,6 +177,36 @@ public class PeopleApiTests(AppHostFixture fixture)
Assert.Contains(motherCard.Family.Children, child => child.Id == card.Id);
}
[Fact]
public async Task Card_ConnectionsCarryOnlyThisPersonsOpinions()
{
using var client = fixture.App.CreateHttpClient("server");
await SchoolApiTests.ResetAsync(client);
var school = await SchoolApiTests.CreateAsync(client, "Связи карточка", Start, seed: 1);
var pupils = await GetPeopleAsync(client, school.Id, "role=student&pageSize=20");
var pupil = pupils.People.First(person => person.Roles.Contains("student"));
var card = await GetCardAsync(client, school.Id, pupil.Id);
Assert.NotNull(card.Connections);
Assert.NotEmpty(card.Connections!.Family.Parents);
Assert.All(card.Connections.Family.Parents, parent =>
{
Assert.NotNull(parent.Opinion);
Assert.True(parent.Opinion > 0);
Assert.False(string.IsNullOrWhiteSpace(parent.OpinionLabel));
});
var linkedIds = card.Connections.Others.Select(row => row.Id).ToHashSet(StringComparer.Ordinal);
foreach (var other in card.Connections.Friends.Concat(card.Connections.Enemies))
{
Assert.DoesNotContain(other.Id, linkedIds);
}
using var bulk = await client.GetAsync($"/api/schools/{school.Id}/people/opinions", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NotFound, bulk.StatusCode);
}
/// <summary>
/// Phases 7 and 9 together: the roster survives a restart, and what comes back is the
/// composition *after* the first-September intake. Generating from the seed again would
@@ -320,7 +350,8 @@ public class PeopleApiTests(AppHostFixture fixture)
IReadOnlyList<LabeledStatResponse> Skills,
IReadOnlyList<DefLabelResponse> Traits,
IReadOnlyList<NeedStatResponse> Needs,
PersonFamilyResponse Family);
PersonFamilyResponse Family,
PersonConnectionsResponse? Connections);
private sealed record LabeledStatResponse(string Id, string Label, string Value);
@@ -332,7 +363,25 @@ public class PeopleApiTests(AppHostFixture fixture)
IReadOnlyList<PersonRelResponse> Siblings,
IReadOnlyList<PersonRelResponse> Partners);
private sealed record PersonRelResponse(string Id, string FullName, bool Female);
private sealed record PersonRelResponse(
string Id,
string FullName,
bool Female,
int? Opinion = null,
string? OpinionLabel = null);
private sealed record PersonOpinionLinkResponse(
string Id,
string FullName,
bool Female,
int Opinion,
string OpinionLabel);
private sealed record PersonConnectionsResponse(
PersonFamilyResponse Family,
IReadOnlyList<PersonOpinionLinkResponse> Friends,
IReadOnlyList<PersonOpinionLinkResponse> Enemies,
IReadOnlyList<PersonOpinionLinkResponse> Others);
private sealed record DirectoryResponse(IReadOnlyList<DirectoryPersonResponse> People);
@@ -1,5 +1,6 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
namespace HSchool.AppHost.Tests;
@@ -104,6 +105,40 @@ public class PortraitApiTests(AppHostFixture fixture)
Assert.False(string.IsNullOrWhiteSpace(settings.ActivePresetId));
}
[Fact]
public async Task CreateSchool_CopiesPortraitSettingsIntoTheSave()
{
using var client = fixture.App.CreateHttpClient("server");
await SchoolApiTests.ResetAsync(client);
var school = await SchoolApiTests.CreateAsync(client, "Пресеты школы", Start);
var directory = await SavesDirectoryAsync(client);
var json = await File.ReadAllTextAsync(
Path.Combine(directory, $"{school.Id}.json"),
TestContext.Current.CancellationToken);
using var document = JsonDocument.Parse(json);
Assert.True(document.RootElement.TryGetProperty("portraitSettings", out var presets));
Assert.True(presets.TryGetProperty("presets", out var list));
Assert.True(list.GetArrayLength() > 0);
}
[Fact]
public async Task CreateSchool_RejectsEmptyPortraitPresets()
{
using var client = fixture.App.CreateHttpClient("server");
await SchoolApiTests.ResetAsync(client);
using var response = await client.PostAsJsonAsync(
"/api/schools",
new
{
name = "Плохие пресеты",
startDate = Start,
portraitSettings = new { activePresetId = "missing", presets = Array.Empty<object>(), ageRules = Array.Empty<object>() },
},
TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("invalid-portrait-settings", await SchoolApiTests.ProblemCodeAsync(response));
}
[Fact]
public async Task DeleteSchool_RemovesPortraitDirectory()
{
+11 -21
View File
@@ -592,26 +592,7 @@ public class SchoolApiTests(AppHostFixture fixture)
internal static async Task ResetAsync(HttpClient client)
{
await LoginAsync(client);
var state = await GetSchoolsAsync(client);
foreach (var school in state.Schools)
{
using var response = await client.DeleteAsync($"/api/schools/{school.Id}", TestContext.Current.CancellationToken);
response.EnsureSuccessStatusCode();
}
foreach (var school in state.Others)
{
using var response = await client.DeleteAsync($"/api/schools/{school.Id}", TestContext.Current.CancellationToken);
if (response.StatusCode == HttpStatusCode.Forbidden)
{
continue;
}
response.EnsureSuccessStatusCode();
}
await WipeAllSavesAsync(client);
}
internal static async Task WipeAllSavesAsync(HttpClient client)
@@ -731,7 +712,16 @@ public class SchoolApiTests(AppHostFixture fixture)
return payload.Path;
}
private sealed record SchoolSaveFile(string? CountryId, string? ClimatePresetId, string? NativeLanguage, string? Owner);
private sealed record SchoolSaveFile(
string? CountryId,
string? ClimatePresetId,
string? NativeLanguage,
string? Owner,
SwarmUiSaveFile? PortraitSettings);
private sealed record SwarmUiSaveFile(string? ActivePresetId, IReadOnlyList<SwarmUiPresetSave>? Presets);
private sealed record SwarmUiPresetSave(string? Id, string? Model);
internal static readonly object SimpleCustomMap = new
{
@@ -71,6 +71,9 @@ public class SchoolOwnerApiTests(AppHostFixture fixture)
{
client.Dispose();
}
using var cleanup = fixture.App.CreateHttpClient("server");
await SchoolApiTests.WipeAllSavesAsync(cleanup);
}
}
@@ -0,0 +1,55 @@
namespace HSchool.People.Tests;
public class OpinionGeneratorTests
{
[Fact]
public void ParentAndChild_HavePositiveOpinionsBothWays_AfterGeneration()
{
var roster = Fixtures.Generate(Fixtures.Classrooms(4));
var people = roster.People.ToDictionary(person => person.Id, StringComparer.Ordinal);
var child = roster.People.First(person => person.IsStudent && !person.IsParent);
var family = roster.Families.Single(row => row.Id.Equals(child.FamilyId, StringComparison.Ordinal));
Assert.NotEmpty(family.ParentIds);
foreach (var parentId in family.ParentIds)
{
Assert.True(child.Opinions.TryGetValue(parentId, out var toParent));
Assert.True(toParent > 0);
var parent = people[parentId];
Assert.True(parent.Opinions.TryGetValue(child.Id, out var toChild));
Assert.True(toChild > 0);
}
}
[Fact]
public void Classmates_HaveNoOpinionEntry_AfterGeneration()
{
var roster = Fixtures.Generate(Fixtures.Classrooms(4));
var pupils = roster.People.Where(person => person.IsStudent).ToArray();
Assert.True(pupils.Length >= 2);
var first = pupils[0];
var classmate = pupils.First(person =>
person.Id != first.Id
&& !OpinionStore.FamilyMemberIds(roster, first).Contains(person.Id));
Assert.False(first.Opinions.ContainsKey(classmate.Id));
Assert.False(classmate.Opinions.ContainsKey(first.Id));
}
[Fact]
public void ParentToChild_AndChildToParent_CanDiffer()
{
var roster = Fixtures.Generate(Fixtures.Classrooms(4));
var people = roster.People.ToDictionary(person => person.Id, StringComparer.Ordinal);
var child = roster.People.First(person => person.IsStudent && !person.IsParent);
var parentId = roster.Families.Single(row => row.Id.Equals(child.FamilyId, StringComparison.Ordinal)).ParentIds[0];
var parent = people[parentId];
Assert.True(parent.Opinions.TryGetValue(child.Id, out var parentView));
Assert.True(child.Opinions.TryGetValue(parentId, out var childView));
Assert.NotEqual(parentView, childView);
}
}
@@ -40,4 +40,18 @@ public class SwarmUiSettingsStoreTests
Assert.Equal("legacy.safetensors", config.Presets[0].Model);
Assert.Equal(12, config.Presets[0].Steps);
}
[Fact]
public void Clone_IsIndependentOfTheSource()
{
var source = SwarmUiConfigFile.CreateDefault();
source.Presets[0].Model = "mutated.safetensors";
var copy = SwarmUiConfigFile.Clone(source);
copy.Presets[0].Model = "other.safetensors";
Assert.Equal("mutated.safetensors", source.Presets[0].Model);
Assert.Equal("other.safetensors", copy.Presets[0].Model);
Assert.Equal(source.ActivePresetId, copy.ActivePresetId);
}
}
@@ -0,0 +1,117 @@
using HSchool.Content;
using HSchool.People;
using HSchool.Schedule;
namespace HSchool.Simulation.Tests;
public class MorningOpinionsTests
{
private static readonly DateTime TuesdayMorning = new(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TuesdayEvening = new(2012, 4, 3, 22, 0, 0, DateTimeKind.Utc);
private static readonly DateTime WednesdayMorning = new(2012, 4, 4, 6, 0, 0, DateTimeKind.Utc);
[Fact]
public void SeveralWorkMornings_DriftClassmateTowardZero_FamilyTowardStart()
{
using var school = OpenStaffed();
var child = school.Roster!.People.First(person => person.IsStudent && !person.IsParent);
var classmate = school.Roster.People.First(person =>
person.IsStudent
&& !person.Id.Equals(child.Id, StringComparison.Ordinal)
&& !OpinionStore.FamilyMemberIds(school.Roster, child).Contains(person.Id));
var family = school.Roster.Families.Single(row => row.Id.Equals(child.FamilyId, StringComparison.Ordinal));
var parentId = family.ParentIds[0];
var rules = school.Catalog!.BehaviorRules!;
OpinionStore.Set(child, classmate.Id, 30);
OpinionStore.Set(child, parentId, rules.OpinionChildToParentStart - 15);
AdvanceTo(school, TuesdayEvening);
for (var day = 0; day < 3; day++)
{
while (school.Clock.Time < WednesdayMorning.AddDays(day))
{
school.Tick(0.2d, 5d);
}
}
Assert.True(child.Opinions.TryGetValue(classmate.Id, out var classmateView));
Assert.True(classmateView < 30);
Assert.True(classmateView <= 30 - rules.OpinionDriftPerMorning);
Assert.True(child.Opinions.TryGetValue(parentId, out var parentView));
Assert.True(parentView > rules.OpinionChildToParentStart - 15);
Assert.True(parentView <= rules.OpinionChildToParentStart);
}
[Fact]
public void SkipEmpty_AppliesOpinionDrift()
{
using var school = OpenEmpty(TuesdayEvening);
var child = school.Roster!.People.First(person => person.IsStudent && !person.IsParent);
var classmate = school.Roster.People.First(person =>
person.IsStudent
&& !person.Id.Equals(child.Id, StringComparison.Ordinal)
&& !OpinionStore.FamilyMemberIds(school.Roster, child).Contains(person.Id));
OpinionStore.Set(child, classmate.Id, 12);
var before = child.Opinions[classmate.Id];
Assert.True(school.TrySkipEmpty().Succeeded);
Assert.True(child.Opinions.TryGetValue(classmate.Id, out var after));
Assert.True(after < before);
}
private static void AdvanceTo(School school, DateTime until)
{
while (school.Clock.Time < until)
{
school.Tick(0.2d, 5d);
}
}
private static School OpenStaffed()
{
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 school = School.Create(1, "Мнения", TuesdayMorning, catalog, map);
school.InstallPeople(roster, seed: 1, "Russia", pool);
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 (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);
}
}