From c001c525a06378dde8764ddda611457bc4c154e1 Mon Sep 17 00:00:00 2001 From: Florian Kinder Date: Sun, 25 Oct 2026 19:01:21 +0100 Subject: [PATCH 1/2] test(go): cover ingestion finalize lifecycle and storage atomic writes - Finalize: no-op without a flusher, recorded chunk errors surfaced as-is (distinguished from the flush wrap), flush failures wrapped, and an empty recording still writes chunk zero because playback always requests it - HandleAddSoldier: a rejoining player keeps their player flag and unit name - HandleAddVehicle: a re-sent Add replaces the record; HandleVehicleState registers unknown vehicles from the state's own capture frame - seedChunkBoundaries: vehicles are seeded alongside soldiers, entities deleted before a boundary are left out, and a failed seed surfaces its write error - derivePlacedObjects: magazine-icon fallback, minefield default, explicit icon precedence, earliest lifecycle event wins the end frame, hits attribute to the placer with vehicle victims keeping the vehicle id, and unknown/victim-less events are skipped - eventsToV1/markersToV1: vehicle ids win victim/killer slots; polylines carry geometry only (matching the pinned v2 writer) while plain markers append a position per state - sideToIndex, projectileEndPos, positionFromExtra, decodePayload: pinned directly, including malformed-payload rejection - WriteJSONGzNamed: gzip artifact readable back, missing output dir fails at create time - writeFileAtomic: rename onto a directory and a missing directory both fail loudly; removeSidecar errors propagate; WriteSidecars aborts on encoder failure and surfaces write failures Verified each behavioral pin fails when the guarded code is broken coverage: ingestion 85.1% -> 90.5%, storage 93.5% -> 94.2% --- internal/ingestion/lifecycle_test.go | 467 +++++++++++++++++++++++++++ internal/storage/precompress_test.go | 80 +++++ 2 files changed, 547 insertions(+) create mode 100644 internal/ingestion/lifecycle_test.go diff --git a/internal/ingestion/lifecycle_test.go b/internal/ingestion/lifecycle_test.go new file mode 100644 index 00000000..69f46ac4 --- /dev/null +++ b/internal/ingestion/lifecycle_test.go @@ -0,0 +1,467 @@ +package ingestion + +import ( + "compress/gzip" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/OCAP2/extension/v5/pkg/core" + "github.com/OCAP2/extension/v5/pkg/streaming" + pb "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A soldier who rejoins arrives as a fresh AddSoldier payload with empty +// call-sign data. The recording must keep calling them a player under their +// original unit name, otherwise the UI loses who this unit is. +func TestHandleAddSoldier_RejoinKeepsPlayerIdentity(t *testing.T) { + s := NewSession() + s.HandleAddSoldier(core.Soldier{ID: 1, JoinFrame: 1, IsPlayer: true, UnitName: "Alpha 1-1", Side: "WEST"}) + + rejoin := core.Soldier{ID: 1, JoinFrame: 40, Side: "WEST"} + s.HandleAddSoldier(rejoin) + + rec := s.soldiers[1] + require.NotNil(t, rec) + assert.True(t, rec.Soldier.IsPlayer, "a rejoining player must stay a player") + assert.Equal(t, "Alpha 1-1", rec.Soldier.UnitName, "the original unit name must survive the rejoin") + assert.Equal(t, core.Frame(40), rec.Soldier.JoinFrame, "the fresh payload still updates unguarded fields") +} + +// A vehicle Add can arrive twice (for example on respawn under the same id); +// the later payload wins. +func TestHandleAddVehicle_UpdateReplacesRecord(t *testing.T) { + s := NewSession() + s.HandleAddVehicle(core.Vehicle{ID: 5, JoinFrame: 1, DisplayName: "Hunter"}) + s.HandleAddVehicle(core.Vehicle{ID: 5, JoinFrame: 30, DisplayName: "Hunter (wreck)"}) + + rec := s.vehicles[5] + require.NotNil(t, rec) + assert.Equal(t, "Hunter (wreck)", rec.Vehicle.DisplayName) + assert.Equal(t, core.Frame(30), rec.Vehicle.JoinFrame) +} + +// A vehicle state may arrive before its Add (independent extension workers +// deliver types in no guaranteed order); it must still be recorded, keyed by +// the state's own capture frame. +func TestHandleVehicleState_UnknownVehicleRegisters(t *testing.T) { + s := NewSession() + s.HandleVehicleState(core.VehicleState{VehicleID: 9, CaptureFrame: 7, IsAlive: true}) + + rec := s.vehicles[9] + require.NotNil(t, rec) + assert.Equal(t, uint16(9), rec.Vehicle.ID) + assert.Equal(t, core.Frame(7), rec.Vehicle.JoinFrame, "the record adopts the state's frame as its join frame") + require.Len(t, rec.States, 1) + assert.Equal(t, core.Frame(7), rec.States[0].CaptureFrame) +} + +func TestFinalize_WithoutFlusherIsNoOp(t *testing.T) { + s := NewSession() + s.HandleAddSoldier(core.Soldier{ID: 1, JoinFrame: 1}) + assert.NoError(t, s.Finalize(t.TempDir())) +} + +// A state write that fails mid-stream is remembered and surfaced by Finalize; +// the session must not finalize into a half-written recording silently. The +// recorded error is surfaced as-is, not re-wrapped as a flush failure. +func TestFinalize_ReturnsRecordedChunkError(t *testing.T) { + dir := t.TempDir() + s := NewSession() + cf, err := NewChunkFlusher(dir, 2) + require.NoError(t, err) + s.SetChunkFlusher(cf) + + // Two chunks' worth of frames, so chunk 0 is flushed to disk and chunk 1 is + // the open buffer. + for _, f := range []core.Frame{0, 1, 2} { + s.HandleSoldierState(core.SoldierState{SoldierID: 1, CaptureFrame: f}) + } + + // Losing an already-flushed chunk makes the next late amend fail while the + // finalize-time flush still succeeds. + require.NoError(t, os.Remove(filepath.Join(dir, "chunks", "0000.pb"))) + s.HandleSoldierState(core.SoldierState{SoldierID: 1, CaptureFrame: 0}) + require.Error(t, s.chunkErr, "the failed amend must have been recorded") + + err = s.Finalize(dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "0000.pb") + assert.NotContains(t, err.Error(), "flush final chunk", "the recorded error is surfaced as-is") +} + +// A write failure at finalize time (here: the output directory vanishing) is +// wrapped as a flush failure rather than lost. +func TestFinalize_WrapsFlushError(t *testing.T) { + dir := t.TempDir() + s := NewSession() + cf, err := NewChunkFlusher(dir, 2) + require.NoError(t, err) + s.SetChunkFlusher(cf) + + s.HandleAddSoldier(core.Soldier{ID: 1, JoinFrame: 1}) + s.HandleSoldierState(core.SoldierState{SoldierID: 1, CaptureFrame: 1}) + + require.NoError(t, os.RemoveAll(filepath.Join(dir, "chunks"))) + + err = s.Finalize(dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "flush final chunk") +} + +// Playback always requests chunk zero, even for a mission with no states, so +// finalizing an empty recording must still write the first chunk. +func TestFinalize_EmptyRecordingWritesChunkZero(t *testing.T) { + dir := t.TempDir() + s := NewSession() + cf, err := NewChunkFlusher(dir, 4) + require.NoError(t, err) + s.SetChunkFlusher(cf) + + require.NoError(t, s.Finalize(dir)) + + chunk := readChunk(t, dir, 0) + assert.Equal(t, uint32(0), chunk.Index) + assert.Empty(t, chunk.Frames) +} + +// Chunk boundaries re-seed the last known state of every surviving entity, so +// seeking into a later chunk does not need the chunks before it. Entities whose +// last state predates the boundary are re-added from their newest sample, and +// ones deleted before the boundary are left out entirely. +func TestSeedChunkBoundaries_SeedsVehiclesAndSkipsDeleted(t *testing.T) { + dir := t.TempDir() + s := NewSession() + cf, err := NewChunkFlusher(dir, 2) + require.NoError(t, err) + s.SetChunkFlusher(cf) + + s.HandleAddSoldier(core.Soldier{ID: 1, JoinFrame: 0, UnitName: "Survivor"}) + s.HandleAddSoldier(core.Soldier{ID: 2, JoinFrame: 0, UnitName: "Doomed"}) + s.HandleAddVehicle(core.Vehicle{ID: 5, JoinFrame: 0, DisplayName: "Hunter"}) + + // The survivor is present across the whole timeline; the doomed soldier and + // the vehicle stop at frame 1, before the first boundary at frame 2. + for _, f := range []core.Frame{0, 1, 2, 3, 4} { + s.HandleSoldierState(core.SoldierState{SoldierID: 1, CaptureFrame: f, Side: "WEST"}) + } + for _, f := range []core.Frame{0, 1} { + s.HandleSoldierState(core.SoldierState{SoldierID: 2, CaptureFrame: f, Side: "WEST"}) + s.HandleVehicleState(core.VehicleState{VehicleID: 5, CaptureFrame: f, IsAlive: true}) + } + // Deleted at frame 2 (one-based wire frame), so the boundary at 2 is past it. + del, err := json.Marshal(map[string]any{"id": 2, "frame": 2}) + require.NoError(t, err) + require.NoError(t, s.HandleMessage(streaming.Envelope{Type: streaming.TypeDeleteSoldier, Payload: del})) + require.Equal(t, core.Frame(1), s.soldiers[2].Soldier.DeleteFrame) + + // Frames 0-3 span chunks 0 and 1; frame 4 opens chunk 2 and flushes chunk 1. + require.NoError(t, s.seedChunkBoundaries()) + + chunk := readChunk(t, dir, 1) + var frame *pb.Frame + for _, f := range chunk.Frames { + if f.FrameNum == 2 { + frame = f + } + } + require.NotNil(t, frame, "the boundary frame must exist in chunk 1") + + ids := []uint32{} + for _, st := range frame.Soldiers { + ids = append(ids, st.Id) + } + assert.Equal(t, []uint32{1}, ids, "only the surviving soldier is seeded; the one deleted before the boundary is not") + + vehicleIDs := []uint32{} + for _, st := range frame.Vehicles { + vehicleIDs = append(vehicleIDs, st.Id) + } + assert.Equal(t, []uint32{5}, vehicleIDs, "the vehicle's newest pre-boundary state is seeded") +} + +// A chunk file that cannot be read back (here: replaced by a directory) must +// fail seeding instead of writing a chunk that silently lost its seed. +func TestSeedChunkBoundaries_PropagatesWriteError(t *testing.T) { + dir := t.TempDir() + s := NewSession() + cf, err := NewChunkFlusher(dir, 2) + require.NoError(t, err) + s.SetChunkFlusher(cf) + + s.HandleAddSoldier(core.Soldier{ID: 1, JoinFrame: 0}) + for _, f := range []core.Frame{0, 1, 2, 3, 4} { + s.HandleSoldierState(core.SoldierState{SoldierID: 1, CaptureFrame: f}) + } + + // Corrupt the already-flushed chunk: seeding has to amend it. + chunkFile := filepath.Join(dir, "chunks", "0001.pb") + require.NoError(t, os.Remove(chunkFile)) + require.NoError(t, os.Mkdir(chunkFile, 0755)) + + assert.Error(t, s.seedChunkBoundaries()) +} + +func TestSideToIndex(t *testing.T) { + cases := map[string]int{ + "EAST": 0, + "OPFOR": 0, + "WEST": 1, + "BLUFOR": 1, + "GUER": 2, + "INDEPENDENT": 2, + "CIV": 3, + "CIVILIAN": 3, + "west": 1, + "": -1, + "ALIEN": -1, + } + for side, want := range cases { + assert.Equal(t, want, sideToIndex(side), "side %q", side) + } +} + +// The hit position outranks the trajectory: the round landed where the hit +// says, not where the last telemetry sample was taken. +func TestProjectileEndPos(t *testing.T) { + hitPos := core.Position3D{X: 30, Y: 40} + lastTraj := core.Position3D{X: 20, Y: 25} + + withHit := core.ProjectileEvent{ + Hits: []core.ProjectileHit{{Position: hitPos}}, + Trajectory: []core.TrajectoryPoint{{FrameNum: 1, Position: core.Position3D{X: 1}}, {FrameNum: 2, Position: lastTraj}}, + } + assert.Equal(t, hitPos, projectileEndPos(withHit)) + + trajectoryOnly := core.ProjectileEvent{ + Trajectory: []core.TrajectoryPoint{{FrameNum: 1, Position: lastTraj}}, + } + assert.Equal(t, lastTraj, projectileEndPos(trajectoryOnly)) + + assert.Equal(t, core.Position3D{}, projectileEndPos(core.ProjectileEvent{})) +} + +func TestPositionFromExtra(t *testing.T) { + _, ok := positionFromExtra(map[string]any{}, "pos") + assert.False(t, ok, "a missing key is not a position") + + _, ok = positionFromExtra(map[string]any{"pos": "not an array"}, "pos") + assert.False(t, ok, "a non-array value is not a position") + + _, ok = positionFromExtra(map[string]any{"pos": []any{1.0}}, "pos") + assert.False(t, ok, "a single coordinate is not a position") + + arr, ok := positionFromExtra(map[string]any{"pos": []any{1.0, 2.0, 3.0}}, "pos") + assert.True(t, ok) + assert.Equal(t, []any{1.0, 2.0, 3.0}, arr) +} + +func TestDecodePayloadRejectsEmptyAndMalformed(t *testing.T) { + err := decodePayload[core.KillEvent](nil, func(core.KillEvent) {}, false) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing payload") + + err = decodePayload[core.KillEvent](json.RawMessage("null"), func(core.KillEvent) {}, false) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing payload") + + err = decodePayload[core.KillEvent](json.RawMessage("{not json"), func(core.KillEvent) {}, false) + require.Error(t, err, "unmarshal failures must surface, not be swallowed") +} + +// WriteJSONGzNamed writes the v1 recording into dataDir under the given name. +func TestWriteJSONGzNamed(t *testing.T) { + s := NewSession() + s.SetMission(&core.Mission{MissionName: "Gzip", CaptureDelay: 1}, &core.World{WorldName: "altis"}) + + dir := t.TempDir() + require.NoError(t, s.WriteJSONGzNamed(dir, "op")) + + f, err := os.Open(filepath.Join(dir, "op.json.gz")) + require.NoError(t, err) + defer f.Close() + gz, err := gzip.NewReader(f) + require.NoError(t, err, "the artifact is gzip-compressed, not raw JSON") + var payload map[string]any + require.NoError(t, json.NewDecoder(gz).Decode(&payload)) + assert.Equal(t, "Gzip", payload["missionName"]) + + // A missing output directory fails at create time with a wrapped error. + err = s.WriteJSONGzNamed(filepath.Join(dir, "nope"), "op") + require.Error(t, err) + assert.Contains(t, err.Error(), "create file") +} + +// Placed objects become markers with an icon derived from their magazine, and +// their lifecycle events become marker end frames and hit events attributed to +// the placer. +func TestDerivePlacedObjects(t *testing.T) { + s := NewSession() + s.SetMission(&core.Mission{MissionName: "Placed", CaptureDelay: 1}, nil) + // Vehicle 5 so a hit against it can be attributed to the vehicle. + s.HandleAddVehicle(core.Vehicle{ID: 5, JoinFrame: 1}) + + handle := func(kind string, payload any) { + raw, err := json.Marshal(payload) + require.NoError(t, err) + require.NoError(t, s.HandleMessage(streaming.Envelope{Type: kind, Payload: raw})) + } + + // Magazine icon fallback, explicit icon, and no icon at all. + handle(streaming.TypeAddPlaced, map[string]any{"id": 7, "joinFrame": 2, "ownerId": 3, "magazineIcon": "mag_rifle", "displayName": "APERS", "position": map[string]any{"x": 10.0, "y": 20.0}}) + handle(streaming.TypeAddPlaced, map[string]any{"id": 8, "joinFrame": 2, "ownerId": 3, "displayName": "Minefield", "position": map[string]any{"x": 50.0, "y": 60.0}}) + handle(streaming.TypeAddPlaced, map[string]any{"id": 9, "joinFrame": 2, "ownerId": 3, "markerIcon": "trench_x", "displayName": "Trench", "position": map[string]any{"x": 1.0, "y": 2.0}, "direction": 90}) + + // deleted wins over a later detonation; the earlier frame is kept. Frames go + // through the one-based protocol path, so wire frame 9 is stored as 8. + handle(streaming.TypePlacedEvent, map[string]any{"placedId": 7, "captureFrame": 12, "eventType": "detonated"}) + handle(streaming.TypePlacedEvent, map[string]any{"placedId": 7, "captureFrame": 9, "eventType": "deleted"}) + handle(streaming.TypePlacedEvent, map[string]any{"placedId": 8, "captureFrame": 15, "eventType": "deleted"}) + + // Hits: one against an unknown soldier id, one against the known vehicle, + // one referencing an unregistered placed object, one with no victim. + handle(streaming.TypePlacedEvent, map[string]any{"placedId": 7, "captureFrame": 11, "eventType": "hit", "position": map[string]any{"x": 13.0, "y": 20.0}, "hitEntityId": 30}) + handle(streaming.TypePlacedEvent, map[string]any{"placedId": 8, "captureFrame": 14, "eventType": "hit", "position": map[string]any{"x": 50.0, "y": 60.0}, "hitEntityId": 5}) + handle(streaming.TypePlacedEvent, map[string]any{"placedId": 99, "captureFrame": 14, "eventType": "hit", "position": map[string]any{"x": 0.0, "y": 0.0}, "hitEntityId": 30}) + handle(streaming.TypePlacedEvent, map[string]any{"placedId": 9, "captureFrame": 14, "eventType": "hit", "position": map[string]any{"x": 1.0, "y": 2.0}}) + + v1 := s.ToV1JSON() + markers, ok := v1["Markers"].([]any) + require.True(t, ok, "Markers must be a list, got %T", v1["Markers"]) + + byName := map[string][]any{} + for _, m := range markers { + arr := m.([]any) + byName[fmt.Sprint(arr[1])] = arr + } + // Marker v1 shape: [type, text, captureFrame, endFrame, owner, color, sideIndex, positions, size, shape, brush]. + require.Contains(t, byName, "APERS") + apers := byName["APERS"] + assert.Equal(t, "magIcons/mag_rifle", apers[0], "the magazine icon becomes the marker type") + assert.Equal(t, 8, apers[3], "the earliest lifecycle event is the end frame") + assert.Equal(t, 3, apers[4], "the placer is the owner") + + require.Contains(t, byName, "Minefield") + minefield := byName["Minefield"] + assert.Equal(t, "Minefield", minefield[0], "an object with no icons at all falls back to the minefield type") + assert.Equal(t, 14, minefield[3]) + + require.Contains(t, byName, "Trench") + assert.Equal(t, "trench_x", byName["Trench"][0], "an explicit marker icon is used verbatim") + + events, ok := v1["events"].([]any) + require.True(t, ok) + var hits [][]any + for _, e := range events { + arr, ok := e.([]any) + if ok && len(arr) >= 3 && arr[1] == "hit" { + hits = append(hits, arr) + } + } + require.Len(t, hits, 2, "the unknown placed object and the victim-less hit produce no event") + + // Placed 7 hit the soldier id 30: v1 shape is [frame, "hit", victim, [source, text], distance]. + assert.Equal(t, core.Frame(10), hits[0][0]) + assert.Equal(t, uint(30), hits[0][2], "a hit against an unknown id keeps the raw game id") + assert.Equal(t, uint(3), hits[0][3].([]any)[0], "the placer is the attribution source") + // sqrt((13-10)^2) with equal y. + assert.InDelta(t, 3.0, hits[0][4].(float32), 0.001) + + // Placed 8 hit the registered vehicle 5: the vehicle wins the victim slot. + assert.Equal(t, core.Frame(13), hits[1][0]) + assert.Equal(t, uint(5), hits[1][2], "a hit against a vehicle is attributed to the vehicle id") +} + +// The v1 hit event prefers vehicle ids when the event carries them. +func TestEventsToV1_VehicleVictimAndShooter(t *testing.T) { + s := NewSession() + s.HandleHitEvent(core.HitEvent{ + CaptureFrame: 4, + VictimVehicleID: ptrUint(9), + ShooterVehicleID: ptrUint(3), + }) + s.HandleKillEvent(core.KillEvent{ + CaptureFrame: 5, + VictimVehicleID: ptrUint(9), + KillerVehicleID: ptrUint(3), + }) + + events := s.eventsToV1() + require.Len(t, events, 2) + + hit := events[0].([]any) + assert.Equal(t, "hit", hit[1]) + assert.Equal(t, uint(9), hit[2], "the vehicle id wins the victim slot") + assert.Equal(t, uint(3), hit[3].([]any)[0], "the vehicle id wins the shooter slot") + + killed := events[1].([]any) + assert.Equal(t, "killed", killed[1]) + assert.Equal(t, uint(9), killed[2]) + assert.Equal(t, uint(3), killed[3].([]any)[0]) +} + +// A polyline marker exports its geometry as the position array; a marker with +// states appends one position entry per state. +func TestMarkersToV1_PolylineAndStates(t *testing.T) { + s := NewSession() + s.HandleAddMarker(core.Marker{ + ID: 1, + MarkerName: "route", + Text: "route", + CaptureFrame: 2, + Shape: "POLYLINE", + Side: "west", + Polyline: core.Polyline{{X: 1, Y: 2}, {X: 3, Y: 4}}, + }) + s.HandleMarkerState(core.MarkerState{MarkerID: 1, CaptureFrame: 6, Position: core.Position3D{X: 5, Y: 6}, Direction: 45, Alpha: 0.5}) + s.HandleAddMarker(core.Marker{ + ID: 2, + MarkerName: "moving", + Text: "moving", + CaptureFrame: 3, + Shape: "ICON", + Position: core.Position3D{X: 1, Y: 1}, + Side: "EAST", + }) + s.HandleMarkerState(core.MarkerState{MarkerID: 2, CaptureFrame: 9, Position: core.Position3D{X: 8, Y: 9}, Direction: 90, Alpha: 0.25}) + + markers := s.markersToV1() + require.Len(t, markers, 2) + byName := map[string][]any{} + for _, mk := range markers { + arr := mk.([]any) + byName[fmt.Sprint(arr[1])] = arr + } + + route := byName["route"] + positions := route[7].([][]any) + require.Len(t, positions, 1, "a polyline carries only its geometry; states are dropped") + assert.Equal(t, []any{core.Frame(2), [][]float64{{1, 2}, {3, 4}}, float32(0), float32(0)}, positions[0]) + assert.Equal(t, 1, route[6], "sides are normalised case-insensitively to their index") + + moving := byName["moving"] + movingPositions := moving[7].([][]any) + require.Len(t, movingPositions, 2, "the initial position plus one entry per state") + assert.Equal(t, []any{core.Frame(3), []float64{1, 1, 0}, float32(0), float32(0)}, movingPositions[0]) + assert.Equal(t, []any{core.Frame(9), []float64{8, 9, 0}, float32(90), float32(0.25)}, movingPositions[1]) +} + +// The flusher keeps its temporary file name from colliding with a chunk that +// is actually a directory; the rename then fails and the error surfaces. +func TestWriteChunk_TargetPathIsDirectory(t *testing.T) { + dir := t.TempDir() + cf, err := NewChunkFlusher(dir, 2) + require.NoError(t, err) + + // A pre-existing chunk directory blocks the rename into place. + require.NoError(t, os.Mkdir(filepath.Join(dir, "chunks", "0000.pb"), 0755)) + + err = cf.FlushThrough(1) + require.Error(t, err) + assert.True(t, strings.Contains(err.Error(), "rename") || os.IsExist(err), "got: %v", err) +} diff --git a/internal/storage/precompress_test.go b/internal/storage/precompress_test.go index 56698ca5..240f2fed 100644 --- a/internal/storage/precompress_test.go +++ b/internal/storage/precompress_test.go @@ -167,3 +167,83 @@ func TestRemoveSidecar_IsIdempotent(t *testing.T) { require.NoError(t, removeSidecar(path+".zst")) require.NoError(t, removeSidecar(path+".gz")) } + +// The rename is the atomic step; a target that cannot be renamed onto (here: a +// directory holding the same name) must fail loudly rather than clobber it. +func TestWriteFileAtomic_TargetPathIsDirectory(t *testing.T) { + dir := t.TempDir() + blocked := filepath.Join(dir, "blocked") + require.NoError(t, os.Mkdir(blocked, 0755)) + require.NoError(t, os.WriteFile(filepath.Join(blocked, "keep"), []byte("x"), 0644)) + + err := writeFileAtomic(blocked, []byte("data")) + require.Error(t, err) + assert.Contains(t, err.Error(), "rename onto") +} + +// A missing output directory fails at temp-file creation, before any rename. +func TestWriteFileAtomic_MissingDirectory(t *testing.T) { + err := writeFileAtomic(filepath.Join(t.TempDir(), "nope", "chunk.zst"), []byte("data")) + require.Error(t, err) + assert.Contains(t, err.Error(), "create temp") +} + +// A sidecar whose removal fails (a directory in its place holding a file) +// surfaces the error instead of reporting success. +func TestRemoveSidecar_ErrorOnUnremovable(t *testing.T) { + dir := t.TempDir() + sidecar := filepath.Join(dir, "chunk.pb.zst") + require.NoError(t, os.Mkdir(sidecar, 0755)) + require.NoError(t, os.WriteFile(filepath.Join(sidecar, "keep"), []byte("x"), 0644)) + + err := removeSidecar(sidecar) + require.Error(t, err) + assert.Contains(t, err.Error(), "remove") +} + +func TestRemoveSidecars_PropagatesError(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "chunk.pb") + sidecar := path + ".zst" + require.NoError(t, os.Mkdir(sidecar, 0755)) + require.NoError(t, os.WriteFile(filepath.Join(sidecar, "keep"), []byte("x"), 0644)) + + err := removeSidecars(path) + require.Error(t, err) + assert.Contains(t, err.Error(), "remove") +} + +// WriteSidecars writes through writeFileAtomic; a sidecar path that cannot be +// renamed onto fails the whole call instead of leaving a half-written variant. +func TestWriteSidecars_WriteFailureSurfaces(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "chunk.pb") + + sidecar := path + ".zst" + require.NoError(t, os.Mkdir(sidecar, 0755)) + require.NoError(t, os.WriteFile(filepath.Join(sidecar, "keep"), []byte("x"), 0644)) + + err := WriteSidecars(path, compressiblePayload()) + require.Error(t, err) + assert.Contains(t, err.Error(), "rename onto") +} + +// An encoder that fails (simulated here with an unknown coding in the encoding +// list) aborts WriteSidecars with the wrapped reason and leaves the raw file +// authoritative. +func TestWriteSidecars_CompressFailureAborts(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "chunk.pb") + + original := PrecompressEncodings + PrecompressEncodings = []string{"bogus"} + t.Cleanup(func() { PrecompressEncodings = original }) + + err := WriteSidecars(path, compressiblePayload()) + require.Error(t, err) + assert.Contains(t, err.Error(), `compress`) + assert.Contains(t, err.Error(), `unknown encoding "bogus"`) + + // The stale sidecars are untouched: the abort happens before any write. + assert.DirExists(t, filepath.Join(dir)) +} From e6d80a9a0bc1d2e6f6b38243d6176f1a9042f6a7 Mon Sep 17 00:00:00 2001 From: Florian Kinder Date: Sun, 25 Oct 2026 19:45:25 +0100 Subject: [PATCH 2/2] test(ui): cover the tab components' interaction and rendering paths - CommsTab (57.6% -> 97.2% statements, 26.3% -> 78.9% branches): heard counts against out-of-range peers, click-to-seek opening the net, pan-to-member, the transmission window, search matching speaker/radio/net with the no-match notes, net narrowing with member auto-expand, unknown-unit fallbacks with no range guess, and the no-data placeholder - OrbatTab (69.4% -> 94.0%): member and role search keeping only hits, the player-faction preselection and explicit picks, follow-on-click, vehicle search by name and by crew, and the empty vehicle note - EventsTab (73.3% -> 92.0%): rendering, click-pan and search haystacks for zeus pings/modules, servicing, static weapons and transmissions - StatsTab (82.5% -> 99.7%): wind direction without a speed sample, gusts, lightnings and waves, movement ranking with formatted distances, and the no-movement note - PlayerProfileDiff (55.3% -> 99.0%, branches 98.4%): every field kind through the grid, body parts, treatments, medical logs, rounds deltas per polarity, radio and stamina views, and the empty-state variants Test-only: no production file is touched. Engine snapshot effects settle on the microtask queue, so seek-dependent assertions await a settle pass first, matching the existing overlay test conventions overall UI coverage: 91.4% -> 94.7% statements, 80.9% -> 83.9% branches, 93.6% -> 96.2% lines --- .../__tests__/CommsTab.test.tsx | 215 ++++++++++++++++++ .../__tests__/EventsTab.test.tsx | 178 +++++++++++++++ .../__tests__/StatsTab.test.tsx | 115 ++++++++++ .../components/__tests__/OrbatTab.test.tsx | 181 ++++++++++++++- .../__tests__/PlayerProfileDiff.test.tsx | 188 +++++++++++++++ 5 files changed, 875 insertions(+), 2 deletions(-) diff --git a/ui/src/pages/recording-playback/__tests__/CommsTab.test.tsx b/ui/src/pages/recording-playback/__tests__/CommsTab.test.tsx index f6612555..7be32cef 100644 --- a/ui/src/pages/recording-playback/__tests__/CommsTab.test.tsx +++ b/ui/src/pages/recording-playback/__tests__/CommsTab.test.tsx @@ -131,3 +131,218 @@ describe("CommsTab net list", () => { expect(header(NET_A).getAttribute("aria-expanded")).toBe("true"); }); }); + +import { vi } from "vitest"; + +function transmission(frameNum: number, unitId: number, action: "Start" | "Stop", frequency: number): EventDef { + return { + type: "radioTransmission", + frameNum, + payload: { unitId, radio: "TFAR_anprc152", type: "SW", action, channel: 1, additional: false, frequency, code: "" }, + }; +} + +/** A player whose radio snapshot carries no radios: no net, no range guess. */ +function bareSnapshot(unitId: number): EventDef { + return { + type: "radioSnapshot", + frameNum: 0, + payload: { unitId, playerUid: `uid${unitId}`, radios: [] }, + } as unknown as EventDef; +} + + +/** Engine snapshot effects settle on the microtask queue after a seek. */ +async function settle() { + for (let i = 0; i < 10; i++) await Promise.resolve(); +} + + +/** Entity states for every frame 0..100, so snapshots resolve at any playhead. */ +function stillAt(x: number, y: number) { + return Array.from({ length: 101 }, () => ({ position: [x, y] as [number, number], direction: 0, alive: 1 as const })); +} + + +describe("CommsTab transmissions", () => { + // Alpha keys up on net 100; Bravo shares the net from the same spot; Charlie + // is on the same net but 9 km away — beyond the radio's 5000 m range. + function renderNet() { + const { engine, renderer } = createTestEngine(); + engine.loadRecording( + makeManifest( + [ + unitDef({ id: 1, name: "Alpha", positions: stillAt(100, 200) }), + unitDef({ id: 2, name: "Bravo", positions: stillAt(100, 200) }), + unitDef({ id: 3, name: "Charlie", positions: stillAt(9100, 200) }), + ], + [ + radioSnapshot(1, 100), + radioSnapshot(2, 100), + radioSnapshot(3, 100), + transmission(5, 1, "Start", 100), + transmission(15, 1, "Stop", 100), + ], + ), + ); + render(() => ( + + + + )); + return { engine }; + } + + it("counts who could hear a live transmission from where they stood", async () => { + const { engine } = renderNet(); + engine.seekTo(10); + await settle(); + + // Charlie is out of range, Bravo in: 1 of 2 peers heard. + expect(screen.getByText("1/2")).toBeTruthy(); + }); + + it("seeks to the transmission's start and opens its net on click", async () => { + const { engine } = renderNet(); + engine.seekTo(10); + await settle(); + + const seek = vi.spyOn(engine, "seekTo"); + fireEvent.click(screen.getByText("Alpha")); + expect(seek).toHaveBeenCalledWith(5); + seek.mockRestore(); + + // The net opened, so the roster is visible. + expect(screen.getByText("Bravo")).toBeTruthy(); + }); + + it("pans to a member when their roster row is clicked", async () => { + const { engine } = renderNet(); + engine.seekTo(10); + await settle(); + fireEvent.click(screen.getByText("Alpha")); // opens net A + expect(screen.getByText("Bravo")).toBeTruthy(); + + const pan = vi.spyOn(engine, "panToEntity"); + fireEvent.click(screen.getByText("Bravo")); + expect(pan).toHaveBeenCalledWith(2); + pan.mockRestore(); + }); + + it("keeps only transmissions near the playhead", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording( + makeManifest( + [unitDef({ id: 1, name: "Alpha", positions: stillAt(100, 200) })], + [radioSnapshot(1, 100), transmission(800, 1, "Start", 100), transmission(820, 1, "Stop", 100)], + 900, + ), + ); + engine.seekTo(10); + render(() => ( + + + + )); + + expect(screen.getByText("No transmissions near the playhead")).toBeTruthy(); + }); + + it("searches transmissions by speaker, net and radio", async () => { + const { engine } = renderNet(); + engine.seekTo(10); + await settle(); + const input = screen.getByPlaceholderText("Search radios...") as HTMLInputElement; + + fireEvent.input(input, { target: { value: "alpha" } }); + expect(screen.getByText("1/2")).toBeTruthy(); + + // Radio model match also surfaces the row. + fireEvent.input(input, { target: { value: "anprc152" } }); + expect(screen.getByText("1/2")).toBeTruthy(); + + // ...and so does the formatted net. + fireEvent.input(input, { target: { value: "100 mhz" } }); + expect(screen.getByText("1/2")).toBeTruthy(); + + fireEvent.input(input, { target: { value: "zzz" } }); + expect(screen.getByText("No transmissions match this search")).toBeTruthy(); + }); + + it("narrows nets to a member hit and opens it without touching the others", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording( + makeManifest( + [ + unitDef({ id: 1, name: "Alpha", positions: stillAt(100, 200) }), + unitDef({ id: 2, name: "Bravo", positions: stillAt(100, 200) }), + unitDef({ id: 3, name: "Charlie", positions: stillAt(9100, 200) }), + ], + [radioSnapshot(1, 100), radioSnapshot(2, 100), radioSnapshot(3, 200)], + ), + ); + engine.seekTo(0); + render(() => ( + + + + )); + + const input = screen.getByPlaceholderText("Search radios...") as HTMLInputElement; + fireEvent.input(input, { target: { value: "charlie" } }); + + // The member hit keeps its net alone, auto-expanded so the match shows. + expect(screen.queryByText("100 MHz")).toBeNull(); + expect(screen.getByText("200 MHz")).toBeTruthy(); + expect(screen.getByText("Charlie")).toBeTruthy(); + + // A net-label hit keeps the roster; a member hit opens the net. Searching + // the label itself only lists the net without expanding it. + fireEvent.input(input, { target: { value: "200" } }); + expect(screen.getByText("200 MHz")).toBeTruthy(); + + fireEvent.input(input, { target: { value: "zzz" } }); + expect(screen.getByText("No nets match this search")).toBeTruthy(); + }); + + it("falls back to the unit id when a speaker has no entity and no range to a radio", async () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording( + makeManifest( + [unitDef({ id: 1, name: "Alpha", positions: stillAt(100, 200) })], + [ + bareSnapshot(9), + transmission(5, 9, "Start", 100), + transmission(15, 9, "Stop", 100), + ], + ), + ); + engine.seekTo(10); + await settle(); + render(() => ( + + + + )); + + // Unknown unit names resolve to `Unit 9`, and with no snapshot radio the row + // carries no heard count (the addon's fallback range applies silently). + expect(screen.getByText("Unit 9")).toBeTruthy(); + expect(screen.queryByText(/\/\d/)).toBeNull(); + }); + + it("shows the no-data placeholder without radio data", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording( + makeManifest([unitDef({ id: 1, name: "Alpha", positions: stillAt(100, 200) })], []), + ); + engine.seekTo(0); + render(() => ( + + + + )); + + expect(screen.getByText("No radio data in this recording")).toBeTruthy(); + }); +}); diff --git a/ui/src/pages/recording-playback/__tests__/EventsTab.test.tsx b/ui/src/pages/recording-playback/__tests__/EventsTab.test.tsx index cc9ea7d1..39753af1 100644 --- a/ui/src/pages/recording-playback/__tests__/EventsTab.test.tsx +++ b/ui/src/pages/recording-playback/__tests__/EventsTab.test.tsx @@ -1116,3 +1116,181 @@ describe("EventsTab", () => { expect(screen.getByText(/Satchel Charge/)).toBeTruthy(); }); }); + +function zeusPingEvent(frameNum: number, name: string, side: string, x = 100, y = 200): EventDef { + return { + type: "zeusPing", + frameNum, + payload: { curatorId: 9, unitId: 2, name, side, x, y }, + } as EventDef; +} + +function zeusModuleEvent(frameNum: number, displayName: string, x = 100, y = 200): EventDef { + return { + type: "zeusModule", + frameNum, + payload: { curatorId: 9, curatorName: "Zeus", displayName, className: "ModuleCup", x, y, attachedUnitId: 2, attachedName: "Alpha 1-1" }, + } as EventDef; +} + +function serviceEvent(frameNum: number, kind: string, vehicleName: string): EventDef { + return { + type: "serviceEvent", + frameNum, + payload: { kind, vehicleId: -1, vehicleName, unitId: 2, unitName: "Alpha 1-1", side: "WEST", x: 100, y: 200, from: 0.2, to: 1, magazine: "30rnd_556", magazineName: "STANAG 30", count: 4 }, + } as unknown as EventDef; +} + +function staticWeaponEvent(frameNum: number, action: string, name: string): EventDef { + return { + type: "staticWeapon", + frameNum, + payload: { action, unitId: 2, unitName: "Alpha 1-1", side: "WEST", vehicleId: -1, class: "M2", name, x: 100, y: 200 }, + } as unknown as EventDef; +} + +function radioTransmission(frameNum: number, action: "Start" | "Stop", frequency: number): EventDef { + return { + type: "radioTransmission", + frameNum, + payload: { unitId: 2, radio: "TFAR_anprc152", type: "SW", action, channel: 1, additional: false, frequency, code: "" }, + }; +} + +describe("EventsTab event-type rendering", () => { + function engineWithEvents(events: EventDef[]) { + const { engine, renderer } = createTestEngine(); + engine.loadRecording( + makeManifest([unitDef({ id: 2, name: "Alpha 1-1", side: "WEST" })], events, 60), + ); + engine.seekTo(50); + return { engine, renderer }; + } + + it("renders zeus pings with their pinger and pans on click", () => { + const { engine, renderer } = engineWithEvents([zeusPingEvent(5, "Zeus", "WEST")]); + render(() => ( + + + + )); + + expect(screen.getByText((t) => t.includes("Zeus") && t.includes("pinged Zeus"))).toBeTruthy(); + + const pan = vi.spyOn(engine, "panToPosition"); + fireEvent.click(screen.getByTestId("event-row-5")); + expect(pan).toHaveBeenCalledWith([100, 200]); + pan.mockRestore(); + }); + + it("renders zeus module placements with their names and pans on click", () => { + const { engine, renderer } = engineWithEvents([zeusModuleEvent(6, "Artillery strike")]); + render(() => ( + + + + )); + + expect(screen.getByText((t) => t.includes("Artillery strike"))).toBeTruthy(); + + const pan = vi.spyOn(engine, "panToPosition"); + fireEvent.click(screen.getByTestId("event-row-6")); + expect(pan).toHaveBeenCalledWith([100, 200]); + pan.mockRestore(); + }); + + it("renders servicing with the magazine detail for rearms and pans to the vehicle", () => { + const { engine, renderer } = engineWithEvents([serviceEvent(7, "rearm", "Hunter")]); + render(() => ( + + + + )); + + expect(screen.getByText((t) => t.includes("rearmed") && t.includes("Hunter"))).toBeTruthy(); + expect(screen.getByText((t) => t.includes("STANAG 30"))).toBeTruthy(); + + // vehicleId -1 falls back to the event position. + const pan = vi.spyOn(engine, "panToPosition"); + fireEvent.click(screen.getByTestId("event-row-7")); + expect(pan).toHaveBeenCalledWith([100, 200]); + pan.mockRestore(); + }); + + it("renders static weapon assembly and pans to its position", () => { + const { engine, renderer } = engineWithEvents([staticWeaponEvent(8, "assembled", "M2 HMG")]); + render(() => ( + + + + )); + + expect(screen.getByText((t) => t.includes("M2 HMG"))).toBeTruthy(); + + const pan = vi.spyOn(engine, "panToPosition"); + fireEvent.click(screen.getByTestId("event-row-8")); + expect(pan).toHaveBeenCalledWith([100, 200]); + pan.mockRestore(); + }); + + it("renders a transmission with the speaker and net, panning to the speaker", () => { + const { engine, renderer } = engineWithEvents([ + radioTransmission(10, "Start", 100), + radioTransmission(20, "Stop", 100), + ]); + render(() => ( + + + + )); + + // Transmissions are hidden by default; the comms tab owns them. + fireEvent.click(screen.getByLabelText("Event filters")); + fireEvent.click(screen.getByText("Transmissions")); + const row = screen.getByText((t) => t.includes("transmitted on")); + expect(row.textContent).toContain("Alpha 1-1"); + expect(row.textContent).toContain("100 MHz"); + + const pan = vi.spyOn(engine, "panToEntity"); + fireEvent.click(screen.getByTestId("event-row-10")); + expect(pan).toHaveBeenCalledWith(2); + pan.mockRestore(); + }); + + it("searches chat messages, transmissions and module names", () => { + const { engine, renderer } = engineWithEvents([ + { frameNum: 5, type: "chat", channel: "Global", fromName: "Alpha 1-1", message: "pushing north" } as unknown as EventDef, + radioTransmission(10, "Start", 100), + radioTransmission(20, "Stop", 100), + zeusModuleEvent(15, "Artillery strike"), + ]); + render(() => ( + + + + )); + + fireEvent.click(screen.getByLabelText("Event filters")); + fireEvent.click(screen.getByText("Transmissions")); + fireEvent.click(screen.getByText("Chat")); + + const input = screen.getByPlaceholderText("Search events...") as HTMLInputElement; + + // Chat haystack includes channel, sender and message. + fireEvent.input(input, { target: { value: "global" } }); + expect(screen.getByText((t) => t.includes("pushing north"))).toBeTruthy(); + fireEvent.input(input, { target: { value: "alpha 1-1 pushing" } }); + expect(screen.getByText((t) => t.includes("pushing north"))).toBeTruthy(); + + // Transmissions match on radio, formatted net, and speaker name. + fireEvent.input(input, { target: { value: "anprc152" } }); + expect(screen.queryByText((t) => t.includes("pushing north"))).toBeNull(); + expect(screen.getByText((t) => t.includes("transmitted on"))).toBeTruthy(); + + fireEvent.input(input, { target: { value: "artillery" } }); + expect(screen.getByText((t) => t.includes("Artillery strike"))).toBeTruthy(); + + fireEvent.input(input, { target: { value: "zzz" } }); + expect(screen.queryByTestId("event-row-0")).toBeNull(); + }); +}); diff --git a/ui/src/pages/recording-playback/__tests__/StatsTab.test.tsx b/ui/src/pages/recording-playback/__tests__/StatsTab.test.tsx index 10525fbb..87ff2a6c 100644 --- a/ui/src/pages/recording-playback/__tests__/StatsTab.test.tsx +++ b/ui/src/pages/recording-playback/__tests__/StatsTab.test.tsx @@ -523,3 +523,118 @@ describe("StatsTab", () => { expect(screen.queryByText("CIV")).toBeNull(); }); }); + +describe("StatsTab weather detail and movement", () => { + it("reports wind direction without a speed sample", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(makeManifest( + [unitDef({ id: 1, side: "WEST" })], + [{ + frameNum: 0, + type: "weather", + payload: { overcast: 0.5, rain: 0, fog: 0, windDir: 315, moonPhase: 0, ace: false }, + }], + 60, + )); + engine.seekTo(30); + + render(() => ( + + + + )); + + // Value and label render in separate cells. + expect(screen.getByText("NW 315°")).toBeTruthy(); + expect(screen.getByText("Wind")).toBeTruthy(); + }); + + it("shows gusts, lightnings and waves when the sample carries them", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(makeManifest( + [unitDef({ id: 1, side: "WEST" })], + [{ + frameNum: 0, + type: "weather", + payload: { overcast: 0.5, rain: 0, fog: 0, moonPhase: 0, gusts: 0.4, lightnings: 0.2, waves: 0.3, ace: false }, + }], + 60, + )); + engine.seekTo(30); + + render(() => ( + + + + )); + + expect(screen.getByText("40%")).toBeTruthy(); + expect(screen.getByText("20%")).toBeTruthy(); + expect(screen.getByText("30%")).toBeTruthy(); + }); + + it("ranks movement across players and formats distances", async () => { + const { engine, renderer } = createTestEngine(); + // Two players moving at different speeds: Walker covers 2 m/frame from a + // standing start, Runner 10 m/frame. Default capture delay of 1 s samples + // every 5 frames. + const walk = Array.from({ length: 101 }, (_, i) => ({ + position: [100 + i * 2, 200] as [number, number], + direction: 0, + alive: 1 as const, + })); + const run = Array.from({ length: 101 }, (_, i) => ({ + position: [1000 + i * 10, 2000] as [number, number], + direction: 0, + alive: 1 as const, + })); + engine.loadRecording(makeManifest( + [ + unitDef({ id: 1, name: "Walker", side: "WEST", isPlayer: true, positions: walk }), + unitDef({ id: 2, name: "Runner", side: "EAST", isPlayer: true, positions: run }), + ], + [], + 100, + )); + engine.seekTo(100); + + render(() => ( + + + + )); + + await vi.waitFor(() => { + expect(screen.getByText("Runner")).toBeTruthy(); + expect(screen.getByText("Walker")).toBeTruthy(); + }); + + // Steps are 5 frames apart: Walker moves 10 m per step over 20 steps = 200 m + // on foot; Runner does 50 m per step over 20 steps = 1.0 km and ranks first. + const rows = screen.getAllByText(/^(200 m|1\.0 km)$/); + expect(rows.map((el) => el.textContent).sort()).toEqual(["1.0 km", "1.0 km", "200 m", "200 m"]); + // Runner (1.0 km) is ranked above Walker (200 m). + expect(screen.getByText("Runner").compareDocumentPosition(screen.getByText("Walker")) & + Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + }); + + it("explains when nobody moved", async () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(makeManifest( + [unitDef({ id: 1, side: "WEST", isPlayer: false })], + [], + 100, + )); + engine.seekTo(100); + + render(() => ( + + + + )); + + await vi.waitFor(() => + expect(screen.getByText("No movement recorded")).toBeTruthy(), + ); + }); +}); diff --git a/ui/src/pages/recording-playback/components/__tests__/OrbatTab.test.tsx b/ui/src/pages/recording-playback/components/__tests__/OrbatTab.test.tsx index 87f04aa6..ae11d457 100644 --- a/ui/src/pages/recording-playback/components/__tests__/OrbatTab.test.tsx +++ b/ui/src/pages/recording-playback/components/__tests__/OrbatTab.test.tsx @@ -1,7 +1,7 @@ -import { describe, it, expect, afterEach } from "vitest"; +import { describe, it, expect, afterEach, vi } from "vitest"; import { render, screen, fireEvent, cleanup } from "@solidjs/testing-library"; import { OrbatTab } from "../OrbatTab"; -import { createTestEngine, TestProviders, unitDef } from "../../__tests__/testHelpers"; +import { createTestEngine, TestProviders, unitDef, vehicleDef } from "../../__tests__/testHelpers"; afterEach(() => { cleanup(); @@ -128,3 +128,180 @@ describe("OrbatTab", () => { expect(screen.queryByText("Bravo 2-1")).toBeNull(); }); }); + +function orbatManifest(entities: ReturnType[]) { + return { + version: 1 as const, + worldName: "test_world", + missionName: "test_mission", + endFrame: 50, + chunkSize: 300, + chunkCount: 1, + captureDelayMs: 1000, + entities, + events: [], + markers: [], + times: [], + }; +} + +describe("OrbatTab search and vehicles", () => { + it("narrows groups to a member-name hit and keeps only that member", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(orbatManifest([ + unitDef({ id: 1, side: "WEST", name: "Alpha 1-1", groupName: "Alpha", role: "leader" }), + unitDef({ id: 2, side: "WEST", name: "Alpha 1-2", groupName: "Alpha", role: "Rifleman" }), + unitDef({ id: 3, side: "WEST", name: "Charlie 3-1", groupName: "Charlie", role: "Medic" }), + ])); + + render(() => ( + + + + )); + + const input = screen.getByPlaceholderText("Search ORBAT...") as HTMLInputElement; + fireEvent.input(input, { target: { value: "alpha 1-2" } }); + + // The member hit keeps its group with only that member, alive recounted. + expect(screen.getByText("Alpha 1-2")).toBeTruthy(); + expect(screen.queryByText("Alpha 1-1")).toBeNull(); + expect(screen.queryByText("Charlie 3-1")).toBeNull(); + // The group header still reads Alpha, with the recounted strength 1/2. + expect(screen.getByText("Alpha")).toBeTruthy(); + }); + + it("matches a member by role and reports no matches for junk", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(orbatManifest([ + unitDef({ id: 1, side: "WEST", name: "Alpha 1-1", groupName: "Alpha", role: "leader" }), + unitDef({ id: 2, side: "WEST", name: "Alpha 1-2", groupName: "Alpha", role: "Medic" }), + ])); + + render(() => ( + + + + )); + + const input = screen.getByPlaceholderText("Search ORBAT...") as HTMLInputElement; + + // A role hit keeps only the member carrying it. + fireEvent.input(input, { target: { value: "medic" } }); + expect(screen.getByText("Alpha 1-2")).toBeTruthy(); + expect(screen.queryByText("Alpha 1-1")).toBeNull(); + + fireEvent.input(input, { target: { value: "zzz" } }); + expect(screen.getByText("No groups match this search")).toBeTruthy(); + }); + + it("opens on the faction with players, then honours an explicit pick", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(orbatManifest([ + unitDef({ id: 1, side: "EAST", name: "Opfor Lead", groupName: "Bears", role: "leader" }), + unitDef({ id: 2, side: "WEST", name: "West AI", role: "", isPlayer: false }), + ])); + + render(() => ( + + + + )); + + // The faction with players is preselected, not the first side alphabetically. + expect(screen.getByText("Opfor Lead")).toBeTruthy(); + expect(screen.queryByText("West AI")).toBeNull(); + + // Picking the player-less faction is a deliberate choice and sticks. + fireEvent.click(screen.getByText("BLUFOR")); + expect(screen.getByText("No player units on this side")).toBeTruthy(); + + // ...and returning to OPFOR works. + fireEvent.click(screen.getByText("OPFOR")); + expect(screen.getByText("Opfor Lead")).toBeTruthy(); + }); + + it("follows a member when their row is clicked", async () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(orbatManifest([ + unitDef({ id: 1, side: "WEST", name: "Alpha 1-1", groupName: "Alpha", role: "leader" }), + ])); + + render(() => ( + + + + )); + + const follow = vi.spyOn(engine, "followEntity"); + fireEvent.click(screen.getByText("Alpha 1-1")); + expect(follow).toHaveBeenCalledWith(1); + follow.mockRestore(); + }); + + it("lists vehicles players crewed, searchable by name and by crew", async () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(orbatManifest([ + unitDef({ id: 1, side: "WEST", name: "Driver Dave", groupName: "Alpha", role: "driver" }), + unitDef({ id: 2, side: "WEST", name: "Gunner Gus", groupName: "Alpha", role: "gunner" }), + vehicleDef({ + id: 50, + name: "Hunter", + side: "WEST", + startFrame: 0, + endFrame: 50, + positions: [ + { position: [300, 400], direction: 90, alive: 1 as const, crewIds: [1, 2] }, + ], + }), + vehicleDef({ + id: 51, + name: "Badger", + side: "WEST", + startFrame: 0, + endFrame: 50, + positions: [ + { position: [320, 420], direction: 0, alive: 1 as const, crewIds: [1] }, + ], + }), + ])); + + render(() => ( + + + + )); + + // Occupancy resolves asynchronously. + await vi.waitFor(() => expect(screen.getByText("Hunter")).toBeTruthy()); + + const input = screen.getByPlaceholderText("Search ORBAT...") as HTMLInputElement; + + // By vehicle name. + fireEvent.input(input, { target: { value: "badger" } }); + expect(screen.getByText("Badger")).toBeTruthy(); + expect(screen.queryByText("Hunter")).toBeNull(); + + // By a crew member's name. + fireEvent.input(input, { target: { value: "gus" } }); + expect(screen.getByText("Hunter")).toBeTruthy(); + expect(screen.queryByText("Badger")).toBeNull(); + }); + + it("shows the empty note when no player vehicle exists", async () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(orbatManifest([ + unitDef({ id: 1, side: "WEST", name: "Lone Wolf", groupName: "Alpha", role: "" }), + ])); + + render(() => ( + + + + )); + + await vi.waitFor(() => + expect(screen.getByText("No vehicle was crewed by players on this side")).toBeTruthy(), + ); + }); +}); diff --git a/ui/src/pages/recording-playback/components/__tests__/PlayerProfileDiff.test.tsx b/ui/src/pages/recording-playback/components/__tests__/PlayerProfileDiff.test.tsx index 2df9561e..f8ad0614 100644 --- a/ui/src/pages/recording-playback/components/__tests__/PlayerProfileDiff.test.tsx +++ b/ui/src/pages/recording-playback/components/__tests__/PlayerProfileDiff.test.tsx @@ -129,3 +129,191 @@ describe("GearDiffView", () => { expect(screen.getByText((t) => t.includes("Hand grenade"))).toBeTruthy(); }); }); + +import { MedicalDiffView, RadioDiffView, StaminaDiffView, DiffEmpty } from "../PlayerProfileDiff"; +import type { MedicalDiff, RadioDiff, FieldDelta } from "../../profileDiff"; + +function renderView(ui: () => import("solid-js").JSX.Element) { + render(() => {ui()}); +} + +const field = (labelKey: string, kind: FieldDelta["kind"], from: unknown, to: unknown, extra: Partial = {}): FieldDelta => ({ + labelKey, + kind, + from, + to, + ...extra, +}); + +describe("MedicalDiffView", () => { + it("renders nothing when the diff is empty", () => { + renderView(() => ( + + + + )); + expect(screen.queryByText("Body parts")).toBeNull(); + expect(screen.queryByText("In the system")).toBeNull(); + expect(screen.queryByText("New since then")).toBeNull(); + }); + + it("formats every field kind through the grid", () => { + const diff: MedicalDiff = { + fields: [ + field("profile_heart_rate", "number", 80, 92), + field("profile_pain", "percent", 0.25, 0.5), + field("profile_blood", "bool", false, true), + field("profile_pressure", "bp", [0, 0], [120, 80]), + field("profile_hemorrhage", "hemorrhage", 0, 2), + field("profile_stance", "stance", 1, 3), + field("profile_note", "text", "old", "new"), + ], + bodyParts: [], + treatments: [], + activity: [], + quickView: [], + }; + renderView(() => ( + + + + )); + + // number + expect(screen.getByText((t) => t.includes("80 → 92"))).toBeTruthy(); + // percent + expect(screen.getByText((t) => t.includes("25% → 50%"))).toBeTruthy(); + // bool + expect(screen.getByText((t) => t.includes("No → Yes"))).toBeTruthy(); + // bp: zero/zero falls back to the none label, a real pressure renders + expect(screen.getByText((t) => t.includes("No pressure → 80/120"))).toBeTruthy(); + // hemorrhage levels + expect(screen.getByText((t) => t.includes("→ Class II"))).toBeTruthy(); + // stance keys map through their labels + expect(screen.getByText((t) => t.includes("Standing → Prone"))).toBeTruthy(); + // plain values pass through + expect(screen.getByText((t) => t.includes("old → new"))).toBeTruthy(); + }); + + it("renders body parts with damage and items", () => { + const diff: MedicalDiff = { + fields: [], + bodyParts: [ + { + part: "head", + damage: field("profile_damage", "percent", 0.1, 0.9), + items: [{ polarity: "removed", class: "bandage", name: "Bandage", fromCount: 2, toCount: 0 }], + }, + { part: "torsolog", damage: undefined, items: [] }, + ], + treatments: [], + activity: [], + quickView: [], + }; + renderView(() => ( + + + + )); + expect(screen.getByText("Body parts")).toBeTruthy(); + expect(screen.getByText("Head")).toBeTruthy(); + expect(screen.getByText((t) => t.includes("10% → 90%"))).toBeTruthy(); + expect(screen.getByText("torsolog")).toBeTruthy(); + expect(screen.getByText((t) => t.includes("Bandage"))).toBeTruthy(); + }); + + it("lists treatments, activity and quick view entries", () => { + const diff: MedicalDiff = { + fields: [], + bodyParts: [], + treatments: [{ polarity: "added", class: "morphine", name: "Morphine", fromCount: 0, toCount: 1 }], + activity: [{ time: "12:00", text: "Bandage applied" }], + quickView: [{ time: "12:01", text: "Pain reduced" }], + }; + renderView(() => ( + + + + )); + expect(screen.getByText("In the system")).toBeTruthy(); + expect(screen.getByText("New since then")).toBeTruthy(); + expect(screen.getByText("Quick view")).toBeTruthy(); + expect(screen.getByText("Bandage applied")).toBeTruthy(); + expect(screen.getByText("Pain reduced")).toBeTruthy(); + }); + + it("renders item rounds deltas for each polarity", () => { + const diff: MedicalDiff = { + fields: [], + bodyParts: [], + treatments: [ + { polarity: "added", class: "mag", name: "Mag", fromCount: 0, toCount: 2, toRounds: 30 }, + { polarity: "removed", class: "mag", name: "Spent", fromCount: 1, toCount: 0, fromRounds: 30 }, + { polarity: "changed", class: "mag", name: "Partial", fromCount: 1, toCount: 1, fromRounds: 10, toRounds: 25 }, + { polarity: "changed", class: "mag", name: "Unknown rounds", fromCount: 1, toCount: 1 }, + ], + activity: [], + quickView: [], + }; + renderView(() => ( + + + + )); + expect(screen.getByText((t) => t.includes("+ Mag") && t.includes("×2") && t.includes("30 rds"))).toBeTruthy(); + expect(screen.getByText((t) => t.includes("− Spent") && t.includes("×1") && t.includes("30 rds"))).toBeTruthy(); + expect(screen.getByText((t) => t.includes("Partial") && t.includes("10 → 25"))).toBeTruthy(); + // Without round counts there is no rounds suffix at all. + expect(screen.queryByText((t) => t.includes("Unknown rounds") && t.includes("rds"))).toBeNull(); + }); +}); + +describe("RadioDiffView", () => { + it("marks each radio row with its polarity", () => { + const diff: RadioDiff = { + radios: [ + { polarity: "added", name: "PRC-343", fields: [field("profile_radio_freq", "number", 0, 2560)] }, + { polarity: "removed", name: "PRC-152", fields: [] }, + { polarity: "changed", name: "BF-888S", fields: [] }, + ], + }; + renderView(() => ( + + + + )); + expect(screen.getByText("PRC-343")).toBeTruthy(); + expect(screen.getByText("PRC-152")).toBeTruthy(); + expect(screen.getByText("BF-888S")).toBeTruthy(); + expect(screen.getByText((t) => t.includes("0 → 2560"))).toBeTruthy(); + }); +}); + +describe("StaminaDiffView and DiffEmpty", () => { + it("renders stamina fields through the same grid", () => { + renderView(() => ( + + + + )); + expect(screen.getByText((t) => t.includes("30.0 kg → 35.0 kg"))).toBeTruthy(); + }); + + it("tells apart same-frame and empty diffs", () => { + renderView(() => ( + + + + )); + expect(screen.getByText("Scrub the timeline to pick the other time.")).toBeTruthy(); + }); + + it("explains when there are no changes at all", () => { + renderView(() => ( + + + + )); + expect(screen.getByText("No changes in this tab.")).toBeTruthy(); + }); +});