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.

16.7 KB
Raw Blame
#nullable enable
using System.Linq;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.UI;
using Statecraft.Sim;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

/// <summary>R-MONEY-004, "Spend the dollars" (#813; owner, 2 November 2026: "Spend the dollars (Recommended)"): the Defence
/// screen's conversion panel, beside the Arms purchase. It queues one ConvertDollars for End turn, shows the foreign-currency
/// reserve beside the order (the top bar's meters are unchanged) and says the sim's refusal before End turn.</summary>
public class DollarConversionTests
{
    static UiText Text(bool he) => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(he ? UiPaths.StringsHebrew : UiPaths.Strings).text);
    static UiText En => Text(false);
    static UiText He => Text(true);

    static SimBridge Bridge(bool modern, bool he)
    {
        var dir = Paths.Content;
        var c = ContentLoader.Load(rel =>
        {
            var path = System.IO.Path.Combine(dir, rel);
            if (!System.IO.File.Exists(path)) return null;
            var value = System.IO.File.ReadAllText(path);
            return modern && rel == "eras.yaml" ? value.Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3") : value;
        }, System.IO.Directory.GetFiles(System.IO.Path.Combine(dir, "events"), "*.yaml").Select(x => "events/" + System.IO.Path.GetFileName(x)));
        var b = new SimBridge(GameSession.New(c, GoldenRun.Seed, Mode.Historical), Text(he));
        if (modern)
        {
            foreach (var r in c.EraRules.Values.Append(c.Rules))
            { r.AttentionCost.Clear(); r.AttentionPerTurn = double.NaN; }
            b.State.Attention = double.NaN;
        }
        return b;
    }

    // R-MONEY-004: the panel lives in Defence and shows the reserve, the total converted against the cap and the Money the
    // amount brings, in the content's own money format; the top bar gains nothing.
    [TestCase(false, false)] [TestCase(false, true)]
    [TestCase(true, false)] [TestCase(true, true)]
    public void ThePanelShowsTheReserveAndTheMoneyItBrings(bool modern, bool he)
    {
        var b = Bridge(modern, he); var t = Text(he); var c = b.Content; var m = c.RulesAt(b.State.Date).Mvp!;
        using var ui = new UiTestKit();
        using var hud = new HudPresenter(ui.Root, b, t);
        using var defence = new DefencePresenter(ui.Root, b, t);
        var panel = ui.Q<VisualElement>("defence-dollars");
        Assert.AreEqual(DisplayStyle.Flex, panel.style.display.value);
        Assert.IsTrue(panel.Contains(ui.Q<Label>("dollars-reserves")));
        Assert.AreEqual(t.Format("dollars.reserves", PlayerText.Money(c, "fx_reserves", b.State.FxReserves)), ui.Q<Label>("dollars-reserves").text);
        Assert.AreEqual(t.Format("dollars.total", PlayerText.Money(c, "fx_reserves", 0), PlayerText.Money(c, "fx_reserves", m.DollarsTotal!.Value)),
            ui.Q<Label>("dollars-total").text);
        var amount = ui.Q<IntegerField>("dollars-amount");
        Assert.AreEqual(m.DollarsPerTurn!.Value, amount.value, "the amount starts at the month's limit");
        amount.value = 3;
        Assert.AreEqual(t.Format("dollars.money", PlayerText.Money(c, "treasury", 3 * m.IlPerDollarOn(b.State.Date))), ui.Q<Label>("dollars-money").text);
        CollectionAssert.AreEqual(new[] { "treasury", "immigration", "security", "support", "cohesion", "standing", "fx" }, HudModel.MeterIds,
            "the top bar's meters are unchanged");
    }

    // R-MONEY-004: Convert queues one order (a second replaces it), the state is untouched until End turn, which converts.
    [TestCase(false)] [TestCase(true)]
    public void ConvertQueuesOneOrderAndEndTurnConverts(bool he)
    {
        var b = Bridge(false, he); var t = Text(he); var c = b.Content;
        using var ui = new UiTestKit();
        using var defence = new DefencePresenter(ui.Root, b, t);
        var before = b.State.Hash();
        // The reserve moves every turn (capital inflow, imports), so the conversion is measured against the turn with no order.
        var fxAfter = Simulation.Step(c, b.TurnStart, System.Array.Empty<Command>()).State.FxReserves - 3;
        var amount = ui.Q<IntegerField>("dollars-amount");
        amount.value = 2; ui.Press("convert-dollars");
        amount.value = 3; ui.Press("convert-dollars");
        Assert.AreEqual(3, ((ConvertDollars)b.Queued.Single()).Amount);
        Assert.AreEqual(before, b.State.Hash());
        Assert.AreEqual(t.Format("dollars.queued", PlayerText.Money(c, "fx_reserves", 3)), ui.Q<Label>("dollars-queued").text);
        ui.Press("withdraw-dollars");
        Assert.IsEmpty(b.Queued);
        ui.Press("convert-dollars");
        b.EndTurn();
        Assert.IsEmpty(b.Queued);
        Assert.AreEqual(3, b.State.DollarsConverted);
        Assert.IsTrue(b.Session.Last!.Why.Any(w => w.Key == CauseKeys.DollarsConverted));
        Assert.AreEqual(t.Format("dollars.total", PlayerText.Money(c, "fx_reserves", 3), PlayerText.Money(c, "fx_reserves", c.RulesAt(b.State.Date).Mvp!.DollarsTotal!.Value)),
            ui.Q<Label>("dollars-total").text);
        Assert.AreEqual(t.Format("dollars.reserves", PlayerText.Money(c, "fx_reserves", b.State.FxReserves)), ui.Q<Label>("dollars-reserves").text);
        Assert.AreEqual(fxAfter, b.State.FxReserves, 1e-9);
        Assert.IsEmpty(ui.Q<Label>("dollars-queued").text);
    }

    // R-MONEY-004: the panel says, before End turn, the reason the sim would refuse the amount (EconomySystem's own check),
    // in the player's language; Convert stays available so the refusal stays explainable.
    [TestCase(false)] [TestCase(true)]
    public void TheSimsRefusalIsShownBeforeEndTurn(bool he)
    {
        var b = Bridge(false, he); var t = Text(he); var c = b.Content;
        using var ui = new UiTestKit();
        using var defence = new DefencePresenter(ui.Root, b, t);
        var amount = ui.Q<IntegerField>("dollars-amount");
        var refusal = ui.Q<Label>("dollars-refusal");
        amount.value = 4;
        Assert.IsEmpty(refusal.text, "$4m in the war is allowed");
        amount.value = 5;
        Assert.AreEqual(t["dollars.refused_monthly"], refusal.text);
        amount.value = 0;
        Assert.AreEqual(t.Format("dollars.refused_minimum", PlayerText.Money(c, "fx_reserves", 1)), refusal.text);
        Assert.IsFalse(ui.Q<Button>("convert-dollars").enabledSelf);
        b.State.DollarsConverted = 98;
        amount.value = 3;
        Assert.AreEqual(t["dollars.refused_total"], refusal.text);
        b.State.DollarsConverted = 0; b.State.FxReserves = 2;
        amount.value = 4; amount.value = 3;
        Assert.AreEqual(t["dollars.refused_reserves"], refusal.text);
        Assert.IsTrue(ui.Q<Button>("convert-dollars").enabledSelf, "a refusal remains explainable");
        ui.Press("convert-dollars");
        Assert.IsEmpty(b.Queued, "an amount the sim refuses is not queued");
        Assert.AreEqual(t["dollars.refused_reserves"], refusal.text, "the refusal stays shown after Convert");
        b.State.GameOver = "finished";
        amount.value = 2;
        Assert.AreEqual(t["order.game_over"], refusal.text);
        Assert.IsFalse(ui.Q<Button>("convert-dollars").enabledSelf);
    }

    // Red-first prediction at ae4bfdaab: Render and Convert inspect reserves 10 before the queued choice spends 8,
    // so the refusal is blank and the conversion is queued even though End turn rejects it for reserves.
    [Test]
    public void AQueuedChoiceThatSpendsReservesRefusesConversionBeforeItIsQueued()
    {
        var b = Bridge(false, false); var t = En; var c = b.Content;
        b.State.Rung = EconomySystem.WarRung;
        b.State.FxReserves = 10;
        b.State.PendingEvents.Clear();
        b.State.PendingEvents.Add("austerity_1949");
        Assert.IsNull(b.Queue(new ChooseEventOption("austerity_1949", "decline")), "the reserve-spending choice is queued first");
        var candidate = new ConvertDollars(4);
        var preview = Simulation.Preview(c, b.TurnStart, b.Session.Committed.Concat(b.Queued).Append(candidate).ToList());
        var rejected = preview.Rejected.Single(x => ReferenceEquals(x.Command, candidate));
        Assert.AreEqual(EconomySystem.RefusedDollarsReserves, rejected.Reason, "precondition: the exact End-turn preview refuses reserves");

        using var ui = new UiTestKit();
        using var defence = new DefencePresenter(ui.Root, b, t);
        var refusal = ui.Q<Label>("dollars-refusal");
        Assert.AreEqual(SimBridge.ReasonText(t, rejected.Reason, c), refusal.text);
        ui.Press("convert-dollars");
        Assert.AreEqual(1, b.Queued.Count);
        Assert.IsInstanceOf<ChooseEventOption>(b.Queued.Single());
        Assert.IsFalse(b.Queued.OfType<ConvertDollars>().Any(), "the refused conversion is not queued");
        Assert.AreEqual(SimBridge.ReasonText(t, rejected.Reason, c), refusal.text, "the preview's refusal stays shown");
    }

    // R-MONEY-004 (owner, 2 November 2026: "Box shows queued order (Recommended)"): with a conversion queued, a new number
    // in the box replaces it at once, so the box, the Money line and what End turn converts agree; the reserve and the total
    // converted keep the turn's start until End turn. An amount the sim refuses clears the queue and shows the refusal.
    [TestCase(false)] [TestCase(true)]
    public void TypingANewAmountReplacesTheQueuedConversion(bool he)
    {
        var b = Bridge(false, he); var t = Text(he); var c = b.Content; var m = c.RulesAt(b.State.Date).Mvp!;
        using var ui = new UiTestKit();
        using var defence = new DefencePresenter(ui.Root, b, t);
        var reserves = ui.Q<Label>("dollars-reserves").text; var total = ui.Q<Label>("dollars-total").text;
        var amount = ui.Q<IntegerField>("dollars-amount");
        amount.value = 4; ui.Press("convert-dollars");
        Assert.AreEqual(4, ((ConvertDollars)b.Queued.Single()).Amount);
        amount.value = 2;
        Assert.AreEqual(2, ((ConvertDollars)b.Queued.Single()).Amount, "the box replaces the queued order");
        Assert.AreEqual(t.Format("dollars.money", PlayerText.Money(c, "treasury", 2 * m.IlPerDollarOn(b.State.Date))), ui.Q<Label>("dollars-money").text);
        Assert.AreEqual(t.Format("dollars.queued", PlayerText.Money(c, "fx_reserves", 2)), ui.Q<Label>("dollars-queued").text);
        Assert.AreEqual(reserves, ui.Q<Label>("dollars-reserves").text, "the reserve keeps the turn's start");
        Assert.AreEqual(total, ui.Q<Label>("dollars-total").text, "the total converted keeps the turn's start");
        amount.value = 5;
        Assert.IsEmpty(b.Queued, "an amount the sim refuses clears the queue");
        Assert.AreEqual(t["dollars.refused_monthly"], ui.Q<Label>("dollars-refusal").text);
        Assert.IsEmpty(ui.Q<Label>("dollars-queued").text);
    }

    // R-MONEY-004 (owner, 2 November 2026: "Grey it with the reason (Recommended)"): outside the war (a rung below 4) the
    // panel stays visible but disabled, with one line saying conversion is for wartime only; in the war it is enabled again.
    [TestCase(false)] [TestCase(true)]
    public void OutsideTheWarThePanelIsGreyedWithTheReason(bool he)
    {
        var b = Bridge(false, he); var t = Text(he);
        using var ui = new UiTestKit();
        using var defence = new DefencePresenter(ui.Root, b, t);
        var panel = ui.Q<VisualElement>("defence-dollars");
        var amount = ui.Q<IntegerField>("dollars-amount");
        b.State.Rung = 3;
        amount.value = 4; amount.value = 3;
        Assert.AreEqual(DisplayStyle.Flex, panel.style.display.value, "the panel stays visible");
        Assert.IsFalse(panel.enabledSelf, "the panel is disabled");
        Assert.IsFalse(ui.Q<Button>("convert-dollars").enabledInHierarchy);
        Assert.AreEqual(t["dollars.wartime_only"], ui.Q<Label>("dollars-refusal").text);
        ui.Press("convert-dollars");
        Assert.IsEmpty(b.Queued);
        b.State.Rung = 4;
        amount.value = 4;
        Assert.IsTrue(panel.enabledSelf);
        Assert.IsEmpty(ui.Q<Label>("dollars-refusal").text);
    }

    // R-MONEY-004: the legacy loop has no conversion.
    [Test]
    public void TheLegacyLoopHidesThePanel()
    {
        var t = En;
        var b = new SimBridge(GameSession.New(SimBridgeGddTests.LoadLegacy(), GoldenRun.Seed, Mode.Historical), t);
        using var ui = new UiTestKit();
        using var defence = new DefencePresenter(ui.Root, b, t);
        Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("defence-dollars").style.display.value);
    }

    // R-MONEY-004: every refusal reaches the end-of-turn toast (SimBridge.ReasonText) as the sim's English, and in Hebrew.
    // The minimum uses the content's money format in both languages; the other Hebrew refusals have no Latin letters.
    [Test]
    public void EveryRefusalHasAStringInBothLanguages()
    {
        var c = Bridge(false, false).Content;
        var refusals = typeof(EconomySystem).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
            .Where(f => f.IsLiteral && f.Name.StartsWith("RefusedDollars")).Select(f => (string)f.GetRawConstantValue()).ToList();
        Assert.AreEqual(5, refusals.Count);
        // The literal text, so a string that still typed "$1m" (Format ignores an unused argument) would fail.
        Assert.AreEqual("Convert at least $1.0m", SimBridge.ReasonText(En, EconomySystem.RefusedDollarsMinimum, c));
        StringAssert.Contains("$1.0m", SimBridge.ReasonText(He, EconomySystem.RefusedDollarsMinimum, c));
        // Without content there is no money format to use, so the sim's own English is shown.
        Assert.AreEqual(EconomySystem.RefusedDollarsMinimum, SimBridge.ReasonText(En, EconomySystem.RefusedDollarsMinimum));
        foreach (var reason in refusals)
        {
            var money = PlayerText.Money(c, "fx_reserves", EconomySystem.DollarsMinimum);   // the constant the sim refuses on (#2704)
            var expected = reason == EconomySystem.RefusedDollarsMinimum ? En.Format("dollars.refused_minimum", money) : reason;
            Assert.AreEqual(expected, SimBridge.ReasonText(En, reason, c), "the English string uses the sim's words and formatted money");
            var he = SimBridge.ReasonText(He, reason, c);
            Assert.AreNotEqual(reason, he, "no Hebrew string for: " + reason);
            StringAssert.IsMatch("[א-ת]", he, reason);
            if (reason == EconomySystem.RefusedDollarsMinimum)
                Assert.AreEqual(He.Format("dollars.refused_minimum", money), he);
            else StringAssert.DoesNotMatch("[A-Za-z]", he, reason);
        }
    }

    // R-MONEY-004: the cause line reads the same as the sim's English, and in Hebrew in the player's language: the dollars
    // first, then the Money they brought, and no Latin letters outside those two figures.
    [Test]
    public void TheCauseLineIsWordedInBothLanguages()
    {
        var b = Bridge(false, false);
        var line = Simulation.Step(b.Content, b.State, new Command[] { new ConvertDollars(4) }).Why.Single(w => w.Key == CauseKeys.DollarsConverted && w.Target == "treasury");
        Assert.AreEqual(line.Message, CauseText.Line(line, b.Content, System.Array.Empty<Statecraft.Game.Map.Units.UnitEntry>(), En));
        var he = CauseText.Line(line, b.Content, System.Array.Empty<Statecraft.Game.Map.Units.UnitEntry>(), He);
        StringAssert.IsMatch("[א-ת]", he);
        var dollars = PlayerText.Money(b.Content, "fx_reserves", 4);
        var money = PlayerText.MoneyChange(b.Content, "treasury", 4 * b.Content.RulesAt(b.State.Date).Mvp!.IlPerDollarOn(b.State.Date));
        Assert.AreEqual(money, PlayerText.MoneyChange(b.Content, "treasury", line.Delta), "the line's Delta is the IL the sim converted");
        int at = he.IndexOf(dollars, System.StringComparison.Ordinal), il = he.IndexOf(money, System.StringComparison.Ordinal);
        Assert.GreaterOrEqual(at, 0, he); Assert.Greater(il, at, he);
        StringAssert.DoesNotMatch("[A-Za-z]", he.Replace(dollars, "").Replace(money, ""), he);
    }

    // #2527: the reserves side of the conversion has its own key, worded as foreign currency, in both languages.
    [Test]
    public void TheReservesLineIsWordedAsForeignCurrencyInBothLanguages()
    {
        var b = Bridge(false, false);
        var line = Simulation.Step(b.Content, b.State, new Command[] { new ConvertDollars(4) }).Why.Single(w => w.Key == CauseKeys.DollarsConvertedFx);
        Assert.AreEqual("fx_reserves", line.Target);
        Assert.AreEqual(line.Message, CauseText.Line(line, b.Content, System.Array.Empty<Statecraft.Game.Map.Units.UnitEntry>(), En));
        var he = CauseText.Line(line, b.Content, System.Array.Empty<Statecraft.Game.Map.Units.UnitEntry>(), He);
        StringAssert.IsMatch("[\u05D0-\u05EA]", he);
        var drop = PlayerText.MoneyChange(b.Content, "fx_reserves", -4);
        StringAssert.Contains(drop, he);
        StringAssert.DoesNotMatch("[A-Za-z]", he.Replace(drop, ""), he);
    }
}