cntrl/tests/level_binary_test.cpp
dandovlatov f36654ff42 Cook levels into a checksummed binary; load binary at runtime
Replace the tracked JSON-in-header bake with a deterministic, bounds-checked CLB binary cooked by the build step. cntrl now loads only the binary; direct JSON loading is restricted to debug builds. Add codec/CLI tests, binary checker, editor bake-on-playtest, and pipeline docs.
2026-11-25 03:19:37 +04:00

77 lines
2.4 KiB
C++

#include <cstdio>
#include <filesystem>
#include <string>
#include <vector>
#include "level/level_binary.hpp"
#include "level/level_data.hpp"
namespace {
int failures = 0;
void check(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "FAIL: %s\n", what);
++failures;
}
}
bool rejects(const std::vector<std::uint8_t>& bytes, level::LevelData& level,
std::string& error, const char* what) {
const std::string before = level::serialize(level);
const bool ok = level::decode_binary(bytes, level, error);
check(!ok, what);
check(level::serialize(level) == before, "rejected binary leaves level untouched");
return !ok;
}
} // namespace
int main() {
const level::LevelData original = level::floor01_default();
const std::string expected = level::serialize(original);
std::string error;
const auto bytes = level::encode_binary(original);
check(bytes.size() > 16, "binary is non-trivial");
level::LevelData decoded;
check(level::decode_binary(bytes, decoded, error), error.c_str());
check(level::serialize(decoded) == expected, "binary round-trip preserves level");
check(level::encode_binary(decoded) == bytes, "encoding is deterministic");
// The client path: write the cooked file, then read it back from disk.
const std::string path = "level_binary_test.bin";
check(level::write_binary(path, original, error), error.c_str());
level::LevelData from_file;
check(level::read_binary(path, from_file, error), error.c_str());
check(level::serialize(from_file) == expected, "file round-trip preserves level");
std::filesystem::remove(path);
// Corrupt inputs must be rejected without touching the caller's level.
std::vector<std::uint8_t> bad = bytes;
bad[0] ^= 0xff;
rejects(bad, decoded, error, "bad magic rejected");
bad = bytes;
bad[8] ^= 0xff;
rejects(bad, decoded, error, "unsupported version rejected");
bad = bytes;
bad.back() ^= 0xff;
rejects(bad, decoded, error, "checksum mismatch rejected");
bad = bytes;
bad.pop_back();
rejects(bad, decoded, error, "truncated binary rejected");
bad = bytes;
bad.insert(bad.begin() + 12, 0);
rejects(bad, decoded, error, "trailing bytes rejected");
check(!level::read_binary("no_such_level.bin", decoded, error),
"missing file rejected");
return failures == 0 ? 0 : 1;
}