18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-02 05:02:45 +01:00

test(editor): self-test scripts that fail, a runner, and a case for each fix of the track editing

The editor's self-test scripts only logged: nothing made a run fail. Now:

- `expect` commands check the state and log `SELFTEST PASS` or `SELFTEST FAIL ... got X, expected Y`:
  the cant at a track end, the joint at an end (gap, angle, cant step), the records of a switch and
  the connections naming it, speed, gauge, a track present or removed, the laying norms' gauge,
  heights and lifts against a mark, whether a track is in the line under the route tool, and the
  includes of a turntable. A command no group takes counts as a failure, so a mistyped one can't
  make the checks after it pass.
- At `quit` the result is logged, and a script whose expectations failed ends the editor with exit
  code 2 (a failed start stays 1; the simulator's test mode is unchanged).
- The commit of the inspector's cant field is `track_cant_commit`, which the inspector and the
  `trackcant` command both call; `routegauge` sets the laying norms as the route tool does, and
  `tracksetdelete` deletes a set of tracks by name.
- `tests/editor/run.py` runs each script of `tests/editor/cases` on a copy of the fixture scenery
  in the game folder, with a wall-time limit and a memory cap, reads the exit code and the
  `SELFTEST` lines, and deletes the copy. A `#> reopen` line restarts the editor on the saved
  scenery. See `tests/editor/README.md`.
- One case per fix of the track editing quick fixes (inspector cant, norms after deleting, the
  gauge paste group, turntable speed saved, deleting a set, a set with a double switch, a slip
  and a crossover, deleting a switch of a crossover, a bent switch). All pass; with the fixes
  reverted all fail.
This commit is contained in:
maj00r
2026-11-23 03:31:57 +01:00
parent c813c03865
commit 690c913ef0
21 changed files with 1573 additions and 24 deletions
+1
View File
@@ -270,6 +270,7 @@ set(SOURCES
"application/editormodeselftestterrain.cpp"
"application/editormodeselftestrails.cpp"
"application/editormodeselftestmonkey.cpp"
"application/editormodeselftestexpect.cpp"
"application/scriptedinput.cpp"
"input/editormouseinput.cpp"
"application/editoruilayer.cpp"
+5
View File
@@ -19,6 +19,7 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "stdafx.h"
#include "application/application.h"
#include "application/editormodeselftest.h"
#include "simulation/simulationtest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
@@ -279,6 +280,10 @@ int main(int argc, char *argv[])
finish_log();
if (initresult < 0)
exitcode = 1;
// a self-test script of the editor whose expectations failed ends with a code of its own, for the runner of the scripts;
// without a script there's none
else if (exitcode == 0 && editor_selftest::failures() > 0)
exitcode = editor_selftest::failed_exit_code;
}
#ifndef _WIN32
fflush(stdout);
+10
View File
@@ -1086,6 +1086,13 @@ class editor_mode : public application_mode, private editor_track::observer, pri
std::vector<TTrack *> const &track_set() const override;
editor_track_tab current_track_tab() const override;
void render_path_ui();
// the cant at an end of a path [mm] from its roll [deg] and back, as the inspector shows and takes it: over 1500 mm between the
// rail axes
static float cant_of_roll(float const Roll);
static float roll_of_cant(float const Cant);
// the cant of the track changed goes on into the tracks joined at its ends, as with the gizmo and the joints tool: the joints would
// step otherwise. The track, whose state before the change is Before, and its neighbours go into one undo step
void track_cant_commit(TTrack &Track, editor_track::state const &Before);
void draw_track_overlay() const;
editor_track::point_ref track_handle_hit() const;
void select_track(scene::basic_node *Node);
@@ -3143,6 +3150,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri
scripted_input input;
std::string badge; // the mouse or the keys drawn over the view, for the clips of the tutorial
glm::vec2 badge_at{0.0f}; // its bottom left corner, in the pixels of the window
std::map<std::string, double> marks; // the heights of the ends of tracks kept by mark, for expect lift
};
selftest m_selftest;
using selftest_result = editor_selftest_result;
@@ -3157,6 +3165,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri
selftest_result selftest_terrain(std::string const &command, std::istringstream &words);
selftest_result selftest_props(std::string const &command, std::istringstream &words);
selftest_result selftest_monkey(std::string const &command, std::istringstream &words);
// the expectations of the script, which make the run fail (editormodeselftestexpect.cpp)
selftest_result selftest_expect(std::string const &command, std::istringstream &words);
selftest_result selftest_dispatch(std::string const &command, std::istringstream &words);
void selftest_step();
// a value typed during a gesture, taken instead of the one the cursor gives
+31 -3
View File
@@ -53,7 +53,7 @@ http://mozilla.org/MPL/2.0/.
editor_mode::selftest_result editor_mode::selftest_dispatch(std::string const &command, std::istringstream &words)
{
for (auto const group : {&editor_mode::selftest_scene, &editor_mode::selftest_sleepers, &editor_mode::selftest_sweep, &editor_mode::selftest_track, &editor_mode::selftest_switch, &editor_mode::selftest_rails, &editor_mode::selftest_join, &editor_mode::selftest_signal, &editor_mode::selftest_terrain, &editor_mode::selftest_props, &editor_mode::selftest_monkey})
for (auto const group : {&editor_mode::selftest_scene, &editor_mode::selftest_sleepers, &editor_mode::selftest_sweep, &editor_mode::selftest_track, &editor_mode::selftest_switch, &editor_mode::selftest_rails, &editor_mode::selftest_join, &editor_mode::selftest_signal, &editor_mode::selftest_terrain, &editor_mode::selftest_props, &editor_mode::selftest_monkey, &editor_mode::selftest_expect})
if (auto const result{(this->*group)(command, words)}; result != selftest_result::unhandled)
return result;
for (auto *tool : m_tools)
@@ -208,7 +208,26 @@ editor_mode::selftest_result editor_mode::selftest_dispatch(std::string const &c
// rideahead, rideprobe, rideleave logs the switch ahead from its blades / logs the place of the ride / ends the ride
// minimap <0|1|2>, stations the minimap shown or hidden (2: the whole scenery in it) / logs the stations the W4 name with their stops
// station <text>, minimapclick <x> <z> the camera to the next stop of the station whose name holds the text / as a click on the map there
// quit
// trackcant <track> <path> <start mm> <end mm> the cant typed into the field of the inspector: the tracks joined at the ends follow,
// in the same undo step
// routegauge <mm> [track] the rail axes distance of the norms set as the route tool sets it, the line of the track opened in
// it first unless it's open already
// tracksetdelete <name>... the tracks made the set, one too, and deleted as Del deletes the set
// mark <label> <track> <start|end> the height of the end of the first path kept, for expect lift
// expect cant <track> <start|end> <mm> <tolerance mm> the cant at the end of the first path, as the inspector shows it
// expect joint <track> <start|end> <gap m> <angle deg> <cant step mm> the end of the first path against the end of another track
// nearest to it within 1 m: the gap, the kink and the step of the cant between them, each at most
// expect records <name> <count> [kind] the records of the switch store of the name, with the connections having the switch among theirs
// expect speed <track> <km/h> [tolerance], expect gauge <track> <m> [tolerance] as editor_track::velocity gives it / the gauge
// expect track <name> <present|removed>
// expect route <track> <in|out> the track is a part of the line open in the route tool, or not
// expect norms gauge <mm> [tolerance] the rail axes distance of the norms the tracks are laid to
// expect height <track> <start|end> <m> <tolerance> the height of the end of the first path
// expect lift <track> <start|end> <label> <m> <tolerance> how far the end of the first path is above the height marked
// expect includes <track> <count> the includes whose parameters name the track: the model and the events of a turntable
// each expect logs SELFTEST PASS or SELFTEST FAIL; a failed one, or a command no group takes,
// makes the run end with editor_selftest::failed_exit_code
// quit logs SELFTEST result: <failed> failed of <expectations>, the editor closes
void editor_mode::selftest_step()
{
auto &test{m_selftest};
@@ -262,7 +281,8 @@ void editor_mode::selftest_step()
words >> test.wait;
return;
}
if (auto const result{selftest_dispatch(command, words)}; result == selftest_result::pause || result == selftest_result::again)
auto const result{selftest_dispatch(command, words)};
if (result == selftest_result::pause || result == selftest_result::again)
{
if (result == selftest_result::again)
--test.next;
@@ -272,6 +292,7 @@ void editor_mode::selftest_step()
{
if (false == test.quitting)
{
WriteLog(format("SELFTEST result: %zu failed of %zu", editor_selftest::failures(), editor_selftest::expectations()));
WriteLog("SELFTEST done");
test.quitting = true;
test.wait = 30;
@@ -281,5 +302,12 @@ void editor_mode::selftest_step()
Application.queue_quit(true);
return;
}
// a command no group took does nothing: a script mistyped, whose expectations after it would pass for nothing
if (result == selftest_result::unhandled)
{
++editor_selftest::expectations();
++editor_selftest::failures();
WriteLog("SELFTEST FAIL " + command + ": no group took the command");
}
}
}
+17
View File
@@ -37,6 +37,23 @@ inline std::size_t &frames_slow()
return count;
}
// the expectations of the script checked, and those of them which failed, with the commands no group knew. At quit the run ends
// with failed_exit_code when any failed, for the runner of the scripts (tests/editor/run.py)
inline std::size_t &expectations()
{
static std::size_t count{0};
return count;
}
inline std::size_t &failures()
{
static std::size_t count{0};
return count;
}
// apart from the 1 of a start which failed or of an error which ended the editor
inline constexpr int failed_exit_code{2};
inline std::string one_line(std::string Text)
{
std::replace(Text.begin(), Text.end(), '\n', ';');
+360
View File
@@ -0,0 +1,360 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "application/editormode.h"
#include "application/editormodeselftest.h"
#include "editor/editorFormat.hpp"
#include "editor/editorIncludeInfo.hpp"
#include "editor/editorSwitchStore.hpp"
#include "scene/scenelayers.h"
#include "simulation/simulation.h"
#include "utilities/Logs.h"
#include "utilities/utilities.h"
#include "world/Track.h"
#include <algorithm>
#include <cmath>
#include <map>
#include <sstream>
#include <string>
#include <vector>
// the expectations of a script: each logged as SELFTEST PASS <what> or SELFTEST FAIL <what>: got <value>, expected <value>, the failed
// ones counted, so the run ends with an error code at quit (editormodeselftest.cpp)
namespace
{
// the end of another track nearest to the end of a path is taken as the one joined there when it's this near, m
double constexpr kJointReach{1.0};
// the conversion of a roll [deg] to the cant [mm] the inspector shows
using cant_conversion = float (*)(float);
void expectation(bool const Passed, std::string const &What, std::string const &Got, std::string const &Wanted)
{
++editor_selftest::expectations();
if (Passed)
{
WriteLog("SELFTEST PASS " + What);
return;
}
++editor_selftest::failures();
WriteLog("SELFTEST FAIL " + What + ": got " + Got + ", expected " + Wanted);
}
void expect_near(std::string const &What, double const Got, double const Wanted, double const Tolerance)
{
expectation(std::abs(Got - Wanted) <= Tolerance, What, format("%.4f", Got), format("%.4f +- %.4f", Wanted, Tolerance));
}
// the arguments of the expectation weren't all there, or weren't numbers where numbers go: it fails
bool malformed(std::string const &What, std::istringstream const &Words)
{
if (false == Words.fail())
return false;
expectation(false, What, "malformed", "the arguments the expectation takes");
return true;
}
// an optional number after the arguments: Fallback when there's none. Read apart, as a failed read gives 0
double optional_number(std::istringstream &Words, double const Fallback)
{
if (double given{0.0}; Words >> given)
return given;
return Fallback;
}
// the end of the first path of the track named, as the expectations name it: <track> <start|end>
struct track_end
{
TTrack const *track{nullptr};
editor_track::point_ref point;
std::string error;
};
track_end read_end(std::istringstream &Words)
{
std::string name;
std::string side;
Words >> name >> side;
track_end result;
result.track = simulation::Paths.find(name);
result.point = {0, side == "end" ? editor_track::point_kind::end : editor_track::point_kind::start};
if (result.track == nullptr || result.track->m_editorremoved || result.track->m_paths.empty())
result.error = "no track " + name;
else if (side != "start" && side != "end")
result.error = "no end " + side;
return result;
}
bool failed_end(std::string const &What, track_end const &End)
{
if (End.error.empty())
return false;
expectation(false, What, End.error, "the end of a track");
return true;
}
// the end of a path of another track nearest to a point, within the reach of a joint
struct joined_end
{
TTrack const *track{nullptr};
editor_track::point_ref point;
double distance{kJointReach};
void take(TTrack const &Track, glm::dvec3 const &Point)
{
for (int path = 0; path < static_cast<int>(Track.m_paths.size()); ++path)
for (auto const kind : {editor_track::point_kind::start, editor_track::point_kind::end})
if (auto const gap{glm::distance(editor_track::point_position(Track, {path, kind}), Point)}; gap < distance)
{
distance = gap;
track = &Track;
point = {path, kind};
}
}
};
// expect cant <track> <start|end> <mm> <tolerance mm>
void expect_cant(std::string const &What, std::istringstream &Words, cant_conversion const Cant)
{
auto const end{read_end(Words)};
double wanted{0.0};
double tolerance{0.0};
Words >> wanted >> tolerance;
if (malformed(What, Words) || failed_end(What, end))
return;
auto const &path{end.track->m_paths.front()};
expect_near(What, Cant(end.point.kind == editor_track::point_kind::start ? path.rolls[0] : path.rolls[1]), wanted, tolerance);
}
// expect joint <track> <start|end> <gap m> <angle deg> <cant step mm>
void expect_joint(std::string const &What, std::istringstream &Words, cant_conversion const Cant)
{
auto const end{read_end(Words)};
double gap{0.0};
double angle{0.0};
double cant{0.0};
Words >> gap >> angle >> cant;
if (malformed(What, Words) || failed_end(What, end))
return;
auto const at{editor_track::point_position(*end.track, end.point)};
joined_end other;
for (auto const *track : simulation::Paths.sequence())
if (track != nullptr && track != end.track && false == track->m_editorremoved)
other.take(*track, at);
if (other.track == nullptr)
{
expectation(false, What, "no end of another track", format("one within %.1f m", kJointReach));
return;
}
auto const out{glm::normalize(editor_track::outward(*end.track, end.point))};
auto const in{-glm::normalize(editor_track::outward(*other.track, other.point))};
auto const kink{glm::degrees(std::acos(std::clamp(glm::dot(out, in), -1.0, 1.0)))};
// the rolls of the two ends are opposite where the joint doesn't step, as editor_track::match_rolls makes them
auto const own{Cant(static_cast<float>(editor_track::joint_roll(*end.track, end.point)))};
auto const theirs{Cant(static_cast<float>(editor_track::joint_roll(*other.track, other.point)))};
auto const step{std::abs(static_cast<double>(own) + static_cast<double>(theirs))};
auto const side{other.point.kind == editor_track::point_kind::start ? "start" : "end"};
expectation(other.distance <= gap && kink <= angle && step <= cant, What, format("gap %.4f m, kink %.4f deg, cant step %.1f mm to %s[%d] %s", other.distance, kink, step, other.track->name().c_str(), other.point.path, side),
format("at most %.4f m, %.4f deg, %.1f mm", gap, angle, cant));
}
// expect records <name> <count> [kind]
void expect_records(std::string const &What, std::istringstream &Words)
{
std::string name;
std::size_t wanted{0};
Words >> name >> wanted;
if (malformed(What, Words))
return;
std::string kind;
Words >> kind;
// the records of the switch, slip or crossing of the name, and the connections having the switch among theirs
auto const counted = [&name, &kind](switch_store::record const &Entry) {
auto const among{Entry.kind == "connection" && std::ranges::find(Entry.parts, name) != Entry.parts.end()};
return (Entry.name == name || among) && (kind.empty() || Entry.kind == kind);
};
auto const count{static_cast<std::size_t>(std::ranges::count_if(switch_store::records(), counted))};
expectation(count == wanted, What, std::to_string(count), std::to_string(wanted));
}
// expect speed <track> <km/h> [tolerance], expect gauge <track> <m> [tolerance]
void expect_track_value(std::string const &What, std::string const &Kind, std::istringstream &Words)
{
std::string name;
double wanted{0.0};
Words >> name >> wanted;
if (malformed(What, Words))
return;
auto const speed{Kind == "speed"};
auto const tolerance{optional_number(Words, speed ? 0.01 : 0.0005)};
auto const *track{simulation::Paths.find(name)};
if (track == nullptr || track->m_editorremoved)
{
expectation(false, What, "no track " + name, "the track");
return;
}
expect_near(What, speed ? editor_track::velocity(*track) : static_cast<double>(track->fTrackWidth), wanted, tolerance);
}
// expect track <name> <present|removed>
void expect_track(std::string const &What, std::istringstream &Words)
{
std::string name;
std::string state;
Words >> name >> state;
if (malformed(What, Words))
return;
if (state != "present" && state != "removed")
{
expectation(false, What, "no state " + state, "present or removed");
return;
}
auto const *track{simulation::Paths.find(name)};
auto const present{track != nullptr && false == track->m_editorremoved};
expectation(present == (state == "present"), What, present ? "present" : "removed", state);
}
// expect route <track> <in|out>
void expect_route(std::string const &What, std::istringstream &Words, std::vector<TTrack *> const &Line)
{
std::string name;
std::string state;
Words >> name >> state;
if (malformed(What, Words))
return;
if (state != "in" && state != "out")
{
expectation(false, What, "no state " + state, "in or out");
return;
}
auto const *track{simulation::Paths.find(name)};
auto const in{track != nullptr && std::ranges::find(Line, track) != Line.end()};
expectation(in == (state == "in"), What, in ? "in" : "out", state);
}
// expect norms gauge <mm> [tolerance]
void expect_norm(std::string const &What, std::istringstream &Words, alignment::limits const &Norms)
{
std::string key;
double wanted{0.0};
Words >> key >> wanted;
if (malformed(What, Words))
return;
if (key != "gauge")
{
expectation(false, What, "no norm " + key, "gauge");
return;
}
expect_near(What, Norms.gauge, wanted, optional_number(Words, 0.5));
}
// expect height <track> <start|end> <m> <tolerance>, expect lift <track> <start|end> <label> <m> <tolerance>
void expect_height(std::string const &What, std::string const &Kind, std::istringstream &Words, std::map<std::string, double> const &Marks)
{
auto const end{read_end(Words)};
std::string label;
if (Kind == "lift")
Words >> label;
double wanted{0.0};
double tolerance{0.0};
Words >> wanted >> tolerance;
if (malformed(What, Words) || failed_end(What, end))
return;
auto height{editor_track::point_position(*end.track, end.point).y};
if (Kind == "lift")
{
auto const mark{Marks.find(label)};
if (mark == Marks.end())
{
expectation(false, What, "no mark " + label, "a height marked");
return;
}
height -= mark->second;
}
expect_near(What, height, wanted, tolerance);
}
// the include is in the scenery, not deleted, and the name is among the values of its parameters: the model and the events of a
// turntable name its track so
bool names_track(scene::instance_handle const Handle, std::string const &Name)
{
if (false == scene::Layers.tracked(Handle))
return false;
auto const &included{scene::Layers.instance(Handle)};
if (included.removed || included.dead || included.file == nullptr)
return false;
std::string file;
std::vector<std::string> values;
return editor_includes::parse_directive(scene::Layers.directive(Handle), file, values) && std::ranges::any_of(values, [&Name](std::string const &Value) { return ToLower(Value) == Name; });
}
// expect includes <track> <count>
void expect_includes(std::string const &What, std::istringstream &Words)
{
std::string name;
std::size_t wanted{0};
Words >> name >> wanted;
if (malformed(What, Words))
return;
std::size_t count{0};
for (scene::instance_handle handle = 1; handle <= scene::Layers.instance_count(); ++handle)
if (names_track(handle, name))
++count;
expectation(count == wanted, What, std::to_string(count), std::to_string(wanted));
}
} // namespace
editor_mode::selftest_result editor_mode::selftest_expect(std::string const &command, std::istringstream &words)
{
if (command == "mark")
{
std::string label;
words >> label;
auto const end{read_end(words)};
if (failed_end("mark " + label, end))
return selftest_result::handled;
auto const height{editor_track::point_position(*end.track, end.point).y};
m_selftest.marks[label] = height;
WriteLog(format("SELFTEST mark %s: %.4f m", label.c_str(), height));
return selftest_result::handled;
}
if (command != "expect")
return selftest_result::unhandled;
// what is expected as the script says it, for the log
auto what{words.str()};
what.erase(0, std::min(what.size(), what.find("expect") + 6));
what.erase(0, std::min(what.size(), what.find_first_not_of(' ')));
std::string kind;
words >> kind;
if (kind == "cant")
expect_cant(what, words, &editor_mode::cant_of_roll);
else if (kind == "joint")
expect_joint(what, words, &editor_mode::cant_of_roll);
else if (kind == "records")
expect_records(what, words);
else if (kind == "speed" || kind == "gauge")
expect_track_value(what, kind, words);
else if (kind == "track")
expect_track(what, words);
else if (kind == "route")
expect_route(what, words, m_route.chain.tracks);
else if (kind == "norms")
expect_norm(what, words, laying_norms());
else if (kind == "height" || kind == "lift")
expect_height(what, kind, words, m_selftest.marks);
else if (kind == "includes")
expect_includes(what, words);
else
expectation(false, what, "no expectation " + kind, "cant, joint, records, speed, gauge, track, route, norms, height, lift or includes");
return selftest_result::handled;
}
+37
View File
@@ -399,6 +399,43 @@ editor_mode::selftest_result editor_mode::selftest_track(std::string const &comm
WriteLog("SELFTEST " + command + ": " + m_route.status + " " + m_route.error);
return selftest_result::handled;
}
if (command == "routegauge")
{
double gauge{1500.0};
std::string name;
words >> gauge >> name;
// the line of the track opened in the route tool, as a click on it with the tool does, unless it's in the line open already
if (auto *track{simulation::Paths.find(name)}; track != nullptr && false == track->m_editorremoved && std::ranges::find(m_route.chain.tracks, track) == m_route.chain.tracks.end())
{
m_track_tab = track_tab::route;
m_route.single = false;
route_load(*track);
}
// as the field of the rail axes distance among the norms of the route tool sets it
m_route.design.norms.gauge = std::max(100.0, gauge);
WriteLog(format("SELFTEST routegauge: %.0f mm, the line of %zu paths open", m_route.design.norms.gauge, m_route.chain.tracks.size()));
return selftest_result::handled;
}
if (command == "trackcant")
{
std::string name;
int index{0};
std::array<float, 2> cants{0.0f, 0.0f};
words >> name >> index >> cants[0] >> cants[1];
auto *track{simulation::Paths.find(name)};
std::string reason;
if (track == nullptr || track->m_editorremoved || index < 0 || index >= static_cast<int>(track->m_paths.size()) || false == editor_track::can_edit_geometry(*track, reason))
{
WriteLog("SELFTEST trackcant: no path " + name + " " + std::to_string(index) + " to edit " + reason);
return selftest_result::handled;
}
// as the field of the inspector takes it: the rolls of the path set, then the edit committed with the track as it was before
auto const before{editor_track::capture(*track)};
track->m_paths[index].rolls = {roll_of_cant(cants[0]), roll_of_cant(cants[1])};
track_cant_commit(*track, before);
WriteLog(format("SELFTEST trackcant %s %d: %.1f %.1f mm", name.c_str(), index, cant_of_roll(track->m_paths[index].rolls[0]), cant_of_roll(track->m_paths[index].rolls[1])));
return selftest_result::handled;
}
if (command == "digitizescenery")
{
// "digitizescenery write" digitizes, without the word only counts what it would do
+29 -20
View File
@@ -1442,6 +1442,32 @@ void editor_mode::render_path_events(TTrack &Track)
ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), STR_C("No such events: %s"), m_track_events_missing.c_str());
}
float editor_mode::cant_of_roll(float const Roll)
{
return static_cast<float>(1500.0 * std::sin(glm::radians(static_cast<double>(Roll))));
}
float editor_mode::roll_of_cant(float const Cant)
{
return static_cast<float>(glm::degrees(std::asin(std::clamp(static_cast<double>(Cant) / 1500.0, -1.0, 1.0))));
}
void editor_mode::track_cant_commit(TTrack &Track, editor_track::state const &Before)
{
std::vector<std::pair<TTrack *, editor_track::state>> states{{&Track, Before}};
std::vector<TTrack *> changed{&Track};
auto const joints{editor_track::joints(Track)};
for (auto const &joint : joints)
if (std::ranges::find(changed, joint.other) == changed.end())
{
states.emplace_back(joint.other, editor_track::capture(*joint.other));
changed.push_back(joint.other);
}
editor_track::match_rolls(Track, joints);
push_track_snapshot(std::move(states));
editor_track::commit(changed);
}
void editor_mode::render_path_ui()
{
auto *track = selected_track();
@@ -1584,30 +1610,13 @@ void editor_mode::render_path_ui()
if (begin_fields("##cantradius", 0.3f))
{
field_row("Cant (mm)");
auto const lift = [](float const Roll) { return static_cast<float>(1500.0 * std::sin(glm::radians(static_cast<double>(Roll)))); };
auto const roll = [](float const Lift) { return static_cast<float>(glm::degrees(std::asin(std::clamp(static_cast<double>(Lift) / 1500.0, -1.0, 1.0)))); };
if (std::array<float, 2> cants{lift(path.rolls[0]), lift(path.rolls[1])}; ImGui::DragFloat2("##roll", cants.data(), 0.5f, -388.0f, 388.0f, "%.0f") && std::isfinite(cants[0]) && std::isfinite(cants[1]))
path.rolls = {roll(cants[0]), roll(cants[1])};
if (std::array<float, 2> cants{cant_of_roll(path.rolls[0]), cant_of_roll(path.rolls[1])}; ImGui::DragFloat2("##roll", cants.data(), 0.5f, -388.0f, 388.0f, "%.0f") && std::isfinite(cants[0]) && std::isfinite(cants[1]))
path.rolls = {roll_of_cant(cants[0]), roll_of_cant(cants[1])};
item_tooltip("Cant at the start and at the end: how much higher one rail is, + raises the left rail looking along the path");
// the cant typed at an end goes on into the track joined there, as with the gizmo and the joints tool: the joint
// would step otherwise. the neighbours go into the same undo step
if (ImGui::IsItemActivated())
m_track_field_before = before;
if (ImGui::IsItemDeactivatedAfterEdit())
{
std::vector<std::pair<TTrack *, editor_track::state>> states{{track, m_track_field_before}};
std::vector<TTrack *> changed{track};
auto const joints{editor_track::joints(*track)};
for (auto const &joint : joints)
if (std::find(changed.begin(), changed.end(), joint.other) == changed.end())
{
states.emplace_back(joint.other, editor_track::capture(*joint.other));
changed.push_back(joint.other);
}
editor_track::match_rolls(*track, joints);
push_track_snapshot(std::move(states));
editor_track::commit(changed);
}
track_cant_commit(*track, m_track_field_before);
field_row("Radius");
if (auto radius{path.radius}; ImGui::InputFloat("##radius", &radius, 0.0f, 0.0f, "%.1f") && std::isfinite(radius))
path.radius = radius;
+16 -1
View File
@@ -2093,6 +2093,21 @@ editor_mode::selftest_result editor_mode::selftest_props(std::string const &Comm
WriteLog(format("SELFTEST tracksel: %zu tracks selected", selected_tracks().size()));
return selftest_result::handled;
}
if (Command == "tracksetdelete")
{
// the set made of the tracks, also of one, and the last of them selected, as the set stays the selection only with it
m_track_set.clear();
for (std::string name; Words >> name;)
if (auto *track{simulation::Paths.find(name)}; track != nullptr && false == track->m_editorremoved)
m_track_set.push_back(track);
m_node = m_track_set.empty() ? nullptr : m_track_set.back();
m_track_point = {};
ui()->set_node(m_node);
auto const count{m_track_set.size()};
track_set_delete();
WriteLog(format("SELFTEST tracksetdelete: %zu tracks in the set", count));
return selftest_result::handled;
}
if (Command == "trackprop")
{
std::string key;
@@ -2140,7 +2155,7 @@ editor_mode::selftest_result editor_mode::selftest_props(std::string const &Comm
}
else if (action == "groups")
{
// the groups ticked, as their numbers: 0 speed ... 9 frogs, 10 sleeper placement
// the groups ticked, as their numbers: 0 speed ... 9 frogs, 10 sleeper placement, 11 gauge
m_track_style.groups.fill(false);
m_track_style.ticks.clear();
for (int group; Words >> group;)
+1
View File
@@ -0,0 +1 @@
out/
+100
View File
@@ -0,0 +1,100 @@
# Self-tests of the track editor
Scripts that drive the track editor through the commands of its self-test (`application/editormodeselftest*.cpp`) and check
what came out with `expect` commands. A failed expectation makes the run fail: the editor ends with a non-zero exit code.
The game data isn't in this repository, so these run against a local game install only, not in CI.
## Running
The editor has to be built with the self-tests, which a normal build leaves out (a script takes over the input of the editor):
```
cmake -S . -B build -DWITH_EDITOR_SELFTESTS=ON
cmake --build build --config RelWithDebInfo
```
Then, with the game folder (one with `scenery/`, `models/` and `dynamic/` of the game data):
```
python tests/editor/run.py --game-dir C:/MaSzyna # all cases
python tests/editor/run.py --game-dir C:/MaSzyna 1_inspector_cant # chosen cases
python tests/editor/run.py --game-dir C:/MaSzyna --ini low.ini # with settings of your own over the runner's
```
- `--exe` names the executable; by default it's the newest `eu07*.exe` under `build/bin`.
- `--ini` is read over the runner's settings (a 640x480 window, no sound, `convertmodels 0`, `log.txt` in the game folder),
which are read over the player's own `eu07.ini`. A file with low settings of the picture makes the runs quicker.
- `--timeout` (240 s) and `--memory-mb` (8192 MB) limit each run of the editor. On Windows the editor runs in a job object
which keeps its memory under the limit and ends it with the runner; the runner also stops it when it goes over the limit.
- `--show` shows the window of the editor; without it the window is never shown nor focused (`EU07_EDITOR_SELFTEST_HIDDEN`),
so the computer can be used meanwhile.
- `--keep` keeps the copies of the scenery, to look at what a script saved.
The cases run one after another, one editor at a time. Each prints the exit code of the editor, its time and memory, the
`SELFTEST FAIL` lines, and `PASS` or `FAIL`; a summary follows. The runner exits with 1 when any case failed. The scripts as
they were run and the logs of the editor are in `tests/editor/out/<case>/`.
## How it works
For each case the runner:
1. copies the fixture, `scenery/autotest_editor.scn`, into the `scenery` folder of the game as `autotest_editor_<case>.scn`,
2. starts `eu07 -ini <runner's settings> [-ini <--ini>] -edit autotest_editor_<case>.scn` in the game folder, with the script in
`EU07_EDITOR_SELFTEST` (the settings first: a `sceneryfile` in them would take the place of the scenery otherwise),
3. waits until the editor quits, or stops it at the limits of time and memory,
4. reads the exit code and the `SELFTEST` lines of `log.txt`,
5. deletes the copy of the scenery and whatever the editor wrote next to it under its name, and says what else the run added
to the `scenery` folder or changed there.
A case passes when every run of the editor ended with the exit code 0, its log has `SELFTEST result: 0 failed of N`, and the
case checked something (N above 0 over all its runs). The editor ends with 2 when an expectation failed or a command of the
script wasn't taken by any group of the self-test (a typo would otherwise let the expectations after it pass for nothing),
with 1 when it couldn't start or an error ended it, and with the system's code on a crash.
The fixture holds plain tracks only, no terrain: lines of straights (`a`, `s`, `d`, the pair `p` and `q` 4.5 m apart), a track
of 1000 mm gauge (`g1`) beside one of the standard gauge (`g2`), a turntable of 16 m with `velocity 10` (`tt1`, with the
include of its model and events), two curves of 600 and 604.5 m side by side with a cant of 60 mm (`i0`..`i9`, `o0`..`o9`,
the straights at their ends taking the cant on and off), and a track apart with a vehicle (`v1`), without which the editor
would put one of its own onto a track of the cases on saving. It uses only what every install of the game has.
## Writing a case
A case is `cases/<name>.txt`: one command a line, `#` for comments, as for `EU07_EDITOR_SELFTEST`. The commands are listed at
the top of `application/editormodeselftest.cpp`. Start with a `wait` of a few frames and end with `quit`, which logs
`SELFTEST result: <failed> failed of <expectations>`.
The expectations (`expect <what> ...`), each logged as `SELFTEST PASS <what>` or `SELFTEST FAIL <what>: got <value>, expected <value>`:
| expectation | checks |
| --- | --- |
| `expect cant <track> <start\|end> <mm> <tolerance mm>` | the cant at the end of the first path, as the inspector shows it (1500 mm between the rail axes) |
| `expect joint <track> <start\|end> <gap m> <angle deg> <cant step mm>` | the end of the first path against the nearest end of another track (within 1 m): the gap, the kink and the step of the cant between them, each at most the value given |
| `expect records <name> <count> [kind]` | the records of the switches (`//$r`) of the name, with the connections having the switch among theirs; only those of the kind (`switch`, `slip`, `crossing`, `double`, `connection`) when given |
| `expect speed <track> <km/h> [tolerance]` | the speed of the track as the editor shows it (`editor_track::velocity`) |
| `expect gauge <track> <m> [tolerance]` | the gauge of the track |
| `expect track <name> <present\|removed>` | a track of the name is in the scenery, or isn't |
| `expect route <track> <in\|out>` | the track is a part of the line open in the route tool, or isn't |
| `expect norms gauge <mm> [tolerance]` | the rail axes distance of the norms the tracks are laid to |
| `expect height <track> <start\|end> <m> <tolerance>` | the height of the end of the first path |
| `expect lift <track> <start\|end> <label> <m> <tolerance>` | how far the end is above the height `mark <label> <track> <start\|end>` kept |
| `expect includes <track> <count>` | the includes whose parameters name the track: the model and the events of a turntable |
A line `#> reopen` ends a run of the editor there (the part before it saves and ends with `quit`) and starts the editor again
on the scenery as it was saved, for what has to be checked after a save and a load. The editor's own `openscenery` starts a
new editor without the script, so it isn't for the cases.
## The cases
The cases check the fixes of PR #450 (the numbers are those of its test plan):
| case | fix |
| --- | --- |
| `1_inspector_cant` | the cant typed into the inspector goes on into the track joined at that end, in the same undo step |
| `3_norms_after_delete` | deleting a track of the line open in the route tool keeps the laying norms |
| `4_gauge_paste_group` | the gauge is a paste group of its own, off by default |
| `5_turntable_speed` | the speed of a turntable set in the editor is the one saved |
| `6_set_delete_records` | deleting a set of tracks takes the records of its switches, and the model and the events of a turntable |
| `6b_set_delete_whole` | a double switch, a slip and a crossover in a set go whole, with their records |
| `7_crossover_delete` | deleting a switch of a crossover on a curve takes the crossover out whole: the outer track comes down, the record goes |
| `7b_bent_switch_delete` | a switch bent out of the shape of its record still takes the record along when deleted |
+21
View File
@@ -0,0 +1,21 @@
# PR #450: the cant typed into the inspector at an end of a track goes on into the track joined there, as the gizmo and
# the joints tool do it, and the neighbour goes into the same undo step. The joint stepped before.
# a1, a2, a3: straights joined one after another, no cant
wait 5
expect cant a1 end 0 0.5
expect cant a2 start 0 0.5
trackcant a1 0 0 80
expect cant a1 end 80 0.5
# the track joined at the end has the cant at the joint too: the joint doesn't step
expect cant a2 start 80 0.5
expect joint a1 end 0.001 0.01 1
# its other end stays as it was
expect cant a2 end 0 0.5
# the free end of a1 too
expect cant a1 start 0 0.5
# one undo puts both tracks back
undo
expect cant a1 end 0 0.5
expect cant a2 start 0 0.5
expect joint a1 end 0.001 0.01 1
quit
@@ -0,0 +1,19 @@
# PR #450: deleting a track of the line open in the route tool keeps the laying norms. They went back to the defaults,
# and every later lay, extend and join used those.
# a1, a2, a3: straights joined one after another
wait 5
expect norms gauge 1500
# the line of a2 opened in the route tool, the rail axes distance of its norms set to 1000 mm there
routegauge 1000 a2
expect route a2 in
expect norms gauge 1000
deletetrack a2
expect track a2 removed
# the line is let go of, the norms stay
expect route a1 out
expect norms gauge 1000
# a track laid on from the end the delete left free is laid to them
lay a1 end 0 160
expect joint a1 end 0.001 0.01 1
expect norms gauge 1000
quit
@@ -0,0 +1,23 @@
# PR #450: the gauge is a paste group of its own, off by default: pasting how a track rides or sounds no longer changes
# its gauge.
# g1: a track of 1000 mm gauge, g2: one of the standard gauge
wait 5
expect gauge g1 1.000
expect gauge g2 1.435
trackstyle copy g1
tracksel g2
# the groups ticked at first: the gauge isn't among them
trackstyle paste
expect gauge g2 1.435
# ride and sound alone (group 8), which the gauge was a part of
trackstyle groups 8
trackstyle paste
expect gauge g2 1.435
# with the gauge ticked (group 11)
trackstyle groups 8 11
trackstyle paste
expect gauge g2 1.000
expect gauge g1 1.000
undo
expect gauge g2 1.435
quit
+16
View File
@@ -0,0 +1,16 @@
# PR #450: the speed of a turntable set in the editor is the one saved. The editor changed the speed the turntable runs
# at, while the file keeps the limit it was loaded with.
# tt1: a turntable with velocity 10 in the scenery file
wait 5
expect speed tt1 10
tracksel tt1
trackprop speed 20
expect speed tt1 20
save
wait 5
quit
#> reopen
# the scenery as saved, loaded again
wait 5
expect speed tt1 20
quit
@@ -0,0 +1,40 @@
# PR #450: deleting a set of tracks does what Del does with each: the records of the switches go with them, and the
# model and the events of a turntable too. The records stayed behind and on saving were given to another switch.
# s1, s2, s3: straights joined one after another; tt1: a turntable with the include of its model and events
wait 5
switchplace Rz_60E1-300-1:9 40 150 1 1
expect records z1 1 switch
expect includes tt1 1
# a set of the switch, the track before it and the turntable
tracksetdelete z1 s2 tt1
expect track z1 removed
expect track s2 removed
expect track tt1 removed
expect records z1 0
expect includes tt1 0
# one undo brings it all back
undo
expect track z1 present
expect track s2 present
expect track tt1 present
expect records z1 1 switch
expect includes tt1 1
redo
expect records z1 0
expect includes tt1 0
save
wait 5
quit
#> reopen
# the scenery as saved, loaded again: no record of the switch, no turntable
wait 5
expect track z1 removed
expect track tt1 removed
expect records z1 0
expect includes tt1 0
# a new switch, given the name z1 freed, has one record, its own
switchplace Rz_60E1-300-1:9 80 150 1 1
expect track z1 present
expect records z1 1
expect records z1 1 switch
quit
@@ -0,0 +1,42 @@
# PR #450: in a set deleted, a double switch, a slip and a crossover go whole, with their records, as Del takes them out.
# d1, d2, d3 and s1, s2, s3: straights joined one after another; p1..p3 and q1..q3: two such lines 4.5 m apart
wait 5
# a double switch: z1 and z1b, one record of both
switchplace Rpd_49E1-190-1:9/1:9 80 150 1 1
expect records z1 1 double
tracksetdelete z1b
expect track z1 removed
expect track z1b removed
expect records z1 0
undo
expect track z1 present
expect track z1b present
expect records z1 1 double
# a double slip: four switches, one record
slipplace Rkpd_60E1-190-1:9 40 150 1 1
expect records editor_dks1 1 slip
tracksetdelete editor_dks1_c
expect track editor_dks1_a removed
expect track editor_dks1_b removed
expect track editor_dks1_c removed
expect track editor_dks1_d removed
expect records editor_dks1 0
undo
expect track editor_dks1_a present
expect track editor_dks1_d present
expect records editor_dks1 1 slip
# a crossover between the straights: z2 and z3, the record of the connection with theirs
connection crossover 120 120 124.5 160 Rz_60E1-300-1:9
expect records z2 1 connection
expect records z3 2
tracksetdelete z3 p1
expect track z2 removed
expect track z3 removed
expect track p1 removed
expect records z2 0
expect records z3 0
undo
expect track z2 present
expect track z3 present
expect records z2 1 connection
quit
+44
View File
@@ -0,0 +1,44 @@
# PR #450: deleting a switch of a crossover takes the crossover out whole, as the connection tools do: the outer track
# of a crossover on a curve comes down by its lift and the record of the connection goes. Alone, the switch left the outer
# track up for good, and the connection to the next switch given its name.
# i0..i9 and o0..o9: curves of 600 and 604.5 m side by side, 4.5 m apart, canted 60 mm
wait 5
mark o2e o2 end
mark o4s o4 start
mark o6s o6 start
# from the inner curve over to the outer one: z1 on the inner, z2 on the outer, which goes up onto the plane of the inner
connection crossover 304.316 71.828 307.512 120.096 Rz_60E1-300-1:9
expect records z1 1 switch
expect records z2 1 switch
expect records z1 1 connection
expect records z2 1 connection
# 4.5 m across the cant of 60 mm in 1500 mm, level between the switches, along ramps outside them
expect lift o4 start o4s 0.180 0.005
expect lift o2 end o2e 0.158 0.005
expect lift o6 start o6s 0.172 0.005
# Del on the second switch
deletetrack z2
expect track z1 removed
expect track z2 removed
expect records z1 0
expect records z2 0
# the outer track down again, the lines whole without steps
expect lift o4 start o4s 0 0.002
expect lift o2 end o2e 0 0.002
expect lift o6 start o6s 0 0.002
expect joint i3 end 0.001 0.01 1
expect joint o4 end 0.001 0.01 1
# a new switch given the name freed doesn't take the connection over
switchplace Rz_60E1-300-1:9 40 150 1 1
expect track z1 present
expect records z1 1
expect records z1 0 connection
# the new switch undone, then the delete in one step: the crossover is back whole, the outer track up
undo
undo
expect track z1 present
expect track z2 present
expect records z1 1 connection
expect records z2 1 connection
expect lift o4 start o4s 0.180 0.005
quit
@@ -0,0 +1,18 @@
# PR #450: a switch bent out of the shape of its record is found by its name when deleted, and its record goes with it.
# s1, s2, s3: straights joined one after another
wait 5
switchplace Rz_60E1-300-1:9 40 150 1 1
expect records z1 1 switch
# the end of the diverging path of z1 moved aside with the gizmo: z1 no longer has the shape its record says
select z1
gizmo begin translate 1 end
gizmo offset 0.5 0 0
gizmo end
expect records z1 1 switch
deletetrack z1
expect track z1 removed
expect records z1 0
undo
expect track z1 present
expect records z1 1 switch
quit
+367
View File
@@ -0,0 +1,367 @@
#!/usr/bin/env python3
"""Self-test scripts of the track editor: run the editor on a copy of a test scenery and check what its expectations say.
A case (cases/<name>.txt) is a script of the editor's self-test commands (application/editormodeselftest*.cpp), with
`expect` commands that log SELFTEST PASS or SELFTEST FAIL and make the editor end with a non-zero exit code when any of
them failed. For each case the runner:
1. copies the fixture (scenery/autotest_editor.scn) into the game's scenery folder as autotest_editor_<case>.scn,
2. starts the editor (eu07 -edit <scenery>) with the script in EU07_EDITOR_SELFTEST, its window hidden, a settings
file of its own (-ini) and the one given with --ini over it, a limit of wall time and of memory,
3. reads the exit code and the SELFTEST lines of log.txt, and prints PASS or FAIL for the case,
4. deletes the copy of the scenery and whatever the editor wrote next to it under its name.
A line `#> reopen` in a script ends the editor there (the part before it ends with quit) and starts it again on the
scenery as the part before saved it, for what has to be seen after a save and a load.
The editor has to be built with -DWITH_EDITOR_SELFTESTS=ON; a build without it runs no script and is stopped at the
time limit. The game data isn't in this repository, so this runs against a local game install only, not in CI.
One editor runs at a time. See README.md.
Usage:
python tests/editor/run.py --game-dir C:/MaSzyna [--ini my.ini] [--exe build/bin/RelWithDebInfo/eu07-....exe] [cases...]
"""
from __future__ import annotations
import argparse
import os
import re
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
HERE = Path(__file__).resolve().parent
REPO = HERE.parents[1]
CASES_DIR = HERE / "cases"
FIXTURE = HERE / "scenery" / "autotest_editor.scn"
OUT_DIR = HERE / "out"
# a part of a script ends with quit before this line, the editor starts again on the scenery saved
REOPEN = "#> reopen"
# the exit code of a run whose expectations failed, editor_selftest::failed_exit_code
FAILED_EXIT_CODE = 2
# settings of the runner, read over the player's eu07.ini and under the file given with --ini: a small window, no sound,
# nothing written into the data of the game, log.txt in the game folder
RUNNER_INI = """\
fullscreen no
fullscreenwindowed no
width 640
height 480
inactivepause no
soundenabled no
convertmodels 0
multiplelogs no
debuglog 1
"""
@dataclass
class StageResult:
exit_code: int | None = None
failure: str = ""
seconds: float = 0.0
peak_mb: float = 0.0
lines: list[str] = field(default_factory=list) # the SELFTEST PASS / FAIL / result lines of its log
# ---------------------------------------------------------------- the process and its memory
if os.name == "nt":
import ctypes
from ctypes import wintypes
class _MemoryCounters(ctypes.Structure):
_fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD), ("PeakWorkingSetSize", ctypes.c_size_t),
("WorkingSetSize", ctypes.c_size_t), ("QuotaPeakPagedPoolUsage", ctypes.c_size_t),
("QuotaPagedPoolUsage", ctypes.c_size_t), ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t),
("QuotaNonPagedPoolUsage", ctypes.c_size_t), ("PagefileUsage", ctypes.c_size_t),
("PeakPagefileUsage", ctypes.c_size_t), ("PrivateUsage", ctypes.c_size_t)]
class _IoCounters(ctypes.Structure):
_fields_ = [(name, ctypes.c_ulonglong) for name in ("ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
class _BasicLimits(ctypes.Structure):
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong), ("PerJobUserTimeLimit", ctypes.c_longlong),
("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),
("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD), ("SchedulingClass", wintypes.DWORD)]
class _ExtendedLimits(ctypes.Structure):
_fields_ = [("BasicLimitInformation", _BasicLimits), ("IoInfo", _IoCounters), ("ProcessMemoryLimit", ctypes.c_size_t),
("JobMemoryLimit", ctypes.c_size_t), ("PeakProcessMemoryUsed", ctypes.c_size_t),
("PeakJobMemoryUsed", ctypes.c_size_t)]
_kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
_kernel32.CreateJobObjectW.restype = wintypes.HANDLE
_kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
_kernel32.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
_kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
_kernel32.K32GetProcessMemoryInfo.argtypes = [wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD]
_kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
_JOB_EXTENDED_LIMITS = 9
_JOB_LIMIT_PROCESS_MEMORY = 0x100
_JOB_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
def guard_process(proc: subprocess.Popen, limit_mb: int):
"""A job object over the editor: its memory can't grow past the limit, and it ends with the runner. None if the
system doesn't allow it (the polling of the memory still stops the editor then)."""
job = _kernel32.CreateJobObjectW(None, None)
if not job:
return None
limits = _ExtendedLimits()
limits.BasicLimitInformation.LimitFlags = _JOB_LIMIT_PROCESS_MEMORY | _JOB_LIMIT_KILL_ON_JOB_CLOSE
limits.ProcessMemoryLimit = limit_mb * 1024 * 1024
if not _kernel32.SetInformationJobObject(job, _JOB_EXTENDED_LIMITS, ctypes.byref(limits), ctypes.sizeof(limits)) \
or not _kernel32.AssignProcessToJobObject(job, int(proc._handle)):
_kernel32.CloseHandle(job)
return None
return job
def release_guard(job) -> None:
if job:
_kernel32.CloseHandle(job)
def memory_mb(proc: subprocess.Popen) -> float:
counters = _MemoryCounters()
counters.cb = ctypes.sizeof(counters)
if not _kernel32.K32GetProcessMemoryInfo(int(proc._handle), ctypes.byref(counters), counters.cb):
return 0.0
return counters.PrivateUsage / (1024 * 1024)
else:
def guard_process(proc: subprocess.Popen, limit_mb: int):
return None
def release_guard(job) -> None:
pass
def memory_mb(proc: subprocess.Popen) -> float:
try:
for line in Path(f"/proc/{proc.pid}/status").read_text().splitlines():
if line.startswith("VmRSS:"):
return int(line.split()[1]) / 1024
except (OSError, ValueError):
pass
return 0.0
def run_editor(exe: Path, game_dir: Path, scenery: str, script: Path, inis: list[Path], timeout: float, limit_mb: int,
show: bool) -> StageResult:
"""Runs the editor on the scenery with the script until it quits, or until the limits stop it."""
# the settings files before the scenery: one naming a sceneryfile of its own would take its place otherwise
cmd = [str(exe)]
for ini in inis:
cmd += ["-ini", str(ini)]
cmd += ["-edit", scenery]
env = dict(os.environ)
env["EU07_EDITOR_SELFTEST"] = str(script)
if show:
env.pop("EU07_EDITOR_SELFTEST_HIDDEN", None)
else:
# the window is never shown nor focused, the computer stays free for whatever else it's used for
env["EU07_EDITOR_SELFTEST_HIDDEN"] = "1"
result = StageResult()
started = time.monotonic()
proc = subprocess.Popen(cmd, cwd=game_dir, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
job = guard_process(proc, limit_mb)
try:
while proc.poll() is None:
time.sleep(0.25)
used = memory_mb(proc)
result.peak_mb = max(result.peak_mb, used)
if used > limit_mb:
result.failure = f"stopped at {used:.0f} MB, over the limit of {limit_mb} MB"
break
if time.monotonic() - started > timeout:
result.failure = f"stopped after {timeout:.0f} s, the time limit"
break
finally:
if proc.poll() is None:
proc.kill()
proc.wait(timeout=30)
release_guard(job)
result.exit_code = proc.returncode
result.seconds = time.monotonic() - started
return result
# ---------------------------------------------------------------- the scripts, the log and the copies
def split_script(text: str) -> list[str]:
"""The parts of a script, each run in an editor of its own."""
parts = re.split(rf"(?m)^{re.escape(REOPEN)}\s*$", text)
return [part.strip("\r\n") + "\n" for part in parts]
def read_log(log: Path) -> str:
try:
return log.read_bytes().decode("utf-8", errors="replace")
except FileNotFoundError:
return ""
def selftest_lines(text: str) -> list[str]:
"""The lines of the expectations and the result in the log of the editor."""
keep = ("SELFTEST PASS", "SELFTEST FAIL", "SELFTEST result")
return [line.strip() for line in text.splitlines() if any(k in line for k in keep)]
def snapshot(folder: Path) -> dict[str, float]:
"""The entries of the folder with the times they were changed, to tell what a run added or changed."""
return {entry.name: entry.stat().st_mtime for entry in os.scandir(folder)}
def clean_up(scenery_dir: Path, stem: str, before: dict[str, float], keep: bool, say) -> None:
"""Deletes the copy of the scenery and what the editor wrote under its name; says what else changed there."""
after = snapshot(scenery_dir)
for name in sorted(after):
path = scenery_dir / name
if stem.lower() in name.lower():
if keep:
say(f" kept {path}")
elif path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
elif name not in before:
say(f" note the run added {path}, left in place")
elif after[name] != before[name]:
say(f" note the run changed {path}")
def describe_exit(code: int | None) -> str:
if code is None:
return "none"
if code == FAILED_EXIT_CODE:
return f"{code} (expectations failed)"
if code == 1:
return "1 (the start failed, or an error ended the editor)"
return f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)" if code else "0"
def run_case(name: str, source: Path, exe: Path, game_dir: Path, user_ini: Path | None, timeout: float, limit_mb: int, show: bool,
keep: bool, say) -> tuple[bool, int, float]:
"""Runs the case; returns whether it passed, the number of its expectations and the seconds it took."""
scenery_dir = game_dir / "scenery"
stem = f"autotest_editor_{name}".lower()
scenery = f"{stem}.scn"
out = OUT_DIR / name
shutil.rmtree(out, ignore_errors=True)
out.mkdir(parents=True)
runner_ini = out / "editor.ini"
runner_ini.write_text(RUNNER_INI)
inis = [runner_ini] + ([user_ini] if user_ini else [])
parts = split_script(source.read_text(encoding="utf-8"))
before = snapshot(scenery_dir)
if scenery in (entry.lower() for entry in before):
sys.exit(f"{scenery_dir / scenery} is there already: a run before this one left it, delete it first")
shutil.copyfile(FIXTURE, scenery_dir / scenery)
passed = True
expectations = 0
seconds = 0.0
try:
for index, part in enumerate(parts, 1):
script = out / f"part{index}.txt"
script.write_text(part, encoding="utf-8", newline="\n")
log = game_dir / "log.txt"
since = time.time() - 1
result = run_editor(exe, game_dir, scenery, script, inis, timeout, limit_mb, show)
seconds += result.seconds
# the log of this run, not one left from before by an editor that didn't start
if log.exists() and log.stat().st_mtime >= since:
shutil.copyfile(log, out / f"part{index}.log")
text = read_log(out / f"part{index}.log")
result.lines = selftest_lines(text)
# the copy of the fixture and no other scenery: the script may save
if not result.failure and f'loading scenario "{scenery}"' not in text.lower():
result.failure = f"the editor didn't load {scenery} (see {out / f'part{index}.log'})"
label = f"part {index} of {len(parts)}" if len(parts) > 1 else "run"
say(f" {label}: exit code {describe_exit(result.exit_code)}, {result.seconds:.0f} s, at most {result.peak_mb:.0f} MB")
for line in result.lines:
if "SELFTEST FAIL" in line or "SELFTEST result" in line:
say(" " + line[line.index("SELFTEST"):])
summary = next((line for line in result.lines if "SELFTEST result" in line), "")
counted = re.search(r"result: (\d+) failed of (\d+)", summary)
if counted:
expectations += int(counted.group(2))
ok = not result.failure and result.exit_code == 0 and counted is not None and counted.group(1) == "0"
if result.failure:
say(f" {result.failure}")
elif counted is None:
say(f" no SELFTEST result line in the log ({out / f'part{index}.log'}): the script didn't reach quit")
if not ok:
passed = False
break
if passed and expectations == 0:
say(" the case checks nothing: no expect in it")
passed = False
finally:
clean_up(scenery_dir, stem, before, keep, say)
return passed, expectations, seconds
def find_exe(explicit: str | None) -> Path:
if explicit:
return Path(explicit).resolve()
patterns = ("build/bin/RelWithDebInfo/eu07*.exe", "build/bin/Release/eu07*.exe", "cmake-build-*/bin/Release/eu07*.exe", "build/bin/eu07*")
candidates = sorted((p for pattern in patterns for p in REPO.glob(pattern) if p.is_file()), key=lambda p: p.stat().st_mtime)
if not candidates:
sys.exit("no eu07 executable found under build/bin, pass --exe")
return candidates[-1]
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("cases", nargs="*", help="case names from cases/, or paths of scripts elsewhere (default: all of cases/)")
ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"), help="game install with scenery/ (or EU07_GAME_DIR)")
ap.add_argument("--exe", help="editor executable, built with -DWITH_EDITOR_SELFTESTS=ON (default: the newest eu07*.exe under build/bin)")
ap.add_argument("--ini", help="settings file read over the runner's own ones, for example a low quality of the picture")
ap.add_argument("--timeout", type=float, default=240.0, help="wall time limit of a run of the editor, seconds (default 240)")
ap.add_argument("--memory-mb", type=int, default=8192, help="memory limit of the editor, MB (default 8192)")
ap.add_argument("--show", action="store_true", help="show the window of the editor")
ap.add_argument("--keep", action="store_true", help="keep the copies of the scenery, to look at what the scripts saved")
args = ap.parse_args()
if not args.game_dir:
sys.exit("pass --game-dir or set EU07_GAME_DIR")
game_dir = Path(args.game_dir).resolve()
exe = find_exe(args.exe)
user_ini = Path(args.ini).resolve() if args.ini else None
print(f"exe: {exe}\ngame: {game_dir}")
# a case by its name in cases/, or a script elsewhere by its path (one being written, say)
sources = {}
for given in args.cases or sorted(p.stem for p in CASES_DIR.glob("*.txt")):
path = Path(given) if given.endswith(".txt") else CASES_DIR / f"{given}.txt"
if not path.is_file():
sys.exit(f"no such case: {given}")
sources[path.stem] = path.resolve()
def say(line):
print(line, flush=True)
started = time.monotonic()
results = {}
for name, source in sources.items():
say(f"\n{name}")
results[name] = run_case(name, source, exe, game_dir, user_ini, args.timeout, args.memory_mb, args.show, args.keep, say)
passed, expectations, seconds = results[name]
say(f"{'PASS' if passed else 'FAIL'} {name} ({expectations} expectations, {seconds:.0f} s)")
print(f"\n=== summary ({time.monotonic() - started:.0f} s)")
for name, (passed, expectations, _) in results.items():
print(f" {'PASS' if passed else 'FAIL'} {name} ({expectations})")
failed = sum(1 for passed, _, _ in results.values() if not passed)
print(f"{len(results) - failed} passed, {failed} failed")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+376
View File
@@ -0,0 +1,376 @@
//$n Autotest of the track editor
//$d The fixture of the self-test scripts of the editor (tests/editor): plain tracks, a turntable and two
//$d canted curves side by side. The runner copies it into the scenery folder under a name of its own.
sky skydome_clouds.t3d endsky
atmo 0 0 0 1000 2000 0 0 0 endatmo
time 10:30 06:30 19:00 endtime
// line a: three straights joined, no cant (the cant of the inspector, the norms after a delete)
node -1 0 a1 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
0 0 0 0
0 0 0
0 0 0
0 0 100 0
0
endtrack
node -1 0 a2 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
0 0 100 0
0 0 0
0 0 0
0 0 200 0
0
endtrack
node -1 0 a3 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
0 0 200 0
0 0 0
0 0 0
0 0 300 0
0
endtrack
// line s: three straights joined, for the switches
node -1 0 s1 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
40 0 0 0
0 0 0
0 0 0
40 0 100 0
0
endtrack
node -1 0 s2 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
40 0 100 0
0 0 0
0 0 0
40 0 200 0
0
endtrack
node -1 0 s3 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
40 0 200 0
0 0 0
0 0 0
40 0 300 0
0
endtrack
// line d: three straights joined, for a double switch and a slip
node -1 0 d1 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
80 0 0 0
0 0 0
0 0 0
80 0 100 0
0
endtrack
node -1 0 d2 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
80 0 100 0
0 0 0
0 0 0
80 0 200 0
0
endtrack
node -1 0 d3 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
80 0 200 0
0 0 0
0 0 0
80 0 300 0
0
endtrack
// lines p and q: straights side by side 4.5 m apart, for a crossover
node -1 0 p1 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
120 0 0 0
0 0 0
0 0 0
120 0 100 0
0
endtrack
node -1 0 p2 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
120 0 100 0
0 0 0
0 0 0
120 0 200 0
0
endtrack
node -1 0 p3 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
120 0 200 0
0 0 0
0 0 0
120 0 300 0
0
endtrack
node -1 0 q1 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
124.5 0 0 0
0 0 0
0 0 0
124.5 0 100 0
0
endtrack
node -1 0 q2 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
124.5 0 100 0
0 0 0
0 0 0
124.5 0 200 0
0
endtrack
node -1 0 q3 track normal 100 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
124.5 0 200 0
0 0 0
0 0 0
124.5 0 300 0
0
endtrack
// a track of 1000 mm gauge and one of the standard gauge (pasting the style of a track)
node -1 0 g1 track normal 50 1 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
160 0 0 0
0 0 0
0 0 0
160 0 50 0
0
endtrack
node -1 0 g2 track normal 50 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
170 0 0 0
0 0 0
0 0 0
170 0 50 0
0
endtrack
// a turntable of 16 m with the speed limit of its own (its speed set in the editor, deleting it in a set)
node -1 0 tt1 track turn 16 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
200 0 17 0
0 0 0
0 0 0
200 0 33 0
0
velocity 10
endtrack
include eng/obrotnica16m_e.inc tt1 200 0 25 0 eng/most1-jezdniablach 0 0 0 0 0 0 0 0 0 0 0 0 end
// curves i (R 600 m) and o (R 604.5 m) side by side 4.5 m apart, canted 60 mm, with straights taking the cant on and off
node -1 0 i0 track normal 60 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
300 0 -60 0
0 0 0
0 0 0
300 0 0 -2.292443
0
endtrack
node -1 0 i1 track normal 30 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
300 0 0 -2.292443
0 0 10.000521
-0.499818 0 -9.988023
300.749844 0 29.987502 -2.292443
600
endtrack
node -1 0 i2 track normal 30 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
300.749844 0 29.987502 -2.292443
0.499818 0 9.988023
-0.998386 0 -9.95056
302.997501 0 59.90005 -2.292443
600
endtrack
node -1 0 i3 track normal 30 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
302.997501 0 59.90005 -2.292443
0.998386 0 9.95056
-1.494459 0 -9.888226
306.737353 0 89.662879 -2.292443
600
endtrack
node -1 0 i4 track normal 30 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
306.737353 0 89.662879 -2.292443
1.494459 0 9.888226
-1.986797 0 -9.801176
311.960053 0 119.201598 -2.292443
600
endtrack
node -1 0 i5 track normal 30 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
311.960053 0 119.201598 -2.292443
1.986797 0 9.801176
-2.474168 0 -9.689629
318.652547 0 148.442376 -2.292443
600
endtrack
node -1 0 i6 track normal 30 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
318.652547 0 148.442376 -2.292443
2.474168 0 9.689629
-2.955356 0 -9.553862
326.798107 0 177.312124 -2.292443
600
endtrack
node -1 0 i7 track normal 30 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
326.798107 0 177.312124 -2.292443
2.955356 0 9.553862
-3.429157 0 -9.394216
336.376372 0 205.738684 -2.292443
600
endtrack
node -1 0 i8 track normal 30 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
336.376372 0 205.738684 -2.292443
3.429157 0 9.394216
-3.894386 0 -9.21109
347.363404 0 233.651005 -2.292443
600
endtrack
node -1 0 i9 track normal 60 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
347.363404 0 233.651005 -2.292443
0 0 0
0 0 0
370.728504 0 288.914665 0
0
endtrack
node -1 0 o0 track normal 60 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
295.5 0 -60 0
0 0 0
0 0 0
295.5 0 0 -2.292443
0
endtrack
node -1 0 o1 track normal 30.225 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
295.5 0 0 -2.292443
0 0 10.075525
-0.503566 0 -10.062933
296.255468 0 30.212408 -2.292443
604.5
endtrack
node -1 0 o2 track normal 30.225 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
296.255468 0 30.212408 -2.292443
0.503566 0 10.062933
-1.005874 0 -10.025189
298.519982 0 60.3493 -2.292443
604.5
endtrack
node -1 0 o3 track normal 30.225 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
298.519982 0 60.3493 -2.292443
1.005874 0 10.025189
-1.505668 0 -9.962387
302.287883 0 90.335351 -2.292443
604.5
endtrack
node -1 0 o4 track normal 30.225 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
302.287883 0 90.335351 -2.292443
1.505668 0 9.962387
-2.001698 0 -9.874685
307.549754 0 120.09561 -2.292443
604.5
endtrack
node -1 0 o5 track normal 30.225 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
307.549754 0 120.09561 -2.292443
2.001698 0 9.874685
-2.492725 0 -9.762301
314.292441 0 149.555693 -2.292443
604.5
endtrack
node -1 0 o6 track normal 30.225 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
314.292441 0 149.555693 -2.292443
2.492725 0 9.762301
-2.977521 0 -9.625516
322.499092 0 178.641965 -2.292443
604.5
endtrack
node -1 0 o7 track normal 30.225 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
322.499092 0 178.641965 -2.292443
2.977521 0 9.625516
-3.454875 0 -9.464673
332.149195 0 207.281725 -2.292443
604.5
endtrack
node -1 0 o8 track normal 30.225 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
332.149195 0 207.281725 -2.292443
3.454875 0 9.464673
-3.923594 0 -9.280173
343.218629 0 235.403388 -2.292443
604.5
endtrack
node -1 0 o9 track normal 60 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
343.218629 0 235.403388 -2.292443
0 0 0
0 0 0
366.58373 0 290.667048 0
0
endtrack
// a track apart with a vehicle of the scenery: the editor saving a scenery without one puts a vehicle of its own onto the
// first track long enough, a track of the cases
node -1 0 v1 track normal 50 1.435 0.15 25.0 20 0 flat vis
rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1
-100 0 0 0
0 0 0
0 0 0
-100 0 50 0
0
endtrack
FirstInit
trainset none v1 20 0
node -1 0 autotest_wmb10 dynamic pkp/wmb10_v1 wmb10-6457 wmb10 0 nobody 0 0 enddynamic
endtrainset