Files
Rail_Enterprise/tests/RailEnterprise.Tests/Economy/EconomyTests.cs
T
Alby96andClaude Opus 5.5 c1a0049bcf
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s
Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*,
variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per
allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos:
CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in
server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly.
Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e
aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 11:14:54 +01:00

219 lines
9.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Economy;
public static class EconomyTests
{
[Test(Description = "Invarianti: la somma di tutti i saldi resta zero, nessun bene nasce dal nulla")]
public static void MoneyAndGoodsInvariantsHold()
{
var w = TestWorlds.Small(101);
for (int month = 0; month < 18; month++)
{
w.RunDays(30);
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro al mese {month}");
for (int g = 0; g < w.Data.GoodCount; g++)
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} al mese {month}");
}
Assert.True(w.Goods.Produced.Sum() > 0, "qualcosa è stato prodotto");
}
[Test(Description = "I prezzi globali restano sempre entro 0,3·Pb e 3·Pb")]
public static void PricesStayWithinLimits()
{
var w = TestWorlds.Small(102, "ferro_e_sangue");
var m = w.Data.Balance.Market;
for (int day = 0; day < 3 * 360; day++)
{
w.RunDays(1);
for (int g = 0; g < w.Data.GoodCount; g++)
{
double pb = w.Data.Goods[g].BasePrice;
Assert.InRange(w.Market.GlobalPrice[g], m.MinPriceFactor * pb - 1e-6, m.MaxPriceFactor * pb + 1e-6);
}
}
}
[Test]
public static void PriceRisesWhenDemandExceedsSupply()
{
var w = TestWorlds.Small(103);
int food = w.Data.GoodIndex("food");
double before = w.Market.GlobalPrice[food];
// nessuna produzione di alimentari raggiunge il mercato: la domanda cittadina spinge il prezzo
w.RunDays(120);
Assert.True(w.Market.GlobalPrice[food] > before * 1.5, $"prezzo alimentari {before} → {w.Market.GlobalPrice[food]}");
}
[Test]
public static void LocalPriceFollowsImbalanceWithinBounds()
{
var lp = TestData.Data.Balance.LocalPrice;
Assert.Approx(100.0, Market.LocalPrice(100, 10, 10, lp), 1e-9);
Assert.True(Market.LocalPrice(100, 50, 0, lp) > 130);
Assert.True(Market.LocalPrice(100, 0, 50, lp) < 70);
Assert.InRange(Market.LocalPrice(100, 1e9, 0, lp), 60, 140);
Assert.InRange(Market.LocalPrice(100, 0, 1e9, lp), 60, 140);
}
[Test]
public static void FreightAndPassengerTariffsFollowFormulas()
{
var t = TestData.Data.Balance.Tariffs;
// a prezzo base: 40 t × tariffa base × 1 × 20^0,9 centesimi
var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0);
Assert.Equal(Money.FromCentsRounded(40 * t.FreightBaseRate * DMath.Pow(20, 0.9)), freight);
// consegna con il doppio del tempo atteso: oltre la soglia del 50 % la tariffa cala
var late = Tariffs.Freight(40, 20, 3800, 3800, 2, 1, t, 1.0);
Assert.True(late < freight && late.Cents >= freight.Cents / 2);
var staff = Tariffs.Passenger(10, 15, PaxClass.Staff, 1, 1, t, 1.0);
var worker = Tariffs.Passenger(10, 15, PaxClass.Worker, 1, 1, t, 1.0);
Assert.Approx(3.0, (double)staff.Cents / worker.Cents, 0.01, "classe personale ×3");
}
[Test(Description = "Solo le industrie servite crescono; con punteggio alto salgono di livello dopo due trimestri")]
public static void ServedIndustryWithGoodScoreUpgrades()
{
var w = TestWorlds.Small(104);
var mine = w.Industries.First(i => i.Def.Kind == IndustryKind.Primary && i.Level == 1 && !i.Closed);
var other = w.Industries.First(i => i != mine && i.Def.Kind == IndustryKind.Primary && !i.Closed);
int otherLevel = other.Level;
for (int q = 0; q < 2; q++)
{
for (int d = 0; d < 90; d++)
{
// tutta la produzione viene spedita e i posti sono coperti
mine.WorkersPresent = mine.JobsWorkers;
mine.StaffPresent = mine.JobsStaff;
mine.CovWorkers = 1;
mine.CovStaff = 1;
mine.RevenueEma = 1_000_000;
mine.CostEma = 100_000;
mine.QuarterShipped = mine.QuarterProduced;
mine.LastServedDay = w.Clock.Day; // servita da un vettore simulato
w.RunDays(1);
}
}
w.RunTicks(1); // il secondo trimestre si chiude nel primo tick del giorno 180
Assert.Equal(2, mine.Level, "livello dopo due trimestri ottimi");
Assert.Equal(otherLevel, other.Level, "un'industria non servita non cambia livello");
}
[Test(Description = "Un'industria servita ma abbandonata scende fino a 0 e chiude dopo quattro trimestri a zero")]
public static void NeglectedServedIndustryDeclinesAndCloses()
{
var w = TestWorlds.Small(105);
var ind = w.Industries.First(i => i.Def.Kind == IndustryKind.Processing && !i.Closed);
int startLevel = ind.Level;
for (int d = 0; d < 90 * (startLevel + 5) + 1; d++)
{
ind.LastServedDay = w.Clock.Day; // servita ma senza consegne né spedizioni
w.RunDays(1);
}
Assert.True(ind.Closed, $"chiusa (livello iniziale {startLevel}, ultimo punteggio {ind.LastScore:F2})");
Assert.True(w.Events.Recent.Any(e => e.Text.Contains(ind.Name, StringComparison.Ordinal) && e.Text.Contains("chiude", StringComparison.Ordinal)));
}
[Test]
public static void TownsGrowWithSatisfactionAndShrinkWithout()
{
var w = TestWorlds.Small(106);
var served = w.Towns[0];
var neglected = w.Towns[1];
int s0 = served.Population, n0 = neglected.Population;
for (int d = 0; d < 360; d++)
{
for (int g = 0; g < w.Data.GoodCount; g++)
{
int need = (int)Math.Ceiling(served.DemandToday[g]) + 1;
if (served.DemandToday[g] > 0 && served.Stock[g] < need)
{
int add = need - served.Stock[g];
served.Stock[g] += add;
w.Goods.Produced[g] += add; // consegna simulata, contabilizzata
}
}
w.RunDays(1);
}
Assert.True(served.OverallSatisfaction > 0.9, $"soddisfazione {served.OverallSatisfaction:F2}");
Assert.True(served.Population > s0, $"la città servita cresce: {s0} → {served.Population}");
Assert.True(neglected.Population < n0, $"la città trascurata cala: {n0} → {neglected.Population}");
Assert.True(served.Services >= 2);
}
[Test]
public static void LoansRespectCreditAndAccrueInterest()
{
var w = TestWorlds.Small(107);
var player = w.Player;
var credit = FinanceSystem.MaxLoan(w, player);
Assert.Equal(new Money(w.Difficulty.InitialCredit), credit);
var cash0 = player.Cash;
w.Enqueue(new TakeLoanCommand(credit + Money.FromLire(1)) { Issuer = player.Id, Seq = 1 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(100_000)) { Issuer = player.Id, Seq = 2 });
w.RunTicks(1);
var results = w.DrainResults();
Assert.Equal(CommandError.CreditLimit, results[0].Error);
Assert.True(results[1].Ok, results[1].Message);
Assert.Equal(cash0 + Money.FromLire(100_000), player.Cash);
Assert.Equal(Money.FromLire(100_000), player.Debt);
w.RunDays(31);
Assert.True(player.Debt < Money.FromLire(100_000), "la rata riduce il debito");
Assert.True(player.YearEntries[(int)LedgerEntry.Interest] < 0, "interessi pagati");
Assert.Equal(0L, w.MoneyBalanceSum());
var loanId = player.Loans[0].Id;
w.Enqueue(new RepayLoanCommand(loanId, player.Debt) { Issuer = player.Id, Seq = 3 });
w.RunTicks(1);
Assert.True(w.DrainResults()[0].Ok);
Assert.Equal(Money.Zero, player.Debt);
}
[Test]
public static void UnimplementedCommandsAreRejectedWithoutSideEffects()
{
var w = TestWorlds.Small(108);
ulong before = RailEnterprise.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new BuyConcessionCommand(new RegionId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
w.Pipeline.Get<CommandSystem>().Step(w.Context);
var results = w.DrainResults();
Assert.Equal(CommandError.NotImplemented, results[0].Error);
Assert.Equal(CommandError.UnknownCompany, results[1].Error);
Assert.Equal(before, RailEnterprise.Core.Persistence.StateHasher.Compute(w));
}
[Test]
public static void WalkingWorkersStaffIndustriesNextToTowns()
{
var w = TestWorlds.Small(109);
w.RunDays(40);
var manufacturing = w.Industries.Where(i => i.Def.Kind == IndustryKind.Manufacturing && !i.Closed).ToList();
Assert.True(manufacturing.Count > 0);
Assert.True(manufacturing.Any(i => i.CovWorkers > 0.9), "almeno una manifattura con lavoratori a piedi dalla città vicina");
Assert.True(w.Commutes.All(c => c.Walking));
foreach (var town in w.Towns)
Assert.True(town.EmployedWorkers <= town.Workforce(w.Data.Balance.Town), $"{town.Name}: occupati oltre la forza lavoro");
}
[Test]
public static void DifficultyChangesStartingConditions()
{
var easy = TestWorlds.Small(110, "apprendista");
var hard = TestWorlds.Small(110, "ferro_e_sangue");
Assert.Equal(Money.FromLire(500_000), easy.Player.Cash);
Assert.Equal(Money.FromLire(100_000), hard.Player.Cash);
Assert.Equal(1 + 1, easy.Companies.Count);
Assert.Equal(1 + 5, hard.Companies.Count);
Assert.Equal(easy.Terrain.ComputeHash(), hard.Terrain.ComputeHash(), "la difficoltà non cambia la mappa");
}
}