Files
Dreierpack-Manager/tests/modern_ui_contract_tests.cpp
T
ClaudeandClaude Opus 5.5 d943494ef4 Modern UI contract: national friendlies
At the national coach's desk the friendly read quotes a match against
another nation on a copy of the Watcom generator (price, payer, ratings,
free dates); friendly.book draws the same ratings and books it. The
opponent bound of the national quote follows the world layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:24:47 +01:00

753 lines
55 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
// The engine side of the Modern interface contract (docs/new_engine/ui-anbindung.md): the
// envelope, identities, money, errors and that a read changes nothing. Needs game data
// (a Modern session on the Classic data).
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include <variant>
#include "cli/json.hpp"
#include "modern/app/modern_session.hpp"
#include "modern/content/ui_contract.hpp"
#include "modern/game/save.hpp"
using namespace bmh;
using J = cli::Json;
using O = J::Object;
namespace {
int failures = 0;
void check(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "FAIL: %s\n", what);
++failures;
}
}
const J& at(const J& j, const char* key) {
static const J none;
const auto* o = j.object();
if (!o) return none;
const auto it = o->find(key);
return it == o->end() ? none : it->second;
}
std::string s(const J& j) { return j.string() ? *j.string() : std::string{}; }
bool truth(const J& j) { const bool* b = std::get_if<bool>(&j.value); return b && *b; }
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::fprintf(stderr, "usage: modern_ui_contract_tests <BMH data>\n");
return 2;
}
try {
modern::app::ModernSession session(argv[1], 1u);
ui::SetupOptions options;
ui::ManagerChoice choice;
choice.name = "TEST";
choice.master_club = 0;
std::string error;
if (!session.confirm_manager(options, choice, error)) throw std::runtime_error("manager: " + error);
ui::CareerInitializationResult init;
if (!session.finish(init, error)) throw std::runtime_error("career start: " + error);
const uint64_t revision = init.desktop.revision;
const auto before = modern::save_stream(session.state());
const std::string career = session.state().career_id;
// session: envelope and identities
const J sess = session.ui_read(O{{"kind", "session"}, {"requestId", "request:1"}}, revision);
check(s(at(sess, "messageType")) == "snapshot", "session is a snapshot");
check(s(at(sess, "requestId")) == "request:1", "request id echoed");
const J& meta = at(sess, "meta");
check(s(at(meta, "contractVersion")) == "bmh-modern-ui@draft1", "contract version");
check(s(at(meta, "careerId")).starts_with("career:") && s(at(meta, "careerId")).size() == 23, "career id");
check(s(at(meta, "stateRevision")) == std::to_string(revision), "state revision as decimal string");
check(s(at(at(meta, "scope"), "managerId")) == "manager:1", "first manager id");
check(s(at(at(meta, "currency"), "code")) == "EUR" && at(at(meta, "currency"), "minorUnits").integer() &&
*at(at(meta, "currency"), "minorUnits").integer() == 2, "currency");
const auto* managers = at(at(sess, "data"), "managers").array();
check(managers && managers->size() == 1 && s(at((*managers)[0], "status")) == "active", "one active manager");
// desktop: money in minor units, menus
const J desk = session.ui_read(O{{"kind", "desktop"}}, revision);
const J status = session.read(O{{"kind", "status"}});
const int64_t euros = at(status, "money").integer() ? *at(status, "money").integer() : -1;
check(s(at(at(at(at(desk, "data"), "accounts"), "cash"), "minor")) == std::to_string(euros * 100), "cash in cents");
const auto* menus = at(at(desk, "data"), "menuAvailability").object();
check(menus && menus->size() == 16 && s(at(menus->at("bank"), "status")) == "available", "menus at a club desk");
// squad: own club with salaries, another club without
const J own = session.ui_read(O{{"kind", "squad"}}, revision);
const auto* players = at(at(own, "data"), "players").array();
check(players && players->size() >= 11, "own squad");
check(players && !players->empty() && at((*players)[0], "salaryMonthly").object(), "own salaries known");
const J other = session.ui_read(O{{"kind", "squad"}, {"teamId", "team:5"}}, revision);
const auto* others = at(at(other, "data"), "players").array();
check(others && !others->empty() && std::holds_alternative<std::nullptr_t>(at((*others)[0], "salaryMonthly").value), "foreign salaries unknown");
// errors
check(s(at(session.ui_read(O{{"kind", "nonsense"}}, revision), "code")) == "unknown_read", "unknown read");
check(s(at(session.ui_read(O{{"kind", "desktop"}, {"managerId", "manager:7"}}, revision), "code")) ==
"manager_not_active", "other manager refused");
check(s(at(session.ui_read(O{{"kind", "squad"}, {"teamId", "club:none"}}, revision), "code")) == "unknown_team",
"unknown team");
// reads change nothing
check(modern::save_stream(session.state()) == before, "reads leave the state unchanged");
check(session.state().career_id == career, "career id unchanged");
// identities: never reused, nothing set is replaced
modern::ModernState copy = session.state();
modern::ensure_ui_identities(copy);
check(copy.manager_ids == session.state().manager_ids && copy.career_id == career, "identities stable");
copy.manager_ids.clear();
modern::ensure_ui_identities(copy);
check(copy.manager_ids.size() == 1 && copy.manager_ids[0] == "manager:2", "a freed slot gets a new id");
// money
check(s(at(modern::ui_money(15), "minor")) == "1500" && s(at(modern::ui_money(-3), "minor")) == "-300", "money");
// camps: read with binding quotes, then camp.book as the first command
const J camps = session.ui_read(O{{"kind", "camps"}}, revision);
const auto* list = at(at(camps, "data"), "camps").array();
check(list && list->size() == session.state().training_camps.size() && !list->empty(), "camp catalogue");
const std::string camp_id = list && !list->empty() ? s(at((*list)[0], "id")) : "";
const std::string price = list && !list->empty() ? s(at(at(at((*list)[0], "quote"), "total"), "minor")) : "";
check(list && !list->empty() && truth(at(at((*list)[0], "quote"), "allowed")), "camp quote allowed");
uint64_t rev = revision;
const auto command = [&](const std::string& id, const std::string& expected, const std::string& manager,
const std::string& camp) {
return J(O{{"messageType", "command"}, {"requestId", id}, {"expectedRevision", expected},
{"owner", O{{"managerId", manager}}}, {"kind", "camp.book"}, {"payload", O{{"campId", camp}}}});
};
const auto unchanged = modern::save_stream(session.state());
check(s(at(session.ui_command(command("request:c1", "999", "manager:1", camp_id), rev), "code")) == "stale_revision",
"stale revision refused");
check(s(at(session.ui_command(command("request:c2", std::to_string(rev), "manager:9", camp_id), rev), "code")) ==
"manager_not_active", "foreign owner refused");
check(s(at(session.ui_command(command("request:c3", std::to_string(rev), "manager:1", "resort:none"), rev), "code")) ==
"unknown_camp", "unknown camp refused");
check(rev == revision && modern::save_stream(session.state()) == unchanged, "refused commands change nothing");
const int64_t cash_before = *at(session.read(O{{"kind", "status"}}), "money").integer();
const J booked = session.ui_command(command("request:c4", std::to_string(rev), "manager:1", camp_id), rev);
check(s(at(booked, "messageType")) == "command_result" && s(at(booked, "newRevision")) == std::to_string(revision + 1) &&
rev == revision + 1, "camp booked, one revision");
const int64_t cash_after = *at(session.read(O{{"kind", "status"}}), "money").integer();
check(std::to_string((cash_before - cash_after) * 100) == price, "the quoted price was charged");
const J again = session.ui_command(command("request:c4", std::to_string(revision), "manager:1", camp_id), rev);
check(cli::dump_json(again) == cli::dump_json(booked) && rev == revision + 1 &&
*at(session.read(O{{"kind", "status"}}), "money").integer() == cash_after, "repeated request answered, not booked twice");
check(s(at(session.ui_command(command("request:c4", std::to_string(rev), "manager:1", camp_id), rev), "code")) ==
"duplicate_request", "same id, other command");
const auto after_booking = modern::save_stream(session.state());
check(s(at(session.ui_command(command("request:c5", std::to_string(rev), "manager:1", camp_id), rev), "code")) ==
"booked_this_week" && modern::save_stream(session.state()) == after_booking && rev == revision + 1,
"second booking in a week refused without change");
const J after = session.ui_read(O{{"kind", "camps"}}, rev);
check(at(at(after, "data"), "staysThisSeason").integer() && *at(at(after, "data"), "staysThisSeason").integer() == 1 &&
truth(at(at(after, "data"), "bookedThisWeek")), "camp read shows the stay");
// lineup, tactics, training: read, one accepted and one refused command each
const auto cmd = [&](const std::string& id, const char* kind, J payload) {
return J(O{{"messageType", "command"}, {"requestId", id}, {"expectedRevision", std::to_string(rev)},
{"owner", O{{"managerId", "manager:1"}}}, {"kind", kind}, {"payload", std::move(payload)}});
};
const J lineup = session.ui_read(O{{"kind", "lineup"}}, rev);
const auto* order = at(at(lineup, "data"), "order").array();
check(order && order->size() >= 12 && at(at(lineup, "data"), "positions").array() &&
at(at(lineup, "data"), "positions").array()->size() == 11, "lineup read");
if (order && order->size() >= 12) {
J::Array wanted = *order;
std::swap(wanted[0], wanted[1]);
std::swap(wanted[10], wanted[11]);
const uint64_t before_lineup = rev;
const J done = session.ui_command(cmd("request:l1", "lineup.commit", O{{"order", wanted}}), rev);
if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "lineup: %s\n", cli::dump_json(done).c_str());
const J reread = session.ui_read(O{{"kind", "lineup"}}, rev);
const auto* now = at(at(reread, "data"), "order").array();
if (now && (s((*now)[0]) != s(wanted[0]) || s((*now)[10]) != s(wanted[10]) || rev != before_lineup + 1))
std::fprintf(stderr, "lineup: rev %llu/%llu, now %s %s %s, wanted %s %s %s\n", (unsigned long long)rev,
(unsigned long long)before_lineup, s((*now)[0]).c_str(), s((*now)[1]).c_str(), s((*now)[10]).c_str(),
s(wanted[0]).c_str(), s(wanted[1]).c_str(), s(wanted[10]).c_str());
check(s(at(done, "messageType")) == "command_result" && rev == before_lineup + 1 && now &&
s((*now)[0]) == s(wanted[0]) && s((*now)[10]) == s(wanted[10]),
"lineup committed");
const auto kept = modern::save_stream(session.state());
check(s(at(session.ui_command(cmd("request:l2", "lineup.commit", O{{"order", J::Array{J("player:none")}}}), rev),
"code")) == "unknown_player" && modern::save_stream(session.state()) == kept && rev == before_lineup + 1,
"unknown player refused without change");
}
const J tactics = session.ui_read(O{{"kind", "tactics"}}, rev);
const auto* controls = at(at(tactics, "data"), "controls").array();
check(controls && controls->size() == 8, "tactics read");
if (controls && controls->size() == 8) {
J::Array values;
for (const auto& c : *controls) values.push_back(at(c, "value"));
const int64_t max7 = *at(at((*controls)[7], "range"), "max").integer();
const int64_t v7 = *values[7].integer();
values[7] = J(v7 == max7 ? v7 - 1 : v7 + 1);
const uint64_t before_tactics = rev;
const J done = session.ui_command(cmd("request:t1", "tactics.commit", O{{"values", values}}), rev);
const J reread = session.ui_read(O{{"kind", "tactics"}}, rev);
const auto* now = at(at(reread, "data"), "controls").array();
check(s(at(done, "messageType")) == "command_result" && rev == before_tactics + 1 && now &&
*at((*now)[7], "value").integer() == *values[7].integer(), "tactics committed");
values[7] = J(max7 + 1);
const auto kept = modern::save_stream(session.state());
check(s(at(session.ui_command(cmd("request:t2", "tactics.commit", O{{"values", values}}), rev), "code")) ==
"invalid_tactic" && modern::save_stream(session.state()) == kept, "tactic above its maximum refused");
}
const J training = session.ui_read(O{{"kind", "training"}}, rev);
check(s(at(training, "messageType")) == "snapshot" && at(at(training, "data"), "areas").array() &&
at(at(training, "data"), "areas").array()->size() == 9, "training read");
{
const uint64_t before_training = rev;
const J done = session.ui_command(cmd("request:p1", "training.commit",
O{{"types", J::Array{J(2), J(2), J(2), J(2)}},
{"areas", J::Array{J(2), J(2), J(2), J(2), J(2), J(2), J(2), J(2), J(2)}}}), rev);
const J now = session.ui_read(O{{"kind", "training"}}, rev);
const auto* areas = at(at(now, "data"), "areas").array();
check(s(at(done, "messageType")) == "command_result" && rev == before_training + 1 && areas &&
*at((*areas)[8], "allocation").integer() == 2, "training committed");
const auto kept = modern::save_stream(session.state());
check(s(at(session.ui_command(cmd("request:p2", "training.commit", O{{"types", J::Array{J(3), J(3), J(3), J(3)}}}), rev),
"messageType")) == "error" && modern::save_stream(session.state()) == kept && rev == before_training + 1,
"training over the limit refused without change");
}
// bank: read, fixed deposit, a share, a refused withdrawal
{
const J bank = session.ui_read(O{{"kind", "bank"}}, rev);
const J& accounts = at(at(bank, "data"), "accounts");
const auto* stocks = at(at(bank, "data"), "stocks").array();
check(s(at(bank, "messageType")) == "snapshot" && stocks && stocks->size() == 12, "bank read");
const std::string deposit_before = s(at(at(accounts, "deposit"), "minor"));
const uint64_t before_bank = rev;
const J done = session.ui_command(cmd("request:b1", "bank.commit",
O{{"action", "deposit"}, {"amount", O{{"minor", "10000000"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev);
const J after = session.ui_read(O{{"kind", "bank"}}, rev);
check(s(at(done, "messageType")) == "command_result" && rev == before_bank + 1 &&
std::stoll(s(at(at(at(at(after, "data"), "accounts"), "deposit"), "minor"))) ==
std::stoll(deposit_before) + 10000000, "100000 euros to the fixed deposit");
const J share = session.ui_command(cmd("request:b2", "bank.commit", O{{"action", "buy"}, {"assetId", "stock:0"}, {"count", 1}}), rev);
check(s(at(share, "messageType")) == "command_result" && rev == before_bank + 2, "one share bought");
const auto kept = modern::save_stream(session.state());
const J refused = session.ui_command(cmd("request:b3", "bank.commit",
O{{"action", "withdraw"}, {"amount", O{{"minor", "99999999900"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev);
check(s(at(refused, "messageType")) == "error" && modern::save_stream(session.state()) == kept && rev == before_bank + 2,
"withdrawal above the deposit refused without change");
}
// contracts: demands as a quote, an offer against it, a stale quote refused
{
const J contracts = session.ui_read(O{{"kind", "contracts"}}, rev);
const auto* players = at(at(contracts, "data"), "players").array();
check(players && !players->empty(), "contracts read");
const std::string player = players && !players->empty() ? s(at((*players)[0], "playerId")) : "";
const uint64_t before = rev;
const J quoted = session.ui_command(cmd("request:k1", "quote.request", O{{"kind", "contract"}, {"playerId", player}}), rev);
check(s(at(quoted, "outcome")) == "offer_pending" && rev == before + 1, "demands quoted");
const J with_quote = session.ui_read(O{{"kind", "contracts"}}, rev);
const J& quote = at(at(with_quote, "data"), "quote");
const auto* demands = at(quote, "demands").array();
check(s(at(quote, "playerId")) == player && demands && demands->size() == 4, "quote with four terms");
if (demands && demands->size() == 4) {
const std::string id = s(at(quote, "id"));
const J offer = session.ui_command(cmd("request:k2", "contract.offer",
O{{"quoteId", id}, {"years", 2}, {"monthlySalary", O{{"minor", "100"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev);
const std::string outcome = s(at(offer, "outcome"));
check(s(at(offer, "messageType")) == "command_result" && (outcome == "applied" || outcome == "offer_rejected") &&
rev == before + 2, "offer answered");
check(s(at(session.ui_command(cmd("request:k3", "contract.offer",
O{{"quoteId", id}, {"years", 2}, {"monthlySalary", O{{"minor", "100"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev),
"code")) == "stale_quote" && rev == before + 2, "a used quote is gone");
}
}
// advertising: the first acceptable offer, a budget
{
const J ads = session.ui_read(O{{"kind", "advertising"}}, rev);
check(s(at(ads, "messageType")) == "snapshot" && at(at(ads, "data"), "boards").array() &&
at(at(ads, "data"), "boards").array()->size() == 14, "advertising read");
std::string offer;
const auto pick = [&](const J& place) {
if (const auto* list = at(place, "offers").array())
for (const auto& o : *list)
if (offer.empty() && truth(at(o, "allowed"))) offer = s(at(o, "id"));
};
pick(at(at(ads, "data"), "shirt"));
pick(at(at(ads, "data"), "television"));
if (const auto* boards = at(at(ads, "data"), "boards").array())
for (const auto& b : *boards) pick(b);
const uint64_t before = rev;
if (!offer.empty()) {
const J done = session.ui_command(cmd("request:w1", "advertising.accept", O{{"offerId", offer}}), rev);
if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "advertising: %s\n", cli::dump_json(done).c_str());
check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "advertising offer accepted");
}
const auto kept = modern::save_stream(session.state());
check(s(at(session.ui_command(cmd("request:w2", "advertising.accept", O{{"offerId", "offer:ad-3-99"}}), rev), "code")) ==
"unknown_offer" && modern::save_stream(session.state()) == kept, "unknown offer refused");
std::printf("(advertising offer %s)\n", offer.empty() ? "none" : offer.c_str());
}
// stadium: periphery, facilities, blocks; the ticket price
{
const J stadium = session.ui_read(O{{"kind", "stadium"}}, rev);
const J& d = at(stadium, "data");
if (s(at(stadium, "messageType")) != "snapshot") std::fprintf(stderr, "stadium: %s\n", cli::dump_json(stadium).c_str());
check(at(d, "periphery").array() && at(d, "periphery").array()->size() == 14 && at(d, "blocks").array() &&
at(d, "blocks").array()->size() == 8 && at(d, "facilities").array() && at(d, "facilities").array()->size() == 8,
"stadium read");
if (const auto* p = at(d, "periphery").array(); p && !p->empty())
check(!s(at((*p)[0], "name")).empty() && at((*p)[0], "stage").integer(), "traffic access with its stage");
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:e1", "ticket.commit", O{{"price", O{{"minor", "1200"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev);
if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "ticket: %s\n", cli::dump_json(done).c_str());
const J after = session.ui_read(O{{"kind", "stadium"}}, rev);
check(s(at(done, "messageType")) == "command_result" && s(at(at(at(after, "data"), "ticketPrice"), "minor")) == "1200" &&
rev <= before + 1, "ticket price set");
check(s(at(session.ui_command(cmd("request:e2", "ticket.commit", O{{"price", O{{"minor", "3000"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev),
"code")) == "invalid_amount", "ticket price above 25 refused");
// building: a periphery object not built yet, then a facility level without the tip
std::string object;
if (const auto* p = at(at(after, "data"), "periphery").array())
for (const auto& o : *p)
if (object.empty() && at(o, "built").value.index() == 1 && !truth(at(o, "built")) && *at(o, "constructionDays").integer() == 0)
object = s(at(o, "id"));
const auto quote_of = [&]() { const J st = session.ui_read(O{{"kind", "stadium"}}, rev); return J(at(at(st, "data"), "quote")); };
if (!object.empty()) {
const uint64_t b0 = rev;
const J q = session.ui_command(cmd("request:e3", "quote.request", O{{"kind", "periphery"}, {"objectId", object}}), rev);
if (s(at(q, "messageType")) != "command_result") std::fprintf(stderr, "periphery quote: %s\n", cli::dump_json(q).c_str());
const J quote = quote_of();
check(s(at(q, "outcome")) == "offer_pending" && s(at(quote, "objectId")) == object && rev == b0 + 1, "periphery quoted");
const J built = session.ui_command(cmd("request:e4", "stadium.commit", O{{"quoteId", at(quote, "id")}, {"accept", true}}), rev);
if (s(at(built, "messageType")) != "command_result") std::fprintf(stderr, "periphery build: %s\n", cli::dump_json(built).c_str());
check(s(at(built, "messageType")) == "command_result" && rev == b0 + 2 && std::holds_alternative<std::nullptr_t>(quote_of().value),
"periphery built, the stadium closed");
}
{
const uint64_t b0 = rev;
const J q = session.ui_command(cmd("request:e5", "quote.request", O{{"kind", "facility"}, {"facilityId", "facility:safety"}, {"increment", 1}}), rev);
const J quote = quote_of();
if (s(at(q, "messageType")) == "command_result") {
check(s(at(quote, "kind")) == "facility" && at(quote, "price").object(), "facility quoted");
const J done = session.ui_command(cmd("request:e6", "stadium.commit", O{{"quoteId", at(quote, "id")}, {"accept", true}, {"tip", false}}), rev);
if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "facility build: %s\n", cli::dump_json(done).c_str());
check(s(at(done, "messageType")) == "command_result" && rev == b0 + 2, "facility ordered");
} else {
std::printf("(facility quote: %s)\n", s(at(q, "code")).c_str());
}
// a stand block: 1000 more places
std::string block;
int64_t places = 0;
if (const auto* blocks = at(at(after, "data"), "blocks").array())
for (const auto& b : *blocks)
if (block.empty() && *at(b, "constructionWeeks").integer() == 0 &&
*at(b, "places").integer() + 1000 <= *at(b, "maxPlaces").integer())
block = s(at(b, "id")), places = *at(b, "places").integer() + 1000;
if (!block.empty()) {
const uint64_t b1 = rev;
const J bq = session.ui_command(cmd("request:eb1", "quote.request", O{{"kind", "block"}, {"blockId", block}, {"places", places}}), rev);
const J quote = quote_of();
if (s(at(bq, "messageType")) != "command_result") std::fprintf(stderr, "block quote: %s\n", cli::dump_json(bq).c_str());
check(s(at(quote, "kind")) == "block" && *at(quote, "places").integer() == places, "block quoted");
const J built = session.ui_command(cmd("request:eb2", "stadium.commit", O{{"quoteId", at(quote, "id")}, {"accept", true}, {"tip", false}}), rev);
if (s(at(built, "messageType")) != "command_result") std::fprintf(stderr, "block build: %s\n", cli::dump_json(built).c_str());
const J st = session.ui_read(O{{"kind", "stadium"}}, rev);
int weeks = -1;
for (const auto& b : *at(at(st, "data"), "blocks").array())
if (s(at(b, "id")) == block) weeks = int(*at(b, "constructionWeeks").integer());
check(s(at(built, "messageType")) == "command_result" && rev == b1 + 2 && weeks > 0, "block expansion under way");
std::printf("(block %s to %lld places: %d weeks)\n", block.c_str(), (long long)places, weeks);
}
const J q2 = session.ui_command(cmd("request:e7", "quote.request", O{{"kind", "facility"}, {"facilityId", "facility:comfort"}, {"increment", 1}}), rev);
if (s(at(q2, "messageType")) == "command_result") {
const J declined = session.ui_command(cmd("request:e8", "stadium.commit", O{{"quoteId", at(quote_of(), "id")}, {"accept", false}}), rev);
check(s(at(declined, "messageType")) == "command_result" && std::holds_alternative<std::nullptr_t>(quote_of().value),
"facility offer declined, the stadium closed");
}
}
}
// transfers: list an own player, bid on a listed one (asking fee and salary reference)
{
const J market = session.ui_read(O{{"kind", "transfer"}}, rev);
const auto* listings = at(at(market, "data"), "listings").array();
const auto* squad = at(at(market, "data"), "squad").array();
check(s(at(market, "messageType")) == "snapshot" && listings && squad && !squad->empty(), "transfer read");
const uint64_t before = rev;
if (squad && squad->size() > 15) {
const std::string seller = s(at(squad->back(), "playerId"));
const J listed = session.ui_command(cmd("request:t9", "transfer.submit", O{{"action", "list"}, {"playerId", seller}}), rev);
if (s(at(listed, "messageType")) != "command_result") std::fprintf(stderr, "list: %s\n", cli::dump_json(listed).c_str());
check(s(at(listed, "messageType")) == "command_result" && rev == before + 1, "own player listed");
}
std::string listing;
J fee, salary;
if (listings)
for (const auto& l : *listings)
if (listing.empty() && !truth(at(l, "ownListing")) && !truth(at(l, "ownBidPending")))
listing = s(at(l, "id")), fee = at(l, "askingFee"), salary = at(l, "salaryReference");
if (!listing.empty()) {
// the salary reference is annual in the market row; the offer takes a monthly salary
const int64_t monthly = std::stoll(s(at(salary, "minor"))) / 12 / 100 * 100;
const uint64_t b2 = rev;
const J bid = session.ui_command(cmd("request:t10", "transfer.submit",
O{{"action", "bid"}, {"listingId", listing}, {"fee", fee},
{"monthlySalary", O{{"minor", std::to_string(monthly)}, {"currency", "EUR"}, {"minorUnits", 2}}}, {"years", 2}}), rev);
std::printf("(bid on %s: %s)\n", listing.c_str(), cli::dump_json(bid).substr(0, 260).c_str());
check((s(at(bid, "messageType")) == "command_result" && rev == b2 + 1) ||
(s(at(bid, "messageType")) == "error" && rev == b2), "bid answered or refused cleanly");
}
check(s(at(session.ui_command(cmd("request:t11", "transfer.submit", O{{"action", "bid"}, {"listingId", "listing:999"}}), rev), "code")) ==
"unknown_listing", "unknown listing refused");
}
// scheduling: move a league match and take it back; a friendly
{
const J sched = session.ui_read(O{{"kind", "scheduling"}}, rev);
const auto* movable = at(at(sched, "data"), "movable").array();
check(s(at(sched, "messageType")) == "snapshot" && movable, "scheduling read");
std::string match, target;
if (movable)
for (const auto& mv : *movable)
if (match.empty() && at(mv, "targetDates").array() && !at(mv, "targetDates").array()->empty())
match = s(at(mv, "id")), target = s(at(mv, "targetDates").array()->front());
if (!match.empty()) {
const uint64_t before = rev;
const J moved = session.ui_command(cmd("request:f1", "fixture.reschedule", O{{"matchId", match}, {"date", target}}), rev);
const J again = session.ui_read(O{{"kind", "scheduling"}}, rev);
check(s(at(moved, "messageType")) == "command_result" && rev == before + 1 && at(at(again, "data"), "moved").array() &&
!at(at(again, "data"), "moved").array()->empty(), "league match moved");
// the calendar of the season: every league match once (two per opponent), the
// moved one on its new date with the planned one as original date
const J cal = session.ui_read(O{{"kind", "calendar"}, {"from", "1900-01-01"}, {"until", "2999-12-31"}}, rev);
const auto* fixtures = at(at(cal, "data"), "fixtures").array();
std::set<std::string> ids, opponents;
std::string own = s(at(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "data"), "team"), "id"));
bool moved_seen = false;
if (fixtures)
for (const auto& f : *fixtures) {
ids.insert(s(at(f, "id")));
const std::string h = s(at(at(f, "home"), "id")), a = s(at(at(f, "away"), "id"));
opponents.insert(h == own ? a : h);
if (s(at(f, "status")) == "rescheduled" && s(at(f, "scheduledDate")) == target && s(at(f, "originalDate")) != target)
moved_seen = true;
}
std::printf("(calendar: %zu days, %zu league matches, %zu opponents)\n",
at(at(cal, "data"), "days").array() ? at(at(cal, "data"), "days").array()->size() : 0, ids.size(), opponents.size());
check(fixtures && ids.size() == fixtures->size() && !opponents.empty() && ids.size() == 2 * opponents.size(),
"calendar: every league match once, two per opponent");
check(moved_seen, "calendar: the moved match on its new date");
const J undone = session.ui_command(cmd("request:f2", "fixture.reschedule", O{{"action", "undo"}, {"date", target}}), rev);
check(s(at(undone, "messageType")) == "command_result", "move taken back");
std::printf("(moved %s to %s and back)\n", match.c_str(), target.c_str());
}
const J friendly = session.ui_read(O{{"kind", "friendly"}, {"opponentId", "team:70"}, {"home", true}}, rev);
const auto* dates = at(at(friendly, "data"), "dates").array();
if (s(at(friendly, "messageType")) != "snapshot") std::fprintf(stderr, "friendly: %s\n", cli::dump_json(friendly).c_str());
check(dates && !dates->empty() && at(at(at(friendly, "data"), "cost"), "minor").string(), "friendly quote with free dates");
if (dates && !dates->empty()) {
const J day = at(dates->front(), "date");
check(s(at(session.ui_command(cmd("request:f3", "friendly.book", O{{"opponentId", "team:70"}, {"date", day}}), rev), "code")) ==
"declined", "the cost must be accepted");
const uint64_t before = rev;
const J booked = session.ui_command(cmd("request:f4", "friendly.book", O{{"opponentId", "team:70"}, {"date", day}, {"acceptCost", true}}), rev);
if (s(at(booked, "messageType")) != "command_result") std::fprintf(stderr, "friendly book: %s\n", cli::dump_json(booked).c_str());
check(s(at(booked, "messageType")) == "command_result" && rev == before + 1, "friendly booked");
}
}
// a bank credit: draft with an edit within its bounds, preview, booking
{
const J credit = session.ui_read(O{{"kind", "credit"}}, rev);
const auto* fields = at(at(credit, "data"), "fields").array();
if (s(at(credit, "messageType")) != "snapshot") std::fprintf(stderr, "credit: %s\n", cli::dump_json(credit).c_str());
check(fields && fields->size() == 8, "credit read with eight fields");
int field = -1;
int64_t value = 0;
if (fields)
for (const auto& f : *fields)
if (field < 0 && truth(at(f, "editable")) && *at(f, "max").integer() > *at(f, "min").integer()) {
field = int(*at(f, "field").integer());
value = (*at(f, "min").integer() + *at(f, "max").integer()) / 2;
}
if (field >= 0) {
const J::Array edits{J(O{{"field", field}, {"value", value}})};
const J preview = session.ui_read(O{{"kind", "credit"}, {"edits", edits}}, rev);
check(s(at(preview, "messageType")) == "snapshot", "credit preview");
int64_t too_high = 0;
for (const auto& f : *fields)
if (*at(f, "field").integer() == field) too_high = *at(f, "max").integer() + 1;
const J::Array bad{J(O{{"field", field}, {"value", too_high}})};
const J refused = session.ui_read(O{{"kind", "credit"}, {"edits", bad}}, rev);
check(s(at(refused, "code")) == "invalid_credit_edit", "credit edit beyond its bound refused");
const uint64_t before = rev;
const J booked = session.ui_command(cmd("request:k9", "bank.commit", O{{"action", "credit"}, {"edits", edits}, {"acceptFees", true}}), rev);
std::printf("(credit field %d to %lld: %s)\n", field, (long long)value, cli::dump_json(booked).substr(0, 160).c_str());
check(s(at(booked, "messageType")) == "command_result" && rev == before + 1, "credit booked");
}
}
// the surroundings: six budgets 0-6
{
const J env = session.ui_read(O{{"kind", "environment"}}, rev);
const auto* items = at(at(env, "data"), "items").array();
check(items && items->size() == 6 && at(at(env, "data"), "youth").array(), "environment read");
if (items && items->size() == 6) {
const int64_t level = *at((*items)[4], "level").integer();
const int64_t wanted = level < 6 ? level + 1 : level - 1;
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:u1", "environment.commit", O{{"itemId", "environment:doctor"}, {"level", wanted}}), rev);
const J after_env = session.ui_read(O{{"kind", "environment"}}, rev);
check(s(at(done, "messageType")) == "command_result" && rev == before + 1 &&
*at((*at(at(after_env, "data"), "items").array())[4], "level").integer() == wanted, "doctor budget changed");
check(s(at(session.ui_command(cmd("request:u2", "environment.commit", O{{"itemId", "environment:doctor"}, {"level", 9}}), rev), "code")) ==
"invalid_payload", "level above 6 refused");
}
}
// toto and the exclusive sponsor
{
const J toto = session.ui_read(O{{"kind", "toto"}}, rev);
check(s(at(toto, "messageType")) == "snapshot" && at(at(at(toto, "data"), "stake"), "minor").string(), "toto read with Money");
const J::Array column{J(1), J(0), J(2), J(1), J(1), J(0), J(2), J(1), J(1), J(0), J(2)};
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:o1", "toto.submit",
O{{"stake", O{{"minor", "5000000"}, {"currency", "EUR"}, {"minorUnits", 2}}}, {"columns", J::Array{J(column), J(column)}}}), rev);
if (truth(at(at(toto, "data"), "open")))
check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "two toto columns submitted");
else
check(s(at(done, "code")) == "toto_refused" && rev == before, "toto closed: refused without change");
check(s(at(session.ui_command(cmd("request:o2", "sponsor.answer", O{{"accept", true}}), rev), "messageType")) == "error",
"no sponsor offer to answer");
}
// session.advance: three kickoffs, each one revision, the date moves on
{
const std::string date_before = s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date"));
for (int k = 0; k < 3; ++k) {
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:a" + std::to_string(k), "session.advance", O{}), rev);
if (s(at(done, "messageType")) != "command_result")
std::fprintf(stderr, "advance: %s\n", cli::dump_json(done).c_str());
check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "advance accepted");
}
const std::string date_after = s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date"));
check(date_after > date_before, "the date moved on");
}
// the live ticker: advance until a kickoff played a match of the human manager, then its recording
{
J fixture;
J live_final;
for (int k = 0; k < 12; ++k) {
fixture = session.read_live(O{{"kind", "fixture"}});
if (truth(at(fixture, "ok"))) break;
check(s(at(fixture, "error")) == "live_no_human_match", "no human match: said so");
session.ui_command(cmd("request:lv" + std::to_string(k), "session.advance", O{}), rev);
}
const auto* frames = at(fixture, "frames").array();
const auto* matches = at(fixture, "matches").array();
check(truth(at(fixture, "ok")) && s(at(fixture, "source")) == "engine-recording" && frames && frames->size() >= 4 &&
matches && !matches->empty() && at(fixture, "owners").array() && !at(fixture, "owners").array()->empty(),
"live fixture of the last kickoff");
if (frames && frames->size() >= 4) {
const J& last = frames->back();
const J one = session.read_live(O{{"kind", "frame"}, {"sequence", int64_t(frames->size() - 1)}});
check(truth(at(one, "ok")) && cli::dump_json(at(at(one, "frame"), "matches")) == cli::dump_json(at(last, "matches")), "one frame by sequence");
live_final = at(at(one, "frame"), "standings");
// the last frame's score is the recorded result of the match
const J m = at(at(last, "matches").array()->front(), "score");
std::printf("(live: %zu frames, %zu matches, conference %zu, final %s)\n", frames->size(), matches->size(),
at(fixture, "conference").array() ? at(fixture, "conference").array()->size() : 0, cli::dump_json(m).c_str());
}
check(s(at(session.read_live(O{{"kind", "frame"}, {"sequence", 99999}}), "error")) == "invalid_live_sequence", "bad sequence");
// the after-match steps of that kickoff
const J post = session.ui_read(O{{"kind", "postmatch"}}, rev);
const J& pd = at(post, "data");
const auto* steps = at(pd, "steps").array();
check(s(at(post, "messageType")) == "snapshot" && steps && steps->size() == 5 && truth(at((*steps)[0], "available")) &&
at(pd, "matches").array() && !at(pd, "matches").array()->empty() && at(pd, "reportMatchIds").array() &&
!at(pd, "reportMatchIds").array()->empty(), "postmatch with results and report");
// the live table at the final whistle is the league table after the matchday
if (const auto* lt = live_final.array(); lt && !lt->empty() && at(pd, "tables").array()) {
std::map<std::string, int64_t> points;
for (const auto& t : *at(pd, "tables").array())
for (const auto& r : *at(t, "rows").array()) points[s(at(at(r, "club"), "id"))] = *at(r, "points").integer();
bool same = true;
for (const auto& r : *at(lt->front(), "rows").array()) {
const auto p = points.find(s(at(at(r, "team"), "id")));
same &= p != points.end() && p->second == *at(r, "points").integer();
}
std::printf("(live table: %zu leagues, %zu rows)\n", lt->size(), at(lt->front(), "rows").array()->size());
check(same, "live table at the final whistle equals the league table");
}
std::printf("(postmatch: %zu matches, %zu tables, %zu elevens)\n", at(pd, "matches").array()->size(),
at(pd, "tables").array() ? at(pd, "tables").array()->size() : 0,
at(pd, "teamOfTheDay").array() ? at(pd, "teamOfTheDay").array()->size() : 0);
}
// a live kickoff: stops in a match of the human manager, steps, intervenes, finishes
{
bool stopped = false;
for (int k = 0; k < 12 && !stopped; ++k) {
const J started = session.ui_command(cmd("request:lr" + std::to_string(k), "session.advance", O{{"live", true}}), rev);
const J state = session.read_live(O{{"kind", "fixture"}});
stopped = truth(at(state, "live"));
if (!stopped)
check(s(at(started, "messageType")) == "command_result", "a live kickoff without a human match runs through");
}
check(stopped, "a live kickoff stood still in a match");
if (stopped) {
check(s(at(session.ui_command(cmd("request:lx", "bank.commit", O{{"action", "deposit"}}), rev), "code")) == "live_running",
"other commands wait for the live kickoff");
const J stepped = session.ui_command(cmd("request:ls", "live.step", O{{"minutes", 30}}), rev);
const J state = session.read_live(O{{"kind", "fixture"}});
check(s(at(stepped, "messageType")) == "command_result" && at(state, "minute").integer() &&
*at(state, "minute").integer() >= 30, "thirty minutes on");
std::printf("(live state: %s)\n", cli::dump_json(state).substr(0, 400).c_str());
check(at(state, "standings").array() != nullptr, "the paused kickoff names its live tables");
std::printf("(paused live tables: %zu)\n", at(state, "standings").array() ? at(state, "standings").array()->size() : 0);
if (const auto* live = at(state, "matches").array(); live && !live->empty()) {
int goals = 0;
for (const auto& e : *at((*live)[0], "events").array()) goals += s(at(e, "kind")) == "goal";
const auto* score = at((*live)[0], "score").array();
check(score && goals == *(*score)[0].integer() + *(*score)[1].integer(), "the live goals match the score");
}
// a substitution: the last field row for the first bench row
const J lineup = session.ui_read(O{{"kind", "lineup"}}, rev);
const auto* order = at(at(lineup, "data"), "order").array();
if (order && order->size() > 11) {
const J sub = session.ui_command(cmd("request:lsub", "live.substitute",
O{{"outPlayerId", (*order)[10]}, {"inPlayerId", (*order)[11]}}), rev);
std::printf("(live substitution: %s)\n", cli::dump_json(sub).substr(0, 200).c_str());
check(s(at(sub, "messageType")) == "command_result" || s(at(sub, "code")) == "substitution_refused",
"live substitution answered");
}
const J tactics = session.ui_read(O{{"kind", "tactics"}}, rev);
if (const auto* controls = at(at(tactics, "data"), "controls").array(); controls && controls->size() == 8) {
J::Array values;
for (const auto& c : *controls) values.push_back(at(c, "value"));
values[7] = J(*values[7].integer() == 0 ? 1 : 0);
const J changed = session.ui_command(cmd("request:ltac", "live.tactics", O{{"values", values}}), rev);
std::printf("(live tactics: %s)\n", cli::dump_json(changed).substr(0, 800).c_str());
check(s(at(changed, "messageType")) == "command_result", "live tactics changed");
}
const J done = session.ui_command(cmd("request:lf", "live.finish", O{}), rev);
check(s(at(done, "messageType")) == "command_result", "live kickoff finished");
const J fixture = session.read_live(O{{"kind", "fixture"}});
if (!truth(at(fixture, "ok"))) std::printf("(fixture: %s)\n", cli::dump_json(fixture).substr(0, 200).c_str());
check(truth(at(fixture, "ok")) && at(fixture, "frames").array() && at(fixture, "frames").array()->size() >= 4,
"the live kickoff's recording");
}
check(s(at(session.ui_command(cmd("request:lz", "live.step", O{}), rev), "code")) == "live_not_running", "no live kickoff");
}
// a paused league match: its live table (the league as it stands with the scores so far)
{
bool seen = false;
for (int k = 0; k < 16 && !seen; ++k) {
session.ui_command(cmd("request:lt" + std::to_string(k), "session.advance", O{{"live", true}}), rev);
const J state = session.read_live(O{{"kind", "fixture"}});
if (!truth(at(state, "live"))) continue;
if (const auto* tables = at(state, "standings").array(); tables && !tables->empty()) {
const auto* rows = at(tables->front(), "rows").array();
seen = rows && rows->size() >= 10 && *at(rows->front(), "rank").integer() == 1;
std::printf("(paused league table: %s, %zu rows)\n", s(at(tables->front(), "name")).c_str(), rows ? rows->size() : 0);
check(seen, "the paused league match has its live table");
}
session.ui_command(cmd("request:ltf" + std::to_string(k), "live.finish", O{}), rev);
}
if (!seen) std::printf("(no paused league match on this path)\n");
}
// a season of kickoffs: running-out contracts stop the run with decision_pending and the
// player; the advance is sent again with the answer (here: release)
{
O expiry;
int decisions = 0, advances = 0;
int national_friendly = -1; // -1 no national desk yet, 0 read, 1 booked
for (int k = 0; k < 200 && advances < 120; ++k) {
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:s" + std::to_string(k), "session.advance", O{{"contractExpiry", expiry}}), rev);
if (s(at(done, "messageType")) == "command_result") {
++advances;
// at the national coach's desk: a friendly against another nation (the quote
// draws ratings; the read previews them without moving the generator)
if (national_friendly < 0) {
const J nf = session.ui_read(O{{"kind", "friendly"}, {"opponentId", "team:384"}}, rev);
if (!truth(at(at(nf, "data"), "national"))) continue;
const J again = session.ui_read(O{{"kind", "friendly"}, {"opponentId", "team:384"}}, rev);
const auto* dates = at(at(nf, "data"), "dates").array();
check(cli::dump_json(at(nf, "data")) == cli::dump_json(at(again, "data")) && dates, "national friendly read is pure");
std::printf("(national friendly: %s)\n", cli::dump_json(at(nf, "data")).substr(0, 300).c_str());
national_friendly = 0;
if (dates && !dates->empty()) {
const J day = at(dates->back(), "date");
const uint64_t was = rev;
const J booked = session.ui_command(cmd("request:nf" + std::to_string(k), "friendly.book",
O{{"opponentId", "team:384"}, {"date", day}, {"acceptCost", true}}), rev);
std::printf("(national friendly booked: %s)\n", cli::dump_json(booked).substr(0, 200).c_str());
check(s(at(booked, "messageType")) == "command_result" && rev == was + 1, "national friendly booked");
national_friendly = 1;
}
}
continue;
}
const std::string code = s(at(done, "code"));
const std::string player = s(at(at(at(done, "message"), "args"), "playerId"));
check(code == "decision_pending" && !player.empty() && rev == before, "a pending contract names the player, nothing changed");
if (code != "decision_pending" || player.empty() || expiry.count(player)) break;
expiry[player] = O{{"action", "release"}};
++decisions;
}
check(advances == 120, "two seasons of kickoffs with answered contract decisions");
check(decisions > 0, "running-out contracts were asked for");
std::printf("(date now %s)\n", s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")).c_str());
std::printf("(%d contract decisions answered)\n", decisions);
}
// almanac view after the kickoffs: index, calendar, day, match
{
const J index = session.read_almanac(O{{"kind", "index"}});
const auto* years = at(index, "years").array();
check(truth(at(index, "ok")) && years && !years->empty() && *at(index, "match_count").integer() > 0, "almanac index");
const J cal = years && !years->empty() ? session.read_almanac(O{{"kind", "calendar"}, {"year", (*years)[0]}}) : J{};
const auto* days = at(cal, "days").array();
check(days && !days->empty(), "almanac calendar");
const J day = days && !days->empty() ? session.read_almanac(O{{"kind", "day"}, {"date", at((*days)[0], "date")}}) : J{};
const auto* matches = at(day, "matches").array();
check(matches && !matches->empty(), "almanac day");
if (matches && !matches->empty()) {
const J& m = (*matches)[0];
const auto* final_score = at(at(m, "result"), "final").array();
check(final_score && final_score->size() == 2 && at(at(m, "home"), "id").string() &&
at(m, "events").array(), "almanac match form");
const J one = session.read_almanac(O{{"kind", "match"}, {"id", at(m, "id")}});
check(truth(at(one, "ok")) && s(at(at(one, "match"), "id")) == s(at(m, "id")), "almanac match by id");
}
check(s(at(session.read_almanac(O{{"kind", "match"}, {"id", "match:0-0"}}), "error")) == "almanac_match_not_found",
"unknown match");
// the statistics screen: real data (fictional false), unrecorded views say so
// (the club views need a club desk: on an international day the manager sits at the national one)
const J minutes = session.read_statistics_screen(O{{"section", 8}});
const bool club_desk = !std::holds_alternative<std::nullptr_t>(at(minutes, "club").value);
check(truth(at(minutes, "ok")) && !truth(at(minutes, "fictional")) &&
(!club_desk || (at(minutes, "rows").array() && at(minutes, "rows").array()->size() == 4)), "minute statistics");
const J transfers = session.read_statistics_screen(O{{"section", 0}});
check(truth(at(transfers, "ok")) && !truth(at(transfers, "available")) && s(at(transfers, "reason")) == "not_recorded",
"title chances not recorded");
check(s(at(session.read_statistics_screen(O{{"section", 9}}), "error")) == "invalid_statistics_filter", "bad section");
const J curves = session.read_statistics_screen(O{{"section", 2}});
check(!club_desk || (at(curves, "series").array() && at(curves, "series").array()->size() == 6), "the six curves of the original");
}
// resigning: needs the confirmation; the last human manager ends the career
{
const auto resign = [&](const std::string& id, J payload) {
return session.ui_command(J(O{{"messageType", "command"}, {"requestId", id}, {"expectedRevision", std::to_string(rev)},
{"owner", O{{"managerId", "manager:1"}}}, {"kind", "manager.resign.commit"},
{"payload", std::move(payload)}}), rev);
};
check(s(at(resign("request:r1", O{}), "code")) == "confirmation_required", "resigning needs the confirmation");
const J done = resign("request:r2", O{{"confirmed", true}});
check(s(at(done, "outcome")) == "career_ended", "the last human manager ends the career");
check(s(at(at(session.ui_read(O{{"kind", "session"}}, rev), "data"), "sessionState")) == "ended", "session ended");
check(s(at(resign("request:r3", O{{"confirmed", true}}), "code")) == "career_ended", "no command after the end");
}
} catch (const std::exception& ex) {
std::fprintf(stderr, "FAIL: %s\n", ex.what());
return 1;
}
if (failures == 0) std::printf("modern ui contract tests passed\n");
return failures == 0 ? 0 : 1;
}