Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

13.1 KB
Raw Blame
using System;
using System.Linq;
using Statecraft.Sim;
using Xunit;

/// <summary>R-TURN-004 and R-SAVE-003 (spec 2026-10-23 sections 3.3 and 3.4): committed orders are final, shown at once,
/// run first at End turn, and survive a reload.</summary>
public class GameSessionTurnTests
{
    static readonly Content C = ContentLoader.Load(RealContentTests.ContentRoot());

    static GameSession Fresh() => GameSession.New(C, GoldenRun.Seed, Mode.Historical);

    [Fact]
    public void ACommittedMoveShowsAtOnceAndEndTurnRunsIt()
    {
        var session = Fresh();
        var move = GoldenRun.SmokeMove(C, session.State);
        var before = (session.State.Units[move.Unit].Q, session.State.Units[move.Unit].R);
        Assert.Null(session.Commit(move));
        Assert.Equal((move.Q, move.R), (session.Now.State.Units[move.Unit].Q, session.Now.State.Units[move.Unit].R));
        Assert.Equal(before, (session.State.Units[move.Unit].Q, session.State.Units[move.Unit].R));
        var ended = session.EndTurn(new Command[0]);
        Assert.Equal(GoldenRun.PlaySmokeOrders(C).Hash(), ended.State.Hash());
        Assert.Empty(session.Committed);
    }

    [Fact]
    public void ARefusedOrderIsNotCommitted()
    {
        var session = Fresh();
        Assert.Equal("That unit is already there", session.Commit(new Move(0, session.State.Units[0].Q, session.State.Units[0].R)));
        Assert.Empty(session.Committed);
        Assert.Throws<ArgumentException>(() => session.Commit(new BuyArms(1)));
        Assert.Throws<ArgumentException>(() => session.Commit(new UnitOrder(0, Demobilization.SendHome)));   // waits for End turn
    }

    // R-TURN-004: End turn runs the committed orders first, as the open turn showed them, so the step's first causes are
    // the open turn's own, in order. The game plays a combat once when it resolves and skips that prefix at End turn
    // (SimBridge.CombatResolved, #1867): a cause added before the committed orders would replay or hide one.
    [Fact]
    public void EndTurnBeginsWithTheOpenTurnsCausesInOrder()
    {
        var session = Fresh();
        var enemy = session.State.Units[9];
        Assert.NotEqual(Movement.PlayerSide, enemy.Side);
        Assert.Null(session.Commit(new UnitOrder(5, Combat.Attack, enemy.Q, enemy.R)));   // unit 5 stands next to unit 9
        // Unit 6 takes the hex unit 9 marches on (R-ENEMY-002), so no path leads there and it attacks instead (R-ENEMY-003).
        var march = C.StartingForces[9].Script[0];
        Assert.Null(session.Commit(new Move(6, march.Q, march.R)));
        var open = session.Now.Why.ToList();
        Assert.Contains(open, x => x.Key == WhyKeys.Engagement);
        var ended = session.EndTurn(new Command[] { new BuyArms(1) });
        Assert.True(ended.Why.Count > open.Count, "the turn adds causes of its own");
        Assert.Equal(open.Select(x => (x.Key, x.Target, x.Message)), ended.Why.Take(open.Count).Select(x => (x.Key, x.Target, x.Message)));
        Assert.Contains(ended.Why.Skip(open.Count), x => x.Key == WhyKeys.Engagement && x.EnemyOrder == Combat.Attack);
    }

    // R-TURN-004: deferred orders run after the committed ones, whatever order they were given in.
    [Fact]
    public void DeferredOrdersRunAfterCommittedOnes()
    {
        var session = Fresh();
        var move = GoldenRun.SmokeMove(C, session.State);
        session.Commit(move);
        session.EndTurn(new Command[] { new BuyArms(1) });
        Assert.Equal(new Command[] { move }.Concat(new Command[] { new BuyArms(1) }).Select(x => x.Kind),
                     session.Save.Turns.Last().Select(x => x.Kind));
    }

    // R-SAVE-003: a reload in the middle of a turn keeps what was done.
    [Fact]
    public void AReloadKeepsTheOpenTurn()
    {
        var session = Fresh();
        var move = GoldenRun.SmokeMove(C, session.State);
        session.Commit(move);
        var loaded = GameSession.Load(C, session.Save.Write(), out var warnings);
        Assert.Empty(warnings);
        Assert.Equal(session.Now.State.Hash(), loaded.Now.State.Hash());
        Assert.Equal(new[] { "move" }, loaded.Committed.Select(x => x.Kind));
    }

    // R-SAVE-003 (#2653): with the same content, an open-turn order the sim refuses on load means the save was edited.
    [Fact]
    public void ARefusedOpenOrderWithTheSameContentIsAnError()
    {
        var session = Fresh();
        var unit = session.State.Units[0];
        session.Save.SetOpen(new Command[] { new Move(0, unit.Q, unit.R) });   // refused: the unit is already there
        var e = Assert.Throws<SaveException>(() => GameSession.Load(C, session.Save.Write(), out _));
        Assert.Contains("The open turn's order 'move' was refused", e.Message);
    }

    // R-SAVE-003 (#2653): with other content, the first refused open order ends the replay: it and every later order
    // are dropped, and the load warns that the replay differs.
    [Fact]
    public void ARefusedOpenOrderWithOtherContentDropsItAndTheRest()
    {
        var session = Fresh();
        var unit = session.State.Units[0];
        var valid = GoldenRun.SmokeMove(C, session.State);
        session.Save.SetOpen(new Command[] { new Move(0, unit.Q, unit.R), valid });
        var text = session.Save.Write().Replace("content " + C.Hash, "content " + new string('0', 64));   // other content
        var loaded = GameSession.Load(C, text, out var warnings);
        Assert.Equal(new[] { GameSession.ContentChanged, GameSession.ReplayDiffers }, warnings);
        Assert.Empty(loaded.Committed);
        Assert.Null(Fresh().Commit(valid));   // the dropped order after it would have been taken on its own
    }

    [Fact]
    public void StepRefusesWhileOrdersAreCommitted()
    {
        var session = Fresh();
        session.Commit(GoldenRun.SmokeMove(C, session.State));
        Assert.Throws<InvalidOperationException>(() => session.Step(new Command[0]));
    }

    // R-SAVE-004: a schema 2 GDD save with a player attack (a standing order then) is refused as older rules. Its final hash
    // matches its replay, so only the attack guard (GameSession.Load, R-SAVE-004) can refuse it (#2733 item 8).
    [Fact]
    public void ASchema2SaveWithAnAttackIsRefusedAsOlderRules()
    {
        var session = Fresh();
        var (unit, q, r) = FirstAttack(session);
        var ended = session.Step(new Command[] { new UnitOrder(unit, Combat.Attack, q, r) });
        Assert.Empty(ended.Rejected);
        var current = session.Save.Write();
        Assert.Contains(FormattableString.Invariant($"order {unit} attack {q} {r}"), current);
        // Control: the same save in schema 3 (R-SAVE-003, R-SAVE-005) replays to its saved hash and loads with no warning.
        var three = current.Replace($"statecraft-save {SaveGame.SchemaVersion}\n", "statecraft-save 3\n");
        Assert.Equal(3, SaveGame.Parse(three).Version);
        GameSession.Load(C, three, out var w3);
        Assert.Empty(w3);
        var two = current.Replace($"statecraft-save {SaveGame.SchemaVersion}\n", "statecraft-save 2\n");
        Assert.Equal(2, SaveGame.Parse(two).Version);
        var e = Assert.Throws<SaveException>(() => GameSession.Load(C, two, out _));
        Assert.Equal(SaveException.OlderRules, e.Code);
    }

    // R-SAVE-004: "Other schema 2 saves load". A GDD save with no attack whose replay ends on its saved hash loads with no
    // warning, has the live game's hash, and is written back in the current schema (R-SAVE-005).
    [Fact]
    public void AnOrdinarySchema2SaveLoads()
    {
        var session = Fresh();
        session.Step(new Command[] { GoldenRun.SmokeMove(C, session.State), new BuyArms(1) });
        session.Step(new Command[0]);
        var current = session.Save.Write();
        var two = current.Replace("statecraft-save 6\n", "statecraft-save 2\n");
        Assert.Equal(2, SaveGame.Parse(two).Version);
        Assert.DoesNotContain(" attack ", two);
        var loaded = GameSession.Load(C, two, out var warnings);
        Assert.Empty(warnings);
        Assert.Equal(session.State.Hash(), loaded.State.Hash());
        Assert.Equal(current, loaded.Save.Write());
    }

    // R-SAVE-003: reloading keeps an attack's result; the same draw comes out.
    [Fact]
    public void AReloadKeepsAnAttacksResult()
    {
        var session = Fresh();
        var (unit, q, r) = FirstAttack(session);
        Assert.Null(session.Commit(new UnitOrder(unit, Combat.Attack, q, r)));
        var loaded = GameSession.Load(C, session.Save.Write(), out _);
        Assert.Equal(session.Now.State.Hash(), loaded.Now.State.Hash());
    }

    // R-TURN-004: a vote queued after an attack runs after it, so it cannot change the attack's draw.
    [Fact]
    public void AVoteQueuedAfterAnAttackDoesNotChangeIt()
    {
        var a = Fresh(); var b = Fresh();
        var (unit, q, r) = FirstAttack(a);
        a.Commit(new UnitOrder(unit, Combat.Attack, q, r)); b.Commit(new UnitOrder(unit, Combat.Attack, q, r));
        var policy = C.At(a.State.Date).Policies.First().Id;
        var withVote = a.EndTurn(new Command[] { new SetPolicy(policy, 0.5) });
        var without = b.EndTurn(new Command[0]);
        Assert.Equal(without.Why.First(w => w.Message.StartsWith("The attack on hex")).Message,
                     withVote.Why.First(w => w.Message.StartsWith("The attack on hex")).Message);
    }

    /// <summary>The first (unit, hex) of the player's that Combat.Check takes on the session's shown state. At the start Golani
    /// (unit 0, 10,9) is next to the Syrian unit on 10,10 (docs/determinism.md, #1240's row), so one exists.</summary>
    static (int, int, int) FirstAttack(GameSession s)
    {
        var st = s.Now.State;
        foreach (var u in st.Units.Values.Where(x => x.Side == Movement.PlayerSide))
            foreach (var e in st.Units.Values.Where(x => x.Side != "" && x.Side != Movement.PlayerSide))
                if (Combat.Check(C, st, u.Id, e.Q, e.R, spent: s.Now.Spent) == null) return (u.Id, e.Q, e.R);
        throw new InvalidOperationException("precondition: no attack is possible at the start");
    }

    // R-SAVE-004: a schema 2 GDD save that does not replay to its saved hash gets the clear older-rules message. #2605: a
    // schema 3 one was played before the soft-event cap kept left-out events waiting, so it loads with replay_differs; a
    // current (schema 6, R-SAVE-006) one that does not is still damaged (no code).
    [Fact]
    public void ASchema2SaveThatReplaysDifferentlyIsRefusedAsOlderRules()
    {
        static string WrongEnd(string text) { var end = text.Substring(text.LastIndexOf("end ", StringComparison.Ordinal) + 4, 64); return text.Replace("end " + end, "end " + new string('0', 64)); }
        var two = WrongEnd(Fresh().Save.Write().Replace("statecraft-save 6", "statecraft-save 2"));
        Assert.Equal(SaveException.OlderRules, Assert.Throws<SaveException>(() => GameSession.Load(C, two, out _)).Code);
        var three = WrongEnd(Fresh().Save.Write().Replace("statecraft-save 6", "statecraft-save 3"));
        GameSession.Load(C, three, out var warnings);
        Assert.Equal(new[] { GameSession.ReplayDiffers }, warnings);
        var six = WrongEnd(Fresh().Save.Write());
        Assert.StartsWith("statecraft-save 6\n", six);
        Assert.Null(Assert.Throws<SaveException>(() => GameSession.Load(C, six, out _)).Code);
    }

    // #2605: the same for a refused open-turn order. A schema 3 save's open turn follows a replay under the earlier soft-event
    // cap, so an order the new replay refuses loads with replay_differs; in a current save it is damage.
    [Fact]
    public void ASchema3SaveWhoseOpenOrderIsRefusedLoadsWithReplayDiffers()
    {
        var bad = Fresh().Save.Write().Replace("end ", "open\nmove 999 1 1\nend ");
        Assert.Throws<SaveException>(() => GameSession.Load(C, bad, out _));
        GameSession.Load(C, bad.Replace("statecraft-save 6", "statecraft-save 3"), out var warnings);
        Assert.Equal(new[] { GameSession.ReplayDiffers }, warnings);
    }

    // R-SAVE-006 (#2544): a schema 5 save was played before a player's order to a unit in an operation cancelled the
    // operation's remaining orders for its other units (R-ENEMY-009), so a replay that ends elsewhere, or an open-turn
    // order the replay now refuses, loads with replay_differs; a current (schema 6) save that does either is damage.
    [Fact]
    public void R_SAVE_006_ASchema5SaveThatReplaysDifferentlyLoadsWithReplayDiffers()
    {
        static string WrongEnd(string text) { var end = text.Substring(text.LastIndexOf("end ", StringComparison.Ordinal) + 4, 64); return text.Replace("end " + end, "end " + new string('0', 64)); }
        var current = Fresh().Save.Write();
        Assert.StartsWith("statecraft-save 6\n", current);
        Assert.Null(Assert.Throws<SaveException>(() => GameSession.Load(C, WrongEnd(current), out _)).Code);
        GameSession.Load(C, WrongEnd(current).Replace("statecraft-save 6\n", "statecraft-save 5\n"), out var warnings);
        Assert.Equal(new[] { GameSession.ReplayDiffers }, warnings);

        var bad = current.Replace("end ", "open\nmove 999 1 1\nend ");
        Assert.Throws<SaveException>(() => GameSession.Load(C, bad, out _));
        GameSession.Load(C, bad.Replace("statecraft-save 6\n", "statecraft-save 5\n"), out warnings);
        Assert.Equal(new[] { GameSession.ReplayDiffers }, warnings);
    }
}