Merge pull request #54 from MaSzyna-EU07/feat/tapes-from-blackbox

feat(tapes): tapes from the black box, live view that keeps up, train tapes setting
This commit is contained in:
2026-11-16 16:00:52 +00:00
committed by GitHub
39 changed files with 1471 additions and 125 deletions

View File

@@ -109,7 +109,7 @@ internal sealed class BlackBoxFile
uint devices = 0x0007, bool extended = true, sbyte cabEnd = 1, byte security = 0,
float lateral = 0.2f, ushort lightsHead = 0x15, ushort lightsTail = 0x22, byte? movement = null,
short hintHead = -1, short hintTail = -1, ushort? equippedHead = null, ushort? equippedTail = null,
byte? engine = null, float oilTemperature = 70) =>
byte? engine = null, float oilTemperature = 70, float? wheelSpeed = null) =>
Record(0x20, w =>
{
w.Write(time);
@@ -181,6 +181,9 @@ internal sealed class BlackBoxFile
w.Write(1.0f); // clutch
w.Write(0.0f); // torque converter
w.Write(2.5f); // the highest brake cylinder of the train
// the speed of the wheels: a recording made before it ends above
if (wheelSpeed is { } wheels)
w.Write(wheels);
}
}
}

View File

@@ -60,13 +60,15 @@ public class BlackBoxListingTests
public void Black_boxes_with_no_launch_noted_go_with_the_tapes_written_about_the_same_time()
{
var early = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
// named in the local time they started at, whatever the zone the tests run in
string first = Box("td", early.AddHours(-1)), second = Box("td", early.AddMinutes(30));
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Log("a.dat"), "t")
.WithFile(Log("td_2026-03-01_11-00-00.blackbox"), "b")
.WithFile(Log("td_2026-03-01_12-30-00.blackbox"), "b")
.WithFile(Log(first), "b")
.WithFile(Log(second), "b")
.WrittenAt(Log("a.dat"), early)
.WrittenAt(Log("td_2026-03-01_11-00-00.blackbox"), early.AddSeconds(2))
.WrittenAt(Log("td_2026-03-01_12-30-00.blackbox"), early.AddHours(1)));
.WrittenAt(Log(first), early.AddSeconds(2))
.WrittenAt(Log(second), early.AddHours(1)));
var sessions = installation.Tapes.Sessions();
@@ -74,12 +76,59 @@ public class BlackBoxListingTests
Assert.All(sessions, session => Assert.Null(session.Launch));
// Newest first: the black box on its own, then the run with the tape.
Assert.Empty(sessions[0].Tapes);
Assert.EndsWith("12-30-00.blackbox", Assert.Single(sessions[0].BlackBoxes).Path);
Assert.EndsWith(second, Assert.Single(sessions[0].BlackBoxes).Path);
Assert.Single(sessions[1].Tapes);
Assert.EndsWith("11-00-00.blackbox", Assert.Single(sessions[1].BlackBoxes).Path);
Assert.EndsWith(first, Assert.Single(sessions[1].BlackBoxes).Path);
Assert.Equal(early, sessions[1].StartedUtc);
}
[Fact]
public void The_tape_of_a_vehicle_left_early_in_a_run_with_no_launch_goes_with_its_black_box()
{
// The black box writes the tapes as it goes: that of the vehicle the player left after ten minutes ends
// twenty minutes before the run, that of the next one with it.
var started = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
string box = Box("td", started);
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Log("first.dat"), "t")
.WithFile(Log("second.dat"), "t")
.WithFile(Log(box), "b")
.WrittenAt(Log("first.dat"), started.AddMinutes(10))
.WrittenAt(Log(box), started.AddMinutes(30))
.WrittenAt(Log("second.dat"), started.AddMinutes(30).AddSeconds(1)));
var session = Assert.Single(installation.Tapes.Sessions());
Assert.Null(session.Launch);
Assert.Equal(new[] { "first", "second" }, session.Tapes.Select(tape => tape.Vehicle).Order());
Assert.EndsWith(box, Assert.Single(session.BlackBoxes).Path);
}
[Fact]
public void A_black_box_downloaded_later_takes_in_no_tapes_of_the_runs_after_it()
{
// Shared and downloaded two weeks later, so last written then; a run of its own with no launch noted since.
var shared = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
var later = shared.AddDays(7);
string old = Box("td", shared), own = Box("td", later);
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Log(old), "b").WrittenAt(Log(old), shared.AddDays(14))
.WithFile(Log(own), "b").WrittenAt(Log(own), later.AddMinutes(30))
.WithFile(Log("ra.dat"), "t").WrittenAt(Log("ra.dat"), later.AddMinutes(30).AddSeconds(1))
.WithFile(Log("left.dat"), "t").WrittenAt(Log("left.dat"), later.AddMinutes(10)));
var recordings = StarterNG.Application.HaslerTapes.Recordings(new[]
{
new StarterNG.Application.BlackBoxRecording(Log(old), shared.AddDays(14), 1),
new StarterNG.Application.BlackBoxRecording(Log(own), later.AddMinutes(30), 1),
});
Assert.EndsWith(own, StarterNG.Application.HaslerTapes.RecordingAt(later.AddMinutes(10), recordings)!.Path);
var mine = Assert.Single(installation.Tapes.Sessions(), session => session.Tapes.Count > 0);
Assert.Equal(new[] { "left", "ra" }, mine.Tapes.Select(tape => tape.Vehicle).Order());
Assert.EndsWith(own, Assert.Single(mine.BlackBoxes).Path);
}
[Fact]
public void The_black_box_of_a_running_session_is_listed_while_it_is_written()
{

View File

@@ -125,6 +125,20 @@ public class HeadCodeTests
Assert.Null(cab[1].Extra);
}
[Fact]
public void The_speed_of_the_wheels_is_read_when_written()
{
var f = new BlackBoxFile().Info();
// the wheels slipping at 40 km/h
f.Cab(0, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1, wheelSpeed: 55.5f);
f.Cab(0.5, 1, 1000, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1);
var cab = BlackBoxReader.Read(f.End(1).Stream()).Cab;
Assert.Equal(55.5f, cab[0].WheelSpeedKmh);
Assert.Equal(40f, cab[0].SpeedKmh);
// an older sample has none
Assert.Null(cab[1].WheelSpeedKmh);
}
[Fact]
public void A_vehicle_with_no_lamps_is_not_judged()
{

View File

@@ -222,6 +222,34 @@ public class BlackBoxViewsTests
Assert.Equal(cab.Said, Controls.Peer(cab).GetHelpText());
}
[Fact]
public void Wheels_turning_apart_from_the_train_are_said_beside_its_speed()
{
var f = new BlackBoxFile().Info()
.Vehicle(Head, "EU07-005", "ROJ1")
.User(0, Head, true, 1);
// slipping for the first ten seconds, then the wheels as fast as the train, give or take the rounding
for (double t = 0; t <= 20; t += 0.5)
f.Cab(t, Head, 1150 + t * 10, 40, movement: 1, equippedHead: 0x15, equippedTail: 0x22, engine: 1,
wheelSpeed: t < 10 ? 55.4f : 40.3f);
var cab = new CabPanel
{
Recording = BlackBoxReader.Read(f.End(20).Stream()),
Strings = new DefaultBlackBoxStrings("en"),
Time = 5
};
Controls.Lay(cab, 600, 900);
Controls.Draw(cab);
Assert.Contains("40 km/h", cab.Said);
Assert.Contains("wheels 55", cab.Said);
cab.Time = 15;
Controls.Draw(cab);
Assert.Contains("40 km/h", cab.Said);
Assert.DoesNotContain("wheels", cab.Said);
}
[Fact]
public void The_cab_stopped_under_the_brakes_and_out_of_the_recording()
{

View File

@@ -0,0 +1,49 @@
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
// The events are coloured with the views' brushes.
[Collection(AvaloniaControls.Name)]
public class CabDoorsTests
{
private static CabSample Sample(sbyte cab, CabDevices devices) =>
default(CabSample) with { CabEnd = cab, Devices = devices | CabDevices.Radio };
[Fact]
public void From_the_rear_cab_the_vehicles_right_doors_are_the_drivers_left()
{
var seen = Sample(-1, CabDevices.DoorsRight | CabDevices.DoorPermitRight).AsTheCabSees;
Assert.True(seen.Has(CabDevices.DoorsLeft));
Assert.True(seen.Has(CabDevices.DoorPermitLeft));
Assert.False(seen.Has(CabDevices.DoorsRight));
Assert.False(seen.Has(CabDevices.DoorPermitRight));
Assert.True(seen.Has(CabDevices.Radio));
}
[Theory]
[InlineData(1)]
[InlineData(0)]
public void From_the_front_cab_or_out_of_one_the_sides_are_the_vehicles(sbyte cab)
{
var sample = Sample(cab, CabDevices.DoorsLeft | CabDevices.DoorPermitRight);
Assert.Equal(sample, sample.AsTheCabSees);
}
[Fact]
public void Going_to_the_other_cab_tells_nothing_of_the_doors_and_still_tells_the_switches()
{
var f = new BlackBoxFile().Info().Vehicle(1, "EN57-1001").User(0, 1, true);
// the left doors permitted from the front cab; in the rear one the permit is still on, and the radio turned off
f.Cab(0, 1, 1000, 0, cabEnd: 1, devices: 0x0007 | (uint)(CabDevices.DoorPermitLeft | CabDevices.Radio));
f.Cab(1, 1, 1000, 0, cabEnd: -1, devices: 0x0007 | (uint)CabDevices.DoorPermitLeft);
var events = EventList.Collect(BlackBoxReader.Read(f.End(1).Stream()), new DefaultBlackBoxStrings("en"))
.Select(e => e.Text).ToList();
Assert.Contains("Radio: off", events);
Assert.DoesNotContain(events, e => e.Contains("doors permitted"));
}
}

View File

@@ -0,0 +1,55 @@
using Avalonia;
using StarterNG.Views.Tapes;
namespace StarterNG.Tests;
/// <summary>The line of a tape, drawn a column of pixels at a time and broken off at a gap.</summary>
public class ColumnLineTests
{
private readonly List<string> _drawn = [];
private ColumnLine Line() =>
new(p => _drawn.Add($"begin {p.X} {p.Y}"), p => _drawn.Add($"line {p.X} {p.Y}"), () => _drawn.Add("end"));
[Fact]
public void A_column_is_entered_where_it_started_and_left_where_it_ended_through_its_lowest_and_highest()
{
var line = Line();
// Falling within the column: from its first through its highest and its lowest to its last.
foreach (double v in new[] { 3.0, 1.0, 4.0, 2.0 })
line.Add(5, v);
// Rising: through its lowest first.
foreach (double v in new[] { 2.0, 4.0, 1.0, 3.0 })
line.Add(6, v);
line.Break();
Assert.Equal(["begin 5 3", "line 5 4", "line 5 1", "line 5 2",
"line 6 2", "line 6 1", "line 6 4", "line 6 3", "end"], _drawn);
}
[Fact]
public void A_break_ends_the_figure_and_the_next_point_begins_another()
{
var line = Line();
line.Add(0, 10);
line.Break();
line.Add(9, 20);
line.Break();
Assert.Equal(["begin 0 10", "line 0 10", "line 0 10", "line 0 10", "end",
"begin 9 20", "line 9 20", "line 9 20", "line 9 20", "end"], _drawn);
}
[Fact]
public void A_break_with_nothing_drawn_ends_nothing()
{
var line = Line();
line.Break();
line.Break();
Assert.Empty(_drawn);
}
}

View File

@@ -6,6 +6,8 @@ using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
// Puts in services of its own: not while the controls read theirs.
[Collection(AvaloniaControls.Name)]
public class ConsistOrientationTests
{
private readonly VehicleCatalog _catalog;

View File

@@ -0,0 +1,29 @@
namespace StarterNG.Tests.Fakes;
/// <summary>A stream read from its start to its end and no other way: no length, no seeking.</summary>
internal sealed class ForwardOnlyStream(Stream inner) : Stream
{
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Flush() { }
protected override void Dispose(bool disposing)
{
if (disposing)
inner.Dispose();
base.Dispose(disposing);
}
}

View File

@@ -20,6 +20,7 @@ public sealed class InMemoryFileSystem : IFileSystem
private readonly HashSet<string> _executable;
private readonly Dictionary<string, string> _links;
private readonly HashSet<string> _unreadable;
private readonly HashSet<string> _unseekable;
private readonly HashSet<string> _unlistable;
private readonly Dictionary<string, DateTime> _written;
@@ -32,6 +33,7 @@ public sealed class InMemoryFileSystem : IFileSystem
_executable = new HashSet<string>(comparer);
_links = new Dictionary<string, string>(comparer);
_unreadable = new HashSet<string>(comparer);
_unseekable = new HashSet<string>(comparer);
_unlistable = new HashSet<string>(comparer);
_written = new Dictionary<string, DateTime>(comparer);
}
@@ -51,6 +53,13 @@ public sealed class InMemoryFileSystem : IFileSystem
return this;
}
/// <summary>The file opens as a stream read only forward, as a pipe or some network shares give it.</summary>
public InMemoryFileSystem OpenedForwardOnly(string path)
{
_unseekable.Add(Normalize(path));
return this;
}
public InMemoryFileSystem AllowReading(string path)
{
_unreadable.Remove(Normalize(path));
@@ -115,7 +124,11 @@ public sealed class InMemoryFileSystem : IFileSystem
public byte[] ReadAllBytes(string path) => Bytes(path);
public Stream OpenRead(string path) => new MemoryStream(Bytes(path), writable: false);
public Stream OpenRead(string path)
{
var stream = new MemoryStream(Bytes(path), writable: false);
return _unseekable.Contains(Normalize(path)) ? new ForwardOnlyStream(stream) : stream;
}
public void WriteAllText(string path, string contents) => WithFile(path, contents);

View File

@@ -6,12 +6,12 @@ namespace StarterNG.Tests;
public class HaslerTapeTests
{
private const string Header =
internal const string Header =
"Time[s] Velocity[m/s] Acceleration[m/ss] Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] " +
"BrakeForce[kN] BrakePress[MPa] PipePress[MPa] MotorCurrent[A] MCP SCP BCP LBP Direction Command CVal1 CVal2 " +
"Security Wheelslip EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]\r\n";
private static string Line(double t, double v, double brake, double current, string command = "none",
internal static string Line(double t, double v, double brake, double current, string command = "none",
int security = 0) =>
string.Create(CultureInfo.InvariantCulture,
$"{t:0.0000} {v:0.0000} 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 {brake:0.0000} 0.5000 {current:0.0000} ") +
@@ -68,6 +68,197 @@ public class HaslerTapeTests
Assert.Equal(5, tape.DistanceM, 6);
}
[Fact]
public void The_security_flag_is_found_where_the_header_puts_it_with_the_vehicle_speed_at_the_end()
{
// the simulator's log since 2026-10: a column of the vehicle's speed after the temperatures
string header = Header.Replace("WaterAuxTemp[Deg]\r\n", "WaterAuxTemp[Deg] VehicleVelocity[km/h]\r\n");
static string WithSpeed(string line, double kmh) =>
line.Replace("\r\n", string.Create(CultureInfo.InvariantCulture, $" {kmh:0.0000}\r\n"));
// the wheels slipping, the alerter quiet: the column before the speed used to be read as the alerter
string slipping = Line(0, 36, 0, 0, security: 0).Replace(" 0 0 0.0000 0.0000 0.0000 0.0000\r\n",
" 0 1 0.0000 0.0000 0.0000 0.0000\r\n");
var tape = HaslerTape.Parse(header + WithSpeed(slipping, 36) + WithSpeed(Line(1, 36, 0, 0, security: 1), 36));
Assert.Equal(2, tape.Samples.Count);
Assert.False(tape.Samples[0].SecurityAlarm);
Assert.True(tape.Samples[1].SecurityAlarm);
}
[Fact]
public void A_command_named_like_a_heading_is_read_as_a_line_not_as_the_header()
{
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0, command: "Security") + Line(1, 36, 0, 0, security: 1));
Assert.Equal(2, tape.Samples.Count);
Assert.False(tape.Samples[0].SecurityAlarm);
Assert.True(tape.Samples[1].SecurityAlarm);
}
[Fact]
public void A_gap_in_the_time_is_neither_driving_nor_standing_and_covers_no_distance()
{
// the player in another vehicle for ten minutes, then back in this one
var tape = HaslerTape.Parse(Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(601, 36, 0, 0)
+ Line(602, 36, 0, 0) + Line(603, 0, 0, 0));
Assert.Equal(603, tape.Duration, 6);
Assert.Equal(600, tape.GapTime, 6);
Assert.Equal(2, tape.RunningTime, 6);
Assert.Equal(1, tape.StandingTime, 6); // the last second, stopping
Assert.Equal(10 + 10 + 5, tape.DistanceM, 6);
Assert.Equal(25 / 3.0 * 3.6, tape.AverageWithStopsKmh, 6);
}
[Fact]
public void A_stall_of_the_simulator_a_little_over_a_second_is_driven_not_a_gap()
{
// a line every 0.05 s, as at 60 FPS, and one step of 1.017 s: the frame held to a second, and the frame after
var text = new System.Text.StringBuilder(Header);
double t = 0;
for (int i = 0; i < 40; i++, t += 0.05)
text.Append(Line(t, 100, 0, 0));
t += 1.017 - 0.05;
for (int i = 0; i < 40; i++, t += 0.05)
text.Append(Line(t, 100, 0, 0));
var tape = HaslerTape.Parse(text.ToString());
Assert.Equal(0, tape.GapTime, 6);
Assert.Equal(tape.Duration, tape.RunningTime, 6);
Assert.Equal(tape.Duration * 100 / 3.6, tape.DistanceM, 6);
}
[Fact]
public void A_tape_read_in_pieces_cut_anywhere_is_the_tape_read_whole()
{
string text = Header + Line(0, 18, 0, 0, command: "Set Velocity") + Line(1, 36, 0.45, 0) + Line(2, 36, 0, 400)
+ Line(602, 36, 0, 0, security: 1) + Line(603, 0, 0, 0);
var whole = HaslerTape.Parse(text);
for (int cut = 1; cut < text.Length; cut += 7)
{
var reader = new HaslerTape.Reader();
reader.Feed(text[..cut]);
reader.Feed(text[cut..]);
Assert.Equal(whole.Samples, reader.Tape(final: true).Samples);
}
}
[Fact]
public void A_line_not_ended_waits_for_its_end_while_the_tape_is_followed()
{
var reader = new HaslerTape.Reader();
string line = Line(1, 36, 0, 0);
reader.Feed(Header + Line(0, 36, 0, 0) + line[..20]);
Assert.Single(reader.Tape(final: false).Samples);
Assert.Single(reader.Tape(final: false).Samples);
reader.Feed(line[20..]);
Assert.Equal(2, reader.Tape(final: false).Samples.Count);
}
[Fact]
public void A_followed_tape_reads_what_was_added_and_one_begun_anew_whole()
{
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
Assert.Single(tapes.Load(file, follow: false)!.Samples);
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0) + Line(2, 36, 0, 0));
Assert.Equal(3, tapes.Load(file, follow: true)!.Samples.Count);
// begun anew, and already longer than was read: its time goes back
files.WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0) + Line(2, 72, 0, 0) + Line(3, 72, 0, 0));
var tape = tapes.Load(file, follow: true)!;
Assert.Equal(4, tape.Samples.Count);
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
// begun anew, and shorter
files.WithFile(path, Header + Line(0, 18, 0, 0));
Assert.Equal(18, Assert.Single(tapes.Load(file, follow: true)!.Samples).SpeedKmh, 6);
}
[Fact]
public void A_log_begun_anew_over_the_end_that_was_read_is_read_whole_once_its_time_goes_back()
{
// the command is free text, here long enough that the end kept of the read part holds no time
string command = new('x', 400);
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(3, 36, 0, 0, command));
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
Assert.Equal(3, Assert.Single(tapes.Load(file, follow: false)!.Samples).Time, 6);
// begun anew: where the read part ended it reads as it did, but the lines added go back to the start
files.WithFile(path, Header + Line(0, 36, 0, 0, command) + Line(1, 36, 0, 0, command) + Line(2, 36, 0, 0, command));
var tape = tapes.Load(file, follow: true)!;
Assert.Equal([0.0, 1.0, 2.0], tape.Samples.Select(s => s.Time));
}
[Fact]
public void A_tape_that_cannot_be_read_is_none_and_told_and_is_read_whole_once_it_can()
{
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0));
var installation = new TestInstallation(files);
var tapes = installation.Tapes;
var file = Assert.Single(tapes.List());
tapes.Load(file, follow: false);
files.FailReading(path);
Assert.Null(tapes.Load(file, follow: true));
Assert.Contains("EU07-424.dat", installation.Log.Text);
files.AllowReading(path).WithFile(path, Header + Line(0, 72, 0, 0) + Line(1, 72, 0, 0));
Assert.All(tapes.Load(file, follow: true)!.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
}
[Fact]
public void A_file_read_only_forward_is_read_whole_each_time()
{
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Header + Line(0, 36, 0, 0)).OpenedForwardOnly(path);
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
Assert.Single(tapes.Load(file, follow: true)!.Samples);
files.WithFile(path, Header + Line(0, 36, 0, 0) + Line(1, 36, 0, 0));
Assert.Equal(2, tapes.Load(file, follow: true)!.Samples.Count);
}
[Fact]
public void Empty_lines_in_a_log_are_passed_over()
{
var tape = HaslerTape.Parse(Header + "\r\n" + Line(0, 36, 0, 0) + " \r\n" + Line(1, 36, 0, 0));
Assert.Equal(2, tape.Samples.Count);
}
[Fact]
public void Forgetting_another_file_keeps_the_followed_tape_and_its_own_lets_it_go()
{
string Lines(int firstSpeed, int count) =>
Header + Line(0, firstSpeed, 0, 0) + string.Concat(Enumerable.Range(1, count).Select(t => Line(t, 36, 0, 0)));
string path = TestInstallation.At("physicslog", "EU07-424.dat");
var files = new InMemoryFileSystem().WithFile(path, Lines(36, 20));
var tapes = new TestInstallation(files).Tapes;
var file = Assert.Single(tapes.List());
tapes.Load(file, follow: false);
// the first line changed, as long as it was and far from the end: a tape still followed doesn't read it again
files.WithFile(path, Lines(72, 21));
tapes.Forget(TestInstallation.At("physicslog", "EU07-111.dat"));
Assert.Equal(36, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6);
tapes.Forget(file.Path);
Assert.Equal(72, tapes.Load(file, follow: true)!.Samples[0].SpeedKmh, 6);
}
[Fact]
public void The_sample_under_a_point_of_the_tape_is_found_by_time_and_by_distance()
{

View File

@@ -0,0 +1,96 @@
using Avalonia.Controls;
using Avalonia.LogicalTree;
using StarterNG.Application;
using StarterNG.Domain.Tapes;
using StarterNG.Tests.Fakes;
using StarterNG.Views.Tapes;
namespace StarterNG.Tests;
/// <summary>The tapes' window over the tapes of an installation of its own, read as it is opened.</summary>
[Collection(AvaloniaControls.Name)]
public class HaslerTapeWindowTests
{
private static readonly DateTime Launched = new(2025, 12, 31, 23, 0, 0, DateTimeKind.Utc);
static HaslerTapeWindowTests() => HeadlessDrawing.Ensure();
private static AppServices Services(InMemoryFileSystem files)
{
var installation = new TestInstallation(files);
installation.Clock.Now = Launched;
return AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
}
// The window reads the tapes off the UI thread and shows them on it: what it shows is waited for.
private static void Until(Func<bool> shown) =>
Assert.True(SpinWait.SpinUntil(() =>
{
Controls.Settle();
return shown();
}, TimeSpan.FromSeconds(5)));
private static Button Button(Window window, string key) =>
window.GetLogicalDescendants().OfType<Button>().Single(b => b.Content as string == App.Loc[key]);
[Fact]
public void With_nothing_recorded_it_offers_to_record_and_turns_on_the_black_box_and_the_trains_tapes()
{
var services = Services(new InMemoryFileSystem());
var window = new HaslerTapeWindow();
bool told = false;
window.LogEnabled += () => told = true;
window.Show();
try
{
var strip = (Control)Button(window, "HaslerRecordingEnable").Parent!;
Until(() => strip.IsVisible);
Button(window, "HaslerRecordingEnable").RaiseEvent(Controls.Click());
Assert.True(services.Settings.BlackBox);
Assert.True(services.Settings.PhysicsLogTrains);
Assert.False(services.Settings.PhysicsLog);
Assert.True(told);
Assert.False(strip.IsVisible);
// the simulator's own log is on as it comes: nothing more to offer
Assert.False(((Control)Button(window, "HaslerLogEnable").Parent!).IsVisible);
}
finally
{
window.Close();
}
}
[Fact]
public void A_tape_of_the_last_launch_is_summed_up_with_its_scenario_and_train()
{
string path = TestInstallation.At("physicslog", "EP07-424.dat");
var files = new InMemoryFileSystem()
.WithFile(path, HaslerTapeTests.Header + HaslerTapeTests.Line(0, 36, 0, 0) + HaslerTapeTests.Line(60, 36, 0, 0));
var services = Services(files);
services.Tapes.RecordLaunch("td.scn", TimeSpan.Zero, Array.Empty<TapeVehicle>(), "EP07-424", new[] { "EP07-424" },
"Tor doświadczalny", "EIE1531");
var window = new HaslerTapeWindow();
window.Show();
try
{
string scenario = string.Format(App.Loc["HaslerScenario"], "Tor doświadczalny");
var texts = window.GetLogicalDescendants().OfType<TextBlock>();
Until(() => texts.Any(t => t.Text?.Contains(scenario) == true));
string summary = texts.First(t => t.Text?.Contains(scenario) == true).Text!;
Assert.StartsWith("EP07-424", summary);
Assert.Contains(string.Format(App.Loc["HaslerTrain"], "EIE1531"), summary);
}
finally
{
window.Close();
}
// closed, the tape it read is no longer followed: begun anew and longer, it is read whole
files.WithFile(path, HaslerTapeTests.Header + HaslerTapeTests.Line(0, 72, 0, 0) + HaslerTapeTests.Line(1, 72, 0, 0)
+ HaslerTapeTests.Line(2, 72, 0, 0));
var tape = services.Tapes.Load(services.Tapes.List().Single(), follow: true)!;
Assert.All(tape.Samples, s => Assert.Equal(72, s.SpeedKmh, 6));
}
}

View File

@@ -0,0 +1,87 @@
using Avalonia.Controls;
using Avalonia.LogicalTree;
using StarterNG.Application;
using StarterNG.Tests.Fakes;
using StarterNG.Views;
namespace StarterNG.Tests;
/// <summary>The starter's questions over its window, answered with the mouse or not at all.</summary>
[Collection(AvaloniaControls.Name)]
public class MessageBoxTests
{
// The buttons are labelled in the starter's language.
static MessageBoxTests()
{
HeadlessDrawing.Ensure();
if (AppServices.CurrentOrNull is null)
{
var installation = new TestInstallation(new InMemoryFileSystem());
AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, installation.Environment);
}
}
private static (Window Owner, Window Dialog, Task<bool?> Answer) Choose()
{
var owner = new Window();
owner.Show();
var answer = MessageBox.Choose(owner, "Zapisać zmiany przed startem?", "Niezapisane zmiany", "Zapisz", "Nie zapisuj");
Controls.Settle();
return (owner, Assert.Single(owner.OwnedWindows), answer);
}
// The answer is given once the dialog's closing has gone through the dispatcher.
private static bool? Answered(Task<bool?> answer)
{
Assert.True(SpinWait.SpinUntil(() =>
{
Controls.Settle();
return answer.IsCompleted;
}, TimeSpan.FromSeconds(5)));
return answer.Result;
}
private static Button[] Buttons(Window dialog) => dialog.GetLogicalDescendants().OfType<Button>().ToArray();
[Theory]
[InlineData(0, true)]
[InlineData(1, false)]
[InlineData(2, null)]
public void A_choice_gives_the_answer_clicked_and_the_way_back_gives_none(int clicked, bool? expected)
{
var (owner, dialog, answer) = Choose();
try
{
Assert.Equal("Niezapisane zmiany", dialog.Title);
Assert.Contains(dialog.GetLogicalDescendants().OfType<TextBlock>(), t => t.Text == "Zapisać zmiany przed startem?");
var buttons = Buttons(dialog);
Assert.Equal(["Zapisz", "Nie zapisuj", App.Loc["Cancel"]], buttons.Select(b => b.Content as string));
Assert.False(answer.IsCompleted);
buttons[clicked].RaiseEvent(Controls.Click());
Assert.Equal(expected, Answered(answer));
Assert.Empty(owner.OwnedWindows);
}
finally
{
owner.Close();
}
}
[Fact]
public void Closing_the_window_of_a_choice_picks_neither_answer()
{
var (owner, dialog, answer) = Choose();
try
{
dialog.Close();
Assert.Null(Answered(answer));
}
finally
{
owner.Close();
}
}
}

View File

@@ -1257,6 +1257,39 @@ public class SettingsStoreTests
Assert.False(store.LoadFailed);
}
[Fact]
public void A_profile_from_before_the_tapes_of_the_trains_is_moved_as_the_ini_would_be()
{
var files = new InMemoryFileSystem()
.WithFile(UserIni, "physicslog no\nphysicslog.trains no\n")
.WithFile(Profile, "physicslog yes\nblackbox yes\n");
var store = WithHome(files).SettingsStore;
store.Load();
Assert.True(store.TryLoadProfile(Profile));
store.Save();
Assert.False(store.Settings.PhysicsLog);
Assert.True(store.Settings.PhysicsLogTrains);
Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
}
[Fact]
public void A_profile_exported_from_a_pages_edits_leaves_the_settings_held_and_the_ini_alone()
{
var files = new InMemoryFileSystem().WithFile(UserIni, "fieldofview 45\n");
var store = WithHome(files).SettingsStore;
store.Load();
var edited = store.Settings.Copy();
edited.FieldOfView = 60;
Assert.True(store.ExportTo(Profile, edited));
Assert.Contains("fieldofview 60", files.ReadAllText(Profile, System.Text.Encoding.UTF8));
Assert.Equal(45, store.Settings.FieldOfView);
Assert.Contains("fieldofview 45", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
}
[Fact]
public void A_missing_profile_leaves_the_settings_as_they_are()
{
@@ -1302,4 +1335,189 @@ public class SettingsStoreTests
Assert.False(store.LoadFailed);
Assert.Equal(60, store.Settings.FieldOfView);
}
[Theory]
[InlineData("physicslog yes\n", true)]
[InlineData("physicslog no\n", false)]
[InlineData("physicslog yes\nblackbox no\n", false)]
[InlineData("physicslog no\nblackbox yes\n", true)]
public void The_black_box_goes_with_the_physics_log_unless_the_ini_says_otherwise(string ini, bool recorded)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
installation.SettingsStore.Load();
Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox);
}
[Fact]
public void Tapes_turned_on_write_the_black_box_and_leave_the_physics_log_off()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.BlackBox = true;
installation.SettingsStore.Save();
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
}
[Fact]
public void A_black_box_that_says_no_more_than_the_physics_log_adds_no_line()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.Width = 1600;
installation.SettingsStore.Save();
Assert.Null(LineFor(installation, "blackbox"));
}
[Theory]
[InlineData("physicslog yes\nblackbox yes\n")]
[InlineData("physicslog no\nblackbox yes\n")]
public void A_black_box_line_of_the_file_says_no_once_the_box_is_off(string ini)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.BlackBox = false;
installation.SettingsStore.Settings.PhysicsLog = false;
installation.SettingsStore.Save();
Assert.Equal("blackbox no", LineFor(installation, "blackbox"));
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
}
[Fact]
public void The_physics_log_turned_off_keeps_the_tapes_it_brought()
{
// an ini of before the black box had a key: the tapes came with the physics log
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.PhysicsLog = false;
installation.SettingsStore.Save();
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
}
[Theory]
[InlineData("physicslog no\n", false, false)]
[InlineData("physicslog no\nphysicslog.trains yes\n", true, true)]
[InlineData("physicslog no\nphysicslog.trains yes\nblackbox no\n", true, false)]
public void The_logs_of_the_trains_are_read_and_bring_the_black_box_as_the_simulator_has_it(string ini, bool trains, bool recorded)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
installation.SettingsStore.Load();
Assert.Equal(trains, installation.SettingsStore.Settings.PhysicsLogTrains);
Assert.Equal(recorded, installation.SettingsStore.Settings.BlackBox);
}
[Theory]
[InlineData("physicslog yes\nblackbox yes\n")]
[InlineData("physicslog no\nblackbox yes\n")]
public void Recording_turned_on_before_the_tapes_of_the_trains_is_moved_to_them(string ini)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
installation.SettingsStore.Load();
var s = installation.SettingsStore.Settings;
Assert.False(s.PhysicsLog);
Assert.True(s.PhysicsLogTrains);
Assert.True(s.BlackBox);
installation.SettingsStore.Save();
Assert.Equal("physicslog no", LineFor(installation, "physicslog"));
Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains"));
Assert.Equal("blackbox yes", LineFor(installation, "blackbox"));
}
[Theory]
[InlineData("physicslog yes\n", true)]
[InlineData("physicslog yes\nblackbox no\n", true)]
[InlineData("physicslog yes\nblackbox yes\nphysicslog.trains no\n", true)]
[InlineData("physicslog no\nblackbox yes\nphysicslog.trains no\n", false)]
public void Without_a_black_box_line_saying_yes_or_with_the_trains_tapes_line_nothing_is_moved(string ini, bool physicsLog)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
installation.SettingsStore.Load();
Assert.Equal(physicsLog, installation.SettingsStore.Settings.PhysicsLog);
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
}
[Fact]
public void An_imported_ini_from_before_the_tapes_of_the_trains_is_moved_as_a_profile_is()
{
string backup = Path.Combine("/home/kolejarz", "backup", "eu07.ini");
var files = new InMemoryFileSystem()
.WithFile(UserIni, "physicslog yes\nphysicslog.trains no\n")
.WithFile(backup, "physicslog yes\nblackbox yes\n");
var store = WithHome(files).SettingsStore;
store.Load();
Assert.True(store.ImportFrom(backup));
store.Save();
Assert.False(store.Settings.PhysicsLog);
Assert.True(store.Settings.PhysicsLogTrains);
Assert.Contains("physicslog.trains yes", files.ReadAllText(UserIni, System.Text.Encoding.UTF8));
}
[Fact]
public void Once_moved_the_physics_log_of_every_vehicle_turned_on_again_stays_on()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog yes\nblackbox yes\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.PhysicsLog = true;
installation.SettingsStore.Settings.PhysicsLogTrains = false;
installation.SettingsStore.Save();
installation.SettingsStore.Load();
Assert.True(installation.SettingsStore.Settings.PhysicsLog);
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
}
[Fact]
public void The_logs_of_the_trains_are_written_only_once_on_or_where_the_file_has_them()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Save();
Assert.Null(LineFor(installation, "physicslog.trains"));
installation.SettingsStore.Settings.PhysicsLogTrains = true;
installation.SettingsStore.Settings.BlackBox = true;
installation.SettingsStore.Save();
Assert.Equal("physicslog.trains yes", LineFor(installation, "physicslog.trains"));
// it says no more than the logs of the trains bring
Assert.Null(LineFor(installation, "blackbox"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.PhysicsLogTrains = false;
installation.SettingsStore.Save();
Assert.Equal("physicslog.trains no", LineFor(installation, "physicslog.trains"));
}
[Fact]
public void A_black_box_line_written_once_goes_away_when_it_says_no_more()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "physicslog no\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.BlackBox = true;
installation.SettingsStore.Save();
installation.SettingsStore.Settings.BlackBox = false;
installation.SettingsStore.Save();
Assert.Null(LineFor(installation, "blackbox"));
}
}

View File

@@ -40,6 +40,18 @@ public class StartSimulationTests
Assert.Contains($"vehicle\t{driven}\tPKP/EP07\tep07.mmd", noted);
}
[Fact]
public void With_the_black_box_alone_the_launch_is_noted_for_the_tapes_it_writes()
{
var (start, _, installation) = Rig(files => files.WithExecutable(Build), sceneryClock: "07:52");
installation.SettingsStore.Settings.BlackBox = true;
start.Execute(freeFly: false, saveSettings: false);
string noted = installation.Files.ReadAllText(TestInstallation.At("physicslog", "starter-launch.txt"));
Assert.Contains("clock\t07:52", noted);
}
[Fact]
public void Without_the_physics_log_nothing_is_noted()
{

View File

@@ -6,6 +6,8 @@ namespace StarterNG.Tests;
// PresetStore keeps the disk of the first test that reaches it, a fake one as every
// composition root in the tests is built on fakes. So each test has a name to itself.
// Puts in services of its own: not while the controls read theirs.
[Collection(AvaloniaControls.Name)]
public class WarehouseEditTests
{
private const string Text =