acdream/tests/AcDream.Launcher.Core.Tests/Status/StatusEventParserTests.cs
Erik 26feba8186 fix(launcher): Campaign LA LA3 review fixes — contract paths omission, probe composition, graceful stop, hygiene
Opus review of LA3 returned FIX FIRST; this addresses every finding in
scope (F1-F5, F7-F12; F6 CI-lane addition excluded per instructions):

- F1 (CRITICAL): SessionProcessSettings.Paths is now nullable and left
  null by SessionConfigComposer unless a caller supplies overrides, so
  the JSON key is entirely absent instead of "paths":{} — the App-side
  loader's strict UnmappedMemberHandling.Disallow would otherwise reject
  every gui/guiSelect session-config document at load.
- F2: added SessionConfigComposer.ComposeProbe and a nullable
  SessionDescriptor.Mode field ("probe", omitted for normal play) per
  the pinned contract — no character/policy/plugins/loginCommands.
- F3: LauncherProcessSupervisor.Stop now tries
  ILauncherChildProcess.TryRequestGracefulStop (Linux: libc SIGINT via
  LibraryImport, K4-proven graceful headless logout) before
  CloseMainWindow. Windows has no reliable no-window-console equivalent
  today; filed docs/ISSUES.md #397 with the CREATE_NEW_PROCESS_GROUP +
  CTRL_BREAK fix direction. Stop()'s blocking-timeout contract is now
  documented for LA4.
- F4: LauncherProfileStore.Save chmods the Linux temp file to 0600
  immediately after creation, before any credential is serialized;
  failure paths and Load() clean up a stale .tmp.
- F5: added LauncherCoreDependencyBoundaryTests asserting Launcher.Core
  references exactly AcDream.Platform and no packages.
- F7: StatusEventParser.Parse no longer throws on a whitespace/null
  line; StatusFileTailer.ReadNewEvents swallows the File.Exists/open
  TOCTOU window (FileNotFoundException/DirectoryNotFoundException/
  IOException) instead of throwing.
- F8: Start() now kills (entire process tree) and disposes a child that
  started successfully but failed while being fed its stdin password,
  instead of orphaning it.
- F9: SetState is monotonic — once Exited, no later transition applies
  or fires StateChanged, closing a Start()-path race where a
  synchronously-exiting child could be "resurrected" to Running.
- F10: CharacterIdFormat.TryParse now requires the "0x" prefix (an
  unprefixed hand-typed decimal id is also valid hex and was silently
  misread); a parsed id of 0 is treated as unusable and falls back to
  the name selector; LauncherProfileStore.MergeRoster normalizes both
  sides through TryParse/ToHexString instead of raw string equality, so
  a legacy unprefixed-hex row self-heals via name match instead of
  duplicating.
- F11: StatusCharacterEntry.SecondsGreyedOut is now uint, matching
  CharacterRosterEntry and the host writer.
- F12: added MalformedStatusEvent, returned for a recognized `e` whose
  payload doesn't match its shape, distinguished from UnknownStatusEvent
  (an unrecognized `e`).

AllowUnsafeBlocks was added to AcDream.Launcher.Core.csproj — required
by the LibraryImport source generator's function-pointer marshalling
stub for F3's Linux SIGINT P/Invoke.

Verification: dotnet build AcDream.slnx -c Release green (0 errors);
dotnet test tests/AcDream.Launcher.Core.Tests -c Release green at 94/94
on native Windows and under WSL (Ubuntu, verified across multiple runs
for the timing-sensitive SIGINT/sharing-violation tests, no flakes
observed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 16:29:39 +02:00

170 lines
6.5 KiB
C#

using AcDream.Launcher.Core.Status;
namespace AcDream.Launcher.Core.Tests.Status;
public sealed class StatusEventParserTests
{
[Fact]
public void ParsesStarted()
{
var e = StatusEventParser.Parse(
"""{"v":1,"e":"started","t":"2026-08-14T12:00:00Z","sessionId":"s1"}""");
var started = Assert.IsType<StartedStatusEvent>(e);
Assert.Equal(1, started.V);
Assert.Equal("started", started.E);
Assert.Equal("s1", started.SessionId);
Assert.Equal(
DateTimeOffset.Parse("2026-08-14T12:00:00Z"),
started.T);
}
[Fact]
public void ParsesConnected()
{
var e = StatusEventParser.Parse(
"""{"v":1,"e":"connected","t":"2026-08-14T12:00:01Z","sessionId":"s1"}""");
Assert.IsType<ConnectedStatusEvent>(e);
}
[Fact]
public void ParsesCharacterListWithMultipleCharacters()
{
var e = StatusEventParser.Parse(
"""
{"v":1,"e":"characterList","t":"2026-08-14T12:00:02Z","sessionId":"s1",
"accountName":"testaccount","slotCount":6,
"characters":[
{"id":1342177290,"name":"+Acdream","secondsGreyedOut":0},
{"id":1342177291,"name":"+Second","secondsGreyedOut":1}
]}
""");
var list = Assert.IsType<CharacterListStatusEvent>(e);
Assert.Equal("testaccount", list.AccountName);
Assert.Equal(6, list.SlotCount);
Assert.Equal(2, list.Characters.Count);
Assert.Equal(1342177290u, list.Characters[0].Id);
Assert.Equal("+Acdream", list.Characters[0].Name);
Assert.Equal(0u, list.Characters[0].SecondsGreyedOut);
Assert.Equal(1342177291u, list.Characters[1].Id);
Assert.Equal(1u, list.Characters[1].SecondsGreyedOut);
}
[Fact]
public void ParsesEnteredWorld()
{
var e = StatusEventParser.Parse(
"""{"v":1,"e":"enteredWorld","t":"2026-08-14T12:00:03Z","sessionId":"s1","characterId":1342177290,"characterName":"+Acdream"}""");
var entered = Assert.IsType<EnteredWorldStatusEvent>(e);
Assert.Equal(1342177290u, entered.CharacterId);
Assert.Equal("+Acdream", entered.CharacterName);
}
[Fact]
public void ParsesPluginLoadedAndPluginFailed()
{
var loaded = Assert.IsType<PluginLoadedStatusEvent>(
StatusEventParser.Parse(
"""{"v":1,"e":"pluginLoaded","t":"2026-08-14T12:00:04Z","sessionId":"s1","plugin":"ExamplePlugin"}"""));
Assert.Equal("ExamplePlugin", loaded.Plugin);
var failed = Assert.IsType<PluginFailedStatusEvent>(
StatusEventParser.Parse(
"""{"v":1,"e":"pluginFailed","t":"2026-08-14T12:00:05Z","sessionId":"s1","plugin":"BadPlugin","error":"boom"}"""));
Assert.Equal("BadPlugin", failed.Plugin);
Assert.Equal("boom", failed.Error);
}
[Fact]
public void ParsesDisconnectedAndExited()
{
var disconnected = Assert.IsType<DisconnectedStatusEvent>(
StatusEventParser.Parse(
"""{"v":1,"e":"disconnected","t":"2026-08-14T12:00:06Z","sessionId":"s1","reason":"serverClosed"}"""));
Assert.Equal("serverClosed", disconnected.Reason);
var exited = Assert.IsType<ExitedStatusEvent>(
StatusEventParser.Parse(
"""{"v":1,"e":"exited","t":"2026-08-14T12:00:07Z","sessionId":"s1","code":0,"reason":"graceful"}"""));
Assert.Equal(0, exited.Code);
Assert.Equal("graceful", exited.Reason);
}
[Fact]
public void UnknownEValueSurfacesAsUnknownEventRatherThanThrowing()
{
var e = StatusEventParser.Parse(
"""{"v":1,"e":"someFutureEvent","t":"2026-08-14T12:00:08Z","sessionId":"s1","extra":true}""");
var unknown = Assert.IsType<UnknownStatusEvent>(e);
Assert.Equal("someFutureEvent", unknown.E);
Assert.Equal("s1", unknown.SessionId);
Assert.Contains("someFutureEvent", unknown.RawJson);
}
[Fact]
public void MalformedJsonSurfacesAsUnknownEventRatherThanThrowing()
{
var e = StatusEventParser.Parse("{not json");
Assert.IsType<UnknownStatusEvent>(e);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("\t")]
public void WhitespaceOrEmptyLineSurfacesAsUnknownEventRatherThanThrowing(string line)
{
// Review finding F7: ArgumentException.ThrowIfNullOrWhiteSpace
// used to guard this method BEFORE the try/catch, so a
// whitespace-only line (e.g. a stray blank line the tailer
// happens to hand over) escaped as an uncaught exception instead
// of degrading like every other malformed-input case.
var e = StatusEventParser.Parse(line);
Assert.IsType<UnknownStatusEvent>(e);
}
[Fact]
public void NullLineSurfacesAsUnknownEventRatherThanThrowing()
{
var e = StatusEventParser.Parse(null!);
Assert.IsType<UnknownStatusEvent>(e);
}
[Fact]
public void KnownEValueWithMissingRequiredFieldSurfacesAsMalformedEventRatherThanThrowing()
{
// characterList without "characters" — a shape mismatch on a
// KNOWN event name. Review finding F12: this must be
// distinguishable from an unrecognized e value, so it now
// surfaces as MalformedStatusEvent rather than UnknownStatusEvent.
var e = StatusEventParser.Parse(
"""{"v":1,"e":"characterList","t":"2026-08-14T12:00:09Z","sessionId":"s1","accountName":"a","slotCount":6}""");
var malformed = Assert.IsType<MalformedStatusEvent>(e);
Assert.Equal("characterList", malformed.E);
Assert.Equal("s1", malformed.SessionId);
Assert.False(string.IsNullOrWhiteSpace(malformed.Error));
}
[Fact]
public void KnownEValueWithAFieldOfTheWrongJsonKindSurfacesAsMalformedEvent()
{
// "characters" present but not an array — this throws
// InvalidOperationException out of JsonElement.EnumerateArray()
// rather than the FormatException a missing/wrong-kind scalar
// field throws, so it exercises the parser's other malformed-
// payload catch path.
var e = StatusEventParser.Parse(
"""{"v":1,"e":"characterList","t":"2026-08-14T12:00:10Z","sessionId":"s1","accountName":"a","slotCount":6,"characters":"not-an-array"}""");
var malformed = Assert.IsType<MalformedStatusEvent>(e);
Assert.Equal("characterList", malformed.E);
Assert.False(string.IsNullOrWhiteSpace(malformed.Error));
}
}