Files
Rail_Enterprise/tests/ViaFerrea.Tests/Economy/EconomyTests.cs
T
Claude 5a318e6528 F3: protocollo binario completo, server con WebSocket e immagine Docker
- Protocol: SpanWriter/SpanReader, frame [u32][u16][payload], tutti i messaggi
  dei due versi con byte di estensione, codec di tutti i 38 comandi, test di
  round-trip, troncamento e corruzione.
- Comandi delle fasi successive con formato definitivo (NotImplemented).
- ClientWorld e ProtocolClient condivisi da client Godot e test: copia del
  terreno a chunk, entità, rete con gli stessi id, moto dei treni.
- TrackPreview estratto dai comandi: anteprima del client e piano del server
  con lo stesso codice; stazioni e depositi demoliti esclusi dagli agganci.
- Server: GameLoop con accumulatore e velocità effettiva, sessioni con coda
  a due classi e ripresa, delta per hash, TrackWorks a lotti, moto dei treni
  nel viewport, resoconti giornalieri, /health, /metrics, /api/saves,
  autosave a rotazione, log JSON, --local e --healthcheck.
- Docker: Dockerfile, compose, modello Unraid; build senza rete.
- viaferrea-tools smoke: collaudo end-to-end contro un server in esecuzione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
2026-10-02 00:14:13 +00:00

219 lines
9.7 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 ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.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 × 150 × 1 × 20^0,9 centesimi
var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0);
Assert.Equal(Money.FromCentsRounded(40 * 150 * 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 = ViaFerrea.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new OverhaulIndustryCommand(new IndustryId(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, ViaFerrea.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");
}
}