Files
stoneheart_at_home/tests/profile_tests.cpp

286 lines
16 KiB
C++

#include "settlement/core/colony_profile.hpp"
#include <Void/Core/Hash.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
template<class T, class E>
T checked(std::expected<T, E> result) {
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
std::string saved(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return std::move(stream).str();
}
std::string checkpoint(const World& world, const WorldCheckpoint& identity) {
return checked(encode_checkpoint(world, identity.world_id, identity.city, identity.rules));
}
void command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
GridPosition target = {}, AgentId resident = 0) {
const auto receipt = world.apply_command(
{1, world.next_command_sequence(1), kind, cell, value, target, resident});
require(receipt.status == CommandStatus::Accepted, "profile command was rejected");
}
std::uint64_t stock(const World& world, ItemType item) {
std::uint64_t count = 0;
for (const auto& storage : world.storages()) count += storage.item_count(item);
for (const auto& agent : world.agents()) count += agent.inventory.item_count(item);
return count;
}
void queue_three_beds(World& world) {
command(world, CommandKind::PlaceBed, {16, 18});
command(world, CommandKind::PlaceBed, {17, 18}, 1);
command(world, CommandKind::PlaceBed, {18, 18});
command(world, CommandKind::SetForaging, {14, 12}, 1);
command(world, CommandKind::SetForaging, {13, 14}, 1);
}
std::size_t count_recipe(const World& world, RecipeId recipe) {
return static_cast<std::size_t>(std::count_if(
world.production_orders().begin(), world.production_orders().end(),
[recipe](const auto& order) { return order.recipe == recipe; }));
}
std::string from_hex(std::string_view hex) {
const auto digit = [](char value) {
return value <= '9' ? value - '0' : value - 'a' + 10;
};
std::string bytes;
for (std::size_t i = 0; i < hex.size(); i += 2) {
bytes.push_back(static_cast<char>(digit(hex[i]) * 16 + digit(hex[i + 1])));
}
return bytes;
}
// Produced by the pre-profile core and header at 60154bd, SHA-256
// 8936352f8f8c939f866195bd434fe58c3bcf9ace49202c937c9cb2a026583d48.
// Checkpoint schema 1 holds an active default-manifest world with simple beds.
const std::string legacy_simple_checkpoint = from_hex(
"53544843484b505401000000b6000000b7000000000000000102030405064708890a0b0c0d0e0f10"
"0100000000000000000000000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72d"
"c0984cfc62cd83d1020000001100736574746c656d656e742e636f6c6f6e790500312e302e3008e1"
"8a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c0890f00736574746c656d65"
"6e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530d0000002f010000000000000500000005000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000000010100000000"
"00000001000000000000000100000000000000010000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000100000002000000"
"0200000000000000000000000000000000000000000000000000000000ada3be851474c1ab6aa6bb"
"0efc1a3cc103430f5b1a69fd602ec6bf02b93f98c6");
struct [[= Void::Testing::name("ProfileTests")]] ProfileTests : Void::Testing::Suite<ProfileTests> {
[[= Void::Testing::tag("profile")]] Test test_compiled_profiles_resolve_exact_content();
[[= Void::Testing::tag("profile")]] Test test_both_first_colonies_complete_with_the_selected_material_chain();
[[= Void::Testing::tag("profile")]] Test test_furnished_rooms_use_the_selected_bed_recipe();
[[= Void::Testing::tag("profile")]] Test test_profiles_replay_and_resume_mid_delivery();
[[= Void::Testing::tag("profile")]] Test test_historical_default_simple_and_inactive_worlds_keep_their_mode();
[[= Void::Testing::tag("profile")]] Test test_supported_profile_gate_rejects_mismatches_without_mutation();
[[= Void::Testing::tag("profile")]] Test test_scenario_profile_cannot_change_after_start();
};
Test ProfileTests::test_compiled_profiles_resolve_exact_content() {
const auto original = checked(colony_rules(ColonyProfile::Default));
const auto planks = checked(colony_rules(ColonyProfile::PlankBeds));
require(original.manifest() == checked(default_rules_manifest()) &&
original.bed_mode() == BedConstructionMode::Staged, "default compilation changed");
require(planks.manifest().packages().size() == 3 && planks.bed_mode() == BedConstructionMode::Plank,
"optional package did not select plank construction");
auto catalog = checked(builtin_rule_packages());
std::reverse(catalog.begin(), catalog.end());
const std::array selected{std::string{"settlement.plankbeds"}};
const auto shuffled = checked(resolve_rules(catalog, selected));
require(shuffled == planks.manifest() &&
checked(compile_colony_rules(shuffled)).profile() == ColonyProfile::PlankBeds,
"catalog order changed the compiled profile");
require(!colony_rules(static_cast<ColonyProfile>(255)), "unknown profile compiled");
require(!make_colony_checkpoint(ColonyProfile::Default, 1),
"parallel one-worker colony was created");
}
Test ProfileTests::test_both_first_colonies_complete_with_the_selected_material_chain() {
for (auto profile : {ColonyProfile::Default, ColonyProfile::PlankBeds}) {
auto candidate = checked(make_colony_checkpoint(profile, 1, ExecutionMode::SerialReference));
require(!candidate.world_id.is_nil() && candidate.city == 1, "colony identity is missing");
require(validate_colony_checkpoint(candidate).has_value(), "new colony profile failed validation");
auto& world = *candidate.world;
queue_three_beds(world);
const bool staged = profile == ColonyProfile::Default;
require(world.staged_beds() == staged &&
count_recipe(world, RecipeId::SawPlank) == (staged ? 0U : 3U),
"bed command ignored its selected recipe");
for (const auto& order : world.production_orders()) {
if (order.recipe != RecipeId::BuildBed) continue;
require(order.bed_material() == (staged ?
(order.bed_base == BedBase::Stone ? ItemType::Stone : ItemType::Wood) : ItemType::Plank),
"material preview does not match the enacted profile");
}
for (int tick = 0; tick < 1200 && !world.scenario_progress().completed; ++tick) world.step();
require(world.scenario_progress().completed && world.scenario_progress().assigned_beds == 3,
"selected first-colony profile did not complete the three-bed food objective");
require(stock(world, ItemType::Cloth) == (staged ? 6U : 12U) &&
stock(world, ItemType::Stone) == (staged ? 5U : 6U),
"bed profile consumed the wrong cloth or foundation material");
require(std::all_of(world.production_orders().begin(), world.production_orders().end(),
[](const auto& order) { return order.state == JobState::Completed; }),
"selected profile left an unfinished prerequisite");
}
}
Test ProfileTests::test_furnished_rooms_use_the_selected_bed_recipe() {
for (auto mode : {BedConstructionMode::Staged, BedConstructionMode::Plank}) {
World world(64, 20, 18, 1, ExecutionMode::SerialReference);
const auto builder = world.spawn_agent({5, 3});
const auto carpenter = world.spawn_agent({3, 3});
const auto materials = world.add_storage({3, 4}, 128);
world.stock_storage(materials, ItemType::Wood, 80);
world.stock_storage(materials, ItemType::Stone, 6);
world.stock_storage(materials, ItemType::Cloth, 2);
const auto food = world.add_storage({2, 4}, 200, StorageKind::Pantry);
world.stock_storage(food, ItemType::Berries, 200);
world.start_scenario({4, 3}, mode);
command(world, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Builder), {}, builder);
command(world, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter);
const RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, RoomTemplate::Miner};
command(world, CommandKind::PlaceRoom, plan.first, plan.placement_value(), plan.last);
require(count_recipe(world, RecipeId::SawPlank) == (mode == BedConstructionMode::Plank ? 1U : 0U),
"furnished room ignored the optional plank prerequisite");
for (int tick = 0; tick < 2200 && world.scenario_progress().assigned_beds == 0; ++tick) world.step();
require(world.scenario_progress().assigned_beds == 1, "room bed did not complete");
require(stock(world, ItemType::Cloth) == (mode == BedConstructionMode::Plank ? 2U : 0U),
"furnished room consumed the wrong bedding");
}
}
Test ProfileTests::test_profiles_replay_and_resume_mid_delivery() {
const auto catalog = checked(builtin_rule_packages());
for (auto profile : {ColonyProfile::Default, ColonyProfile::PlankBeds}) {
auto initial = checked(make_colony_checkpoint(profile, 1, ExecutionMode::SerialReference));
queue_three_beds(*initial.world);
const auto initial_bytes = checkpoint(*initial.world, initial);
std::vector<WorldCheckpoint> runs;
for (std::size_t workers : {2U, 6U, 12U}) {
runs.push_back(checked(decode_checkpoint(initial_bytes, catalog, workers)));
}
std::shared_ptr<const World> held;
std::string held_bytes;
bool resumed = false;
for (int tick = 0; tick < 500; ++tick) {
initial.world->step();
for (auto& run : runs) run.world->step();
const auto expected = checkpoint(*initial.world, initial);
for (const auto& run : runs) {
require(checkpoint(*run.world, run) == expected, "profile parallel replay diverged");
}
if (!resumed && std::any_of(initial.world->agents().begin(), initial.world->agents().end(),
[](const auto& agent) {
return agent.state == AgentState::Hauling &&
(agent.inventory.item_count(ItemType::Wood) != 0 ||
agent.inventory.item_count(ItemType::Stone) != 0 ||
agent.inventory.item_count(ItemType::Plank) != 0 ||
agent.inventory.item_count(ItemType::Cloth) != 0);
})) {
held = initial.world->capture();
held_bytes = saved(*held);
runs.push_back(checked(decode_checkpoint(expected, catalog, 1, ExecutionMode::SerialReference)));
resumed = true;
}
}
require(resumed && saved(*held) == held_bytes, "held material snapshot changed or was never captured");
require(initial.world->scenario_progress().assigned_beds == 3, "replay profile failed its bed objective");
}
}
Test ProfileTests::test_historical_default_simple_and_inactive_worlds_keep_their_mode() {
const auto catalog = checked(builtin_rule_packages());
auto legacy = checked(decode_checkpoint(legacy_simple_checkpoint, catalog, 1, ExecutionMode::SerialReference));
require(legacy.world->scenario_active() && !legacy.world->staged_beds(),
"authentic schema-1 fixture lost its historical mode");
const auto before = saved(*legacy.world);
require(validate_colony_checkpoint(legacy).has_value() && saved(*legacy.world) == before,
"default profile gate rewrote a historical simple colony");
auto current = checked(decode_checkpoint(checkpoint(*legacy.world, legacy), catalog, 1, ExecutionMode::SerialReference));
require(validate_colony_checkpoint(current).has_value() && saved(*current.world) == before,
"resaving historical defaults changed their enacted rules");
// The corresponding v2 raw format omitted the staged flag and used an FNV footer.
auto raw_v2 = before;
raw_v2[8] = 2;
raw_v2.pop_back();
auto digest = Void::Hash::fnv1a64_offset_basis;
digest = Void::Hash::fnv1a64_update(digest, std::as_bytes(std::span{raw_v2}));
for (unsigned shift = 0; shift < 64; shift += 8) raw_v2.push_back(static_cast<char>(digest >> shift));
std::istringstream input(raw_v2, std::ios::binary);
legacy.world = World::read_save(input, 1, ExecutionMode::SerialReference);
require(legacy.world->scenario_active() && !legacy.world->staged_beds() &&
validate_colony_checkpoint(legacy).has_value(), "active raw-v2 import lost default compatibility");
legacy.world = std::make_unique<World>(17, 5, 5, 1, ExecutionMode::SerialReference);
const auto inactive_before = saved(*legacy.world);
require(validate_colony_checkpoint(legacy).has_value() && saved(*legacy.world) == inactive_before,
"inactive historical default was rejected or modified");
}
Test ProfileTests::test_supported_profile_gate_rejects_mismatches_without_mutation() {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 1, ExecutionMode::SerialReference));
const auto before = saved(*candidate.world);
candidate.rules = checked(colony_rules(ColonyProfile::PlankBeds)).manifest();
auto invalid = validate_colony_checkpoint(candidate);
require(!invalid && invalid.error().package == "settlement.plankbeds" &&
saved(*candidate.world) == before, "staged world with plank rules was accepted or changed");
auto catalog = checked(builtin_rule_packages());
auto altered = std::string(catalog.back().canonical_json());
const auto work = altered.find("\"work_ticks\":14");
require(work != std::string::npos, "plank fixture has no work duration");
altered.replace(work, std::string_view{"\"work_ticks\":14"}.size(), "\"work_ticks\":15");
catalog.back() = checked(load_rule_package("altered/plankbeds", altered));
const std::array selected{std::string{"settlement.plankbeds"}};
candidate.rules = checked(resolve_rules(catalog, selected));
require(!validate_colony_checkpoint(candidate) && saved(*candidate.world) == before,
"modified recipe content was accepted as an implemented profile");
const std::array core_only{std::string{"settlement.core"}};
require(!compile_colony_rules(checked(resolve_rules(catalog, core_only))), "incomplete profile compiled");
const auto extra = checked(load_rule_package("extra",
R"({"schema":1,"id":"game.extra","version":"1.0.0","dependencies":[],"exclusive_capabilities":[],"definitions":[]})"));
catalog.push_back(extra);
const std::array with_extra{std::string{"settlement.colony"}, std::string{"game.extra"}};
require(!compile_colony_rules(checked(resolve_rules(catalog, with_extra))), "unimplemented package compiled");
require(!resolve_rules(catalog, std::array{std::string{"missing.package"}}), "missing package resolved");
}
Test ProfileTests::test_scenario_profile_cannot_change_after_start() {
World world(17, 5, 5, 1, ExecutionMode::SerialReference);
const auto before = saved(world);
Void::Testing::expect_throw<std::invalid_argument>([&] {
world.start_scenario({2, 2}, static_cast<BedConstructionMode>(255));
});
require(saved(world) == before, "invalid mode changed the world");
world.start_scenario({2, 2}, BedConstructionMode::Plank);
const auto started = saved(world);
Void::Testing::expect_throw<std::invalid_argument>([&] { world.start_scenario({2, 2}); });
require(saved(world) == started, "started colony changed its creation profile");
}
} // namespace