Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-07 11:14:54 +01:00
1 parent f6c2a17b4d
commit c1a0049bcf
300 files changed
+1602 -1045

No files matched your search

@@ -0,0 +1,98 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Basics;
public static class CommonTests
{
[Test]
public static void MoneyFormatsItalian()
{
Assert.Equal("₤ 1.284.500", Money.FromLire(1_284_500).ToString());
Assert.Equal("₤ 1.284.500,25", Money.FromLire(1_284_500.25m).ToString("it2"));
Assert.Equal("₤ 3,91 mln", Money.FromLire(3_910_000).ToString("short"));
Assert.Equal("₤ 48.200", Money.FromLire(48_200).ToString("short"));
Assert.Equal("−₤ 19.700", Money.FromLire(-19_700).ToString());
Assert.Equal("₤ 0", Money.Zero.ToString());
Assert.Equal("₤ 999", Money.FromLire(999).ToString());
}
[Test]
public static void MoneyArithmeticIsExact()
{
var a = Money.FromLire(10.10m);
var b = Money.FromLire(0.20m);
Assert.Equal(1030L, (a + b).Cents);
Assert.Equal(990L, (a - b).Cents);
Assert.Equal(3030L, (a * 3).Cents);
Assert.Equal(1515L, (a * 1.5).Cents);
Assert.True(a > b);
Assert.Throws<OverflowException>(() => _ = new Money(long.MaxValue) + new Money(1));
}
[Test]
public static void XxHash64MatchesReferenceVectors()
{
Assert.Equal(0xef46db3751d8e999UL, XxHash64.Hash([]));
Assert.Equal(0xd24ec4f1a98c6e5bUL, XxHash64.Hash("a"u8));
Assert.Equal(0x44bc2cf5ad770999UL, XxHash64.Hash("abc"u8));
Assert.Equal(0x81cf4b9562ee9c31UL, XxHash64.Hash("Rail Enterprise"u8));
Assert.Equal(0x95584af7701f808dUL, XxHash64.Hash([], 12345));
var hundred = new byte[100];
for (int i = 0; i < hundred.Length; i++) hundred[i] = (byte)i;
Assert.Equal(0x6ac1e58032166597UL, XxHash64.Hash(hundred));
Assert.Equal(0x28ba1ae2de4de27UL, XxHash64.Hash(hundred, 12345));
}
[Test(Description = "DMath coincide con Math entro 1e-14 relativi su argomenti casuali")]
public static void DMathMatchesMathClosely()
{
var rng = new Rng(2024);
for (int i = 0; i < 20_000; i++)
{
double x = rng.NextDouble(-50, 50);
Check(Math.Exp(x), DMath.Exp(x), "exp", x);
double p = rng.NextDouble(1e-6, 1e6);
Check(Math.Log(p), DMath.Log(p), "log", p);
double a = rng.NextDouble(-1000, 1000);
CheckAbs(Math.Sin(a), DMath.Sin(a), "sin", a);
CheckAbs(Math.Cos(a), DMath.Cos(a), "cos", a);
double t = rng.NextDouble(-100, 100);
Check(Math.Atan(t), DMath.Atan(t), "atan", t);
double y = rng.NextDouble(-5, 5), xx = rng.NextDouble(-5, 5);
CheckAbs(Math.Atan2(y, xx), DMath.Atan2(y, xx), "atan2", y);
double b = rng.NextDouble(0.01, 300), e = rng.NextDouble(-3, 3);
Check(Math.Pow(b, e), DMath.Pow(b, e), "pow", b);
}
Assert.Equal(1.0, DMath.Exp(0));
Assert.Equal(0.0, DMath.Log(1));
Assert.Equal(8.0, DMath.Pow(2, 3));
Assert.Equal(0.125, DMath.Pow(2, -3));
Assert.True(double.IsNaN(DMath.Log(-1)));
Assert.Equal(double.PositiveInfinity, DMath.Exp(1000));
Assert.Equal(0.0, DMath.Exp(-1000));
Assert.Approx(Math.Exp(-740), DMath.Exp(-740), 1e-320);
Assert.Approx(Math.Log(5e-310), DMath.Log(5e-310), 1e-12);
}
private static void Check(double expected, double actual, string fn, double arg)
{
double tol = Math.Max(1e-300, Math.Abs(expected) * 2e-14);
Assert.Approx(expected, actual, tol, $"{fn}({arg:R})");
}
private static void CheckAbs(double expected, double actual, string fn, double arg)
{
Assert.Approx(expected, actual, 1e-13, $"{fn}({arg:R})");
}
[Test]
public static void TypedIdsAreDistinctAndOrdered()
{
var a = new StationId(3);
var b = new StationId(5);
Assert.True(a.CompareTo(b) < 0);
Assert.False(StationId.None.IsValid);
Assert.Equal("Station#3", a.ToString());
}
}
@@ -0,0 +1,66 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Basics;
public static class RngTests
{
[Test(Description = "Vettore di riferimento di xoshiro256** con stato {1,2,3,4}")]
public static void Xoshiro256StarStarMatchesReferenceVector()
{
var rng = Rng.FromState(1, 2, 3, 4);
Assert.Equal(11520UL, rng.NextU64());
Assert.Equal(0UL, rng.NextU64());
Assert.Equal(1509978240UL, rng.NextU64());
Assert.Equal(1215971899390074240UL, rng.NextU64());
}
[Test]
public static void SameSeedGivesSameSequence()
{
var a = new Rng(42);
var b = new Rng(42);
for (int i = 0; i < 1000; i++) Assert.Equal(a.NextU64(), b.NextU64());
}
[Test]
public static void ForkIsStableAndDoesNotConsumeParent()
{
var root = new Rng(7);
var before = root.State;
var f1 = root.Fork("industries");
var f2 = root.Fork("industries");
var f3 = root.Fork("towns");
Assert.Equal(before, root.State);
Assert.Equal(f1.NextU64(), f2.NextU64());
Assert.NotEqual(new Rng(7).Fork("industries").NextU64(), f3.NextU64());
}
[Test]
public static void NextIntIsInRangeAndRoughlyUniform()
{
var rng = new Rng(123);
var counts = new int[10];
for (int i = 0; i < 100_000; i++)
{
int v = rng.NextInt(10);
Assert.True(v is >= 0 and < 10);
counts[v]++;
}
foreach (int c in counts) Assert.InRange(c, 9_500, 10_500);
}
[Test]
public static void NextDoubleIsInUnitInterval()
{
var rng = new Rng(99);
double sum = 0;
for (int i = 0; i < 100_000; i++)
{
double d = rng.NextDouble();
Assert.True(d >= 0 && d < 1);
sum += d;
}
Assert.Approx(0.5, sum / 100_000, 0.01);
}
}
@@ -0,0 +1,46 @@
using RailEnterprise.Core.Time;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Basics;
public static class TimeTests
{
private static Calendar Cal() => new(TestData.Data.Balance.Time, 1850);
[Test]
public static void CalendarConstantsMatchGuide()
{
var c = Cal();
Assert.Equal(240, c.TicksPerDay);
Assert.Equal(360, c.DaysPerYear);
Assert.Approx(3.0, c.TrainSecondsPerTick, 1e-12, "un tick = 3 s di orologio dei treni");
Assert.Approx(2.5, c.TrainMinutesToDays(30), 1e-12, "30 minuti di orologio = 2,5 giorni");
}
[Test]
public static void DatesRoundTripAndFormatInItalian()
{
var c = Cal();
var d = c.DateOfDay(22 * 360 + 2 * 30 + 13);
Assert.Equal(new GameDate(1872, 3, 14), d);
Assert.Equal("14 marzo 1872", d.ToString());
Assert.Equal(22L * 360 + 2 * 30 + 13, c.DayOf(d));
}
[Test]
public static void ClockFlagsFireAtBoundaries()
{
var clock = new GameClock(Cal());
Assert.True(clock.IsNewDay && clock.IsNewMonth && clock.IsNewYear);
clock.Advance();
Assert.False(clock.IsNewDay);
clock.Restore(240L * 30);
Assert.True(clock.IsNewMonth);
Assert.False(clock.IsNewQuarter);
clock.Restore(240L * 90);
Assert.True(clock.IsNewQuarter);
clock.Restore(240L * 360);
Assert.True(clock.IsNewYear);
Assert.Equal(1851, clock.Year);
}
}
@@ -0,0 +1,148 @@
using System.Text.Json.Nodes;
using RailEnterprise.Core.Data;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Data;
public static class DataTests
{
[Test(Description = "I file dati reali superano schema e validazione semantica, con le quantità minime richieste")]
public static void RealDataLoadsWithMinimumCounts()
{
var d = TestData.Data;
Assert.True(d.Goods.Count >= 12, "almeno 12 beni");
Assert.True(d.Industries.Count >= 14, "almeno 14 industrie");
Assert.True(d.Vehicles.Count >= 8, "almeno 8 veicoli");
Assert.True(d.Eras.Eras.Count >= 4, "almeno 4 ere");
Assert.Equal(5, d.Tiers.Tiers.Count);
Assert.True(d.Difficulty.Presets.Count >= 4, "almeno 4 difficoltà");
Assert.Equal("spare_parts", d.Goods[d.SparePartsGood].Id);
Assert.Equal("machinery", d.Goods[d.MachineryGood].Id);
Assert.NotEqual(0UL, d.Hash);
}
[Test]
public static void ReferencesAreResolvedToIndices()
{
var d = TestData.Data;
var steel = d.Industry("steel_mill");
Assert.Equal(d.GoodIndex("iron_ore"), steel.Recipe.Inputs[0].GoodIndex);
Assert.Equal(d.GoodIndex("steel"), steel.Recipe.Outputs[0].GoodIndex);
Assert.Equal(Traction.Steam, d.Vehicle("loco_steam_1850").Traction);
Assert.True(d.Vehicle("wagon_hopper").GoodIndices.Contains(d.GoodIndex("coal")));
Assert.Equal(120, steel.Capacity(1));
Assert.Equal(900, steel.Capacity(5));
}
[Test]
public static void DifficultyPresetsMatchGuideTable()
{
var d = TestData.Data;
var a = d.DifficultyPreset("apprendista");
var f = d.DifficultyPreset("ferro_e_sangue");
Assert.Equal(50_000_000L, a.InitialCapital);
Assert.Equal(180, a.BankruptcyDays);
Assert.Equal(TakeoverRule.Disabled, a.PlayerTakeover);
Assert.Equal(5, f.AiCompetitors);
Assert.True(f.PublicFromStart);
Assert.Approx(0.6, f.PlayerShareAtStart, 1e-12);
Assert.Equal(IronmanRule.Yes, f.Ironman);
}
[Test]
public static void HashIgnoresFormatting()
{
var files = MemoryDataSource.Snapshot(TestData.Source);
var node = JsonNode.Parse(files["goods.json"])!;
files["goods.json"] = node.ToJsonString(new System.Text.Json.JsonSerializerOptions { WriteIndented = false });
var reformatted = GameData.Load(new MemoryDataSource(files));
Assert.Equal(TestData.Data.Hash, reformatted.Hash);
}
[Test]
public static void HashChangesWithContent()
{
var files = MemoryDataSource.Snapshot(TestData.Source);
files["goods.json"] = files["goods.json"].Replace("\"basePrice\": 3800", "\"basePrice\": 3900", StringComparison.Ordinal);
Assert.NotEqual(TestData.Data.Hash, GameData.Load(new MemoryDataSource(files)).Hash);
}
[Test]
public static void SchemaRejectsUnknownAndMissingProperties()
{
var errors = LoadErrors(files =>
{
var root = JsonNode.Parse(files["goods.json"])!;
root["goods"]![0]!["colour"] = "black";
root["goods"]![1]!.AsObject().Remove("basePrice");
files["goods.json"] = root.ToJsonString();
});
Assert.True(errors.Any(e => e.Contains("colour", StringComparison.Ordinal)), "proprietà sconosciuta segnalata");
Assert.True(errors.Any(e => e.Contains("basePrice", StringComparison.Ordinal)), "proprietà mancante segnalata");
}
[Test]
public static void SchemaRejectsOutOfRangeAndBadEnum()
{
var errors = LoadErrors(files =>
{
var root = JsonNode.Parse(files["industries.json"])!;
root["industries"]![0]!["kind"] = "magical";
root["industries"]![0]!["capacityPerLevel"] = new JsonArray(1, 2, 3);
files["industries.json"] = root.ToJsonString();
});
Assert.True(errors.Any(e => e.Contains("non tra quelli ammessi", StringComparison.Ordinal)));
Assert.True(errors.Any(e => e.Contains("almeno 5 elementi", StringComparison.Ordinal)));
}
[Test]
public static void SemanticRejectsUnknownReferenceAndDuplicates()
{
var errors = LoadErrors(files =>
{
var root = JsonNode.Parse(files["industries.json"])!;
root["industries"]![7]!["recipe"]!["inputs"]![0]!["good"] = "unobtanium";
root["industries"]![1]!["id"] = "coal_mine";
files["industries.json"] = root.ToJsonString();
});
Assert.True(errors.Any(e => e.Contains("unobtanium", StringComparison.Ordinal)));
Assert.True(errors.Any(e => e.Contains("duplicato «coal_mine»", StringComparison.Ordinal)));
}
[Test(Description = "Un refuso in balance.json (sezione con schema aperto) è comunque bloccato dal deserializzatore")]
public static void TypoInBalanceIsRejected()
{
var errors = LoadErrors(files =>
{
files["balance.json"] = files["balance.json"].Replace("\"wagePerWorkerPerMonth\"", "\"wagePerWorkerPerMoth\"", StringComparison.Ordinal);
});
Assert.True(errors.Count > 0);
Assert.True(errors.Any(e => e.Contains("balance.json", StringComparison.Ordinal)));
}
[Test]
public static void SemanticRejectsBrokenFailureShares()
{
var errors = LoadErrors(files =>
{
files["maintenance.json"] = files["maintenance.json"].Replace("\"minorShare\": 0.70", "\"minorShare\": 0.60", StringComparison.Ordinal);
});
Assert.True(errors.Any(e => e.Contains("failure.*Share", StringComparison.Ordinal)));
}
private static IReadOnlyList<string> LoadErrors(Action<Dictionary<string, string>> mutate)
{
var files = MemoryDataSource.Snapshot(TestData.Source);
mutate(files);
try
{
GameData.Load(new MemoryDataSource(files));
}
catch (DataValidationException ex)
{
return ex.Errors;
}
Assert.Fail("i dati alterati dovevano essere rifiutati");
return [];
}
}
@@ -0,0 +1,87 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Ai;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Economy;
/// <summary>Concorrenti IA (guida 12.1, test di 14.5): comandi validi, crescita, determinismo.</summary>
public static class AiTests
{
[Test(Slow = true, Description = "Le IA agiscono solo con i comandi e ne vedono rifiutati al massimo il 5 %")]
public static void AiCommandsAreRarelyRejected()
{
var w = TestWorlds.Small(42);
w.RunYears(5);
Assert.True(w.AiStates.Count >= 2, "uno stato per ogni IA");
long issued = 0;
foreach (var s in w.AiStates)
{
issued += s.Issued;
Assert.True(s.RejectedShare <= w.Data.Ai.Planning.MaxRejectedShare,
$"{w.Company(s.Company).Name}: {s.Rejected} rifiutati su {s.Issued}");
}
Assert.True(issued > 20, $"le IA costruiscono e gestiscono la rete ({issued} comandi)");
Assert.True(w.AiStates.Any(s => s.Projects.Any(p => p.Stage == AiProjectStage.Running)), "almeno una linea in esercizio");
// i binari, i treni e le stazioni delle IA esistono davvero nel mondo
foreach (var s in w.AiStates)
{
foreach (var p in s.Projects.Where(p => p.Stage == AiProjectStage.Running))
{
Assert.True(w.Network.IsAlive(w.Network.Stations[p.StationA.Value]) || w.Company(s.Company).Defunct);
Assert.True(p.Trains.All(t => w.Trains[t.Value].Owner == s.Company || w.Company(s.Company).Merged));
}
}
}
[Test(Slow = true, Description = "Un'IA con capitale ×2 supera il giocatore passivo in 10 anni")]
public static void AiWithDoubleCapitalBeatsAPassivePlayer()
{
var w = TestWorlds.Small(42, "imprenditore", ("aiCapitalMultiplier", 2));
w.RunYears(10);
var player = w.Player;
var best = w.Companies.Where(c => !c.IsPlayer).MaxBy(c => c.NetWorth.Cents)!;
Assert.True(best.NetWorth > player.NetWorth, $"{best.Name}: {best.NetWorth} contro {player.NetWorth}");
Assert.True(best.NetWorth.Cents > w.Difficulty.InitialCapital * 2, $"{best.Name} ha fatto crescere il capitale: {best.NetWorth}");
}
[Test(Slow = true, Description = "Determinismo con le IA: stesso seme e stessi comandi, stesso hash dopo 5 anni (anche passando da un salvataggio)")]
public static void SameSeedWithAiGivesSameHash()
{
static World Make()
{
var w = TestWorlds.Small(77, "magnate");
w.Enqueue(new TakeLoanCommand(Money.FromLire(50_000)) { Issuer = w.Player.Id, Seq = 1 });
return w;
}
var a = Make();
var b = Make();
a.RunYears(2);
b.RunYears(2);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
var c = SaveFile.Load(TestData.Data, SaveFile.Save(b, "test"));
a.RunYears(3);
c.RunYears(3);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(c));
Assert.True(a.AiStates.Sum(s => s.Issued) > 0, "le IA hanno agito");
}
[Test(Slow = true, Description = "Accettazione F5: in «Magnate», con il giocatore passivo, almeno un'IA raggiunge il livello 3 in 15 anni")]
public static void OnMagnateAnAiReachesTierThreeIn15Years()
{
var w = WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = 7, SizeKm = 128, DifficultyId = "magnate" });
int best = 1;
for (int y = 0; y < 15 && best < 3; y++)
{
w.RunYears(1);
best = w.Companies.Where(c => !c.IsPlayer).Max(c => c.Tier);
}
var leader = w.Companies.Where(c => !c.IsPlayer).MaxBy(c => (c.Tier, c.NetWorth.Cents))!;
Console.WriteLine($" {leader.Name}: livello {leader.Tier} nel {w.Clock.Year}, patrimonio {leader.NetWorth}, rating {leader.Rating}, " +
$"città collegate {Core.Simulation.Systems.Tiers.ConnectedTowns(w, leader.Id, 1000)}");
Assert.True(best >= 3, $"livello massimo delle IA: {best}");
Assert.Equal(1, w.Player.Tier, "il giocatore passivo resta al livello 1");
}
}
@@ -0,0 +1,218 @@
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");
}
}
@@ -0,0 +1,206 @@
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;
/// <summary>Manutenzione degli impianti (guida, sezione 11) e industrie possedute dal giocatore.</summary>
public static class IndustryMaintenanceTests
{
private static Industry Pick(World w, IndustryKind kind) =>
w.Industries.First(i => !i.Closed && i.Level > 0 && i.Def.Kind == kind);
private static CommandResult Do(World w, GameCommand c)
{
w.Enqueue(c with { Issuer = w.Player.Id });
w.RunTicks(1);
return w.DrainResults().Last();
}
[Test]
public static void EfficiencyMultiplierFollowsTheGuide()
{
var m = TestData.Data.Balance.IndustryMaintenance;
Assert.Approx(1.0, IndustryMath.ConditionMultiplier(100, m), 1e-9);
Assert.Approx(1.0, IndustryMath.ConditionMultiplier(70, m), 1e-9);
Assert.Approx(0.75, IndustryMath.ConditionMultiplier(45, m), 1e-9);
Assert.Approx(0.5, IndustryMath.ConditionMultiplier(20, m), 1e-9);
Assert.Approx(0.3, IndustryMath.ConditionMultiplier(10, m), 1e-9);
}
[Test(Description = "Usura con l'utilizzo; il budget Alto recupera; senza ricambi il recupero si dimezza")]
public static void WearFollowsUseAndBudgetRecovers()
{
var w = TestWorlds.NoAi(301);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Primary);
w.RunDays(5);
// senza manutenzione la condizione scende con l'utilizzo
ind.Budget = IndustryBudget.None;
ind.Condition = 80;
w.RunDays(60);
double dropped = 80 - ind.Condition;
Assert.True(dropped > 0, $"usura senza budget: {dropped:F3}");
Assert.True(dropped <= m.WearPerDay * 1.2 * ind.Def.WearIntensity * w.Difficulty.WearMultiplier * 60 + 1e-6, "usura entro il massimo della formula");
// budget alto con ricambi: il recupero (0,12 al giorno) supera l'usura; senza ricambi si dimezza.
// Due finestre di 10 giorni nello stesso mese (il consumo mensile ricalcola la mancanza di ricambi).
int dpm = w.Calendar.DaysPerMonth;
w.RunDays(dpm - (int)(w.Clock.Day % dpm) + 1);
ind.Budget = IndustryBudget.High;
ind.Condition = 60;
ind.PartsShort = false;
w.RunDays(10);
double withParts = ind.Condition - 60;
Assert.True(withParts > 0, $"recupero con budget alto: {withParts:F3}");
ind.Condition = 60;
ind.PartsShort = true;
w.RunDays(10);
double withoutParts = ind.Condition - 60;
var budget = m.For(IndustryBudget.High);
Assert.Approx(budget.RecoveryPerDay * (1 - m.NoPartsRecoveryFactor) * 10, withParts - withoutParts, 0.05,
$"senza ricambi il recupero si dimezza: {withoutParts:F3} contro {withParts:F3}");
Assert.Equal(0L, w.MoneyBalanceSum());
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"bene {w.Data.Goods[g].Id}");
}
[Test(Description = "Sotto 40 arrivano i fermi: niente produzione, storico, città colpita; sotto 10 l'incidente grave")]
public static void LowConditionBringsStopsAndAccidents()
{
var w = TestWorlds.NoAi(302);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Processing);
ind.Budget = IndustryBudget.None;
ind.Condition = 5;
bool stopped = false;
for (int d = 0; d < 720 && !stopped; d++)
{
ind.Condition = 5;
w.RunDays(1);
stopped = ind.IsStopped(w.Clock.Day);
}
Assert.True(stopped, "con condizione 5 un fermo arriva");
Assert.Equal(IndustryStop.Accident, ind.StopKind, "un'industria di trasformazione sotto 10 ha un incidente grave");
Assert.Equal(m.AccidentDays, ind.StopHistory[^1].Days);
w.RunDays(2);
Assert.Equal(0, ind.ProducedToday.Sum(), "nessuna produzione durante il fermo");
Assert.Approx(0.0, ind.Efficiency, 1e-9);
// un'industria primaria a 25 ha solo fermi per guasto da 5 a 20 giorni
var mine = Pick(w, IndustryKind.Primary);
mine.Budget = IndustryBudget.None;
bool broke = false;
for (int d = 0; d < 2000 && !broke; d++)
{
mine.Condition = 25;
w.RunDays(1);
broke = mine.IsStopped(w.Clock.Day);
}
Assert.True(broke, "a 25 il rischio giornaliero produce un fermo");
Assert.Equal(IndustryStop.Breakdown, mine.StopKind);
Assert.InRange(mine.StopHistory[^1].Days, m.BreakdownDays[0], m.BreakdownDays[1]);
// il rischio cresce al calare della condizione
Assert.True(m.BreakdownBase * DMath.Exp((m.BreakdownPivot - 10) / m.BreakdownScale) > m.BreakdownBase * DMath.Exp((m.BreakdownPivot - 30) / m.BreakdownScale));
}
[Test(Description = "Acquisto (livello 3, offerta ≥ valore), revisione che aspetta i macchinari e riporta la condizione a 100, ammodernamento di livello")]
public static void OwnedIndustryOverhaulAndUpgrade()
{
var w = TestWorlds.NoAi(303);
var m = w.Data.Balance.IndustryMaintenance;
var player = w.Player;
w.Money.Transfer(Account.External, Account.Of(player.Id), Money.FromLire(10_000_000), LedgerEntry.Other);
var ind = Pick(w, IndustryKind.Processing);
w.RunDays(3);
var locked = Do(w, new BuyIndustryCommand(ind.Id, Money.FromLire(9_000_000)));
Assert.Equal(CommandError.TierLocked, locked.Error, "l'acquisto si sblocca al livello 3");
player.Tier = 3;
var price = IndustryMath.Valuation(w, ind);
var low = Do(w, new BuyIndustryCommand(ind.Id, price - Money.FromLire(1)));
Assert.Equal(CommandError.InvalidArgument, low.Error, "offerta sotto il valore");
price = IndustryMath.Valuation(w, ind);
var cash = player.Cash;
var ok = Do(w, new BuyIndustryCommand(ind.Id, price + Money.FromLire(100)));
Assert.True(ok.Ok, ok.Message);
Assert.Equal(player.Id, ind.Owner);
Assert.True(player.Cash < cash, "l'acquisto si paga");
// revisione: aspetta i macchinari (e il personale), poi 30 giorni di fermo e condizione 100
ind.Condition = 30;
Assert.True(Do(w, new OverhaulIndustryCommand(ind.Id)).Ok);
Assert.Equal(IndustryWork.Overhaul, ind.PendingWork);
w.RunDays(5);
Assert.False(ind.IsStopped(w.Clock.Day), "senza macchinari la revisione non parte");
int need = IndustryMath.MachineryRequired(ind, m);
ind.Machinery += need;
w.Goods.Produced[w.Data.MachineryGood] += need;
ind.CovStaff = 1;
w.RunDays(2);
Assert.True(ind.IsStopped(w.Clock.Day), "con macchinari e personale la revisione parte");
Assert.Equal(IndustryStop.Overhaul, ind.StopKind);
w.RunDays(m.OverhaulDays + 1);
Assert.False(ind.IsStopped(w.Clock.Day));
Assert.True(ind.Condition > 99, $"condizione dopo la revisione: {ind.Condition:F1}");
// ammodernamento: costo in capitale e macchinari, 60 giorni, livello + 1
int level = ind.Level;
if (level < w.Data.Balance.Growth.MaxLevel)
{
Assert.True(Do(w, new UpgradeIndustryCommand(ind.Id)).Ok);
int machinery = IndustryMath.MachineryRequired(ind, m);
ind.Machinery += machinery;
w.Goods.Produced[w.Data.MachineryGood] += machinery;
var before = player.Cash;
w.RunDays(2);
Assert.Equal(IndustryStop.Upgrade, ind.StopKind);
Assert.True(player.Cash < before, "il proprietario paga l'ammodernamento");
w.RunDays(m.UpgradeDays + 1);
Assert.Equal(level + 1, ind.Level);
}
// «Ordina ricambi» crea domanda esplicita oltre la scorta della politica
Assert.True(Do(w, new OrderPartsCommand(DepotId.None, 30) { Industry = ind.Id }).Ok);
Assert.True(IndustryMath.ServiceNeed(w, ind, w.Data.SparePartsGood) >= 30);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Ogni mese l'industria posseduta trattiene la riserva e versa il resto al proprietario")]
public static void OwnerReceivesTheSurplus()
{
var w = TestWorlds.NoAi(304);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Primary);
ind.Owner = w.Player.Id;
w.Money.Transfer(Account.External, Account.Of(ind.Id), Money.FromLire(500_000), LedgerEntry.Other);
var before = w.Player.Cash;
w.RunDays(w.Calendar.DaysPerMonth + 1);
Assert.Equal(m.OwnerCashReserve, ind.Cash.Cents, "l'industria trattiene la riserva");
Assert.True(w.Player.Cash > before, "il surplus va al proprietario");
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Industries] > 0);
}
[Test(Description = "Proprietari privati: budget dal margine e revisione sotto 35 se la cassa basta")]
public static void NpcOwnersFollowTheirRules()
{
var w = TestWorlds.NoAi(305);
var ind = Pick(w, IndustryKind.Primary);
ind.RevenueEma = 10_000;
ind.CostEma = 5_000;
ind.Condition = 30;
w.Money.Transfer(Account.External, Account.Of(ind.Id), Money.FromLire(1_000_000), LedgerEntry.Other);
w.RunDays(w.Calendar.DaysPerMonth + 1);
Assert.Equal(IndustryWork.Overhaul, ind.PendingWork, "sotto 35 il privato programma la revisione");
// margine negativo: nessun budget
var other = w.Industries.First(i => !i.Closed && i.Level > 0 && i != ind && i.Def.Kind == IndustryKind.Primary);
other.RevenueEma = 1_000;
other.CostEma = 5_000;
w.RunDays(w.Calendar.DaysPerMonth);
Assert.True(other.Margin < 0);
Assert.Equal(IndustryBudget.None, other.Budget);
}
}
@@ -0,0 +1,285 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Economy;
/// <summary>Borsa, quotazione, dividendi, scalate e loro esiti (guida 12.2–12.3, test di 14.5).</summary>
public static class StockMarketTests
{
private static CommandResult Do(World w, GameCommand c, Company issuer)
{
w.Enqueue(c with { Issuer = issuer.Id });
w.RunTicks(1);
return w.DrainResults().Last();
}
private static void Give(World w, Company c, long lire) =>
w.Money.Transfer(Account.External, Account.Of(c.Id), Money.FromLire(lire), LedgerEntry.Other);
/// <summary>Le IA non devono intervenire: mondo con concorrenti ma senza agenti attivi.</summary>
private static World WithIdleAi(ulong seed, string difficulty = "imprenditore", int competitors = 2)
{
var w = TestWorlds.Small(seed, difficulty, ("aiCompetitors", competitors));
w.AiPaused = true;
return w;
}
[Test(Description = "Prezzo = max(patrimonio, 8 × utile) / azioni × sentiment, con il sentiment tra 0,8 e 1,3")]
public static void PriceFollowsFundamentals()
{
var w = WithIdleAi(401);
var sm = w.Data.Balance.StockMarket;
w.RunDays(40);
foreach (var c in w.Companies)
{
Assert.Equal(sm.Shares, c.Shares.Total);
Assert.Equal(c.Shares.Total, c.Shares.Sum());
Assert.InRange(c.Sentiment, sm.SentimentMin, sm.SentimentMax);
double fundamental = Math.Max(c.NetWorth.Cents, sm.EarningsMultiple * c.AnnualProfit) / c.Shares.Outstanding;
Assert.Approx(fundamental * c.Sentiment, c.SharePrice, fundamental * 0.05 + 0.01, c.Name);
}
Assert.False(w.Player.Listed, "il giocatore parte privato (Imprenditore)");
Assert.True(w.Companies.Where(c => !c.IsPlayer).All(c => c.Listed), "le IA sono quotate");
var iron = WithIdleAi(402, "ferro_e_sangue");
Assert.True(iron.Player.Listed, "Ferro e sangue: quotata dall'inizio");
Assert.Approx(0.6, iron.Player.Shares.FounderFraction, 1e-6);
}
[Test(Description = "Quotazione al livello 4 fino al 40 %, compravendita al prezzo con lo spread, dividendi agli azionisti")]
public static void IpoTradingAndDividends()
{
var w = WithIdleAi(403);
var player = w.Player;
var ai = w.Companies.First(c => !c.IsPlayer);
Give(w, player, 5_000_000);
w.RunDays(2);
Assert.Equal(CommandError.TierLocked, Do(w, new IpoCommand(0.3), player).Error);
player.Tier = 4;
Assert.Equal(CommandError.InvalidArgument, Do(w, new IpoCommand(0.5), player).Error, "oltre il 40 %");
var cash = player.Cash;
Assert.True(Do(w, new IpoCommand(0.3), player).Ok);
Assert.True(player.Listed);
Assert.True(player.Cash > cash, "la quotazione porta capitale");
Assert.Approx(0.7, player.Shares.FounderFraction, 1e-6);
// acquisto di azioni di un'IA: lettera = prezzo × (1 + spread/2)
long n = 20_000;
double ask = Corporate.Ask(w, ai);
cash = player.Cash;
long free = ai.Shares.Public;
var buy = Do(w, new BuySharesCommand(ai.Id, n, Money.Zero), player);
Assert.True(buy.Ok, buy.Message);
Assert.Equal(n, ai.Shares.Of(player.Id));
Assert.Equal(free - n, ai.Shares.Public);
Assert.Approx(n * ask, (cash - player.Cash).Cents, n * ask * 0.02 + 2);
w.RunDays(1);
Assert.True(player.PortfolioValue.Cents > 0, "le partecipazioni contano nel patrimonio");
var sell = Do(w, new SellSharesCommand(ai.Id, n / 2, Money.Zero), player);
Assert.True(sell.Ok, sell.Message);
Assert.Equal(n / 2, ai.Shares.Of(player.Id));
// dividendo: ogni azione in circolazione riceve l'importo; le compagnie azioniste lo incassano
var aiCash = ai.Cash;
Give(w, ai, 1_000_000);
aiCash = ai.Cash;
var holderCash = player.Cash;
Assert.True(Do(w, new PayDividendCommand(new Money(10)), ai).Ok);
Assert.Equal(aiCash.Cents - 10 * ai.Shares.Outstanding, ai.Cash.Cents);
Assert.Equal(holderCash.Cents + 10 * (n / 2), player.Cash.Cents);
Assert.True(ai.DividendRing.Sum() > 0, "i dividendi entrano nel sentiment");
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Scalata ostile completata quando il flottante lo consente (14.5); fallita quando non basta")]
public static void HostileTakeoverCompletesWhenTheFloatAllows()
{
var w = WithIdleAi(404);
var player = w.Player;
var target = w.Companies.First(c => !c.IsPlayer);
Give(w, player, 50_000_000);
w.RunDays(2);
// flottante del 70 %: il fondatore privato non aderisce (premio sotto la sua soglia)
long moved = target.Shares.Founder - (long)(target.Shares.Total * 0.3);
target.Shares.Founder -= moved;
target.Shares.Public += moved;
Assert.Equal(CommandError.TierLocked, Do(w, new LaunchBidCommand(target.Id, new Money(1), 0.51), player).Error);
player.Tier = 5;
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
var bid = Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.51), player);
Assert.True(bid.Ok, bid.Message);
bool done = false;
for (int d = 0; d < 100 && !done; d++)
{
w.RunDays(1);
done = w.Bids.Any(b => b.State != BidState.Open);
}
Assert.Equal(BidState.Succeeded, w.Bids.Single().State);
Assert.True(target.Shares.FractionOf(player.Id) >= 0.51, $"quota {target.Shares.FractionOf(player.Id):P1}");
w.RunDays(1);
Assert.Equal(player.Id, target.ControlledBy, "chi supera il 50 % controlla");
// stessa offerta su un'IA con il 30 % di flottante: le adesioni non bastano, l'offerta scade
var other = w.Companies.Last(c => !c.IsPlayer);
long p2 = (long)Math.Ceiling(other.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(other.Id, new Money(p2), 0.51), player).Ok);
w.RunDays(w.Data.Balance.StockMarket.BidDurationDays + 2);
var second = w.Bids.Single(b => b.Target == other.Id);
Assert.Equal(BidState.Failed, second.State);
Assert.Equal(0L, other.Shares.Of(player.Id));
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Difese del bersaglio: il riacquisto toglie flottante all'offerente, il cavaliere bianco lo compra")]
public static void TargetsCanDefend()
{
var w = WithIdleAi(405, competitors: 3);
var player = w.Player;
var target = w.Companies[1];
var knight = w.Companies[2];
Give(w, player, 50_000_000);
Give(w, knight, 50_000_000);
Give(w, target, 5_000_000);
player.Tier = 5;
w.RunDays(2);
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.51), player).Ok);
var bid = w.Bids.Single();
long floatBefore = Corporate.FreeFloat(w, target);
var buyback = Do(w, new RespondBidCommand(bid.Id, false) { Defense = BidDefense.Buyback }, target);
Assert.True(buyback.Ok, buyback.Message);
Assert.True(Corporate.FreeFloat(w, target) < floatBefore, "il riacquisto riduce il flottante");
var white = Do(w, new RespondBidCommand(bid.Id, false) { Defense = BidDefense.WhiteKnight, Knight = knight.Id }, target);
if (Corporate.FreeFloat(w, target) > 0 || white.Ok) Assert.True(white.Ok || white.Error == CommandError.InsufficientFunds, white.Message);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "La controllata versa gli utili; dopo un anno di controllo si può fondere")]
public static void SubsidiaryPaysAndCanBeMerged()
{
var w = WithIdleAi(406);
var player = w.Player;
var sub = w.Companies[1];
Give(w, player, 50_000_000);
// il giocatore compra il 60 % dal fondatore privato (come dopo un'offerta riuscita)
long stake = (long)(sub.Shares.Total * 0.6);
sub.Shares.Founder -= stake;
sub.Shares.Add(player.Id, stake);
w.RunDays(2);
Assert.Equal(player.Id, sub.ControlledBy);
Assert.Equal(CommandError.NotAllowed, Do(w, new MergeCompanyCommand(sub.Id), player).Error, "serve un anno di controllo");
w.RunDays(w.Data.Balance.StockMarket.MergeAfterDays + 1);
int trainsBefore = w.Trains.Count(t => t.Owner == player.Id);
var merge = Do(w, new MergeCompanyCommand(sub.Id), player);
Assert.True(merge.Ok, merge.Message);
Assert.True(sub.Merged && sub.Defunct);
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1000)), sub).Error, "la fusa non dà più comandi");
Assert.True(w.Trains.Count(t => t.Owner == player.Id) >= trainsBefore);
Assert.Equal(0L, w.MoneyBalanceSum());
}
/// <summary>Un'IA prende più del 50 % del giocatore quotato.</summary>
private static (World W, Company Ai) PlayerTakenOver(string difficulty)
{
var w = WithIdleAi(407, difficulty);
var player = w.Player;
var ai = w.Companies[1];
w.RunDays(2);
if (!player.Listed) Corporate.InitShares(w, player, true, 0.45);
long stake = (long)(player.Shares.Total * 0.55);
long fromPublic = Math.Min(stake, player.Shares.Public);
player.Shares.Public -= fromPublic;
player.Shares.Founder -= stake - fromPublic;
player.Shares.Add(ai.Id, stake);
w.RunDays(2);
return (w, ai);
}
[Test(Description = "Se l'IA compra il giocatore: amministrazione controllata (Imprenditore), fine immediata (Ferro e sangue), mai (Apprendista)")]
public static void PlayerTakeoverOutcomesByDifficulty()
{
// Imprenditore: amministrazione controllata per 3 anni, niente prestiti, riscatto possibile
var (w, ai) = PlayerTakenOver("imprenditore");
var player = w.Player;
Assert.True(player.Receivership, "amministrazione controllata");
Assert.True(w.GameOver is null, "la partita continua");
Assert.Equal(w.Clock.Day - 2 + 3L * w.Calendar.DaysPerYear, player.ReceivershipUntilDay, "3 anni per il riscatto");
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1000)), player).Error);
Give(w, player, 100_000_000);
long max = (long)(player.Shares.Total * w.Data.Balance.StockMarket.MaxDailyTradeShare);
for (int i = 0; i < 40 && player.Receivership; i++)
{
var r = Do(w, new BuySharesCommand(player.Id, max, Money.Zero), player);
Assert.True(r.Ok, r.Message);
w.RunDays(1);
}
Assert.False(player.Receivership, $"riscatto riuscito: fondatore al {player.Shares.FounderFraction:P0}");
// Ferro e sangue: fine immediata, poi si osserva
var (w2, ai2) = PlayerTakenOver("ferro_e_sangue");
Assert.NotNull(w2.GameOver);
Assert.Equal(GameOverReason.Takeover, w2.GameOver!.Reason);
Assert.Equal(ai2.Id, w2.GameOver.Winner);
Assert.Equal(CommandError.NotAllowed, Do(w2, new TakeLoanCommand(Money.FromLire(1000)), w2.Player).Error, "osservatore");
w2.RunDays(10); // il mondo continua
// Apprendista: nessuna IA può superare il 50 % del giocatore
var w3 = WithIdleAi(408, "apprendista");
var p3 = w3.Player;
var ai3 = w3.Companies[1];
Corporate.InitShares(w3, p3, true, 0.3);
Give(w3, ai3, 100_000_000);
w3.RunDays(1);
long chunk = (long)(p3.Shares.Total * w3.Data.Balance.StockMarket.MaxDailyTradeShare);
CommandResult last = null!;
for (int i = 0; i < 20; i++) last = Do(w3, new BuySharesCommand(p3.Id, chunk, Money.Zero), ai3);
Assert.Equal(CommandError.NotAllowed, last.Error);
Assert.True(p3.Shares.FractionOf(ai3.Id) <= 0.5);
Assert.Equal(CommandError.NotAllowed, Do(w3, new LaunchBidCommand(p3.Id, new Money(1), 0.51), ai3).Error);
}
[Test(Description = "Un'IA fallita va all'asta: il giocatore se ne aggiudica gli attivi")]
public static void BankruptAiIsAuctioned()
{
var w = WithIdleAi(409);
var player = w.Player;
var ai = w.Companies[1];
Give(w, player, 10_000_000);
w.RunDays(2);
ai.Bankrupt = true;
w.RunDays(1);
var auction = w.Auctions.Single(a => a.Seller == ai.Id);
long perShare = auction.MinPriceCents / ai.Shares.Total + 1;
var offer = Do(w, new LaunchBidCommand(ai.Id, new Money(perShare), 1), player);
Assert.True(offer.Ok, offer.Message);
w.RunDays(w.Data.Balance.StockMarket.AuctionDays + 1);
Assert.True(ai.Merged, "attivi passati al compratore");
Assert.Equal(player.Id, ai.MergedInto);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Offerte, soci, amministrazione controllata e storico sopravvivono al salvataggio")]
public static void CorporateStateSurvivesSaveAndLoad()
{
var w = WithIdleAi(410, "magnate");
var player = w.Player;
Give(w, player, 50_000_000);
player.Tier = 5;
w.RunDays(370);
var target = w.Companies[1];
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.6), player).Ok);
w.RunDays(5);
var bytes = SaveFile.Save(w, "test");
var loaded = SaveFile.Load(TestData.Data, bytes);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
w.RunDays(30);
loaded.RunDays(30);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
Assert.True(player.History.Count >= 1, "storico annuale");
}
}
@@ -0,0 +1,99 @@
using System.Runtime.CompilerServices;
namespace RailEnterprise.Tests.Harness;
/// <summary>Fallimento di un'asserzione, con posizione nel sorgente.</summary>
public sealed class AssertionException(string message) : Exception(message);
/// <summary>Asserzioni minime del harness interno.</summary>
public static class Assert
{
public static void Equal<T>(T expected, T actual, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (!EqualityComparer<T>.Default.Equals(expected, actual))
Fail($"atteso <{expected}> ma ottenuto <{actual}>", message, file, line);
}
public static void NotEqual<T>(T notExpected, T actual, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (EqualityComparer<T>.Default.Equals(notExpected, actual))
Fail($"valore diverso da <{notExpected}> atteso", message, file, line);
}
public static void SequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
var e = expected.ToList();
var a = actual.ToList();
if (e.Count != a.Count)
Fail($"lunghezze diverse: attese {e.Count}, ottenute {a.Count}", message, file, line);
for (int i = 0; i < e.Count; i++)
{
if (!EqualityComparer<T>.Default.Equals(e[i], a[i]))
Fail($"elemento {i}: atteso <{e[i]}> ma ottenuto <{a[i]}>", message, file, line);
}
}
public static void True(bool condition, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (!condition) Fail("condizione falsa", message, file, line);
}
public static void False(bool condition, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (condition) Fail("condizione vera", message, file, line);
}
public static void NotNull(object? value, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (value is null) Fail("valore nullo", message, file, line);
}
/// <summary>Confronto tra reali con tolleranza assoluta.</summary>
public static void Approx(double expected, double actual, double tolerance, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (double.IsNaN(actual) || Math.Abs(expected - actual) > tolerance)
Fail($"atteso {expected} ± {tolerance} ma ottenuto {actual}", message, file, line);
}
/// <summary>Verifica che value sia nell'intervallo chiuso [min, max].</summary>
public static void InRange(double value, double min, double max, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (double.IsNaN(value) || value < min || value > max)
Fail($"valore {value} fuori da [{min}, {max}]", message, file, line);
}
public static TException Throws<TException>(Action action, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0) where TException : Exception
{
try
{
action();
}
catch (TException ex)
{
return ex;
}
catch (Exception ex)
{
Fail($"attesa {typeof(TException).Name} ma lanciata {ex.GetType().Name}: {ex.Message}", message, file, line);
}
Fail($"attesa {typeof(TException).Name} ma nessuna eccezione", message, file, line);
return null!;
}
[System.Diagnostics.CodeAnalysis.DoesNotReturn]
public static void Fail(string reason, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
string where = $"{Path.GetFileName(file)}:{line}";
throw new AssertionException(message is null ? $"{reason} ({where})" : $"{message}: {reason} ({where})");
}
}
@@ -0,0 +1,18 @@
namespace RailEnterprise.Tests.Harness;
/// <summary>
/// Marca un metodo come test. Il metodo può essere statico o d'istanza (classe con costruttore
/// senza parametri), restituire void o Task.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class TestAttribute : Attribute
{
/// <summary>Test lungo (simulazioni pluriennali): escluso con --skip-slow.</summary>
public bool Slow { get; init; }
/// <summary>Test che non può girare in parallelo con altri (porte di rete, processi figli).</summary>
public bool Isolated { get; init; }
/// <summary>Descrizione facoltativa mostrata in --list.</summary>
public string? Description { get; init; }
}
@@ -0,0 +1,120 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Reflection;
namespace RailEnterprise.Tests.Harness;
/// <summary>
/// Scopre i metodi [Test] per reflection e li esegue. Opzioni:
/// filtri liberi (sottostringa del nome), --list, --serial, --skip-slow.
/// Il codice di uscita è 0 solo se tutti i test selezionati passano.
/// </summary>
public static class TestRunner
{
private sealed record TestCase(string Name, MethodInfo Method, TestAttribute Attribute);
private sealed record TestOutcome(string Name, bool Passed, long Millis, string? Error);
public static int Run(string[] args, Assembly assembly)
{
bool list = args.Contains("--list");
bool serial = args.Contains("--serial");
bool skipSlow = args.Contains("--skip-slow");
var filters = args.Where(a => !a.StartsWith("--", StringComparison.Ordinal)).ToArray();
var tests = Discover(assembly)
.Where(t => filters.Length == 0 || filters.Any(f => t.Name.Contains(f, StringComparison.OrdinalIgnoreCase)))
.Where(t => !(skipSlow && t.Attribute.Slow))
.OrderBy(t => t.Name, StringComparer.Ordinal)
.ToList();
if (list)
{
foreach (var t in tests)
Console.WriteLine($"{t.Name}{(t.Attribute.Slow ? " [lento]" : "")}{(t.Attribute.Description is { } d ? " — " + d : "")}");
return 0;
}
Console.WriteLine($"Rail Enterprise — {tests.Count} test selezionati");
var total = Stopwatch.StartNew();
var outcomes = new ConcurrentBag<TestOutcome>();
var parallel = tests.Where(t => !serial && !t.Attribute.Isolated).ToList();
var sequential = tests.Where(t => serial || t.Attribute.Isolated).ToList();
Parallel.ForEach(parallel, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount) },
t =>
{
var o = Execute(t);
Report(o);
outcomes.Add(o);
});
foreach (var t in sequential)
{
var o = Execute(t);
Report(o);
outcomes.Add(o);
}
var failed = outcomes.Where(o => !o.Passed).OrderBy(o => o.Name, StringComparer.Ordinal).ToList();
Console.WriteLine();
Console.WriteLine($"Eseguiti {outcomes.Count}, superati {outcomes.Count - failed.Count}, falliti {failed.Count} in {total.Elapsed.TotalSeconds:F1} s");
foreach (var f in failed)
Console.WriteLine($" FALLITO {f.Name}: {f.Error}");
return failed.Count == 0 && tests.Count > 0 ? 0 : 1;
}
private static readonly Lock ConsoleLock = new();
private static void Report(TestOutcome o)
{
lock (ConsoleLock)
{
if (o.Passed)
Console.WriteLine($" ok {o.Name} ({o.Millis} ms)");
else
Console.WriteLine($" FALLITO {o.Name} ({o.Millis} ms)\n {o.Error}");
}
}
private static IEnumerable<TestCase> Discover(Assembly assembly)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
foreach (var type in assembly.GetTypes())
{
foreach (var method in type.GetMethods(flags))
{
var attr = method.GetCustomAttribute<TestAttribute>();
if (attr is null) continue;
if (method.GetParameters().Length != 0)
throw new InvalidOperationException($"Il test {type.Name}.{method.Name} non deve avere parametri");
yield return new TestCase($"{type.Name}.{method.Name}", method, attr);
}
}
}
private static TestOutcome Execute(TestCase t)
{
var sw = Stopwatch.StartNew();
try
{
object? instance = t.Method.IsStatic ? null : Activator.CreateInstance(t.Method.DeclaringType!);
object? result = t.Method.Invoke(instance, null);
if (result is Task task) task.GetAwaiter().GetResult();
(instance as IDisposable)?.Dispose();
return new TestOutcome(t.Name, true, sw.ElapsedMilliseconds, null);
}
catch (TargetInvocationException ex) when (ex.InnerException is not null)
{
return new TestOutcome(t.Name, false, sw.ElapsedMilliseconds, Describe(ex.InnerException));
}
catch (Exception ex)
{
return new TestOutcome(t.Name, false, sw.ElapsedMilliseconds, Describe(ex));
}
}
private static string Describe(Exception ex) => ex is AssertionException
? ex.Message
: $"{ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}";
}
+126
View File
@@ -0,0 +1,126 @@
using System.Diagnostics;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Map;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Map;
public static class MapTests
{
[Test(Description = "Accettazione F1: mappa da 128 km generata in meno di 3 s", Slow = true, Isolated = true)]
public static void Map128GeneratesUnderThreeSeconds()
{
TestWorlds.Map(1, 64); // riscaldamento JIT
var sw = Stopwatch.StartNew();
var map = TestWorlds.Map(3, 128);
sw.Stop();
Assert.Equal(1280, map.Terrain.Width);
Assert.True(sw.ElapsedMilliseconds < 3000, $"generazione in {sw.ElapsedMilliseconds} ms");
}
[Test]
public static void SameSeedSameMapDifferentSeedDifferentMap()
{
var a = TestWorlds.Map(5, 64);
var b = TestWorlds.Map(5, 64);
var c = TestWorlds.Map(6, 64);
Assert.Equal(a.Terrain.ComputeHash(), b.Terrain.ComputeHash());
Assert.SequenceEqual(a.Towns.Select(t => t.Name), b.Towns.Select(t => t.Name));
Assert.NotEqual(a.Terrain.ComputeHash(), c.Terrain.ComputeHash());
}
[Test(Description = "Distanze della guida: città ≥ 6 km, industrie entro i vincoli di collocazione")]
public static void PlacementDistancesAreRespected()
{
var data = TestData.Data;
foreach (ulong seed in new ulong[] { 11, 12 })
{
var map = TestWorlds.Map(seed, 128);
double cs = map.Terrain.CellSizeM;
int expectedTowns = data.Balance.Map.Towns.CountBySize["128"];
Assert.True(map.Towns.Count >= expectedTowns * 0.8, $"città {map.Towns.Count} su {expectedTowns}");
for (int i = 0; i < map.Towns.Count; i++)
{
for (int j = i + 1; j < map.Towns.Count; j++)
{
var a = map.Towns[i];
var b = map.Towns[j];
double km = Math.Sqrt(Sq(a.CellX - b.CellX) + Sq(a.CellY - b.CellY)) * cs / 1000;
Assert.True(km >= data.Balance.Map.Towns.MinDistanceKm - 1e-9, $"{a.Name}–{b.Name}: {km:F2} km");
}
}
foreach (var ind in map.Industries)
{
var def = data.Industries[ind.TypeIndex];
var p = map.Terrain.CellCenter(ind.CellX, ind.CellY);
double nearest = map.Towns.Min(t => MapGenerator.TownEdgeDistanceKm(t, p, cs));
if (def.Placement.MinTownDistanceKm is { } mn) Assert.True(nearest >= mn, $"{ind.Name}: {nearest:F2} km < {mn}");
if (def.Placement.MaxTownDistanceKm is { } mx) Assert.True(nearest <= mx, $"{ind.Name}: {nearest:F2} km > {mx}");
if (def.Placement.MaxInputDistanceKm is { } maxIn)
{
foreach (var input in def.Recipe.Inputs)
{
bool near = map.Industries.Any(o => data.Industries[o.TypeIndex].Recipe.Outputs.Any(x => x.Good == input.Good)
&& Math.Sqrt(Sq(o.CellX - ind.CellX) + Sq(o.CellY - ind.CellY)) * cs / 1000 <= maxIn + 1e-9);
Assert.True(near, $"{ind.Name}: nessun produttore di {input.Good} entro {maxIn} km");
}
}
if (def.Placement.Needs == PlacementNeed.Deposit)
{
Assert.True(ind.SiteIndex >= 0, $"{ind.Name} senza giacimento");
Assert.Equal(def.Placement.Resource, map.Sites[ind.SiteIndex].Kind);
}
var (x0, y0) = GeneratedMap.FootprintOrigin(ind.CellX, ind.CellY, ind.FootprintCells);
for (int y = y0; y < y0 + ind.FootprintCells; y++)
for (int x = x0; x < x0 + ind.FootprintCells; x++)
Assert.Equal(CellType.Industry, map.Terrain.TypeAt(x, y));
}
Assert.True(map.Hubs.Any(h => h.Kind == HubKind.Port), "almeno un porto");
Assert.True(map.Hubs.Any(h => h.Kind == HubKind.Border), "almeno un valico");
}
}
private static double Sq(double v) => v * v;
[Test]
public static void TerrainHasSeaRiversAndCover()
{
var map = TestWorlds.Map(21, 64);
var t = map.Terrain;
var counts = new int[11];
foreach (byte b in t.Types) counts[b]++;
Assert.True(counts[(int)CellType.Sea] > 0, "mare presente");
Assert.True(counts[(int)CellType.Water] > 0, "fiumi o laghi presenti");
Assert.True(counts[(int)CellType.Forest] > 0, "boschi presenti");
Assert.True(counts[(int)CellType.Plain] > t.Types.Length / 10, "pianure abbondanti");
// il mare tocca il lato scelto ed è a quota zero
bool seaOnEdge = false;
for (int i = 0; i < t.Width; i++)
{
seaOnEdge |= t.TypeAt(i, 0) == CellType.Sea || t.TypeAt(i, t.Height - 1) == CellType.Sea
|| t.TypeAt(0, i) == CellType.Sea || t.TypeAt(t.Width - 1, i) == CellType.Sea;
}
Assert.True(seaOnEdge);
for (int i = 0; i < t.Types.Length; i++)
{
if (t.Types[i] == (byte)CellType.Sea) Assert.Equal((ushort)0, t.Heights[i]);
}
Assert.True(t.RiverWidth.Any(w => w >= 2), "almeno un fiume largo più di una cella");
}
[Test]
public static void SamplerInterpolatesBetweenCellCenters()
{
var t = new Terrain(4, 4, 100, 64);
for (int y = 0; y < 4; y++)
for (int x = 0; x < 4; x++)
t.Heights[t.Index(x, y)] = Terrain.ToDecimeters(x * 10); // pendenza costante del 10 %
var s = new TerrainSampler(t);
Assert.Approx(0.0, s.HeightAt(50, 150), 1e-9);
Assert.Approx(5.0, s.HeightAt(100, 150), 1e-9);
Assert.Approx(15.0, s.HeightAt(200, 250), 1e-9);
Assert.Approx(0.1, s.Slope(150, 150), 1e-9);
Assert.Approx(DMath.Pi, Math.Abs(s.Aspect(150, 150)), 1e-9, "discesa verso ovest");
}
}
@@ -0,0 +1,104 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Persistence;
public static class PersistenceTests
{
[Test(Description = "Determinismo: stesso seme e stessi comandi agli stessi tick → stesso hash")]
public static void SameSeedAndCommandsGiveSameHash()
{
ulong Run()
{
var w = TestWorlds.Small(200);
w.RunDays(45);
w.Enqueue(new TakeLoanCommand(Money.FromLire(50_000)) { Issuer = w.Player.Id, Seq = 1 });
w.RunDays(400);
return w.LastStateHash;
}
ulong a = Run();
ulong b = Run();
Assert.Equal(a, b);
var other = TestWorlds.Small(201);
other.RunDays(445);
Assert.NotEqual(a, other.LastStateHash);
}
[Test(Description = "Salvataggio e caricamento: stesso hash subito e dopo altri 200 giorni")]
public static void SaveLoadRoundTripPreservesFuture()
{
var a = TestWorlds.Small(202);
a.Enqueue(new TakeLoanCommand(Money.FromLire(80_000)) { Issuer = a.Player.Id });
a.RunDays(100);
byte[] file = SaveFile.Save(a, "test");
var b = SaveFile.Load(TestData.Data, file);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
Assert.Equal(a.LastStateHash, b.LastStateHash);
Assert.Equal(a.Clock.Tick, b.Clock.Tick);
Assert.Equal(a.Events.Total, b.Events.Total);
a.RunDays(200);
b.RunDays(200);
Assert.Equal(a.LastStateHash, b.LastStateHash);
Assert.Equal(0L, b.MoneyBalanceSum());
// un secondo giro di salvataggio produce un file identico
Assert.SequenceEqual(SaveFile.Save(a, "test"), SaveFile.Save(b, "test"));
}
[Test]
public static void SaveHeaderIsReadableWithoutDecompressing()
{
var w = TestWorlds.Small(203);
w.RunDays(10);
var info = SaveFile.ReadInfo(SaveFile.Save(w, "0.1.0"));
Assert.Equal("0.1.0", info.GameVersion);
Assert.Equal(w.Clock.Tick, info.Tick);
Assert.Equal(w.Settings.Seed, info.Seed);
Assert.Equal(w.Player.Name, info.CompanyName);
Assert.Equal(w.Data.Hash, info.DataHash);
}
[Test]
public static void CorruptSavesAreRejected()
{
var w = TestWorlds.Small(204);
byte[] file = SaveFile.Save(w, "test");
Assert.Throws<InvalidDataException>(() => SaveFile.Load(TestData.Data, "XXXX"u8.ToArray()));
var truncated = file.AsSpan(0, file.Length / 2).ToArray();
Assert.Throws<Exception>(() => SaveFile.Load(TestData.Data, truncated));
}
[Test]
public static void SaveWriterReaderRoundTripPrimitives()
{
var wtr = new SaveWriter(4);
wtr.Write((byte)7);
wtr.Write(true);
wtr.Write(-12345);
wtr.Write(long.MinValue);
wtr.Write(ulong.MaxValue);
wtr.Write(Math.PI);
wtr.Write("Città d'acqua €");
wtr.Write((string?)null);
wtr.Write(new[] { 1, 2, 3 }.AsSpan());
wtr.Write(new ushort[] { 0, 65535 }.AsSpan());
var r = new SaveReader(wtr.ToArray());
Assert.Equal((byte)7, r.ReadByte());
Assert.True(r.ReadBool());
Assert.Equal(-12345, r.ReadInt32());
Assert.Equal(long.MinValue, r.ReadInt64());
Assert.Equal(ulong.MaxValue, r.ReadUInt64());
Assert.Equal(Math.PI, r.ReadDouble());
Assert.Equal("Città d'acqua €", r.ReadString());
Assert.Equal(null, r.ReadString());
Assert.SequenceEqual(new[] { 1, 2, 3 }, r.ReadInt32Array());
Assert.SequenceEqual(new ushort[] { 0, 65535 }, r.ReadUInt16Array());
Assert.True(r.AtEnd);
Assert.Throws<InvalidDataException>(() => r.ReadInt32());
}
}
+11
View File
@@ -0,0 +1,11 @@
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests;
/// <summary>
/// Punto d'ingresso unico: dotnet run --project tests/RailEnterprise.Tests [-- filtri] [--list] [--serial] [--skip-slow].
/// </summary>
public static class TestProgram
{
public static int Main(string[] args) => TestRunner.Run(args, typeof(TestProgram).Assembly);
}
@@ -0,0 +1,391 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Protocol;
public static class ProtocolTests
{
private static readonly Vec2 P = new(1234.5, 6789.25);
/// <summary>Un esemplare con campi non predefiniti per ogni messaggio del protocollo.</summary>
public static IEnumerable<IMessage> SampleMessages()
{
yield return new Hello { ClientVersion = "0.1.0", Token = "segreto", ResumeSessionId = 42, DataHash = 0xDEADBEEFUL };
yield return new Ping { Nonce = 7 };
yield return new Subscribe { X0 = -3, Y0 = 4, X1 = 300, Y1 = 200, Lod = 1 };
yield return new CommandMessage { Seq = 99, Command = new BuildStationCommand(P, 3, "Stazione Nord") };
yield return new SetSpeed { Speed = 4 };
yield return new RequestDetail { Kind = DetailKind.Workshop, Target = 3 };
yield return new ListSaves();
yield return new Save { Name = "partita è bella" };
yield return new Load { SaveId = "auto-0003" };
yield return new NewGame { Seed = 123, SizeKm = 128, StartYear = 1860, DifficultyPreset = "personalizzata", Overrides = [("wearMultiplier", 1.3), ("aiCompetitors", 2)], EndlessFlags = 0x7F };
yield return new Welcome
{
SessionId = 77,
Summary = new WorldSummary
{
Seed = 5, SizeKm = 64, StartYear = 1850, Tick = 1000, Date = "3 gennaio 1850", CompanyId = 0, CompanyName = "Società",
RegionId = "valdoria", WidthCells = 640, HeightCells = 640, CellSizeM = 100, ChunkCells = 64, Speed = 1, TerrainHash = 99,
},
DataHash = 12345,
Difficulty = "imprenditore",
};
yield return new Reject { Code = RejectCode.BadToken, Reason = "Token errato" };
yield return new Pong { Nonce = 7, ServerTick = 123456 };
yield return SampleChunk();
yield return new EntitySnapshot { Tick = 55, Entities = SampleEntities() };
yield return new EntityDelta { Tick = 56, Changed = SampleEntities(), Removed = [(EntityType.Train, 3), (EntityType.Station, 9)] };
yield return new TrackWorks { Edges = [SampleEdge()], Removed = [4, 5] };
yield return new TrainMotion
{
TrainId = 12, Tick = 999, State = 2, Condition = 87.5f, Speed = 13.4f, LengthM = 71, HeadDistance = 120.5,
Segments = [new MotionSegment(3, true, 10, 300), new MotionSegment(4, false, 500, 0)],
};
yield return new DailyDigest
{
Day = 31, Tick = 7440, Date = "1 febbraio 1850", Cash = new Money(123456789), NetWorth = new Money(-5), Rating = "BBB",
Prices = [new Money(3800), new Money(4200)], Events = [SampleEvent()], StateHash = 0xABCDEF, Slow = true, Speed = 2, TickMs = 0.84f,
};
yield return new MaintenanceAlert { Train = 12, Component = "brakes", Condition = 35, DueDays = 4, Text = "Treno 12: freni al 35 %" };
yield return new EmploymentReport
{
Day = 60,
Rows =
[
new EmploymentRow
{
Industry = 2, JobsWorkers = 40, JobsStaff = 2, WorkersPresent = 39.5f, StaffPresent = 2, Reason = "capacità delle carrozze insufficiente",
Sources = [new EmploymentSource { Town = 1, HomeStation = 3, Line = 1, Category = 0, Headcount = 28, Coverage = 0.97f }],
Kind = 1, WorkersReason = 5, StaffReason = 4, WorkersReasonLine = 2, StaffReasonLine = -1,
},
],
Agreements =
[
new AgreementInfo
{
Id = 4, Industry = 2, Carrier = 0, SeatsPerDay = 28, MonthlyFee = new Money(70000), State = 1, ProposedDay = 300,
StartDay = 310, EndDay = 1030, Coverage = 0.95f, ShortDays = 2,
},
],
};
yield return new MaintenanceCard
{
Train = 12, Day = 400, Condition = 38.5f, Status = TrainMaintenanceStatus.Booked, Policy = 1, PolicyOverride = 2, Reserve = false,
Failure = 1, FailedVehicle = 6, FailedComponent = "brakes", RescueHours = 2.5f, NextIntervention = "service", NextDueDays = -3.5f,
PlannedIntervention = "repair_minor", MaintenanceDepot = 1, ServiceKmPerDay = 195, CostThisYear = new Money(123400),
CostLastYear = new Money(98700), FailuresThisYear = 2, FailuresTotal = 5, CoveredBy = 14, Covering = -1,
Vehicles =
[
new VehicleCard
{
Vehicle = 6, Type = "loco_steam_1850", OdometerKm = 45000, AgeYears = 3.5f, AgeFactor = 1,
Components = [new ComponentCard { Component = "engine", Condition = 61.2f, WearPerDay = 0.8f }, new ComponentCard { Component = "brakes", Condition = 38.5f, WearPerDay = 1.1f }],
},
],
History = [new MaintenanceRecordInfo { Day = 350, Intervention = "inspection", Cost = new Money(9000), Depot = 1, Parts = 0 }],
};
yield return new WorkshopRegister
{
Depot = 1, Day = 400, Stalls = 4, JobsStaff = 16, StaffPresent = 12.5f, WorkRate = 0.8f, SpareParts = 7, PartsTarget = 40, PartsReserved = 3,
Jobs = [new WorkshopJobInfo { Train = 12, Intervention = "service", InStall = true, Started = true, Progress = 1.6f, Days = 3, Parts = 3, QueuedDay = 398 }],
Booked = [new WorkshopJobInfo { Train = 13, Intervention = "inspection", Days = 1, QueuedDay = -1 }],
};
yield return new MarketTape
{
Day = 90,
Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true, PriceCents = 1234.25, Outstanding = 990_000, FreeFloat = 300_000, FounderShare = 0.6f, ControlledBy = 2 }],
Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180, State = 1, CommittedShare = 0.42, Defenses = 3, Knight = 3, Accepted = true }],
};
yield return new CompanyCard
{
Company = 1, TotalShares = 1_000_000, Treasury = 10_000,
Holdings = [new HoldingInfo { Holder = HoldingInfo.Founder, Shares = 600_000 }, new HoldingInfo { Holder = HoldingInfo.Market, Shares = 290_000 }, new HoldingInfo { Holder = 2, Shares = 100_000 }],
PriceHistory = [12.5, 13.25, 14],
History = [new CompanyYearInfo { Year = 1851, NetWorth = new Money(500), Cash = new Money(-20), Revenue = new Money(900), Profit = new Money(-30), Tier = 2, Trains = 4, TrackKm = 12.5f, SharePrice = new Money(13) }],
AnnualProfit = new Money(-123), DividendsYear = new Money(45), Debt = new Money(678), MarketCap = new Money(9_000_000), ControlDays = 400,
AuctionMin = new Money(10), AuctionBest = new Money(20), AuctionBestBidder = 3, AuctionEndDay = 999,
};
yield return new IndustryCard
{
Industry = 4, Margin = -0.1f, ConditionMultiplier = 0.8f, WearPerDay = 0.05f, RecoveryPerDay = 0.12f, MaintenanceCostPerDay = new Money(77),
MaintenanceSpentYear = new Money(9999), PartsTarget = 9, PartsPerMonth = 3, PartsOrdered = 20, MachineryRequired = 6, UpgradeCost = new Money(3_000_000),
Valuation = new Money(4_500_000), Cash = new Money(2_000_000), BreakdownChancePerYear = 0.3f,
Stops = [new IndustryStopInfo { Day = 300, Days = 12, Kind = 1 }, new IndustryStopInfo { Day = 500, Days = 30, Kind = 3 }],
};
yield return new Chronicle
{
GameOver = true, Reason = 2, Text = "La Predatoria prende il controllo", Winner = 2, Day = 3600, Company = "Società", FoundedYear = 1850, Prestige = 1234,
History = [new CompanyYearInfo { Year = 1850, NetWorth = new Money(1), Tier = 1 }],
Records = [new RecordInfo { Title = "Patrimonio massimo", Value = "₤ 1.000.000", Year = 1855 }],
Highlights = ["Fondata nel 1850", "Livello 3 nel 1858"],
};
yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
yield return new Notification { Event = SampleEvent() };
yield return new Newspaper { Day = 30, Title = "La Cronaca di Valdoria", Articles = [("Nuova linea", "Inaugurata la linea per il valico."), ("Prezzi", "Il carbone sale.")] };
yield return new SaveList { Saves = [new SaveInfo { SaveId = "s1", Name = "Prima", GameDate = "1 marzo 1851", SizeBytes = 4096, SavedUnixMs = 1_700_000_000_000, Autosave = true }] };
}
private static EventInfo SampleEvent() => new()
{
Day = 31, Kind = 4, Severity = 2, Text = "Treno 12 è fermo da 20 giorni", Entity = 6, EntityIndex = 12, Company = 0,
};
private static MapChunk SampleChunk()
{
int w = 7, h = 5;
var heights = new ushort[w * h];
var types = new byte[w * h];
var river = new byte[w * h];
for (int i = 0; i < heights.Length; i++)
{
heights[i] = (ushort)(i * 997 % 65535);
types[i] = (byte)(i % 11);
river[i] = (byte)(i % 5);
}
return new MapChunk { Cx = 2, Cy = 3, Width = w, Height = h, Heights = heights, Types = types, RiverWidth = river };
}
private static EdgeInfo SampleEdge() => new()
{
Id = 4, Owner = 0, A = 1, B = 2, TrackClass = 1, DoubleTrack = true, Electrified = false, State = 1, Condition = 92, StructureCondition = 100, Progress = 0.4f,
S = [0, 25, 50], X = [0, 25, 50.5], Y = [10, 10, 11], H = [100, 101.25, 102.5], Ground = [100, 99, 103], Kinds = [0, 3, 1], SpeedLimitKmh = [60, 60, 45.5],
Signals = [12.5],
};
private static EntityLists SampleEntities() => new()
{
Companies = [new CompanyInfo
{
Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2, MaintenancePolicy = 2,
Personality = "predatory", Listed = true, SharePriceCents = 22.75, Sentiment = 1.1f, FounderShare = 0.55f, ControlledBy = 2, Merged = true,
Receivership = true, ReceivershipUntilDay = 777, AnnualProfit = new Money(-5),
}],
Towns = [new TownInfo { Id = 0, Name = "Valdoria", Position = P, Population = 12400, RadiusCells = 4.5, Satisfaction = 0.6f, Services = 3 }],
Industries = [new IndustryInfo
{
Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1,
Budget = 2, SpareParts = 5, Machinery = 3, StoppedUntilDay = 1234, StopKind = 3, PendingWork = 2, PartsShort = true,
}],
Hubs = [new HubInfo { Id = 0, Kind = "port", Name = "Porto", Position = P }],
Nodes = [new NodeInfo { Id = 3, Position = P, HeightM = 120.5, Owner = 0, Station = 1, Depot = -1, Edges = [1, 4] }],
Stations = [new StationInfo { Id = 1, Owner = 0, Name = "Acciaieria", Node = 3, Position = P, Platforms = 4, WaitingUnits = 30, Industries = [1], Towns = [0] }],
Depots = [new DepotInfo { Id = 0, Owner = 0, Name = "Deposito", Node = 5, Position = P, Size = "small", Stalls = 2, JobsStaff = 8, StaffPercent = 75, SpareParts = 9, PartsTarget = 40, Jobs = 1, WaitingParts = true }],
Lines = [new LineInfo { Id = 0, Owner = 0, Name = "Linea 1", Color = "#e0a526", Stops = [new LineStop(new StationId(1)), new LineStop(new StationId(2), WaitFull: true, MaxWaitDays: 2)], Policy = 0 }],
Vehicles = [new VehicleInfo { Id = 7, Owner = 0, Type = "wagon_hopper", Depot = -1, Train = 2, Condition = 99.5f }],
Trains =
[
new TrainInfo
{
Id = 2, Owner = 0, Name = "Treno 12", Line = 0, State = 3, Vehicles = [6, 7], MaxSpeedKmh = 60, LengthM = 27, Load = 20, Capacity = 20,
Condition = 41, Maintenance = TrainMaintenanceStatus.MinorFailure, Reserve = true, Policy = 2, NextIntervention = "inspection",
NextDueDays = -2, MaintenanceDepot = 0,
},
],
};
/// <summary>Un esemplare per ogni tipo di comando, con campi non predefiniti.</summary>
public static IEnumerable<GameCommand> SampleCommands()
{
yield return new BuildTrackCommand([P, P + new Vec2(1000, 0), P + new Vec2(2000, 500)], 1.5, false, true, "c100", true, true, 123456);
yield return new RenewTrackCommand(new EdgeId(3));
yield return new UpgradeTrackCommand(new EdgeId(3), "c160", true, true);
yield return new DemolishCommand(DemolishTarget.Signal, 8);
yield return new BuildStationCommand(P, 4);
yield return new BuildDepotCommand(P, "medium", "Officina");
yield return new PlaceSignalCommand(new EdgeId(2), 812.5);
yield return new BuyVehicleCommand("loco_steam_1850", new DepotId(1), 2);
yield return new SellVehicleCommand(new VehicleId(9));
yield return new ComposeTrainCommand(new DepotId(1), [new VehicleId(1), new VehicleId(2)], "Treno 1");
yield return new CreateLineCommand("Linea 1", "#4f7cac", [new LineStop(new StationId(1), true, false, true, 3), new LineStop(new StationId(2))]);
yield return new EditLineCommand(new LineId(1), [new LineStop(new StationId(2))]);
yield return new AssignTrainCommand(new TrainId(4), LineId.None);
yield return new SendToDepotCommand(new TrainId(4), new DepotId(0));
yield return new SetReserveCommand(new TrainId(4), true);
yield return new SetMaintenancePolicyCommand(MaintenanceScope.Line, 2, "thorough");
yield return new ScheduleServiceCommand(new TrainId(4), "overhaul");
yield return new OrderPartsCommand(new DepotId(1), 30);
yield return new OrderPartsCommand(DepotId.None, 25) { Industry = new IndustryId(4) };
yield return new TakeLoanCommand(Money.FromLire(50000));
yield return new RepayLoanCommand(new LoanId(1), new Money(999));
yield return new AcceptAgreementCommand(new AgreementId(5));
yield return new RejectAgreementCommand(new AgreementId(6));
yield return new BuyGoodsCommand(new StationId(1), "coal", 100, new Money(4000));
yield return new SellGoodsCommand(new StationId(2), "steel", 50, new Money(15000));
yield return new BuyIndustryCommand(new IndustryId(3), Money.FromLire(1_000_000));
yield return new SetIndustryPolicyCommand(new IndustryId(3), IndustryBudget.High);
yield return new OverhaulIndustryCommand(new IndustryId(3));
yield return new UpgradeIndustryCommand(new IndustryId(3));
yield return new IpoCommand(0.3);
yield return new BuySharesCommand(new CompanyId(2), 10_000, new Money(1500));
yield return new SellSharesCommand(new CompanyId(2), 5_000, new Money(1400));
yield return new PayDividendCommand(new Money(12));
yield return new LaunchBidCommand(new CompanyId(1), new Money(2000), 0.51);
yield return new RespondBidCommand(new BidId(1), false);
yield return new RespondBidCommand(new BidId(2), false) { Defense = BidDefense.WhiteKnight, Knight = new CompanyId(3) };
yield return new BuyConcessionCommand(new RegionId(2));
yield return new AcceptContractCommand(new ContractId(8));
yield return new FundResearchCommand("electric_traction", Money.FromLire(20000));
yield return new DelegateRegionCommand(new RegionId(1), "crescita", Money.FromLire(500000));
yield return new MergeCompanyCommand(new CompanyId(2));
}
[Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")]
public static void EveryMessageRoundTrips()
{
var seen = new HashSet<MessageId>();
foreach (var m in SampleMessages())
{
byte[] frame = Frame.Encode(m);
var decoded = Frame.Decode(frame);
Assert.Equal(m.GetType(), decoded.GetType());
Assert.Equal(m.Id, decoded.Id);
Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(decoded)), $"{m.Id}: i byte ricodificati differiscono");
seen.Add(m.Id);
}
foreach (var id in Enum.GetValues<MessageId>()) Assert.True(seen.Contains(id), $"manca l'esemplare di {id}");
}
[Test(Description = "Ogni tipo di comando sopravvive al round-trip dentro un messaggio Command")]
public static void EveryCommandRoundTrips()
{
var seen = new HashSet<CommandType>();
foreach (var c in SampleCommands())
{
var message = new CommandMessage { Seq = 17, Command = c };
byte[] frame = Frame.Encode(message);
var decoded = (CommandMessage)Frame.Decode(frame);
Assert.Equal(c.GetType(), decoded.Command.GetType());
Assert.Equal(17u, decoded.Command.Seq);
Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(decoded)), $"{c.Type}: i byte ricodificati differiscono");
seen.Add(c.Type);
}
foreach (var t in Enum.GetValues<CommandType>()) Assert.True(seen.Contains(t), $"manca l'esemplare del comando {t}");
}
[Test]
public static void FieldsSurviveTheRoundTrip()
{
var track = (BuildTrackCommand)((CommandMessage)Frame.Decode(Frame.Encode(new CommandMessage { Seq = 1, Command = SampleCommands().First() }))).Command;
Assert.Equal(3, track.Polyline.Count);
Assert.Equal(P, track.Polyline[0]);
Assert.Equal("c100", track.TrackClass);
Assert.True(track.DoubleTrack && track.Electrified && !track.AllowBridges);
Assert.Equal(123456L, track.ExpectedCostCents);
var chunk = (MapChunk)Frame.Decode(Frame.Encode(SampleChunk()));
Assert.True(chunk.Heights.AsSpan().SequenceEqual(SampleChunk().Heights));
Assert.True(chunk.RiverWidth.AsSpan().SequenceEqual(SampleChunk().RiverWidth));
var hello = (Hello)Frame.Decode(Frame.Encode(SampleMessages().OfType<Hello>().First()));
Assert.Equal(Frame.ProtocolVersion, hello.ProtocolVersion);
Assert.Equal("segreto", hello.Token);
var delta = (EntityDelta)Frame.Decode(Frame.Encode(SampleMessages().OfType<EntityDelta>().First()));
Assert.Equal((EntityType.Station, 9), delta.Removed[1]);
Assert.Equal("Treno 12", delta.Changed.Trains[0].Name);
Assert.True(delta.Changed.Lines[0].Stops[1].WaitFull);
}
[Test(Description = "Frame troncati o corrotti producono solo ProtocolException")]
public static void TruncatedAndCorruptedFramesFailCleanly()
{
var rng = new Rng(2024);
foreach (var m in SampleMessages())
{
byte[] frame = Frame.Encode(m);
for (int cut = 0; cut < frame.Length; cut += Math.Max(1, frame.Length / 17))
{
byte[] part = frame.AsSpan(0, cut).ToArray();
Assert.Throws<ProtocolException>(() => Frame.Decode(part), $"{m.Id} troncato a {cut}");
}
for (int k = 0; k < 40; k++)
{
byte[] bad = (byte[])frame.Clone();
int at = Frame.HeaderSize + rng.NextInt(Math.Max(1, bad.Length - Frame.HeaderSize));
if (at >= bad.Length) continue;
bad[at] ^= (byte)(1 + rng.NextInt(255));
try
{
Frame.Decode(bad);
}
catch (ProtocolException)
{
}
}
}
// un messaggio sconosciuto e una lunghezza incoerente
Assert.Throws<ProtocolException>(() => Frame.Decode([2, 0, 0, 0, 0xE7, 0x03]));
Assert.Throws<ProtocolException>(() => Frame.Decode([9, 0, 0, 0, 2, 0, 1]));
}
[Test(Description = "Un lettore ignora i byte di estensione che non conosce (campi futuri in coda)")]
public static void ReadersIgnoreUnknownTrailingFields()
{
byte[] frame = Frame.Encode(new Ping { Nonce = 5 });
byte[] longer = new byte[frame.Length + 3];
frame.CopyTo(longer, 0);
longer[frame.Length - 1] = 1; // flags: un blocco opzionale segue
longer[frame.Length] = 0xAA;
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(longer, (uint)(longer.Length - 4));
var ping = (Ping)Frame.Decode(longer);
Assert.Equal(5UL, ping.Nonce);
}
[Test]
public static void VarUIntAndStringsEncodeCompactly()
{
var w = new SpanWriter(8);
w.VarUInt(0);
w.VarUInt(127);
w.VarUInt(128);
w.VarUInt(ulong.MaxValue);
w.String("città");
var r = new SpanReader(w.ToArray());
Assert.Equal(0UL, r.VarUInt());
Assert.Equal(127UL, r.VarUInt());
Assert.Equal(128UL, r.VarUInt());
Assert.Equal(ulong.MaxValue, r.VarUInt());
Assert.Equal("città", r.String());
Assert.Equal(0, r.Remaining);
Assert.Equal(1 + 1 + 2 + 10 + 1 + 6, w.Length);
}
}
public static class CommandLogTests
{
[Test(Description = "Registro dei comandi: salvataggio di partenza + comandi riapplicati ai loro tick = stesso hash")]
public static void RecordedCommandsReplayToTheSameState()
{
var f = RailEnterprise.Tests.Rail.RailFixture.Valdoria();
var w = f.W;
byte[] start = RailEnterprise.Core.Persistence.SaveFile.Save(w, "test");
w.CommandLog = [];
var (mine, mill, depot) = f.BuildFreightNetwork(waitForConstruction: false);
f.Ok(new TakeLoanCommand(Money.FromLire(10_000)));
w.RunDays(3);
var file = new MemoryStream();
CommandLogFile.WriteHeader(file);
foreach (var (tick, command) in w.CommandLog) CommandLogFile.Append(file, tick, command);
long endTick = w.Clock.Tick;
ulong expected = RailEnterprise.Core.Persistence.StateHasher.Compute(w);
var commands = CommandLogFile.ReadAll(file.ToArray());
Assert.Equal(w.CommandLog.Count, commands.Count);
var replay = RailEnterprise.Core.Persistence.SaveFile.Load(TestData.Data, start);
int next = 0;
while (replay.Clock.Tick < endTick)
{
while (next < commands.Count && commands[next].Tick == replay.Clock.Tick) replay.Enqueue(commands[next++].Command);
replay.Tick();
}
Assert.Equal(commands.Count, next);
Assert.Equal(expected, RailEnterprise.Core.Persistence.StateHasher.Compute(replay));
Assert.True(mine >= 0 && mill >= 0 && depot >= 0);
}
}
@@ -0,0 +1,204 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Tests.Harness;
using static RailEnterprise.Tests.Rail.RailFixture;
namespace RailEnterprise.Tests.Rail;
public static class CommutingTests
{
/// <summary>Linea operai Borgo Ceresio ↔ acciaieria con un deposito sulla diramazione.</summary>
private static (RailFixture F, Industry Mill, int Train, int Line) WorkersLine(int coaches, int staffCoaches = 0)
{
var f = Valdoria();
int mill = f.Ok(new BuildStationCommand(K(10.6, 5.4), 2, "Acciaieria"));
int borgo = f.Ok(new BuildStationCommand(K(12.4, 8.0), 2, "Borgo Ceresio"));
int depot = f.Ok(new BuildDepotCommand(K(11.6, 7.4), "small", "Deposito di Borgo"));
f.Ok(new BuildTrackCommand(f.Scenario!.Route("borgo", f.Me).Polyline));
f.Ok(new BuildTrackCommand(new[] { K(11.6, 7.4), K(11.7, 6.85) }));
Assert.True(f.RunUntil(() => f.W.Network.Edges.All(e => e.State == EdgeState.Active), 400), "cantieri completati");
int train = staffCoaches > 0
? f.Train(depot, "Operai 1", ("loco_steam_1850", 1), ("coach_worker", coaches), ("coach_staff", staffCoaches))
: f.Train(depot, "Operai 1", ("loco_steam_1850", 1), ("coach_worker", coaches));
int line = f.Ok(new CreateLineCommand("Operai di Borgo", "#4f7cac",
new[] { new LineStop(new StationId(borgo)), new LineStop(new StationId(mill)) }));
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
return (f, f.W.Industries.First(i => i.Def.Id == "steel_mill"), train, line);
}
/// <summary>Avanza fino a dopo il prossimo abbinamento mensile.</summary>
private static void RunToNextMonth(RailFixture f)
{
long month = f.W.Clock.Day / f.W.Calendar.DaysPerMonth;
while (f.W.Clock.Day / f.W.Calendar.DaysPerMonth == month) f.W.RunDays(1);
f.W.RunDays(1);
}
[Test(Description = "Pendolarismo (14.5): con città raggiungibile e capacità sufficiente la copertura supera 0.9 in 60 giorni")]
public static void ReachableTownWithCapacityCoversJobsWithinSixtyDays()
{
var (f, mill, _, _) = WorkersLine(coaches: 2);
RunToNextMonth(f);
var contracts = f.W.Commutes.Where(c => !c.Walking && c.Workplace.Index == mill.Id.Value && c.Category == PaxClass.Worker).ToList();
Assert.True(contracts.Count > 0, "contratti su rotaia creati all'abbinamento mensile");
Assert.Equal(mill.JobsWorkers - (int)Math.Round(mill.JobsWorkers * f.W.Data.Balance.Industry.OnSiteWorkerShare), contracts.Sum(c => c.Headcount));
foreach (var c in contracts)
{
Assert.Equal("Borgo Ceresio", f.W.Towns[c.Town.Value].Name);
Assert.True(c.ExpectedMinutes <= f.W.Data.Balance.Employment.WorkerMaxMinutes);
}
f.W.RunDays(60);
foreach (var c in contracts) Assert.True(c.Coverage > 0.9, $"copertura del contratto {c.Coverage:F2}");
Assert.True(mill.CovWorkers > 0.9, $"copertura dei lavoratori dell'acciaieria {mill.CovWorkers:F2}");
Assert.True(f.W.Player.YearEntries[(int)LedgerEntry.PassengerRevenue] > 0, "tariffe incassate");
Assert.Equal(0L, f.W.MoneyBalanceSum());
}
[Test(Description = "L'abbinamento non supera la capacità residua stimata della linea")]
public static void MatchingRespectsLineCapacity()
{
var (f, mill, _, line) = WorkersLine(coaches: 1);
// l'acciaieria al livello 3 offre più posti di quanti una carrozza ne porti
mill.Level = 3;
RunToNextMonth(f);
var graph = f.W.LineGraphs.For(f.W, f.Me);
double seats = graph.DailyCapacity[line].Workers * f.W.Data.Balance.Employment.LineCapacityUtilization;
int contracted = f.W.Commutes.Where(c => !c.Walking).Sum(c => c.Headcount);
Assert.True(contracted > 0 && contracted <= seats, $"{contracted} pendolari per {seats:F0} posti al giorno");
Assert.True(contracted < EmploymentOpen(f, mill), "restano posti scoperti per mancanza di carrozze");
}
private static int EmploymentOpen(RailFixture f, Industry mill) =>
mill.JobsWorkers - (int)Math.Round(mill.JobsWorkers * f.W.Data.Balance.Industry.OnSiteWorkerShare);
[Test(Description = "Senza più treni sulla linea i contratti si sciolgono e la città se ne lamenta")]
public static void ContractsDissolveWhenTheRouteDisappears()
{
var (f, mill, train, _) = WorkersLine(coaches: 2);
RunToNextMonth(f);
Assert.True(f.W.Commutes.Any(c => !c.Walking));
var borgo = f.W.Towns.First(t => t.Name == "Borgo Ceresio");
int employedBefore = borgo.EmployedWorkers;
f.Ok(new AssignTrainCommand(new TrainId(train), LineId.None));
RunToNextMonth(f);
Assert.False(f.W.Commutes.Any(c => !c.Walking), "contratti sciolti");
Assert.True(borgo.WorkDissatisfaction > 0, "insoddisfazione «lavoro»");
Assert.True(borgo.EmployedWorkers < employedBefore, "i lavoratori tornano liberi");
Assert.True(f.W.Events.Recent.Any(e => e.Text.Contains("perdono il posto", StringComparison.Ordinal)));
Assert.Equal(0, mill.ContractedWorkers);
}
[Test(Description = "Il personale qualificato viene solo da città con servizi: Borgo Ceresio non ne fornisce")]
public static void StaffComesOnlyFromTownsWithServices()
{
var (f, mill, _, _) = WorkersLine(coaches: 2, staffCoaches: 1);
RunToNextMonth(f);
Assert.True(f.W.Commutes.Any(c => !c.Walking && c.Category == PaxClass.Worker));
Assert.False(f.W.Commutes.Any(c => !c.Walking && c.Category == PaxClass.Staff));
Assert.True(mill.StaffPresent < mill.JobsStaff, "il personale resta scoperto");
}
[Test(Description = "I depositi assumono pendolari: senza servizi in città manca il personale e l'officina rallenta")]
public static void DepotsHireCommutersAndExplainMissingStaff()
{
// il deposito di Borgo Ceresio: la città è troppo piccola per avere personale qualificato
var (f, _, _, _) = WorkersLine(coaches: 2);
var officina = f.W.Network.Depots[0];
Assert.True(officina.JobsWorkers > 0 && officina.JobsStaff == officina.Stalls * f.W.Data.Maintenance.Depots.StaffPerStall);
RunToNextMonth(f);
var borgo = f.W.Towns.First(t => t.Name == "Borgo Ceresio");
Assert.Equal(0, borgo.StaffPool(f.W.Data.Balance.Town));
Assert.Equal(officina.JobsWorkers, officina.ContractedWorkers);
Assert.True(f.W.Commutes.Any(c => c.Walking && c.Workplace == officina.Ref && c.Category == PaxClass.Worker), "lavoratori a piedi");
Assert.Approx(officina.JobsWorkers, officina.WorkersPresent, 1e-9);
Assert.Equal(UncoveredReason.NoStaffServices, officina.StaffReason);
Assert.True(FleetMaintenanceSystem.WorkRate(f.W, officina) < 0.5, "senza personale l'officina lavora a un terzo");
// quando la città ha i servizi, il personale arriva a piedi e l'officina lavora a pieno ritmo
var g = Valdoria();
var net = g.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 0);
var full = g.W.Network.Depots[net.Officina];
Assert.True(g.W.Towns.First(t => t.Name == "Valdoria").StaffPool(g.W.Data.Balance.Town) > 0);
RunToNextMonth(g);
Assert.Equal(full.JobsStaff, full.ContractedStaff);
Assert.Approx(full.JobsStaff, full.StaffPresent, 1e-9);
Assert.Equal(UncoveredReason.None, full.StaffReason);
Assert.Approx(1.0, FleetMaintenanceSystem.WorkRate(g.W, full), 1e-12);
}
[Test(Description = "Registro degli impieghi: posti scoperti per mancanza di stazioni o di capacità delle carrozze")]
public static void RegisterExplainsUncoveredJobs()
{
var bare = Valdoria();
RunToNextMonth(bare);
var lonelyMill = bare.W.Industries.First(i => i.Def.Id == "steel_mill");
Assert.Equal(UncoveredReason.NoStation, lonelyMill.WorkersReason);
var (f, mill, _, line) = WorkersLine(coaches: 1);
mill.Level = 3;
RunToNextMonth(f);
Assert.Equal(UncoveredReason.LineCapacity, mill.WorkersReason);
Assert.Equal(line, mill.WorkersReasonLine.Value);
// la linea non ha carrozze per tecnici e nessuna città è a distanza pedonale
Assert.Equal(UncoveredReason.NoTownInReach, mill.StaffReason);
}
[Test(Description = "Convenzioni: l'industria propone, il vettore accetta e incassa il canone; senza capacità salta con penale")]
public static void AgreementIsProposedPaidAndBrokenWithPenalty()
{
var (f, mill, train, _) = WorkersLine(coaches: 2);
CommuteAgreement? proposal = null;
for (int m = 0; m < 12 && proposal is null; m++)
{
RunToNextMonth(f);
proposal = f.W.Agreements.FirstOrDefault(a => a.State == AgreementState.Proposed);
}
Assert.True(proposal is not null, "proposta entro un anno");
Assert.Equal(mill.Id, proposal!.Industry);
Assert.True(proposal.SeatsPerDay >= f.W.Data.Balance.Employment.Agreements.MinSeats);
Assert.True(f.W.Events.Recent.Any(e => e.Severity == EventSeverity.Opportunity && e.Text.Contains("convenzione", StringComparison.Ordinal)));
Assert.False(f.Do(new AcceptAgreementCommand(new AgreementId(999))).Ok);
f.Ok(new AcceptAgreementCommand(proposal.Id));
Assert.Equal(AgreementState.Active, proposal.State);
Assert.False(f.Do(new RejectAgreementCommand(proposal.Id)).Ok, "non si rifiuta una convenzione attiva");
long fees = f.W.Player.YearEntries[(int)LedgerEntry.Contracts] + f.W.Player.LastYearEntries[(int)LedgerEntry.Contracts];
RunToNextMonth(f);
long feesAfter = f.W.Player.YearEntries[(int)LedgerEntry.Contracts] + f.W.Player.LastYearEntries[(int)LedgerEntry.Contracts];
Assert.True(feesAfter - fees >= proposal.MonthlyFee.Cents, "canone mensile incassato");
Assert.Equal(AgreementState.Active, proposal.State);
// senza treni la capacità garantita manca: dopo 30 giorni la convenzione salta con penale
f.Ok(new AssignTrainCommand(new TrainId(train), LineId.None));
Assert.True(f.RunUntil(() => proposal.State == AgreementState.Broken, 90), $"convenzione ancora {proposal.State}");
Assert.True(f.W.Player.YearEntries[(int)LedgerEntry.Penalties] < 0, "penale pagata");
Assert.True(f.W.Events.Recent.Any(e => e.Text.Contains("saltata", StringComparison.Ordinal)));
Assert.Equal(0L, f.W.MoneyBalanceSum());
}
[Test(Description = "Una convenzione rifiutata non viene riproposta prima del periodo di attesa")]
public static void RejectedAgreementWaitsBeforeANewProposal()
{
var (f, _, _, _) = WorkersLine(coaches: 2);
CommuteAgreement? proposal = null;
for (int m = 0; m < 12 && proposal is null; m++)
{
RunToNextMonth(f);
proposal = f.W.Agreements.FirstOrDefault(a => a.State == AgreementState.Proposed);
}
Assert.True(proposal is not null);
f.Ok(new RejectAgreementCommand(proposal!.Id));
Assert.Equal(AgreementState.Rejected, proposal.State);
int cooldown = f.W.Data.Balance.Employment.Agreements.CooldownMonths;
for (int m = 0; m < cooldown - 1; m++)
{
RunToNextMonth(f);
Assert.False(f.W.Agreements.Any(a => a.State == AgreementState.Proposed), "nessuna nuova proposta durante l'attesa");
}
}
}
@@ -0,0 +1,341 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Tests.Harness;
using static RailEnterprise.Tests.Rail.RailFixture;
namespace RailEnterprise.Tests.Rail;
public static class MaintenanceTests
{
private static MaintenanceFile M => TestData.Data.Maintenance;
[Test(Description = "Manutenzione (14.5): il rischio di guasto non cresce con la condizione")]
public static void HazardFallsAsConditionRises()
{
double previous = double.MaxValue;
for (double c = 0; c <= 100; c += 0.5)
{
double h = Fleet.Hazard(c, M.Failure);
Assert.True(h <= previous + 1e-15, $"rischio {h} a condizione {c} oltre {previous}");
Assert.True(h > 0, "rischio positivo");
previous = h;
}
Assert.Approx(M.Failure.H0 / M.Failure.HealthyDivisor, Fleet.Hazard(80, M.Failure), 1e-12);
Assert.Approx(M.Failure.H0 * Math.Exp(0.8), Fleet.Hazard(40, M.Failure), 1e-9);
}
[Test(Description = "Manutenzione (14.5): l'usura cresce con km, pendenza, alta velocità, carico, età e difficoltà")]
public static void WearGrowsWithEveryFactor()
{
var p = M.Wear;
double Wear(double km = 100, double grade = 0.2, double fast = 0.3, double load = 0.5, double age = 1, double diff = 1) =>
Fleet.DailyWear(0.25, km, grade, fast, load, age, diff, p);
Assert.Equal(0.0, Wear(km: 0));
Assert.Approx(0.25, Fleet.DailyWear(0.25, 100, 0, 0, 0, 1, 1, p), 1e-12);
double base0 = Wear();
Assert.True(Wear(km: 200) > base0);
Assert.True(Wear(grade: 0.5) > base0);
Assert.True(Wear(fast: 0.9) > base0);
Assert.True(Wear(load: 1) > base0);
Assert.True(Wear(age: 1.5) > base0);
Assert.True(Wear(diff: 1.3) > base0);
}
[Test(Description = "Manutenzione (14.5): senza interventi la condizione dei componenti non sale mai")]
public static void ComponentsNeverImproveWithoutAnIntervention()
{
var f = Valdoria();
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
var w = f.W;
var trains = net.Trains.Select(id => w.Trains[id]).ToList();
var before = trains.SelectMany(t => t.Vehicles).ToDictionary(v => v.Value, v => (double[])w.Vehicles[v.Value].Components.Clone());
var records = trains.ToDictionary(t => t.Id.Value, t => t.History.Count > 0 ? t.History[^1] : default);
bool worn = false;
for (int d = 0; d < 150; d++)
{
w.RunDays(1);
foreach (var t in trains)
{
var last = t.History.Count > 0 ? t.History[^1] : default;
bool intervention = last != records[t.Id.Value];
records[t.Id.Value] = last;
foreach (var id in t.Vehicles)
{
var now = w.Vehicles[id.Value].Components;
for (int j = 0; j < now.Length; j++)
{
if (!intervention) Assert.True(now[j] <= before[id.Value][j] + 1e-12, $"{t.Name}: componente {j} risalito senza intervento");
if (now[j] < before[id.Value][j]) worn = true;
}
before[id.Value] = (double[])now.Clone();
}
}
}
Assert.True(worn, "i treni in servizio si usurano");
Assert.True(trains.Any(t => t.History.Count > 0), "il pianificatore ha mandato i treni in officina");
}
/// <summary>Treno fermo nel deposito (senza binari), con i componenti impostati.</summary>
private static (RailFixture F, Train Train, Depot Depot) TrainInDepot(params double[] components)
{
var f = Valdoria();
int depot = f.Ok(new BuildDepotCommand(K(13.2, 5.4), "medium", "Officina di Valdoria"));
int train = f.Train(depot, "Prova", ("loco_steam_1850", 1), ("wagon_box", 1));
var t = f.W.Trains[train];
foreach (var id in t.Vehicles)
{
var v = f.W.Vehicles[id.Value];
for (int j = 0; j < v.Components.Length; j++) v.Components[j] = components[j % components.Length];
}
return (f, t, f.W.Network.Depots[depot]);
}
[Test(Description = "Manutenzione (14.5): tagliando, revisione e ispezione riportano la condizione attesa, scalata dalla politica")]
public static void ServiceAndOverhaulRestoreTheExpectedCondition()
{
var (f, t, _) = TrainInDepot(20, 45, 70, 90);
var w = f.W;
var standard = M.Policy(MaintenancePolicy.Standard);
var economy = M.Policy(MaintenancePolicy.Economy);
var snapshot = t.Vehicles.Select(id => (double[])w.Vehicles[id.Value].Components.Clone()).ToList();
void Reset()
{
for (int k = 0; k < t.Vehicles.Count; k++) snapshot[k].CopyTo(w.Vehicles[t.Vehicles[k].Value].Components, 0);
}
Fleet.Apply(w, t, M.Intervention("service"), standard);
for (int k = 0; k < t.Vehicles.Count; k++)
{
var v = w.Vehicles[t.Vehicles[k].Value];
for (int j = 0; j < v.Components.Length; j++) Assert.Approx(Math.Min(100, snapshot[k][j] + 40), v.Components[j], 1e-9);
Assert.Equal(w.Clock.Day, v.LastServiceDay);
}
Reset();
Fleet.Apply(w, t, M.Intervention("service"), economy);
Assert.Approx(20 + 40 * 0.7, w.Vehicles[t.Vehicles[0].Value].Components[0], 1e-9);
Reset();
Fleet.Apply(w, t, M.Intervention("overhaul"), standard);
foreach (var id in t.Vehicles) Assert.True(w.Vehicles[id.Value].Components.All(c => Math.Abs(c - 100) < 1e-9), "revisione: tutto a 100");
Reset();
Fleet.Apply(w, t, M.Intervention("overhaul"), economy);
Assert.Approx(20 + 80 * 0.7, w.Vehicles[t.Vehicles[0].Value].Components[0], 1e-9);
Reset();
Fleet.Apply(w, t, M.Intervention("inspection"), standard);
var loco = w.Vehicles[t.Vehicles[0].Value];
var comps = Fleet.ComponentsOf(w.Data, loco.Def);
for (int j = 0; j < comps.Count; j++)
{
double expected = comps[j].Id == Fleet.Brakes ? 100 : Math.Min(100, snapshot[0][j] + 10);
Assert.Approx(expected, loco.Components[j], 1e-9, comps[j].Id);
}
Assert.Equal(w.Clock.Day + M.Inspection.HazardDays, loco.HazardReducedUntilDay);
// la revisione riduce il fattore d'età di un veicolo oltre la vita utile, senza scendere sotto 1
loco.BoughtDay = w.Clock.Day - 40L * w.Calendar.DaysPerYear;
Assert.Approx(2.5, Fleet.AgeFactor(w, loco), 1e-9);
Fleet.Apply(w, t, M.Intervention("overhaul"), standard);
Assert.Approx(2.0, Fleet.AgeFactor(w, loco), 1e-9);
for (int i = 0; i < 5; i++) Fleet.Apply(w, t, M.Intervention("overhaul"), standard);
Assert.Approx(1.0, Fleet.AgeFactor(w, loco), 1e-9);
}
[Test(Description = "Un tagliando programmato in officina preleva i ricambi, si paga e riporta la condizione attesa")]
public static void ScheduledServiceRunsInTheWorkshop()
{
var (f, t, depot) = TrainInDepot(30, 50, 65, 80);
var w = f.W;
var before = t.Vehicles.Select(id => (double[])w.Vehicles[id.Value].Components.Clone()).ToList();
int parts = depot.SpareParts;
long costs = w.Player.YearEntries[(int)LedgerEntry.FleetMaintenance];
var r = f.Do(new ScheduleServiceCommand(t.Id, "service"));
Assert.True(r.Ok, r.Message);
Assert.True(t.InWorkshop, "il treno è già nel deposito: entra subito in officina");
Assert.False(f.Do(new ScheduleServiceCommand(t.Id, "service")).Ok, "non si prenota due volte");
Assert.True(f.RunUntil(() => t.History.Count == 1, 20), "tagliando completato");
Assert.False(t.InWorkshop);
Assert.Equal(parts - t.Vehicles.Count, depot.SpareParts);
long price = t.Vehicles.Sum(id => w.Vehicles[id.Value].Def.Price);
Assert.Equal(-(long)Math.Round(price * M.Intervention("service").CostShare), w.Player.YearEntries[(int)LedgerEntry.FleetMaintenance] - costs);
for (int k = 0; k < t.Vehicles.Count; k++)
{
var v = w.Vehicles[t.Vehicles[k].Value];
for (int j = 0; j < v.Components.Length; j++) Assert.Approx(Math.Min(100, before[k][j] + 40), v.Components[j], 1e-9);
}
Assert.Equal(M.InterventionIndex("service"), t.History[0].Intervention);
Assert.False(f.Do(new ScheduleServiceCommand(t.Id, "repair_minor")).Ok, "le riparazioni non si programmano");
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
}
[Test(Description = "Manutenzione (14.5): con politica Standard e ricambi disponibili il pianificatore non lascia scendere un treno sotto 30")]
public static void PlannerKeepsTrainsAboveThirtyWithStandardPolicyAndParts()
{
var f = Valdoria();
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
var w = f.W;
var officina = w.Network.Depots[net.Officina];
// ricambi abbondanti, contabilizzati come importati
w.Goods.Imported[w.Data.SparePartsGood] += 390;
officina.SpareParts += 390;
officina.PartsTarget = 400;
var trains = net.Trains.Select(id => w.Trains[id]).ToList();
double min = 100;
for (int d = 0; d < 2 * w.Calendar.DaysPerYear; d++)
{
w.RunDays(1);
foreach (var t in trains) min = Math.Min(min, Fleet.TrainCondition(w, t));
}
Assert.True(min >= w.Data.Maintenance.Planner.CriticalCondition, $"condizione minima {min:F1}");
Assert.True(trains.All(t => t.History.Count > 0));
Assert.True(trains.Sum(t => t.MaintenanceThisYear + t.MaintenanceLastYear) > 0, "interventi pagati");
}
/// <summary>Avanza a tick finché il treno non è in marcia in linea, carico se richiesto.</summary>
private static void RunUntilMoving(World w, Train t, bool loaded = false)
{
for (int i = 0; i < 400 * w.Calendar.TicksPerDay; i++)
{
w.RunTicks(1);
if (t.State == TrainState.Moving && !t.AtNode.IsValid && t.Speed > 1 && (!loaded || t.Cargo.Any(p => p.Kind == PacketKind.Freight)))
return;
}
throw new AssertionException($"{t.Name} non è mai in marcia");
}
[Test(Description = "Guasto grave: fermo in linea fino al soccorso, rimorchio all'officina, riserva sulla linea durante la riparazione")]
public static void MajorFailureRescueRepairAndReserveCover()
{
var f = Valdoria();
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
var w = f.W;
int reserveId = f.Train(net.Officina, "Riserva 1", ("loco_steam_1850", 1));
Assert.True(f.Do(new SetReserveCommand(new TrainId(reserveId), true)).Ok);
var reserve = w.Trains[reserveId];
var t = w.Trains[net.Trains[0]];
RunUntilMoving(w, t);
double hours = FleetMaintenanceSystem.RescueHours(w, t);
var officina = w.Network.Depots[net.Officina];
double viaCrew = Vec2.Distance(Fleet.Position(w, t), officina.Position) / 1000 / M.Failure.RescueSpeedKmh + M.Failure.RescueExtraHours;
Assert.True(hours < viaCrew, "la locomotiva di riserva arriva prima della squadra");
var engine = w.Vehicles[t.Vehicles[0].Value];
FleetMaintenanceSystem.Fail(w.Context, t, FailureKind.Major, engine, 0);
Assert.Equal(TrainState.Broken, t.State);
Assert.True(t.Held.Count > 0, "il treno fermo tiene il binario");
long rescue = t.RescueTick;
Assert.True(rescue > w.Clock.Tick);
w.RunTicks(rescue - w.Clock.Tick + 1);
Assert.True(t.State != TrainState.Broken, "soccorso arrivato");
Assert.True(t.Towed && t.TopSpeedKmh <= M.Failure.RescueSpeedKmh + 1e-9, "rimorchiato a 40 km/h");
Assert.Equal(net.Officina, t.MaintenanceDepot.Value);
Assert.True(f.RunUntil(() => t.InWorkshop, 60), "in officina");
Assert.True(f.RunUntil(() => t.CoveredBy.IsValid, 5), "la riserva copre la linea");
Assert.Equal(t.Line, reserve.Line);
Assert.True(f.RunUntil(() => t.Failure == FailureKind.None && !t.InWorkshop, 60), "riparato");
Assert.Equal(M.InterventionIndex("repair_major"), t.History[^1].Intervention);
Assert.False(t.Towed);
Assert.Equal(TrainId.None, t.CoveredBy);
Assert.Equal(LineId.None, reserve.Line);
Assert.True(f.RunUntil(() => reserve.State == TrainState.InDepot, 30), "la riserva rientra in deposito");
Assert.True(t.FailuresTotal >= 1);
}
[Test(Description = "Deragliamento: carico perso (contabilizzato), binario chiuso tre giorni, notizia negativa")]
public static void DerailmentLosesCargoAndClosesTheTrack()
{
var f = Valdoria();
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
var w = f.W;
var t = w.Trains[net.Trains[0]];
RunUntilMoving(w, t, loaded: true);
var edge = w.Network.Edges[t.Route[t.RouteIndex].Edge.Value];
int cargo = t.Cargo.Where(p => p.Kind == PacketKind.Freight).Sum(p => p.Units);
Assert.True(cargo > 0);
long decayed = w.Goods.Decayed.Sum();
FleetMaintenanceSystem.Fail(w.Context, t, FailureKind.Catastrophic, w.Vehicles[t.Vehicles[0].Value], 0);
Assert.Equal(TrainState.Broken, t.State);
Assert.Equal(0, t.Cargo.Count);
Assert.Equal(decayed + cargo, w.Goods.Decayed.Sum());
Assert.False(edge.IsUsable, "binario danneggiato");
Assert.True(w.Events.Recent.Any(e => e.Severity == EventSeverity.Critical && e.Text.Contains("Deragliamento", StringComparison.Ordinal)));
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
w.RunDays(M.Failure.DerailmentTrackDays + 1);
Assert.True(edge.IsUsable, "binario riaperto dopo tre giorni");
Assert.Equal(M.InterventionIndex("repair_catastrophic"), f.RunUntil(() => t.MaintenanceDepot.IsValid, 20) ? t.PlannedIntervention : -1);
}
[Test(Description = "I ricambi arrivano in treno dall'hub del porto fino all'officina e ne ricostituiscono la scorta")]
public static void SparePartsReachTheWorkshopByTrain()
{
var f = Valdoria();
var net = f.BuildMaintenanceNetwork(partsLine: true, trainsPerLine: 1);
var w = f.W;
var officina = w.Network.Depots[net.Officina];
int good = w.Data.SparePartsGood;
long imported = w.Goods.Imported[good];
Assert.True(w.Network.Stations[net.Valdoria].Depots.Contains(officina.Id), "l'officina è nel bacino di Valdoria");
int maxStock = 0;
for (int d = 0; d < 120; d++)
{
w.RunDays(1);
maxStock = Math.Max(maxStock, officina.SpareParts);
}
Assert.True(w.Goods.Imported[good] > imported, "ricambi importati dal porto");
Assert.True(maxStock >= officina.PartsTarget, $"scorta massima {maxStock} su {officina.PartsTarget}");
Assert.True(w.Goods.Consumed[good] > 0, "ricambi usati dagli interventi");
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Politiche di manutenzione: treno, poi linea, poi compagnia; scorta desiderata dei ricambi")]
public static void PoliciesOverrideAndPartsOrders()
{
var f = Valdoria();
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
var w = f.W;
var t = w.Trains[net.Trains[0]];
Assert.Equal(MaintenancePolicy.Standard, Fleet.PolicyOf(w, t).Id);
f.Ok(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, "economy"));
Assert.Equal(MaintenancePolicy.Economy, Fleet.PolicyOf(w, t).Id);
f.Ok(new SetMaintenancePolicyCommand(MaintenanceScope.Line, net.Lines[0], "thorough"));
Assert.Equal(MaintenancePolicy.Thorough, Fleet.PolicyOf(w, t).Id);
Assert.Equal(MaintenancePolicy.Economy, Fleet.PolicyOf(w, w.Trains[net.Trains[1]]).Id);
f.Ok(new SetMaintenancePolicyCommand(MaintenanceScope.Train, t.Id.Value, "standard"));
Assert.Equal(MaintenancePolicy.Standard, Fleet.PolicyOf(w, t).Id);
f.Ok(new SetMaintenancePolicyCommand(MaintenanceScope.Train, t.Id.Value, "inherit"));
Assert.Equal(MaintenancePolicy.Thorough, Fleet.PolicyOf(w, t).Id);
Assert.False(f.Do(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, "inherit")).Ok);
Assert.False(f.Do(new SetMaintenancePolicyCommand(MaintenanceScope.Line, 99, "standard")).Ok);
Assert.False(f.Do(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, "lusso")).Ok);
f.Ok(new OrderPartsCommand(new DepotId(net.Officina), 120));
Assert.Equal(120, w.Network.Depots[net.Officina].PartsTarget);
Assert.False(f.Do(new OrderPartsCommand(new DepotId(net.Officina), M.Depots.MaxSpareParts + 1)).Ok);
Assert.False(f.Do(new OrderPartsCommand(new DepotId(net.Officina), -1)).Ok);
}
[Test(Description = "Lo stato della manutenzione (officine, prenotazioni, guasti) sopravvive al salvataggio")]
public static void MaintenanceStateSurvivesSaveAndLoad()
{
var f = Valdoria();
var net = f.BuildMaintenanceNetwork(partsLine: true, trainsPerLine: 1);
var w = f.W;
Assert.True(f.RunUntil(() => w.Network.Depots[net.Officina].Jobs.Any(j => j.Started), 120), "un lavoro in officina");
var t = w.Trains[net.Trains[1]];
FleetMaintenanceSystem.Fail(w.Context, t, FailureKind.Minor, w.Vehicles[t.Vehicles[0].Value], 0);
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
Assert.Equal(w.Network.Depots[net.Officina].Jobs.Count, loaded.Network.Depots[net.Officina].Jobs.Count);
w.RunDays(60);
loaded.RunDays(60);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
}
}
@@ -0,0 +1,148 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Scenarios;
using RailEnterprise.Tests.Harness;
using RailEnterprise.Tests.Scenarios;
namespace RailEnterprise.Tests.Rail;
/// <summary>Mondo con comandi di comodo per i test ferroviari.</summary>
public sealed class RailFixture
{
public World W { get; }
public LoadedScenario? Scenario { get; }
public CompanyId Me => W.Player.Id;
public RailFixture(World w, LoadedScenario? scenario = null)
{
W = w;
Scenario = scenario;
}
public static RailFixture Valdoria() { var s = ScenarioHelper.Load("valdoria"); return new RailFixture(s.World, s); }
public static Vec2 K(double x, double y) => new(x * 1000, y * 1000);
/// <summary>Esegue il comando nel prossimo tick e ne restituisce l'esito.</summary>
public CommandResult Do(GameCommand c, CompanyId? issuer = null)
{
W.Enqueue(c with { Issuer = issuer ?? Me });
W.RunTicks(1);
return W.DrainResults().Last();
}
public int Ok(GameCommand c, CompanyId? issuer = null)
{
var r = Do(c, issuer);
Assert.True(r.Ok, $"{c.Type}: {r.Error} {r.Message}");
return r.Created.Length > 0 ? r.Created[0] : -1;
}
/// <summary>Esegue giorni finché la condizione è vera (o scade il limite).</summary>
public bool RunUntil(Func<bool> condition, int maxDays)
{
for (int d = 0; d < maxDays * 8; d++)
{
if (condition()) return true;
W.RunTicks(W.Calendar.TicksPerDay / 8);
}
return condition();
}
/// <summary>Compra veicoli e compone un treno nel deposito.</summary>
public int Train(int depot, string loco, int locos, string car, int cars, string name)
{
var ids = new List<VehicleId>();
ids.AddRange(W_Buy(loco, depot, locos));
if (cars > 0) ids.AddRange(W_Buy(car, depot, cars));
return Ok(new ComposeTrainCommand(new DepotId(depot), ids, name));
}
/// <summary>Compra veicoli di più tipi e compone un treno nel deposito.</summary>
public int Train(int depot, string name, params (string Type, int Count)[] vehicles)
{
var ids = new List<VehicleId>();
foreach (var (type, count) in vehicles) ids.AddRange(W_Buy(type, depot, count));
return Ok(new ComposeTrainCommand(new DepotId(depot), ids, name));
}
private IEnumerable<VehicleId> W_Buy(string type, int depot, int count) =>
Do(new BuyVehicleCommand(type, new DepotId(depot), count)).Created.Select(i => new VehicleId(i));
/// <summary>
/// Rete merci di Valdoria: stazione delle miniere, stazione dell'acciaieria, deposito e
/// tracciato per il valico; restituisce (miniera, acciaieria, deposito).
/// </summary>
public (int Mine, int Mill, int Depot) BuildFreightNetwork(bool waitForConstruction = true)
{
int mine = Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna"));
int mill = Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria"));
int depot = Ok(new BuildDepotCommand(K(2.6, 4.4), "small", "Deposito Rocca Bruna"));
Ok(new BuildTrackCommand(Scenario!.Route("valico", Me).Polyline, AllowTunnels: false));
Ok(new BuildTrackCommand(new[] { K(2.6, 4.4), K(2.92, 4.95) }));
if (waitForConstruction)
Assert.True(RunUntil(() => W.Network.Edges.All(e => e.State == EdgeState.Active), 400), "cantieri completati");
return (mine, mill, depot);
}
/// <summary>
/// Rete di Valdoria dimensionata per la manutenzione (F4): miniere, acciaieria (6 binari), Borgo
/// Ceresio, Valdoria (4 binari), officina media di Valdoria sulla diramazione a sud-est della
/// stazione; facoltativamente la stazione del Porto di Levante con la linea dei ricambi verso
/// Valdoria. Tre linee (merci, operai, tecnici) con <paramref name="trainsPerLine"/> treni ciascuna,
/// tutti comprati nell'officina.
/// </summary>
public MaintenanceNet BuildMaintenanceNetwork(bool partsLine, int trainsPerLine)
{
W.Money.Transfer(Core.Economy.Account.External, Core.Economy.Account.Of(Me), new Money(50_000_000_00), Core.Economy.LedgerEntry.Other);
int mine = Ok(new BuildStationCommand(K(2.2, 2.6), 3, "Rocca Bruna"));
int mill = Ok(new BuildStationCommand(K(10.6, 5.4), 6, "Acciaieria"));
int borgo = Ok(new BuildStationCommand(K(12.4, 8.0), 2, "Borgo Ceresio"));
int valdoria = Ok(new BuildStationCommand(K(12.8, 4.9), 4, "Valdoria"));
int officina = Ok(new BuildDepotCommand(K(13.2, 5.4), "medium", "Officina di Valdoria"));
Ok(new BuildTrackCommand(Scenario!.Route("valico", Me).Polyline, AllowTunnels: false));
Ok(new BuildTrackCommand(Scenario!.Route("borgo", Me).Polyline));
Ok(new BuildTrackCommand(Scenario!.Route("valdoria", Me).Polyline));
Ok(new BuildTrackCommand(new[] { K(13.2, 5.4), K(12.8, 4.9) }));
int port = -1;
if (partsLine)
{
port = Ok(new BuildStationCommand(K(14.5, 6.3), 2, "Porto di Levante"));
Ok(new BuildTrackCommand(new[] { K(14.5, 6.3), K(13.7, 6.0), K(13.2, 5.4) }));
}
Assert.True(RunUntil(() => W.Network.Edges.All(e => e.State == EdgeState.Active), 500), "cantieri completati");
var lines = new[]
{
Ok(new CreateLineCommand("Linea 1, minerale e acciaio", "#e0a526",
new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)), new LineStop(new StationId(valdoria)) })),
Ok(new CreateLineCommand("Linea 2, operai di Borgo", "#4f7cac",
new[] { new LineStop(new StationId(borgo)), new LineStop(new StationId(mill)) })),
Ok(new CreateLineCommand("Linea 3, tecnici di Valdoria", "#b3573e",
new[] { new LineStop(new StationId(valdoria)), new LineStop(new StationId(mill)) })),
};
var trains = new List<int>();
for (int n = 1; n <= trainsPerLine; n++)
{
trains.Add(Train(officina, $"Merci {n}", ("loco_steam_1850", 1), ("wagon_hopper", 6), ("wagon_flat", 2)));
Ok(new AssignTrainCommand(new TrainId(trains[^1]), new LineId(lines[0])));
trains.Add(Train(officina, $"Operai {n}", ("loco_steam_1850", 1), ("coach_worker", 2)));
Ok(new AssignTrainCommand(new TrainId(trains[^1]), new LineId(lines[1])));
trains.Add(Train(officina, $"Tecnici {n}", ("loco_steam_1850", 1), ("coach_staff", 1)));
Ok(new AssignTrainCommand(new TrainId(trains[^1]), new LineId(lines[2])));
}
int partsTrain = -1;
if (partsLine)
{
partsTrain = Train(officina, "Ricambi 1", ("loco_steam_1850", 1), ("wagon_box", 2));
int line = Ok(new CreateLineCommand("Linea 4, ricambi dal porto", "#7a5c9e",
new[] { new LineStop(new StationId(port)), new LineStop(new StationId(valdoria)) }));
Ok(new AssignTrainCommand(new TrainId(partsTrain), new LineId(line)));
}
return new MaintenanceNet(mine, mill, borgo, valdoria, officina, port, lines, trains, partsTrain);
}
}
/// <summary>Identificativi della rete di prova della manutenzione.</summary>
public sealed record MaintenanceNet(int Mine, int Mill, int Borgo, int Valdoria, int Officina, int Port, int[] Lines, List<int> Trains, int PartsTrain);
@@ -0,0 +1,130 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Tests.Harness;
using static RailEnterprise.Tests.Rail.RailFixture;
namespace RailEnterprise.Tests.Rail;
public static class RailNetworkTests
{
[Test(Description = "Il tracciato del valico si completa nei giorni previsti dal piano e il costo è addebitato")]
public static void TrackIsBuiltInPlannedDays()
{
var f = Valdoria();
var cash = f.W.Player.Cash;
var r = f.Do(new BuildTrackCommand(f.Scenario!.Route("valico", f.Me).Polyline, AllowTunnels: false));
Assert.True(r.Ok, r.Message);
var edge = f.W.Network.Edges[r.Created[0]];
var project = f.W.Network.Projects[r.Created[3]];
Assert.Equal(EdgeState.UnderConstruction, edge.State);
Assert.True(f.W.Player.Cash < cash, "costo addebitato");
f.RunUntil(() => edge.State == EdgeState.Active, 400);
Assert.Equal(EdgeState.Active, edge.State);
Assert.Approx(project.TotalDays, project.ProgressDays, 1.0, "giorni di cantiere");
Assert.Equal(0L, f.W.MoneyBalanceSum());
}
[Test(Description = "Le squadre limitano i cantieri contemporanei: con due squadre il terzo progetto aspetta")]
public static void CrewsLimitConcurrentProjects()
{
var f = Valdoria();
f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.3), K(14.3, 7.3) }));
f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.6), K(14.3, 7.6) }));
f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.9), K(14.3, 7.9) }));
f.W.RunDays(2);
var projects = f.W.Network.Projects;
Assert.Equal(2, ConstructionSystem.Crews(f.W, f.W.Player));
Assert.True(projects[0].Crew >= 0 && projects[1].Crew >= 0);
Assert.Equal(-1, projects[2].Crew, "terzo progetto in attesa");
Assert.True(f.RunUntil(() => projects.All(p => p.Done), 200));
Assert.True(projects[2].StartedDay >= projects[0].StartedDay + projects[0].TotalDays - 1);
}
[Test]
public static void AttachingToTrackSplitsTheEdge()
{
var f = Valdoria();
int main = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }));
f.Ok(new BuildTrackCommand(new[] { K(12.5, 9.53), K(12.5, 11.0) }));
var net = f.W.Network;
Assert.Equal(3, net.Edges.Count);
var junction = net.Nodes[net.Edges[main].B.Value];
Assert.Equal(3, junction.Edges.Count, "scambio con tre archi");
Assert.Approx(12500, junction.Position.X, 13);
Assert.Approx(3000, net.Edges[main].Length + net.Edges[1].Length, 1e-6, "le due metà sommano la lunghezza originale");
Assert.True(f.RunUntil(() => net.Edges.All(e => e.State == EdgeState.Active), 100), "anche la metà nuova finisce col cantiere");
}
[Test(Description = "Attraversare il binario di un'altra compagnia richiede un cavalcavia automatico")]
public static void CrossingForeignTrackBuildsAnOverpass()
{
var f = Valdoria();
// lo scenario non ha concorrenti: se ne aggiunge uno fermo (agenti sospesi)
f.W.AiPaused = true;
var rival = WorldFactory.CreateAiCompany(f.W, f.W.Stream("companies")).Id;
f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }), rival);
var r = f.Do(new BuildTrackCommand(new[] { K(12.5, 8.8), K(12.5, 10.2) }));
Assert.True(r.Ok, r.Message);
var edge = f.W.Network.Edges[r.Created[0]];
Assert.True(edge.LengthOf(WorkKind.Bridge) > 0, "cavalcavia");
int k = Enumerable.Range(0, edge.S.Length).MinBy(i => Math.Abs(edge.Y[i] - 9500));
double otherH = f.W.Network.Edges[0].HeightAt(1500);
Assert.True(edge.H[k] >= otherH + f.W.Data.Construction.Rules.OverpassClearanceM - 0.5, "franco sul binario altrui");
// incrociare a raso il proprio binario è vietato
var own = f.Do(new BuildTrackCommand(new[] { K(13.5, 9.0), K(13.5, 10.0) }), rival);
Assert.Equal(CommandError.InvalidTrack, own.Error);
}
[Test]
public static void InvalidRequestsAreRejectedWithoutSideEffects()
{
var f = Valdoria();
var cash = f.W.Player.Cash;
Assert.Equal(CommandError.InvalidTrack, f.Do(new BuildTrackCommand(f.Scenario!.Route("diretto", f.Me).Polyline, AllowTunnels: false)).Error);
Assert.Equal(CommandError.NotAllowed, f.Do(new BuildStationCommand(K(13.6, 4.6), 2)).Error, "stazione dentro la città");
Assert.Equal(CommandError.InvalidArgument, f.Do(new BuildDepotCommand(K(5, 5), "huge")).Error);
Assert.Equal(CommandError.NotFound, f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(3))).Error);
Assert.Equal(cash, f.W.Player.Cash);
Assert.Equal(0, f.W.Network.Edges.Count);
f.W.Money.Transfer(RailEnterprise.Core.Economy.Account.Of(f.Me), RailEnterprise.Core.Economy.Account.External, f.W.Player.Cash, RailEnterprise.Core.Economy.LedgerEntry.Other);
Assert.Equal(CommandError.InsufficientFunds, f.Do(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) })).Error);
}
[Test]
public static void StationsHaveCatchmentsAndDemolitionRefunds()
{
var f = Valdoria();
int mill = f.Ok(new BuildStationCommand(K(10.6, 5.4), 3, "Acciaieria"));
var st = f.W.Network.Stations[mill];
Assert.True(st.Industries.Any(i => f.W.Industries[i.Value].Def.Id == "steel_mill"));
Assert.True(st.Towns.Count == 0, "Valdoria è oltre il bacino di 2 km");
int track = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }));
var before = f.W.Player.Cash;
Assert.True(f.Do(new DemolishCommand(DemolishTarget.Edge, track)).Ok);
Assert.True(f.W.Player.Cash > before, "rimborso del 10 %");
Assert.True(f.Do(new DemolishCommand(DemolishTarget.Station, mill)).Ok);
Assert.Equal(0L, f.W.MoneyBalanceSum());
}
[Test]
public static void SignalsSplitBlocksAndRenewalRestoresCondition()
{
var f = Valdoria();
int track = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }));
f.RunUntil(() => f.W.Network.Edges[track].State == EdgeState.Active, 50);
Assert.True(f.Do(new PlaceSignalCommand(new EdgeId(track), 1500)).Ok);
var e = f.W.Network.Edges[track];
Assert.Equal(2, e.BlocksForward.Length);
Assert.Approx(1500, TrainSystem.BlockEnd(e, true, 0), 1e-9);
Assert.Approx(1500, TrainSystem.BlockEnd(e, false, 0), 1e-9);
e.Condition = 40;
Assert.Approx(0.6, ConstructionSystem.ConditionFactor(f.W, e), 1e-12);
Assert.True(f.Do(new RenewTrackCommand(new EdgeId(track))).Ok);
Assert.Equal(EdgeState.Closed, e.State);
f.RunUntil(() => e.State == EdgeState.Active, 50);
Assert.Equal(100.0, e.Condition);
}
}
@@ -0,0 +1,44 @@
using RailEnterprise.Core.Map;
namespace RailEnterprise.Tests.Rail;
/// <summary>Terreni costruiti a mano per i test del pianificatore (celle da 100 m).</summary>
public static class SyntheticTerrain
{
public static Terrain Build(int width, int height, Func<double, double, double> heightAtMeters, Func<int, int, CellType>? type = null)
{
var t = new Terrain(width, height, 100, 64);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double hx = (x + 0.5) * 100, hy = (y + 0.5) * 100;
t.Heights[t.Index(x, y)] = Terrain.ToDecimeters(heightAtMeters(hx, hy));
t.Types[t.Index(x, y)] = (byte)(type?.Invoke(x, y) ?? CellType.Plain);
}
}
return t;
}
public static Terrain Flat(int size = 60, double h = 100) => Build(size, size, (_, _) => h);
/// <summary>Collina a cupola centrata in (cx, cy) metri.</summary>
public static Func<double, double, double> Hill(double cx, double cy, double radiusM, double heightM, double baseM = 100) =>
(x, y) =>
{
double r = Math.Sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / radiusM;
return baseM + (r >= 1 ? 0 : heightM * (1 - r * r) * (1 - r * r));
};
/// <summary>Pianura con un fiume nord-sud largo «widthCells» celle intorno a x = riverX metri.</summary>
public static Terrain River(int size, double riverXm, int widthCells, double baseM = 100, double waterM = 96)
{
int x0 = (int)(riverXm / 100) - widthCells / 2;
var t = Build(size, size, (x, _) => (int)(x / 100) >= x0 && (int)(x / 100) < x0 + widthCells ? waterM : baseM,
(x, _) => x >= x0 && x < x0 + widthCells ? CellType.Water : CellType.Plain);
for (int y = 0; y < size; y++)
for (int x = x0; x < x0 + widthCells; x++)
t.RiverWidth[t.Index(x, y)] = (byte)Math.Min(4, widthCells);
return t;
}
}
@@ -0,0 +1,170 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Map;
using RailEnterprise.Core.Rail;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Rail;
public static class TrackPlannerTests
{
private static TrackPlanContext Ctx(Terrain t, int year = 1850, double costMultiplier = 1.0) =>
new() { Data = TestData.Data, Sampler = new TerrainSampler(t), Year = year, CostMultiplier = costMultiplier };
private static TrackPlanRequest Line(params (double X, double Y)[] pts) =>
new() { Polyline = pts.Select(p => new Vec2(p.X, p.Y)).ToList(), AllowBridges = true, AllowTunnels = true };
[Test]
public static void FlatStraightLineIsAllNaturalWithExpectedCostAndDays()
{
var plan = TrackPlanner.Plan(Ctx(SyntheticTerrain.Flat()), Line((1000, 3000), (3000, 3000)));
Assert.True(plan.Valid, string.Join("; ", plan.Errors.Select(e => e.Message)));
Assert.Equal(1, plan.Works.Count);
Assert.Equal(WorkKind.Natural, plan.Works[0].Kind);
Assert.Approx(2000, plan.LengthM, 1e-6);
Assert.Equal(81, plan.Samples.Count, "un campione ogni 25 m");
var c = TestData.Data.Construction;
Assert.Equal((long)Math.Round(2000 * c.Costs.BasePerMeter), plan.WorksCost.Cents);
Assert.Equal(10, plan.Days, "200 m al giorno su sede naturale");
Assert.Approx(0, plan.MaxGradient, 1e-12);
}
[Test(Description = "Le due passate rispettano gMax ovunque e lasciano gli estremi alla quota del terreno")]
public static void ProfileRespectsMaxGradientOnRandomTerrain()
{
var rng = new Rng(77);
for (int trial = 0; trial < 25; trial++)
{
var noise = new ValueNoise(rng.NextU64());
double amp = rng.NextDouble(20, 200);
var t = SyntheticTerrain.Build(80, 80, (x, y) => 300 + amp * noise.Fbm(x, y, 4, 3000, 0.5, 2));
var req = Line((500, rng.NextDouble(500, 7500)), (4000, rng.NextDouble(500, 7500)), (7500, rng.NextDouble(500, 7500)))
with { HeightOffsetM = rng.NextDouble(-20, 20) };
var plan = TrackPlanner.Plan(Ctx(t), req);
if (!plan.Valid && plan.Errors.All(e => e.Code is PlanIssueCode.TunnelTooLong or PlanIssueCode.RadiusTooSmall)) continue;
Assert.True(plan.Valid, $"prova {trial}: {string.Join("; ", plan.Errors.Select(e => e.Message))}");
double g = plan.GradientLimit;
for (int i = 1; i < plan.Samples.Count; i++)
{
double grade = Math.Abs(plan.Samples[i].TrackM - plan.Samples[i - 1].TrackM) / (plan.Samples[i].S - plan.Samples[i - 1].S);
Assert.True(grade <= g + 1e-9, $"prova {trial}: pendenza {grade:P3} al km {plan.Samples[i].S / 1000:F2}");
}
Assert.Approx(plan.Samples[0].TerrainM, plan.Samples[0].TrackM, 0.05);
Assert.Approx(plan.Samples[^1].TerrainM, plan.Samples[^1].TrackM, 0.05);
}
}
[Test(Description = "Collina ripida senza gallerie: il tracciato viola gMax e viene rifiutato")]
public static void SteepHillWithoutTunnelsIsRejected()
{
var t = SyntheticTerrain.Build(60, 30, SyntheticTerrain.Hill(3000, 1500, 1200, 120));
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 1500), (5500, 1500)) with { AllowTunnels = false });
Assert.False(plan.Valid);
Assert.Equal(PlanIssueCode.GradientExceeded, plan.Errors[0].Code);
}
[Test]
public static void HillWithTunnelsProducesCuttingsAndATunnel()
{
var t = SyntheticTerrain.Build(60, 30, SyntheticTerrain.Hill(3000, 1500, 700, 50));
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 1500), (5500, 1500)));
Assert.True(plan.Valid, string.Join("; ", plan.Errors.Select(e => e.Message)));
Assert.True(plan.LengthOf(WorkKind.Tunnel) > 0, "galleria");
Assert.True(plan.LengthOf(WorkKind.Cutting) > 0, "trincee agli imbocchi");
Assert.True(plan.LengthOf(WorkKind.Tunnel) <= 1000, "entro il limite del 1850");
// la galleria costa 12 volte la sede naturale al metro
var tunnel = plan.Works.First(w => w.Kind == WorkKind.Tunnel);
Assert.Approx(12 * TestData.Data.Construction.Costs.BasePerMeter * tunnel.LengthM, tunnel.CostCents, tunnel.CostCents * 1e-9 + 1);
Assert.Equal((int)Math.Ceiling(tunnel.LengthM / 8), tunnel.Days, "8 m al giorno in galleria");
}
[Test]
public static void LongTunnelIsLimitedByEra()
{
var t = SyntheticTerrain.Build(80, 30, SyntheticTerrain.Hill(4000, 1500, 2600, 160));
var req = Line((300, 1500), (7700, 1500));
var early = TrackPlanner.Plan(Ctx(t, 1850), req);
Assert.True(early.Errors.Any(e => e.Code == PlanIssueCode.TunnelTooLong), "nel 1850 la galleria supera 1 km");
var later = TrackPlanner.Plan(Ctx(t, 1900), req);
Assert.True(later.Valid, string.Join("; ", later.Errors.Select(e => e.Message)));
}
[Test(Description = "Ponte obbligatorio sull'acqua, con luce libera e rampe entro gMax")]
public static void RiverRequiresBridgeWithClearance()
{
var t = SyntheticTerrain.River(60, 3000, 2);
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000)));
Assert.True(plan.Valid, string.Join("; ", plan.Errors.Select(e => e.Message)));
var bridge = plan.Works.Single(w => w.Kind == WorkKind.Bridge);
Assert.True(bridge.StartM < 2500 && bridge.EndM > 2500, "il ponte scavalca il fiume (x = 3 km, cioè s = 2,5 km)");
foreach (var s in plan.Samples.Where(s => s.Cell == CellType.Water))
Assert.True(s.TrackM >= s.TerrainM + TestData.Data.Construction.Profile.RiverClearanceM - 1e-6, "luce libera di 6 m");
Assert.True(plan.LengthOf(WorkKind.Embankment) > 0, "rampe in rilevato verso il ponte");
Assert.Equal("wood", plan.BridgeType);
var noBridges = TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000)) with { AllowBridges = false });
Assert.Equal(PlanIssueCode.BridgeNeeded, noBridges.Errors[0].Code);
}
[Test(Description = "Campata massima per era: un fiume di classe 3 (120 m) non si passa in legno (60 m) ma sì in ferro (150 m)")]
public static void WideRiverNeedsLongerSpanEra()
{
var t = SyntheticTerrain.River(60, 3000, 3, waterM: 96);
var plan1850 = TrackPlanner.Plan(Ctx(t, 1850), Line((500, 3000), (5500, 3000)));
Assert.True(plan1850.Errors.Any(e => e.Code == PlanIssueCode.BridgeTooLong), "nel 1850 il legno non basta");
var plan1870 = TrackPlanner.Plan(Ctx(t, 1870), Line((500, 3000), (5500, 3000)));
Assert.True(plan1870.Valid, string.Join("; ", plan1870.Errors.Select(e => e.Message)));
Assert.Equal("iron", plan1870.BridgeType);
}
[Test]
public static void ClassificationFollowsHeightDifference()
{
// valle leggera: con lo scostamento +6 m il binario corre in rilevato
var t = SyntheticTerrain.Flat(60);
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000)) with { HeightOffsetM = 6 });
Assert.True(plan.Valid);
Assert.True(plan.LengthOf(WorkKind.Embankment) > 3000, "rilevato di 6 m nel mezzo");
Assert.True(plan.Works.Where(w => w.Kind == WorkKind.Embankment).All(w => w.MaxHeightM <= 8 + 1e-9));
// con −6 m in trincea
var cut = TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000)) with { HeightOffsetM = -6 });
Assert.True(cut.LengthOf(WorkKind.Cutting) > 3000);
// il costo del rilevato cresce con l'altezza: ×(1 + 0,25·d)
Assert.True(plan.WorksCost.Cents > TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000))).WorksCost.Cents * 1.5);
}
[Test]
public static void SharpCurvesAreRejectedAndCurveSpeedIsLimited()
{
var t = SyntheticTerrain.Flat(60);
var tight = TrackPlanner.Plan(Ctx(t), Line((1000, 1000), (1100, 1000), (1100, 1100)));
Assert.True(tight.Errors.Any(e => e.Code == PlanIssueCode.RadiusTooSmall));
var ok = TrackPlanner.Plan(Ctx(t), Line((1000, 1000), (3000, 1000), (3000, 3000)));
Assert.True(ok.Valid, string.Join("; ", ok.Errors.Select(e => e.Message)));
Assert.Approx(200, ok.MinRadiusM, 1e-6);
double curveSpeed = 3.6 * Math.Sqrt(0.65 * 200);
Assert.Approx(curveSpeed, ok.Samples.Min(s => s.SpeedLimitKmh), 1e-6);
Assert.Approx(2000 + 2000 - 2 * 200 + Math.PI / 2 * 200, ok.LengthM, 1e-6, "lunghezza con il raccordo");
}
[Test]
public static void TownsAndIndustriesCannotBeCrossed()
{
var t = SyntheticTerrain.Build(60, 60, (_, _) => 100, (x, y) => x == 30 && y == 30 ? CellType.Town : CellType.Plain);
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 3050), (5500, 3050)));
Assert.Equal(PlanIssueCode.ForbiddenArea, plan.Errors[0].Code);
}
[Test]
public static void ClassMultipliesCostAndDifficultyToo()
{
var t = SyntheticTerrain.Flat();
var basePlan = TrackPlanner.Plan(Ctx(t, 1990), Line((500, 3000), (4500, 3000)));
var fast = TrackPlanner.Plan(Ctx(t, 1990), Line((500, 3000), (4500, 3000)) with { TrackClass = "c160", DoubleTrack = true, Electrified = true });
Assert.True(fast.Valid, string.Join("; ", fast.Errors.Select(e => e.Message)));
Assert.Approx(2.2 * 1.8 * 1.35, (double)fast.WorksCost.Cents / basePlan.WorksCost.Cents, 1e-6);
var hard = TrackPlanner.Plan(Ctx(t, 1990, 1.5), Line((500, 3000), (4500, 3000)));
Assert.Approx(1.5, (double)hard.TotalCost.Cents / basePlan.TotalCost.Cents, 1e-6);
var early = TrackPlanner.Plan(Ctx(t, 1850), Line((500, 3000), (4500, 3000)) with { TrackClass = "c160" });
Assert.Equal(PlanIssueCode.ClassNotAvailable, early.Errors[0].Code);
}
}
@@ -0,0 +1,94 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Rail;
using RailEnterprise.Tests.Harness;
using static RailEnterprise.Tests.Rail.RailFixture;
namespace RailEnterprise.Tests.Rail;
public static class TrainTests
{
private static (RailFixture F, Train Train, int Line) FreightLine(int wagons = 5)
{
var f = Valdoria();
var (mine, mill, depot) = f.BuildFreightNetwork();
int tr = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", wagons, "Treno 12");
int line = f.Ok(new CreateLineCommand("Linea 3, carbone", "#e0a526",
new[] { new LineStop(new StationId(mine), WaitFull: true, MaxWaitDays: 2), new LineStop(new StationId(mill)) }));
f.Ok(new AssignTrainCommand(new TrainId(tr), new LineId(line)));
return (f, f.W.Trains[tr], line);
}
[Test(Description = "La linea merci porta minerale e carbone all'acciaieria e il vettore incassa le tariffe")]
public static void FreightLineDeliversAndEarns()
{
var (f, t, _) = FreightLine();
var steel = f.W.Industries.First(i => i.Def.Id == "steel_mill");
long revenueBefore = f.W.Player.YearEntries[(int)LedgerEntry.FreightRevenue];
f.W.RunDays(60);
Assert.True(t.Odometer > 50_000, $"il treno ha viaggiato ({t.Odometer / 1000:F1} km)");
Assert.True(steel.InputStock.All(s => s > 0), "l'acciaieria riceve minerale e carbone");
Assert.True(f.W.Player.YearEntries[(int)LedgerEntry.FreightRevenue] > revenueBefore, "tariffe incassate");
Assert.True(steel.ServedWithin(f.W.Clock.Day, 10), "industria servita dal vettore");
Assert.Equal(0L, f.W.MoneyBalanceSum());
for (int g = 0; g < f.W.Data.GoodCount; g++)
Assert.Equal(f.W.Goods.ExpectedStock(g), f.W.TotalStock(g), $"merce {f.W.Data.Goods[g].Id}");
}
[Test(Description = "Due treni in versi opposti sullo stesso binario semplice si incrociano in stazione senza stallo")]
public static void OpposingTrainsOnSingleTrackDoNotDeadlock()
{
var (f, t1, line) = FreightLine();
int depot = f.W.Network.Depots[0].Id.Value;
int tr2 = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 5, "Treno 13");
var t2 = f.W.Trains[tr2];
// il secondo parte più tardi: i due si troveranno in versi opposti
f.W.RunDays(3);
f.Ok(new AssignTrainCommand(new TrainId(tr2), new LineId(line)));
f.W.RunDays(120);
Assert.True(t1.Odometer > 150_000 && t2.Odometer > 150_000, $"entrambi viaggiano: {t1.Odometer / 1000:F0} e {t2.Odometer / 1000:F0} km");
foreach (var e in f.W.Network.Edges) Assert.True(e.LockCount <= 2);
Assert.False(f.W.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal)));
}
[Test(Description = "Un treno troppo pesante per la salita resta fermo (Stalled) e genera un avviso")]
public static void OverloadedTrainStallsOnTheGrade()
{
var f = Valdoria();
var (mine, mill, depot) = f.BuildFreightNetwork();
int tr = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 20, "Treno pesante");
// carica forzata: 20 tramogge piene di minerale (contabilizzate come prodotte)
var t = f.W.Trains[tr];
int ore = f.W.Data.GoodIndex("iron_ore");
var st = f.W.Network.Stations[mine];
st.Waiting.Add(new Packet { Id = f.W.NextIds.Packet++, Kind = PacketKind.Freight, Good = ore, Units = 400, Origin = st.Id, Destination = new StationId(mill), HopLine = LineId.None, Contract = -1, ExpiresTick = long.MaxValue });
f.W.Goods.Produced[ore] += 400;
int line = f.Ok(new CreateLineCommand("Pesante", "#b3573e", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
for (int i = 0; i < st.Waiting.Count; i++) { var p = st.Waiting[i]; p.HopLine = new LineId(line); p.HopEnd = new StationId(mill); st.Waiting[i] = p; }
f.Ok(new AssignTrainCommand(new TrainId(tr), new LineId(line)));
Assert.True(f.RunUntil(() => t.State == TrainState.Stalled, 60), $"stato {t.State}");
Assert.True(f.W.Events.Recent.Any(e => e.Text.Contains("non supera la salita", StringComparison.Ordinal)));
}
[Test(Description = "Determinismo e salvataggio con treni in movimento")]
public static void TrainsAreDeterministicAndSurviveSaveLoad()
{
var (a, ta, _) = FreightLine();
a.W.RunDays(17);
a.W.RunTicks(77); // a metà strada, fuori dal confine del giorno
var b = SaveFile.Load(TestData.Data, SaveFile.Save(a.W, "test"));
Assert.Equal(StateHasher.Compute(a.W), StateHasher.Compute(b));
a.W.RunDays(40);
b.RunDays(40);
Assert.Equal(a.W.LastStateHash, b.LastStateHash);
Assert.Approx(ta.Odometer, b.Trains[ta.Id.Value].Odometer, 1e-9);
var (c, _, _) = FreightLine();
c.W.RunDays(17);
c.W.RunTicks(77);
c.W.RunDays(40);
Assert.Equal(a.W.LastStateHash, c.W.LastStateHash, "due esecuzioni identiche");
}
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Harness di test interno: nessun framework esterno, si esegue con dotnet run. -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>RailEnterprise.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RailEnterprise.Core\RailEnterprise.Core.csproj" />
<ProjectReference Include="..\..\src\RailEnterprise.Protocol\RailEnterprise.Protocol.csproj" />
<ProjectReference Include="..\..\src\RailEnterprise.Server\RailEnterprise.Server.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\data\**\*.json" LinkBase="data" CopyToOutputDirectory="PreserveNewest" />
<Content Include="scenarios\**\*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -0,0 +1,74 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Tests.Harness;
using RailEnterprise.Tests.Rail;
using static RailEnterprise.Tests.Rail.RailFixture;
namespace RailEnterprise.Tests.Scenarios;
public static class CommutingAcceptanceTests
{
/// <summary>
/// Rete di Valdoria con tre linee: merci (miniere → acciaieria → Valdoria, con minerale, carbone
/// e acciaio), lavoratori (Borgo Ceresio → acciaieria) e personale (Valdoria → acciaieria).
/// </summary>
internal static (RailFixture F, Core.Economy.Industry Mill) ThreeLines()
{
var f = Valdoria();
var (mine, mill, depot) = f.BuildFreightNetwork(waitForConstruction: false);
int borgo = f.Ok(new BuildStationCommand(K(12.4, 8.0), 2, "Borgo Ceresio"));
int valdoria = f.Ok(new BuildStationCommand(K(12.8, 4.9), 2, "Valdoria"));
f.Ok(new BuildTrackCommand(f.Scenario!.Route("borgo", f.Me).Polyline));
f.Ok(new BuildTrackCommand(f.Scenario!.Route("valdoria", f.Me).Polyline));
Assert.True(f.RunUntil(() => f.W.Network.Edges.All(e => e.State == EdgeState.Active), 500), "cantieri completati");
var steel = f.W.Industries.First(i => i.Def.Id == "steel_mill");
Assert.True(steel.Efficiency < 0.4, $"efficienza iniziale {steel.Efficiency:P0}");
int freight = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 6), ("wagon_flat", 2));
int workers = f.Train(depot, "Operai 1", ("loco_steam_1850", 1), ("coach_worker", 2));
int staff = f.Train(depot, "Tecnici 1", ("loco_steam_1850", 1), ("coach_staff", 1));
int lineFreight = f.Ok(new CreateLineCommand("Linea 1, minerale, carbone e acciaio", "#e0a526",
new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)), new LineStop(new StationId(valdoria)) }));
int lineWorkers = f.Ok(new CreateLineCommand("Linea 2, operai di Borgo", "#4f7cac",
new[] { new LineStop(new StationId(borgo)), new LineStop(new StationId(mill)) }));
int lineStaff = f.Ok(new CreateLineCommand("Linea 3, tecnici di Valdoria", "#b3573e",
new[] { new LineStop(new StationId(valdoria)), new LineStop(new StationId(mill)) }));
f.Ok(new AssignTrainCommand(new TrainId(freight), new LineId(lineFreight)));
f.Ok(new AssignTrainCommand(new TrainId(workers), new LineId(lineWorkers)));
f.Ok(new AssignTrainCommand(new TrainId(staff), new LineId(lineStaff)));
return (f, steel);
}
[Test(Description = "Accettazione F2: con tre linee (merci, lavoratori, personale) l'acciaieria passa da < 40 % a > 80 % in 2 anni senza stalli")]
public static void ThreeLinesBringTheSteelMillAboveEightyPercent()
{
var (f, steel) = ThreeLines();
int startLevel = steel.Level;
double bestMonth = 0;
int dpm = f.W.Calendar.DaysPerMonth;
for (int month = 0; month < 24; month++)
{
// media mensile dell'efficienza giornaliera: un picco di un giorno non basta
double sum = 0;
for (int d = 0; d < dpm; d++)
{
f.W.RunDays(1);
sum += steel.Efficiency;
}
bestMonth = Math.Max(bestMonth, sum / dpm);
}
Assert.True(bestMonth > 0.8, $"efficienza media mensile massima {bestMonth:P0}");
Assert.False(steel.Closed);
Assert.True(steel.Level >= startLevel, $"livello {steel.Level}");
Assert.False(f.W.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal)), "nessuno stallo");
Assert.True(f.W.Commutes.Any(c => !c.Walking && c.Category == PaxClass.Worker), "contratti di lavoratori su rotaia");
Assert.True(f.W.Commutes.Any(c => !c.Walking && c.Category == PaxClass.Staff), "contratti di personale su rotaia");
Assert.True(f.W.Player.YearEntries[(int)Core.Economy.LedgerEntry.PassengerRevenue] > 0, "tariffe dei pendolari incassate");
Assert.Equal(0L, f.W.MoneyBalanceSum());
for (int g = 0; g < f.W.Data.GoodCount; g++)
Assert.Equal(f.W.Goods.ExpectedStock(g), f.W.TotalStock(g), $"merce {f.W.Data.Goods[g].Id}");
}
}
@@ -0,0 +1,62 @@
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Tests.Harness;
using RailEnterprise.Tests.Rail;
using static RailEnterprise.Tests.Rail.RailFixture;
namespace RailEnterprise.Tests.Scenarios;
public static class MaintenanceAcceptanceTests
{
/// <summary>Esito di tre anni di esercizio della rete di prova con due treni per linea.</summary>
private sealed record FleetRun(double MinFleet, int FirstDayBelow40, int Failures, double ServiceKm, bool Stalls)
{
public double FailuresPerMillionKm => Failures / ServiceKm * 1e6;
}
private static FleetRun Run(bool partsLine)
{
var f = Valdoria();
var net = f.BuildMaintenanceNetwork(partsLine, trainsPerLine: 2);
var w = f.W;
var trains = net.Trains.Select(id => w.Trains[id]).ToList();
var lastOdo = new double[trains.Count];
double minFleet = 100, km = 0;
int firstBelow = -1;
int days = 3 * w.Calendar.DaysPerYear;
for (int d = 0; d < days; d++)
{
w.RunDays(1);
// flotta: media sui treni del componente più debole di ciascuno (ADR 0010)
double fleet = trains.Average(t => Fleet.TrainCondition(w, t));
minFleet = Math.Min(minFleet, fleet);
if (fleet < 40 && firstBelow < 0) firstBelow = d;
for (int k = 0; k < trains.Count; k++)
{
double odo = w.Vehicles[trains[k].Vehicles[0].Value].OdometerKm;
if (odo >= lastOdo[k]) km += odo - lastOdo[k];
lastOdo[k] = odo;
}
}
for (int g = 0; g < w.Data.GoodCount; g++)
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
Assert.Equal(0L, w.MoneyBalanceSum());
bool stalls = w.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal));
return new FleetRun(minFleet, firstBelow, trains.Sum(t => t.FailuresTotal), km, stalls);
}
[Test(Description = "Accettazione F4: senza linea dei ricambi la flotta scende sotto 40 entro 3 anni e i guasti raddoppiano; con la linea resta sopra 60")]
public static void WithoutSparePartsTheFleetDecaysWithTheLineItStaysAboveSixty()
{
var without = Run(partsLine: false);
var with = Run(partsLine: true);
Console.WriteLine($" senza linea: flotta minima {without.MinFleet:F0} (sotto 40 dal giorno {without.FirstDayBelow40}), {without.Failures} guasti, {without.FailuresPerMillionKm:F1} per milione di km");
Console.WriteLine($" con la linea: flotta minima {with.MinFleet:F0}, {with.Failures} guasti, {with.FailuresPerMillionKm:F1} per milione di km");
Assert.True(without.FirstDayBelow40 >= 0, $"senza ricambi la flotta resta a {without.MinFleet:F0}");
Assert.True(with.MinFleet > 60, $"con la linea dei ricambi la flotta scende a {with.MinFleet:F0}");
Assert.True(without.Failures >= 2 * Math.Max(1, with.Failures), $"guasti {without.Failures} senza linea contro {with.Failures} con la linea");
Assert.True(without.FailuresPerMillionKm >= 2 * with.FailuresPerMillionKm, "il tasso di guasto per km almeno raddoppia");
Assert.False(with.Stalls, "nessuno stallo della rete con la linea dei ricambi");
}
}
@@ -0,0 +1,34 @@
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Scenarios;
namespace RailEnterprise.Tests.Scenarios;
/// <summary>Accesso agli scenari di riferimento copiati accanto ai test.</summary>
public static class ScenarioHelper
{
public static string PathOf(string name)
{
string beside = Path.Combine(AppContext.BaseDirectory, "scenarios", name + ".json");
if (File.Exists(beside)) return beside;
var dir = new DirectoryInfo(Directory.GetCurrentDirectory());
while (dir is not null)
{
string candidate = Path.Combine(dir.FullName, "tests", "RailEnterprise.Tests", "scenarios", name + ".json");
if (File.Exists(candidate)) return candidate;
dir = dir.Parent;
}
throw new FileNotFoundException($"Scenario {name} non trovato");
}
public static LoadedScenario Load(string name) => ScenarioLoader.LoadFile(TestData.Data, PathOf(name));
public static TrackPlanContext PlanContext(World w) => new()
{
Data = w.Data,
Sampler = w.Sampler,
Year = w.Clock.Year,
CostMultiplier = w.Difficulty.ConstructionCostMultiplier,
NearestTownEdgeKm = p => w.Towns.Min(t => w.TownEdgeDistanceKm(t, p)),
};
}
@@ -0,0 +1,55 @@
using RailEnterprise.Core.Map;
using RailEnterprise.Core.Rail;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Scenarios;
public static class ValdoriaTests
{
[Test]
public static void ScenarioLoadsWithExpectedEntities()
{
var s = ScenarioHelper.Load("valdoria");
var w = s.World;
Assert.Equal(160, w.Terrain.Width);
Assert.Equal(3, w.Towns.Count);
Assert.Equal("Valdoria", w.Towns[0].Name);
Assert.Equal(12400, w.Towns[0].Population);
Assert.True(w.Industries.Any(i => i.Def.Id == "steel_mill"));
Assert.Equal(2, w.Sites.Count);
Assert.True(w.Terrain.Types.Count(t => t == (byte)CellType.Water) > 50, "fiume");
Assert.True(w.Terrain.Types.Count(t => t == (byte)CellType.Marsh) > 50, "palude");
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Accettazione F2: il tracciato diretto sulla collina viola gMax ed è rifiutato")]
public static void DirectRouteOverTheHillIsRejected()
{
var s = ScenarioHelper.Load("valdoria");
var plan = TrackPlanner.Plan(ScenarioHelper.PlanContext(s.World), s.Route("diretto", s.World.Player.Id));
Assert.False(plan.Valid);
Assert.Equal(PlanIssueCode.GradientExceeded, plan.Errors[0].Code);
// anche con le gallerie la collina richiede trafori oltre il limite del 1850
var tunnel = TrackPlanner.Plan(ScenarioHelper.PlanContext(s.World), s.Route("diretto_galleria", s.World.Player.Id));
Assert.True(tunnel.Errors.Any(e => e.Code == PlanIssueCode.TunnelTooLong));
}
[Test(Description = "Accettazione F2: il tracciato per il valico con trincea e ponte è accettato e costa più del doppio")]
public static void PassRouteWithCuttingAndBridgeIsAcceptedAndExpensive()
{
var s = ScenarioHelper.Load("valdoria");
var w = s.World;
var ctx = ScenarioHelper.PlanContext(w);
var plan = TrackPlanner.Plan(ctx, s.Route("valico", w.Player.Id));
Assert.True(plan.Valid, string.Join("; ", plan.Errors.Select(e => e.Message)));
Assert.True(plan.LengthOf(WorkKind.Cutting) > 0, "trincea nel valico");
Assert.True(plan.LengthOf(WorkKind.Bridge) > 0, "ponte sul fiume");
Assert.True(plan.MaxGradient <= plan.GradientLimit + 1e-9);
double naturalCost = plan.LengthM * w.Data.Construction.Costs.BasePerMeter * ctx.CostMultiplier + plan.LandCost.Cents;
Assert.True(plan.TotalCost.Cents > 2 * naturalCost, $"costo {plan.TotalCost} contro {naturalCost / 100:F0} lire in piano");
// tempi coerenti: somma delle opere alle velocità delle squadre
double expected = plan.Works.Sum(x => Math.Ceiling(x.LengthM / w.Data.Construction.Crews.MetersPerDay[TrackPlanner.KindKey(x.Kind)]));
Assert.Equal((int)expected, plan.Days);
Assert.InRange(plan.Days, 60, 400);
}
}
@@ -0,0 +1,322 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using RailEnterprise.Server;
using RailEnterprise.Tests.Harness;
using RailEnterprise.Tests.Scenarios;
namespace RailEnterprise.Tests.Server;
/// <summary>Server in processo su una porta casuale, con un client WebSocket vero.</summary>
public sealed class ServerFixture : IAsyncDisposable
{
public WebApplication App { get; }
public GameHost Host { get; }
public int Port { get; }
public string DataDir { get; }
public const string Token = "segreto-di-prova";
private ServerFixture(WebApplication app, string dataDir)
{
App = app;
DataDir = dataDir;
Host = app.Services.GetRequiredService<HostHolder>().Host!;
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses;
Port = new Uri(addresses.First()).Port;
}
public static ServerFixture Start(World world, int tickMs = 1)
{
string dir = Path.Combine(Path.GetTempPath(), "railenterprise-test-" + Path.GetRandomFileName());
var config = new ServerConfig { Local = true, Token = Token, TickMs = tickMs, AutosaveMinutes = 0, DataDir = dir, LogLevel = "Error" };
var app = ServerProgram.Build(config, [], world, TestData.Data);
app.Start();
return new ServerFixture(app, dir);
}
public Uri WebSocketUri => new($"ws://127.0.0.1:{Port}/ws");
public async ValueTask DisposeAsync()
{
await App.StopAsync();
await App.DisposeAsync();
try
{
Directory.Delete(DataDir, true);
}
catch (IOException)
{
}
}
}
/// <summary>Client di prova: applica i messaggi alla copia locale e raccoglie gli esiti dei comandi.</summary>
public sealed class TestClient : IAsyncDisposable
{
public ProtocolClient Connection { get; }
public ClientWorld World { get; } = new(TestData.Data);
public Dictionary<uint, CommandResultMessage> Results { get; } = [];
public List<IMessage> Received { get; } = [];
public Welcome Welcome { get; private set; } = null!;
private TestClient(ProtocolClient connection) => Connection = connection;
public static async Task<TestClient> ConnectAsync(ServerFixture server, ulong resume = 0)
{
var connection = await ProtocolClient.ConnectAsync(server.WebSocketUri);
var client = new TestClient(connection);
client.Welcome = await connection.HandshakeAsync(new Hello { ClientVersion = "test", Token = ServerFixture.Token, DataHash = TestData.Data.Hash, ResumeSessionId = resume });
client.World.Apply(client.Welcome);
return client;
}
/// <summary>Riceve e applica messaggi finché la condizione è vera.</summary>
public async Task<T> WaitFor<T>(Func<T?> condition, string what, int timeoutMs = 60_000) where T : class
{
using var cts = new CancellationTokenSource(timeoutMs);
while (true)
{
var value = condition();
if (value is not null) return value;
IMessage m;
try
{
m = await Connection.ReceiveAsync(cts.Token);
}
catch (OperationCanceledException)
{
throw new AssertionException($"tempo scaduto in attesa di: {what}");
}
Received.Add(m);
if (m is CommandResultMessage r) Results[r.Seq] = r;
World.Apply(m);
}
}
public Task<bool> WaitUntil(Func<bool> condition, string what, int timeoutMs = 60_000) =>
WaitFor(() => condition() ? (object)true : null, what, timeoutMs).ContinueWith(_ => true);
/// <summary>Invia un comando e ne attende l'esito.</summary>
public async Task<CommandResultMessage> Do(GameCommand command)
{
uint seq = await Connection.SendCommandAsync(command);
return await WaitFor(() => Results.GetValueOrDefault(seq), $"esito di {command.Type}");
}
public async Task<int> Ok(GameCommand command)
{
var r = await Do(command);
Assert.True(r.Ok, $"{command.Type}: {r.Error} {r.Message}");
return r.Created.Length > 0 ? r.Created[0] : -1;
}
public Task SubscribeAll() => Connection.SendAsync(new Subscribe
{
X0 = 0, Y0 = 0, X1 = World.Summary!.WidthCells - 1, Y1 = World.Summary.HeightCells - 1,
});
public ValueTask DisposeAsync() => Connection.DisposeAsync();
}
public static class ServerTests
{
private static Vec2 K(double x, double y) => new(x * 1000, y * 1000);
[Test(Slow = true, Description = "Accettazione F3 (senza grafica): linea con ponte costruita via WebSocket, anteprima identica al server, treno in moto con posizione coerente")]
public static void BuildLineWithBridgeOverTheNetworkAndWatchTheTrain() => Run().GetAwaiter().GetResult();
private static async Task Run()
{
var scenario = ScenarioHelper.Load("valdoria");
await using var server = ServerFixture.Start(scenario.World);
await using var client = await TestClient.ConnectAsync(server);
var w = client.World;
Assert.Equal(160, w.Summary!.WidthCells);
await client.SubscribeAll();
int chunks = ((w.Summary.WidthCells + 63) / 64) * ((w.Summary.HeightCells + 63) / 64);
await client.WaitUntil(() => w.Chunks.Count == chunks && w.Towns.Count == 3, "terreno e entità");
// il terreno ricevuto è identico a quello del server
Assert.Equal(scenario.World.Terrain.ComputeHash(), w.Terrain!.ComputeHash());
int mine = await client.Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna"));
int mill = await client.Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria"));
int depot = await client.Ok(new BuildDepotCommand(K(2.6, 4.4), "small", "Deposito"));
await client.WaitUntil(() => w.Stations.ContainsKey(mill) && w.Depots.ContainsKey(depot), "stazioni nella copia locale");
// anteprima del client = piano del server (il server rifiuta un costo diverso)
var valico = new BuildTrackCommand(scenario.Route("valico", w.Company).Polyline, AllowTunnels: false);
var preview = w.PreviewTrack(valico);
Assert.True(preview.Valid, string.Join("; ", preview.Errors.Select(e => e.Message)));
Assert.True(preview.LengthOf(WorkKind.Bridge) > 0, "il tracciato passa il fiume su un ponte");
int edge = await client.Ok(valico with { ExpectedCostCents = preview.TotalCost.Cents });
await client.WaitUntil(() => w.Edges.ContainsKey(edge), "arco del valico");
var info = w.Edges[edge];
Assert.Equal(preview.Samples.Count, info.S.Length);
for (int i = 0; i < info.S.Length; i++)
{
Assert.Equal(preview.Samples[i].TrackM, info.H[i], $"quota del campione {i}");
Assert.Equal((byte)preview.Samples[i].Kind, info.Kinds[i], $"opera del campione {i}");
}
var spur = new BuildTrackCommand([K(2.6, 4.4), K(2.92, 4.95)]);
var spurPreview = w.PreviewTrack(spur);
Assert.True(spurPreview.Valid);
await client.Ok(spur with { ExpectedCostCents = spurPreview.TotalCost.Cents });
// un'anteprima sbagliata viene respinta
var wrong = await client.Do(new BuildTrackCommand([K(3.0, 1.0), K(4.0, 1.2)], ExpectedCostCents: 1));
Assert.Equal((ushort)CommandError.PreviewMismatch, wrong.Error);
await client.Connection.SendAsync(new SetSpeed { Speed = 8 });
await client.WaitUntil(() => w.Edges.Count >= 3 && w.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri completati", 120_000);
var loco = await client.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var wagons = await client.Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3));
Assert.True(loco.Ok && wagons.Ok);
int train = await client.Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
int line = await client.Ok(new CreateLineCommand("Linea 1", "#e0a526", [new LineStop(new StationId(mine)), new LineStop(new StationId(mill))]));
await client.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Speed > 5, "treno in moto", 120_000);
// in pausa: la posizione disegnata dal client coincide con quella del server
await client.Connection.SendAsync(new SetSpeed { Speed = 0 });
// la pausa vale da quando il ciclo di gioco ha elaborato SetSpeed (sotto carico può tardare)
for (int i = 0; i < 500 && server.Host.Speed != 0; i++) await Task.Delay(10);
Assert.Equal((byte)0, server.Host.Speed);
long tick;
Vec2? head;
while (true)
{
(tick, head) = await server.Host.InvokeAsync(world => (world.Clock.Tick, Projection.HeadPoint(world, world.Trains[train])));
await Task.Delay(60);
long again = await server.Host.InvokeAsync(world => world.Clock.Tick);
if (again == tick) break;
}
// in pausa il server rimanda i moti dei treni in marcia ogni 100 ms
await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Tick == tick, "moto all'ultimo tick", 10_000);
var drawn = w.TrainHead(train);
Assert.True(drawn is not null && head is not null);
double gap = Vec2.Distance(drawn!.Value, head!.Value);
Assert.True(gap < w.Summary.CellSizeM, $"scarto tra client e server {gap:F2} m");
Assert.True(gap < 0.01, $"scarto atteso nullo, misurato {gap:F4} m");
Assert.True(client.Received.OfType<DailyDigest>().Any(), "resoconti giornalieri ricevuti");
}
[Test(Description = "F4 in rete: riepilogo di manutenzione nei record, cartella, registro officina e registro impieghi su richiesta")]
public static void MaintenanceDetailsOnRequest() => RunDetails().GetAwaiter().GetResult();
private static async Task RunDetails()
{
var scenario = ScenarioHelper.Load("valdoria");
await using var server = ServerFixture.Start(scenario.World, tickMs: 50);
await using var client = await TestClient.ConnectAsync(server);
var w = client.World;
await client.WaitFor(() => client.Received.OfType<EntitySnapshot>().FirstOrDefault(), "snapshot");
int depot = await client.Ok(new BuildDepotCommand(K(13.2, 5.4), "medium", "Officina di Valdoria"));
var loco = await client.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var wagon = await client.Do(new BuyVehicleCommand("wagon_box", new DepotId(depot), 1));
int train = await client.Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagon.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
await client.WaitUntil(() => w.Trains.ContainsKey(train) && w.Depots.ContainsKey(depot), "treno e officina nella copia locale");
Assert.Equal((byte)100, w.Trains[train].Condition);
Assert.Equal("inspection", w.Trains[train].NextIntervention);
Assert.Equal(4, w.Depots[depot].Stalls);
Assert.Equal(TestData.Data.Maintenance.Depots.InitialSpareParts, w.Depots[depot].SpareParts);
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.TrainCard, Target = train });
var card = await client.WaitFor(() => w.Cards.GetValueOrDefault(train), "cartella di manutenzione");
Assert.Equal(2, card.Vehicles.Count);
Assert.Equal(4, card.Vehicles[0].Components.Count);
Assert.Equal("engine", card.Vehicles[0].Components[0].Component);
Assert.Equal((byte)1, card.Policy);
await client.Ok(new ScheduleServiceCommand(new TrainId(train), "service"));
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Workshop, Target = depot });
var register = await client.WaitFor(() => w.Workshops.GetValueOrDefault(depot), "registro officina");
Assert.Equal(4, register.Stalls);
Assert.Equal(1, register.Jobs.Count);
Assert.Equal("service", register.Jobs[0].Intervention);
await client.WaitUntil(() => w.Trains[train].Maintenance == TrainMaintenanceStatus.InWorkshop, "treno in officina nel riepilogo");
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
var report = await client.WaitFor(() => w.Employment, "registro degli impieghi");
var row = report.Rows.FirstOrDefault(r => r.Kind == 1 && r.Industry == depot);
Assert.True(row is not null, "l'officina compare nel registro");
Assert.Equal(16, row!.JobsStaff);
// dettagli di entità altrui o inesistenti: nessuna risposta, nessun errore
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.TrainCard, Target = 999 });
await client.Connection.SendAsync(new Ping { Nonce = 5 });
await client.WaitFor(() => client.Received.OfType<Pong>().FirstOrDefault(p => p.Nonce == 5), "il server risponde ancora");
}
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();
private static async Task RunRejections()
{
await using var server = ServerFixture.Start(TestWorlds.Small(301), tickMs: 50);
async Task<RejectCode?> Try(Hello hello)
{
await using var c = await ProtocolClient.ConnectAsync(server.WebSocketUri);
try
{
await c.HandshakeAsync(hello);
return null;
}
catch (SessionRejectedException e)
{
return e.Reject.Code;
}
}
Assert.Equal(RejectCode.BadToken, await Try(new Hello { Token = "sbagliato" }));
Assert.Equal(RejectCode.DataMismatch, await Try(new Hello { Token = ServerFixture.Token, DataHash = 1 }));
Assert.Equal(RejectCode.ProtocolVersion, await Try(new Hello { Token = ServerFixture.Token, ProtocolVersion = 999 }));
Assert.Equal((RejectCode?)null, await Try(new Hello { Token = ServerFixture.Token }));
}
[Test(Description = "Ping, salvataggi, ripresa della sessione e API HTTP")]
public static void PingSavesResumeAndHttp() => RunMisc().GetAwaiter().GetResult();
private static async Task RunMisc()
{
await using var server = ServerFixture.Start(TestWorlds.Small(302), tickMs: 50);
ulong sessionId;
await using (var client = await TestClient.ConnectAsync(server))
{
sessionId = client.Welcome.SessionId;
await client.Connection.SendAsync(new Ping { Nonce = 41 });
var pong = await client.WaitFor(() => client.Received.OfType<Pong>().FirstOrDefault(), "pong");
Assert.Equal(41UL, pong.Nonce);
await client.Connection.SendAsync(new Save { Name = "prova rete" });
var list = await client.WaitFor(() => client.Received.OfType<SaveList>().FirstOrDefault(), "elenco dei salvataggi");
Assert.Equal(1, list.Saves.Count);
Assert.True(list.Saves[0].SaveId.StartsWith("prova_rete-", StringComparison.Ordinal), list.Saves[0].SaveId);
await client.WaitFor(() => client.Received.OfType<EntitySnapshot>().FirstOrDefault(), "snapshot");
}
// ripresa con lo stesso id: stessa sessione, stato rimandato per intero
await using (var again = await TestClient.ConnectAsync(server, resume: sessionId))
{
Assert.Equal(sessionId, again.Welcome.SessionId);
await again.WaitFor(() => again.Received.OfType<EntitySnapshot>().FirstOrDefault(), "snapshot dopo la ripresa");
}
using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") };
Assert.Equal("ok", await http.GetStringAsync("/health"));
string metrics = await http.GetStringAsync("/metrics");
foreach (string name in new[] { "tick_ms", "trains", "packets", "contracts", "sessions" })
Assert.True(metrics.Contains($"\n{name} ", StringComparison.Ordinal), $"metrica {name}");
var posted = await http.PostAsync("/api/saves?name=da-http", null);
Assert.Equal(System.Net.HttpStatusCode.Created, posted.StatusCode);
string saves = await http.GetStringAsync("/api/saves");
Assert.True(saves.Contains("da-http", StringComparison.Ordinal), saves);
string id = saves.Split("\"id\":\"")[1].Split('"')[0];
var file = await http.GetByteArrayAsync($"/api/saves/{id}");
Assert.True(file.AsSpan(0, 4).SequenceEqual("RESV"u8));
}
}
+13
View File
@@ -0,0 +1,13 @@
using RailEnterprise.Core.Data;
namespace RailEnterprise.Tests;
/// <summary>Dati di gioco caricati una volta sola e condivisi dai test (sono immutabili).</summary>
public static class TestData
{
private static readonly Lazy<GameData> Shared = new(() => GameData.Load(Source), LazyThreadSafetyMode.ExecutionAndPublication);
public static DirectoryDataSource Source => DirectoryDataSource.FindDefault();
public static GameData Data => Shared.Value;
}
+25
View File
@@ -0,0 +1,25 @@
using RailEnterprise.Core.Map;
using RailEnterprise.Core.Simulation;
namespace RailEnterprise.Tests;
/// <summary>Mondi di prova generati dal seme (64 km: veloci da creare).</summary>
public static class TestWorlds
{
public static World Small(ulong seed = 42, string difficulty = "imprenditore") =>
WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = seed, SizeKm = 64, DifficultyId = difficulty });
/// <summary>Mondo piccolo con i ritocchi di difficoltà indicati (es. nessun concorrente IA).</summary>
public static World Small(ulong seed, string difficulty, params (string Key, double Value)[] overrides) =>
WorldFactory.Create(TestData.Data, new NewGameSettings
{
Seed = seed, SizeKm = 64, DifficultyId = difficulty,
DifficultyOverride = Core.Data.DifficultyOverrides.Apply(TestData.Data.DifficultyPreset(difficulty), overrides),
});
/// <summary>Mondo piccolo senza concorrenti IA.</summary>
public static World NoAi(ulong seed = 42, string difficulty = "imprenditore") => Small(seed, difficulty, ("aiCompetitors", 0));
public static GeneratedMap Map(ulong seed, int sizeKm) =>
MapGenerator.Generate(TestData.Data, new MapSpec(seed, sizeKm, TestData.Data.Balance.Time.DefaultStartYear));
}
@@ -0,0 +1,49 @@
{
"name": "Valdoria",
"description_it": "Scenario di riferimento (guida, F2): tra le miniere di Rocca Bruna e l'acciaieria di Valdoria ci sono una collina e un fiume con la sua palude. Il tracciato diretto sulla collina viola la pendenza massima; quello per il valico, con trincea e viadotto, è accettato.",
"seed": 1872,
"startYear": 1850,
"difficulty": "imprenditore",
"aiCompetitors": 0,
"terrain": {
"widthCells": 160,
"heightCells": 120,
"baseHeightM": 110,
"tiltEastMPerKm": -2.0,
"noiseM": 1.5,
"features": [
{ "kind": "sea", "side": "east", "widthKm": 0.8 },
{ "kind": "hill", "x": 5.0, "y": 3.5, "radiusKm": 2.4, "heightM": 130 },
{ "kind": "hill", "x": 5.0, "y": 10.0, "radiusKm": 2.2, "heightM": 110 },
{ "kind": "hill", "x": 5.0, "y": 6.8, "radiusKm": 1.2, "heightM": 32 },
{ "kind": "marsh", "x": 8.9, "y": 6.8, "radiusXKm": 1.1, "radiusYKm": 1.2 },
{ "kind": "river", "points": [ [ 8.6, 0.0 ], [ 8.8, 4.0 ], [ 9.0, 7.0 ], [ 9.6, 9.5 ], [ 12.0, 11.2 ], [ 16.0, 11.6 ] ], "widthClass": 2, "depthM": 4 },
{ "kind": "forest", "x": 2.4, "y": 9.4, "radiusKm": 1.0 },
{ "kind": "forest", "x": 13.0, "y": 10.0, "radiusXKm": 1.2, "radiusYKm": 0.6 },
{ "kind": "field", "x": 12.4, "y": 6.6, "radiusKm": 0.7 }
]
},
"towns": [
{ "name": "Valdoria", "x": 13.6, "y": 4.6, "population": 12400 },
{ "name": "Borgo Ceresio", "x": 12.8, "y": 8.6, "population": 3100 },
{ "name": "Sant'Elia", "x": 10.2, "y": 1.2, "population": 2200 }
],
"industries": [
{ "type": "iron_mine", "name": "Miniera di ferro Rocca Bruna", "x": 1.2, "y": 3.0, "level": 4, "reserveTonnes": 600000 },
{ "type": "coal_mine", "name": "Miniera di carbone Monteferro", "x": 1.8, "y": 1.4, "level": 3, "reserveTonnes": 600000 },
{ "type": "steel_mill", "name": "Acciaieria di Valdoria", "x": 10.8, "y": 4.4, "level": 1 },
{ "type": "tool_factory", "name": "Fabbrica di attrezzi", "x": 12.6, "y": 3.0, "level": 1 },
{ "type": "farm", "name": "Fattoria Piana Verde", "x": 12.0, "y": 6.6, "level": 1 }
],
"hubs": [
{ "kind": "port", "name": "Porto di Levante", "x": 15.0, "y": 6.0 }
],
"player": { "name": "Società Ferroviaria Valdoria", "cash": 100000000 },
"routes": {
"diretto": { "points": [ [ 2.2, 2.6 ], [ 10.6, 5.4 ] ], "allowTunnels": false },
"diretto_galleria": { "points": [ [ 2.2, 2.6 ], [ 10.6, 5.4 ] ] },
"valico": { "points": [ [ 2.2, 2.6 ], [ 3.4, 6.4 ], [ 6.8, 6.9 ], [ 9.6, 6.6 ], [ 10.6, 5.4 ] ], "allowTunnels": false },
"borgo": { "points": [ [ 12.4, 8.0 ], [ 11.2, 6.2 ], [ 10.6, 5.4 ] ] },
"valdoria": { "points": [ [ 12.8, 4.9 ], [ 10.6, 5.4 ] ] }
}
}