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>
392 lines
22 KiB
C#
392 lines
22 KiB
C#
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);
|
|
}
|
|
}
|