acdream/tests/AcDream.Launcher.Core.Tests/Status/StatusFileTailerTests.cs
Erik 37d74e4402 feat(launcher): Campaign LA LA3 — AcDream.Launcher.Core profile store, composer, supervisor, status tailer
New AcDream.Launcher.Core (BCL-only, ProjectReference: AcDream.Platform
ONLY) plus tests/AcDream.Launcher.Core.Tests, both registered in
AcDream.slnx. This is the file-contract orchestrator core the Avalonia
launcher (LA4) will bind to — the game solution (Core/Runtime/App/
Headless) stays entirely out of this dependency graph, so the launcher
can never accidentally grow a game-protocol coupling.

- Profiles/: LauncherProfileStore owns launcher-profiles.json (spec §5
  schema: version 1, servers[]/accounts[]/characters[]), strict
  camelCase System.Text.Json (UnmappedMemberHandling.Disallow), typed
  CRUD (add/edit/remove server; add/edit/remove account; edit character
  settings), and MergeRoster (fold a reported roster into an account's
  characters[] while preserving user-owned launchMode/plugins/
  loginCommands, adding new rows with default guiSelect, and retaining
  rows absent from the roster — they may be pending-delete). 0600 on
  Linux via File.SetUnixFileMode after save.
- Launching/: SessionConfigComposer builds the pinned session-config
  contract (Headless K1 shape + plugins/loginCommands/
  loginCommandDelayMs/statusFile) from a profile character + install
  record — character selector omitted entirely for guiSelect, policy
  {id:"idle"} only for headless, credential always standardInput/
  session. Passwords never enter this document (proven by a dedicated
  test). LauncherProcessSupervisor spawns a host, feeds the password to
  stdin then closes it, and exposes Starting/Running/Exited lifecycle;
  Stop calls CloseMainWindow falling back to Kill after a timeout, both
  reachable through an injectable ILauncherChildProcess/factory seam so
  the state machine is unit-testable without real OS process timing.
- Status/: StatusEventParser decodes the v1 status.jsonl vocabulary
  (started/connected/characterList/enteredWorld/pluginLoaded/
  pluginFailed/disconnected/exited); an unrecognized "e" or a malformed
  line degrades to a typed Unknown event rather than throwing.
  StatusFileTailer incrementally reads new lines, tolerating a
  not-yet-existing file and a partial trailing line (only advances its
  read position past confirmed '\n' boundaries; a truncated tail is
  simply re-read next poll, never parsed early).
- Integrity/: streaming SHA-256 + hex verify for later pak/download
  checks (LA9/LA10).

Tests: 71 passed (profile CRUD + roster-merge matrix + strict-schema
rejection; composer golden-shape tests for gui/guiSelect/headless +
password-absence; supervisor tests against both an injected fake child
(state-machine determinism) and a real spawned `dotnet --version`
child (genuine cross-platform stdin/exit-code proof); tailer tests
incl. partial-line and not-yet-existing-file; SHA-256 tests). Verified
green on Windows (Release) and native WSL/Linux (Release) — the Linux
0600 test executes its real assertion body under WSL rather than
early-returning.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 15:49:13 +02:00

172 lines
5.5 KiB
C#

using System.Text;
using AcDream.Launcher.Core.Status;
namespace AcDream.Launcher.Core.Tests.Status;
public sealed class StatusFileTailerTests : IDisposable
{
private readonly string _root;
private readonly string _path;
public StatusFileTailerTests()
{
_root = Path.Combine(
Path.GetTempPath(),
"acdream-launcher-tailer-tests",
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
_path = Path.Combine(_root, "status.jsonl");
}
public void Dispose()
{
if (Directory.Exists(_root))
{
Directory.Delete(_root, recursive: true);
}
}
[Fact]
public void ReturnsNoEventsWhenTheFileDoesNotExistYet()
{
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void ReturnsNoEventsWhenNothingHasBeenAppendedSinceTheLastPoll()
{
AppendShared(Line("started", "s1"));
var tailer = new StatusFileTailer(_path);
Assert.Single(tailer.ReadNewEvents());
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void ReadsMultipleCompleteLinesInOnePoll()
{
AppendShared(Line("started", "s1") + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
Assert.IsType<StartedStatusEvent>(events[0]);
Assert.IsType<ConnectedStatusEvent>(events[1]);
}
[Fact]
public void TolerateAPartialLastLineAndCompletesItOnALaterPoll()
{
string full = Line("started", "s1");
int splitAt = full.Length - 10; // cut mid-object, before the closing brace/newline
AppendShared(full[..splitAt]);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> firstPoll = tailer.ReadNewEvents();
Assert.Empty(firstPoll);
AppendShared(full[splitAt..]);
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(secondPoll);
Assert.IsType<StartedStatusEvent>(onlyEvent);
}
[Fact]
public void APartialLineFollowedByAFullLineOnlyEmitsTheCompleteOne()
{
AppendShared(Line("started", "s1"));
string partial = """{"v":1,"e":"connected","t":"2026-08-14T12:00:00Z","sessionId":"s1"""; // no closing
AppendShared(partial);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(events);
Assert.IsType<StartedStatusEvent>(onlyEvent);
// Completing the second line on a later poll produces exactly
// one more event, proving the partial bytes were retained (not
// dropped and not double-counted).
AppendShared("\"}\n");
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
StatusEvent completed = Assert.Single(secondPoll);
Assert.IsType<ConnectedStatusEvent>(completed);
}
[Fact]
public void SkipsBlankLines()
{
AppendShared("\n" + Line("started", "s1") + "\n" + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
}
[Fact]
public void ReadsWithAWriterHoldingTheFileOpenForAppend()
{
// Share-tolerant reads: the writer's handle stays open the whole
// time (FileShare.ReadWrite on both sides), matching a live host
// process appending status.jsonl while the launcher tails it.
using var writer = new FileStream(
_path,
FileMode.Create,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
var tailer = new StatusFileTailer(_path);
byte[] first = Encoding.UTF8.GetBytes(Line("started", "s1"));
writer.Write(first, 0, first.Length);
writer.Flush();
IReadOnlyList<StatusEvent> firstPoll = tailer.ReadNewEvents();
Assert.Single(firstPoll);
byte[] second = Encoding.UTF8.GetBytes(Line("connected", "s1"));
writer.Write(second, 0, second.Length);
writer.Flush();
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
Assert.Single(secondPoll);
Assert.IsType<ConnectedStatusEvent>(secondPoll[0]);
}
[Fact]
public void RestartsFromTheTopWhenTheFileIsTruncatedOrReplaced()
{
AppendShared(Line("started", "s1") + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
Assert.Equal(2, tailer.ReadNewEvents().Count);
File.Delete(_path);
AppendShared(Line("started", "s2"));
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(events);
Assert.Equal("s2", onlyEvent.SessionId);
}
private static string Line(string e, string sessionId) =>
$$"""{"v":1,"e":"{{e}}","t":"2026-08-14T12:00:00Z","sessionId":"{{sessionId}}"}""" + "\n";
private void AppendShared(string text)
{
using var stream = new FileStream(
_path,
FileMode.Append,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
byte[] bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
}