Correzioni dalla revisione della scheda industria e della schermata di
connessione.
- Dati di altre compagnie: la forza lavoro della scheda mostra solo i
contratti a piedi, quelli della compagnia della sessione e, se
l'industria è sua, quelli di tutti i vettori, come il Registro degli
impieghi. Lo stesso filtro vale per provenienze, conteggio e viaggio
medio.
- Prezzo: «prezzo medio realizzato» mescolava una media mobile dei
ricavi con i totali del trimestre in corso. Al suo posto c'è il prezzo
di vendita, cioè il prezzo globale del giorno (SalePrice).
- Avvisi del server: hanno il giorno −1, così il rifiuto di Load o
NewGame non si confonde più con gli eventi del mondo che arrivano
mentre si aspetta il Welcome.
- Schermata di connessione:
- all'apertura avvia la strada scelta l'ultima volta;
- cambiando strada chiude la sessione dell'altra;
- senza sessione «Connetti e riprendi» la apre;
- il cambio di lingua passa la sessione alla schermata nuova;
- la scelta del salvataggio si tiene per id;
- Load e nuova partita chiedono conferma;
- stato del server su 3×2 con la versione del protocollo, salvataggi
su tre colonne, «Attivo da» che avanza.
- Scheda dell'industria:
- collegamenti e nodi non collegati sono leggibili;
- testo per l'industria inattiva;
- revisione e ammodernamento disabilitati, con il motivo, quando il
server li rifiuterebbe;
- l'esito dell'acquisto compare accanto al pulsante;
- le righe lunghe vanno a capo;
- «in sede» al posto di «al lavoro ora».
- Gli avvisi dei comandi compaiono anche sulle schermate a tutto
schermo.
- Pilota automatico:
- la schermata 20 sta su un suo CanvasLayer sopra l'interfaccia;
- 12 e 12b sono ora la scheda a tutto schermo.
- Test: pendolari di altri vettori nascosti, Load rifiutato via
WebSocket, Welcome senza ServerInfo. 202 test, 183 senza i lenti.
Refs #42.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
526 lines
31 KiB
C#
526 lines
31 KiB
C#
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);
|
||
}
|
||
}
|
||
|
||
/// <summary>Come WaitFor; il tempo scaduto fa fallire il test (prima veniva ingoiato, #24).</summary>
|
||
public async Task WaitUntil(Func<bool> condition, string what, int timeoutMs = 60_000) =>
|
||
await WaitFor(() => condition() ? (object)true : null, what, timeoutMs);
|
||
|
||
/// <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. La pausa
|
||
// deve cogliere il treno in marcia: fermo (in stazione, a un segnale) il server non
|
||
// rimanda il moto e il client ne tiene uno di un tick precedente (#24)
|
||
long tick = 0;
|
||
Vec2? head = null;
|
||
for (int attempt = 0; ; attempt++)
|
||
{
|
||
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);
|
||
float speed;
|
||
while (true)
|
||
{
|
||
(tick, head, speed) = await server.Host.InvokeAsync(world =>
|
||
(world.Clock.Tick, Projection.HeadPoint(world, world.Trains[train]), Projection.Motion(world, world.Trains[train])?.Speed ?? 0f));
|
||
await Task.Delay(60);
|
||
long again = await server.Host.InvokeAsync(world => world.Clock.Tick);
|
||
if (again == tick) break;
|
||
}
|
||
if (speed > 0) break;
|
||
Assert.True(attempt < 20, "in 20 pause il treno non era mai in marcia");
|
||
await client.Connection.SendAsync(new SetSpeed { Speed = 8 });
|
||
long paused = tick;
|
||
await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Tick > paused && m.Speed > 0, "treno di nuovo in moto", 120_000);
|
||
}
|
||
// 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");
|
||
|
||
// il server manda il registro anche da solo a inizio mese (anche al giorno 0, prima dell'officina):
|
||
// si aspetta quello che arriva dopo la richiesta, non uno già in mano (#24)
|
||
var stale = w.Employment;
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
|
||
var report = await client.WaitFor(() => ReferenceEquals(w.Employment, stale) ? null : 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 {depot} compare nel registro del giorno {report.Day}; righe: "
|
||
+ string.Join(", ", report.Rows.Select(r => $"{r.Kind}:{r.Industry}")));
|
||
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(Slow = true, Description = "F6 in rete: il quadro del mercato globale arriva su richiesta con beni, storico, previsione, hub e commercio")]
|
||
public static void MarketReportOnRequest() => RunMarket().GetAwaiter().GetResult();
|
||
|
||
private static async Task RunMarket()
|
||
{
|
||
var scenario = ScenarioHelper.Load("valdoria");
|
||
int hubs = scenario.World.Hubs.Count;
|
||
await using var server = ServerFixture.Start(scenario.World);
|
||
await using var client = await TestClient.ConnectAsync(server);
|
||
var w = client.World;
|
||
var data = TestData.Data;
|
||
await client.WaitUntil(() => w.LastDigest is { Day: >= 3 }, "tre giorni di prezzi");
|
||
|
||
// il server non manda il quadro da solo: si aspetta la risposta a questa richiesta
|
||
var stale = w.Market;
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Market, Target = 0 });
|
||
var report = await client.WaitFor(() => ReferenceEquals(w.Market, stale) ? null : w.Market, "quadro del mercato");
|
||
Assert.True(report.Day >= 3, $"giorno {report.Day}");
|
||
Assert.Equal(data.GoodCount, report.Goods.Count);
|
||
Assert.Equal(hubs, report.Hubs.Count);
|
||
Assert.True(report.Index > 0, $"indice {report.Index}");
|
||
var coal = report.Goods[data.Goods.First(g => g.Id == "coal").Index];
|
||
Assert.True(coal.Available && coal.Price > 0, "carbone disponibile");
|
||
Assert.True(coal.History.Count >= 1 && coal.History[^1].Price > 0, "storico del carbone");
|
||
Assert.Equal(data.Balance.Market.Outlook.ForecastMonths, coal.Forecast.Count);
|
||
Assert.True(coal.SellPlaces.Count is > 0 and <= 3, $"destinazioni {coal.SellPlaces.Count}");
|
||
Assert.True(coal.SellPlaces.All(p => p.Line == -1), "nessuna linea: nessuna destinazione collegata");
|
||
Assert.True(report.Hubs.All(h => h.Line == -1 && h.MonthlyCapacity > 0), "hub non collegati");
|
||
var tier = data.Tiers.Tiers.First(t => t.Unlocks.Trading);
|
||
Assert.False(report.TradingUnlocked);
|
||
Assert.Equal((byte)tier.Level, report.TradingTier);
|
||
Assert.Equal(tier.Requirements.CreditRating.ToString(), report.RatingRequired);
|
||
Assert.Equal(new Money(tier.Requirements.NetWorth), report.NetWorthRequired);
|
||
Assert.True(report.TradingProgress is >= 0 and < 1, $"avanzamento {report.TradingProgress}");
|
||
}
|
||
|
||
[Test(Description = "F6 in rete: il quadro della scalata arriva su richiesta con livelli, sblocchi, requisiti e stato patrimoniale")]
|
||
public static void ClimbReportOnRequest() => RunClimb().GetAwaiter().GetResult();
|
||
|
||
private static async Task RunClimb()
|
||
{
|
||
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;
|
||
var data = TestData.Data;
|
||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||
|
||
// il server non manda il quadro da solo: si aspetta la risposta a questa richiesta
|
||
Assert.True(w.Climb is null, "nessun quadro prima della richiesta");
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||
var report = await client.WaitFor(() => w.Climb, "quadro della scalata");
|
||
Assert.True(report.Day >= 2, $"giorno {report.Day}");
|
||
Assert.Equal(w.Summary!.CompanyId, report.Company);
|
||
Assert.Equal((byte)1, report.Tier);
|
||
Assert.Equal((byte)2, report.NextTier);
|
||
Assert.Equal(data.Tiers.Tiers.Count, report.Tiers.Count);
|
||
var tier = data.Tiers.Tiers[1];
|
||
Assert.Equal(tier.NameIt, report.Tiers[1].NameIt);
|
||
Assert.Equal(new Money(tier.Requirements.NetWorth), report.NetWorthRequired);
|
||
Assert.Equal(tier.Requirements.CreditRating.ToString(), report.RatingRequired);
|
||
Assert.True(report.Tiers[0].Reached && !report.Tiers[1].Reached, "solo il livello 1 raggiunto");
|
||
Assert.True(report.Tiers[1].Unlocks.Any(u => u.Kind == UnlockInfo.Trading), "il livello 2 sblocca il commercio");
|
||
Assert.True(report.Progress is >= 0 and < 1, $"avanzamento {report.Progress}");
|
||
Assert.Equal(report.BalanceNetWorth, report.TotalAssets - report.TotalLiabilities);
|
||
Assert.Equal(5, report.Assets.Count);
|
||
Assert.True(report.History.Count >= 1, "storico del patrimonio");
|
||
|
||
// dopo un prestito una nuova richiesta riporta il debito: si aspetta la risposta nuova, non quella vecchia
|
||
var result = await client.Do(new TakeLoanCommand(Money.FromLire(5_000)));
|
||
Assert.True(result.Error == 0, result.Message);
|
||
var stale = w.Climb;
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||
var after = await client.WaitFor(() => ReferenceEquals(w.Climb, stale) ? null : w.Climb, "quadro aggiornato");
|
||
Assert.Equal(1, after.LoanList.Count);
|
||
Assert.Equal(Money.FromLire(5_000), after.Loans);
|
||
}
|
||
|
||
[Test(Description = "Il quadro delle finanze arriva su richiesta e dopo un prestito riporta il prestito nuovo (ADR 0019)")]
|
||
public static void FinanceReportOnRequest() => RunFinance().GetAwaiter().GetResult();
|
||
|
||
private static async Task RunFinance()
|
||
{
|
||
var scenario = ScenarioHelper.Load("valdoria");
|
||
int limit = scenario.World.Difficulty.BankruptcyDays;
|
||
await using var server = ServerFixture.Start(scenario.World);
|
||
await using var client = await TestClient.ConnectAsync(server);
|
||
var w = client.World;
|
||
var data = TestData.Data;
|
||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||
|
||
// il server non manda il quadro da solo: si aspetta la risposta a questa richiesta
|
||
Assert.True(w.Finance is null, "nessun quadro prima della richiesta");
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Finance, Target = 0 });
|
||
var report = await client.WaitFor(() => w.Finance, "quadro delle finanze");
|
||
Assert.True(report.Day >= 2, $"giorno {report.Day}");
|
||
Assert.Equal(w.Summary!.CompanyId, report.Company);
|
||
Assert.Equal(global::RailEnterprise.Core.Economy.Company.EntryCount, report.Lines.Count);
|
||
Assert.Equal(IncomeColumnInfo.CurrentMonth, report.Columns[0].Kind);
|
||
Assert.True(report.Columns.Any(c => c.Kind == IncomeColumnInfo.CurrentYear), "colonna dell'anno in corso");
|
||
foreach (var col in report.Columns)
|
||
{
|
||
long operating = report.Lines.Where(l => l.Section != FinanceLineInfo.SectionCapital).Sum(l => col.Value(l.Kind).Cents);
|
||
Assert.Equal(col.Profit.Cents, operating, $"le voci d'esercizio sommano all'utile ({col.Kind} {col.Month}/{col.Year})");
|
||
}
|
||
Assert.Equal(data.Balance.Finance.RatingByScore.Length, report.Thresholds.Count);
|
||
// con TickMs = 1 il primo mese può già essere passato su una macchina lenta: il rating iniziale vale solo prima
|
||
int dpm = scenario.World.Calendar.DaysPerMonth;
|
||
if (report.Day < dpm) Assert.True(report.RatingInitial, "prima del primo mese il rating è quello iniziale");
|
||
Assert.Equal(limit, report.BankruptcyDays);
|
||
Assert.Equal(0, report.LoanList.Count);
|
||
|
||
// dopo un prestito una nuova richiesta riporta il prestito: si aspetta la risposta nuova, non quella vecchia
|
||
var result = await client.Do(new TakeLoanCommand(Money.FromLire(5_000)));
|
||
Assert.True(result.Error == 0, result.Message);
|
||
var stale = w.Finance;
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Finance, Target = 0 });
|
||
var after = await client.WaitFor(() => ReferenceEquals(w.Finance, stale) ? null : w.Finance, "quadro aggiornato");
|
||
Assert.Equal(1, after.LoanList.Count);
|
||
var loan = after.LoanList[0];
|
||
Assert.Equal(Money.FromLire(5_000), loan.Principal);
|
||
// il tasso del prestito è quello di un rating (base + spread all'accensione); se il quadro è dello stesso
|
||
// mese del prestito il rating non è cambiato e coincide con il tasso di un prestito nuovo
|
||
double baseRate = scenario.World.Difficulty.BaseInterestRate;
|
||
var rates = data.Balance.Finance.RatingSpreads.Values.Select(s => (float)(baseRate + s)).ToList();
|
||
Assert.True(rates.Any(r => Math.Abs(r - loan.AnnualRate) < 1e-6), $"tasso {loan.AnnualRate} = base + spread di un rating");
|
||
if (after.Day / dpm == report.Day / dpm) Assert.Approx(after.NewLoanRate, loan.AnnualRate, 1e-6, "tasso fissato all'accensione");
|
||
Assert.True(loan.Payment.Cents > 0 && loan.MaturityDay > after.Day, "rata e scadenza");
|
||
Assert.Equal(Money.FromLire(5_000), after.Loans);
|
||
}
|
||
|
||
[Test(Description = "F6 in rete: la scheda dell'industria arriva su richiesta con la catena produttiva; il Welcome porta lo stato del server e ListSaves l'elenco (ADR 0021)")]
|
||
public static void IndustrySheetAndServerStatusOnRequest() => RunIndustrySheet().GetAwaiter().GetResult();
|
||
|
||
private static async Task RunIndustrySheet()
|
||
{
|
||
var scenario = ScenarioHelper.Load("valdoria");
|
||
var steel = scenario.World.Industries.First(i => i.Def.Id == "steel_mill");
|
||
await using var server = ServerFixture.Start(scenario.World);
|
||
await using var client = await TestClient.ConnectAsync(server);
|
||
var w = client.World;
|
||
var data = TestData.Data;
|
||
|
||
// stato del server nel blocco 1 del Welcome
|
||
var info = client.Welcome.Server;
|
||
Assert.True(info is not null, "stato del server nel Welcome");
|
||
Assert.Equal(server.Host.GameVersion, info!.Version);
|
||
Assert.Equal(1f, info.TickMs);
|
||
Assert.True(info.Sessions >= 1 && info.Sessions <= info.MaxSessions, $"sessioni {info.Sessions} su {info.MaxSessions}");
|
||
Assert.True(info.Local, "server in processo avviato come locale");
|
||
Assert.True(info.Os.Length > 0 && info.UptimeSeconds >= 0, "sistema e tempo di attività");
|
||
Assert.True(w.Server is not null && w.Server.Version == info.Version, "la copia locale tiene lo stato del server");
|
||
|
||
// elenco dei salvataggi: risposta a ListSaves, poi a Save con il salvataggio nuovo
|
||
await client.Connection.SendAsync(new ListSaves());
|
||
var empty = await client.WaitFor(() => w.Saves, "elenco dei salvataggi");
|
||
var stale = w.Saves;
|
||
await client.Connection.SendAsync(new Save { Name = "Valdoria" });
|
||
var saves = await client.WaitFor(() => ReferenceEquals(w.Saves, stale) ? null : w.Saves, "elenco dopo il salvataggio");
|
||
Assert.Equal(empty.Saves.Count + 1, saves.Saves.Count);
|
||
Assert.True(saves.Saves.Any(x => !x.Autosave && (x.Name.Contains("Valdoria", StringComparison.Ordinal) || x.SaveId.Contains("Valdoria", StringComparison.OrdinalIgnoreCase))), "il salvataggio nuovo è nell'elenco");
|
||
|
||
// scheda dell'industria: si aspetta la risposta alla richiesta, non una scheda vecchia
|
||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||
var old = w.IndustryCards.GetValueOrDefault(steel.Id.Value);
|
||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Industry, Target = steel.Id.Value });
|
||
var card = await client.WaitFor(() => w.IndustryCards.TryGetValue(steel.Id.Value, out var c) && !ReferenceEquals(c, old) ? c : null, "scheda dell'industria");
|
||
var sheet = card.Sheet;
|
||
Assert.True(sheet is not null, "scheda nel blocco 1");
|
||
Assert.Equal(steel.Def.Recipe.Inputs.Count, sheet!.Inputs.Count);
|
||
Assert.Equal(steel.Def.Recipe.Outputs.Count, sheet.Outputs.Count);
|
||
Assert.Equal(data.Goods.First(g => g.Id == "iron_ore").Index, sheet.Inputs[0].Good);
|
||
Assert.True(sheet.Inputs[0].Partners.Count > 0 && sheet.Inputs[0].Partners.All(p => p.Line == -1), "fornitori, nessuno collegato");
|
||
Assert.Equal(data.Balance.Growth.MaxLevel, (int)sheet.MaxLevel);
|
||
Assert.Equal(-1, sheet.ServingLine);
|
||
Assert.True(sheet.ForSale && !sheet.BuyUnlocked, "in vendita, acquisto non ancora sbloccato");
|
||
Assert.Equal(data.Tiers.Tiers.First(t => t.Unlocks.BuyIndustry).Level, (int)sheet.BuyTier);
|
||
Assert.Equal(steel.JobsWorkers, sheet.Workers.Jobs);
|
||
}
|
||
|
||
[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");
|
||
// un Load rifiutato risponde con un avviso del server: giorno −1, distinto dagli eventi del mondo
|
||
await client.Connection.SendAsync(new Load { SaveId = "non-esiste" });
|
||
var refused = await client.WaitFor(() => client.Received.OfType<Notification>().FirstOrDefault(n => n.Event.Day < 0), "avviso del Load rifiutato");
|
||
Assert.Equal(GameHost.ServerNoticeDay, refused.Event.Day);
|
||
Assert.True(refused.Event.Text.StartsWith("Caricamento non riuscito", StringComparison.Ordinal), refused.Event.Text);
|
||
Assert.False(client.Received.OfType<Notification>().Any(n => n.Event.Day >= 0 && n.Event.Text.StartsWith("Caricamento", StringComparison.Ordinal)), "nessun evento del mondo scambiato per l'avviso");
|
||
}
|
||
// 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));
|
||
}
|
||
}
|