Writing a unit test
The framework's tests run with no window, no GPU and no display, in milliseconds, under the sanitizers. They can, because everything that changes between two runs — the clock, the input devices, the size of the screen, the seed — enters the framework through a seam a test replaces. This page is how to write one: where the file goes, what it looks like, which seams there are, and how to see it fail before you trust it to pass.
Testing describes what the tests are and what each stage of
rmp test runs. This page is for adding to them.
Where a test goes#
A test goes in the file of the program that can run it. Each kind of file is found by a pattern, so a new file of a kind that is already there needs no change to CMake; a Python module may need a stage, below.
| What it tests | The file | Built into | Run by |
|---|---|---|---|
A module of src/rmp/ | tests/<module>_test.cpp | unit_test | rmp test unit |
| The interface's layout, headless | a case in tests/ui_layout_test.cpp | ui_layout_test, a program of its own | rmp test layout |
| The interface on a real GPU | a case in tests/ui_render_test.cpp | ui_render_test | rmp test ui-render |
| What holds for every input | tests/property/<module>_prop.cpp | property_test | rmp test property — Properties |
| A parser, fuzzed | tests/fuzz/<name>.cpp | fuzz_<name> | rmp test fuzz — Fuzzing |
| An example, played | tests/e2e/<area>/<name>.e2e | e2e_<area>_<name> | rmp test examples — Examples and e2e scripts |
A tool of tools/ | tests/<tool>_test.py | Python's unittest | the stage whose pattern finds it — below |
| A game's own code | tests/game/<name>_test.cpp | game_test | rmp test unit — below |
Every
tests/*_test.cpp but the two interface tests with a main() of their own
is compiled into unit_test, and the pattern is read again on every build: without
that, a new test file is not compiled until somebody happens to reconfigure, and a test that never
runs looks exactly like one that passes.
Files
a test reads — a map, a picture, a save cut short — go in tests/fixtures/. The build
compiles in the absolute path of that folder, so a test finds them whatever directory it is run
from.
A test file#
Here is the smallest test file of the framework, whole: what it holds and why, at the top; doctest; the header of the module it tests; and one suite, named after the module, with a case for each thing the module promises.
// ---------------------------------------------------------------------------
// rmp::ads off Android: the stubs of thirdparty/raymob/admob.h, through the
// wrapper in src/rmp/ads/ads.cpp. What a game that shows ads does on a desktop,
// a browser or a CI runner -- every call compiles, links and does nothing --
// is what this holds. The real ads are Android's, and only a phone shows one.
// ---------------------------------------------------------------------------
#include <doctest.h>
#include <rmp/ads.h>
TEST_SUITE("ads") {
TEST_CASE("off Android an interstitial never loads, and showing it does nothing") {
CHECK_FALSE(rmp::ads::is_interstitial_loaded());
rmp::ads::request_interstitial();
CHECK_FALSE(rmp::ads::is_interstitial_loaded());
rmp::ads::show_interstitial();
CHECK_FALSE(rmp::ads::is_interstitial_loaded());
}
TEST_CASE("off Android a rewarded ad never loads and never earns anything") {
rmp::ads::request_rewarded();
CHECK_FALSE(rmp::ads::is_rewarded_loaded());
rmp::ads::show_rewarded();
CHECK_FALSE(rmp::ads::take_reward_earned());
CHECK(rmp::ads::reward_amount() == 0);
// The documented use: show it only when it has loaded, grant only
// what was earned -- which off Android is never.
if (rmp::ads::is_rewarded_loaded()) rmp::ads::show_rewarded();
CHECK_FALSE(rmp::ads::take_reward_earned());
}
}
The suite's name is not decoration. It is what you select a run by, and what a
mutation floor
selects the tests of its module by — tests/mutation/floors/random.txt runs
unit_test -ts=random.
A
test that needs the framework's own internals — the seams below — includes their headers by a
relative path after doctest and before the public headers, as tests/clock_test.cpp
does: #include "../src/rmp/internal.h" for the clock and the reports, and
#include "../src/rmp/ui/internal.h" for the interface.
Running it#
rmp test unit
./build/debug/unit_test -ts=random
./build/debug/unit_test -tc="*fixed step*"
./build/debug/unit_test -sf="*clock_test.cpp"rmp test unit configures the debug build with the tests on, builds
unit_test and runs it; after that the program takes doctest's own options: a suite,
a case or a source file by name, with * for anything.
A
source file is matched against the whole path the compiler was given, which starts wherever the
checkout is, so its pattern begins with *.
The stage runs every case twice: in the order they are written, then shuffled with a fixed seed. A case that passes only because the one before it left something behind fails the second run, and fails it again on every run after, because the seed does not change. To play the shuffled run yourself:
bash tools/test_locales.sh build/test-locales
LOCPATH=build/test-locales ./build/debug/unit_test --order-by=rand --rand-seed=1337 --test-suite-exclude="audio: device"The
first line builds the two test locales a save is read back under — a decimal point that is a
comma, and one that is two bytes long — and the second points the run at them. Without them those
cases skip and say so; CI makes the skip a failure. The audio: device suite opens the
real sound device and runs in the first pass only.
Both runs are a debug build, so both are under AddressSanitizer and UndefinedBehaviorSanitizer, and the build has warnings as errors: a warning in a test fails the stage like a warning in the framework. Security says what the sanitizers catch.
The seams#
A
seam is the one function through which the framework reads something that changes from run to run.
A test replaces it, and every answer the framework gives comes from what the test put there.
rmp test seam fails when any other file of src/rmp/ or
include/rmp/ reads the clock, the devices, the screen or the random state on its own,
because one such read is enough to make a test pass on one machine and fail on the next.
| What changes | The seam a test sets | Declared in | Put back with |
|---|---|---|---|
The keyboard, mouse and gamepad, as rmp::input reads them | rmp::input::detail::set_sample_provider(), with a function that fills a rmp::input::detail::DeviceState | include/rmp/input.h | rmp::input::detail::reset() |
| How long a frame is | set_fixed_delta(), in rmp::app::detail | src/rmp/internal.h | set_fixed_delta(0) |
| The seed a run starts from | set_test_seed(), in rmp::app::detail, or rmp::random::seed() itself | src/rmp/internal.h | set_test_seed(std::nullopt) |
| The pointer, as the interface reads it | set_pointer_provider(), in rmp::ui::detail | src/rmp/ui/internal.h | pointer_from_raylib |
| The keys and buttons the interface navigates with | set_nav_provider(), with a function that fills a NavState | src/rmp/ui/internal.h | nav_from_raylib |
| How wide a line of text is | set_measure_provider() | src/rmp/ui/internal.h | measure_with_raylib |
| What the keyboard typed into a text field | set_text_provider() | src/rmp/ui/internal.h | nullptr |
| The size of the window | set_test_viewport(), which also stops the interface drawing | src/rmp/ui/internal.h | set_test_viewport(0, 0) |
| What the framework says about a mistake in the game | set_report_sink(), report_count(), in rmp::detail | src/rmp/internal.h | set_report_sink({}) and reset_reports_for_tests() |
The
input has two seams, and that is on purpose: the game reads rmp::input and the
interface reads its own navigation. Keys fed to the first move the player and leave the menus deaf.
A test of a menu sets the second; a test of a game with a menu over it sets both.
The input#
A
test writes the devices it wants into a struct and hands the framework a function that copies it
out. rmp::input::detail::begin_frame() is one turn of the loop: everything about an
edge — the frame a key went down — is the difference between two of them, so a test that calls it
once is testing the wrong thing. This is the fixture tests/input_test.cpp starts every
case with, and a case of the kind it holds:
namespace {
// The devices the test holds down: there is nothing between this and
// what rmp::input answers.
struct {
rmp::input::detail::DeviceState devices;
} fake;
void fake_sample(rmp::input::detail::DeviceState &out) { out = fake.devices; }
// Every case starts from nothing and leaves nothing: the cases also run
// shuffled, and the next one may be anyone's.
struct Fixture {
Fixture() {
rmp::input::detail::reset();
fake.devices = rmp::input::detail::DeviceState{};
rmp::input::detail::set_sample_provider(fake_sample);
}
Fixture(const Fixture &) = delete;
Fixture &operator=(const Fixture &) = delete;
~Fixture() {
rmp::input::detail::reset();
fake.devices = rmp::input::detail::DeviceState{};
}
};
} // namespace
TEST_CASE_FIXTURE(Fixture, "jump is just pressed on the frame Space goes down, and only then") {
rmp::input::action("jump", KEY_SPACE);
rmp::input::detail::begin_frame();
CHECK_FALSE(rmp::input::just_pressed("jump"));
fake.devices.keys[KEY_SPACE] = true;
rmp::input::detail::begin_frame();
CHECK(rmp::input::just_pressed("jump"));
rmp::input::detail::begin_frame();
CHECK_FALSE(rmp::input::just_pressed("jump"));
CHECK(rmp::input::pressed("jump"));
}The
fixture puts things back in its destructor, and rmp::input::detail::reset() forgets
every action and every reading and puts raylib back as the provider.
Its
copies are deleted because a class that writes its destructor says what becomes of the rest:
rmp lint asks, with cppcoreguidelines-special-member-functions.
The clock and the seed#
With
a fixed step, every frame hands the game exactly that many seconds, still clamped by
[app] max_delta, whatever the machine took; 0 goes back to the real clock. The
interface animates by the same number, so the menus and the game cannot disagree about how long a
frame was. The seed is what rmp::random starts a run from instead of the wall clock.
Together they are what lets a test — or a
script — get the same frame twice:
namespace {
// Back to the real clock and no seed, whatever a case did.
struct Fixture {
Fixture() { reset(); }
~Fixture() { reset(); }
Fixture(const Fixture &) = delete;
Fixture &operator=(const Fixture &) = delete;
static void reset() {
rmp::app::detail::set_fixed_delta(0);
rmp::app::detail::set_test_seed(std::nullopt);
}
};
constexpr float STEP = 1.0F / 60;
} // namespace
TEST_CASE_FIXTURE(Fixture, "a fixed step is what the game is handed, and what the interface animates by") {
rmp::app::detail::set_fixed_delta(STEP);
CHECK(rmp::app::detail::step_delta() == STEP);
CHECK(rmp::ui::detail::frame_time() == STEP);
}tests/clock_test.cpp
holds the clock itself to this, case by case. Code that reads GetTime() or
GetFrameTime() for itself is out of the test's reach: a game that does cannot be played
from a script, and the platformer's flag once did.
What the framework says#
A
mistake in the game — an action nobody defined, a widget outside begin() and
end() — is said once, through RMP_REPORT_ONCE, and a test of that
mistake checks it was said, and said once. report_count() is how many have been said
since reset_reports_for_tests(), and a sink set with set_report_sink()
hears each line. A test that turns [dev] strict on to see the first report stop the
run replaces what stopping does, with set_strict_handler(), so that the test program
is not the thing that stops. The fixture of tests/report_test.cpp sets each of these
and puts each back.
What the machine does wrong — no sound device, a folder that cannot be written — is not a mistake in the game, and is a plain log line, never RMP_REPORT_ONCE: strict mode would stop a correct game on a CI runner. A test of such a path does not expect a report.
The interface, with no window#
The
interface's layout is Clay's, and Clay's layout is arithmetic. With the text measurement and the
pointer replaced by functions of the test's, and a viewport given instead of a window, a whole menu
is laid out with no window and no GPU, and drawing is skipped. Then the test asks where each
control ended up with bounds_of(): the label, which occurrence of it, and which
begin()/end() pass of the frame.
namespace {
// Every glyph half its size wide, a line one size tall: the questions are
// about arrangement, not typography. The parameters are Clay's.
// NOLINTBEGIN(custom-rmp-raw-pointer): Clay's signature, not ours to choose
Clay_Dimensions measure_stub(Clay_StringSlice text, Clay_TextElementConfig *config,
void * /*user*/) {
// NOLINTEND(custom-rmp-raw-pointer)
const auto size = static_cast<float>(config->fontSize);
return Clay_Dimensions{ static_cast<float>(text.length) * size * 0.5F, size };
}
// No pointer at all: nothing is hovered, nothing is clicked.
void pointer_stub(Clay_Vector2 &position, bool &down) {
position = Clay_Vector2{ -1.0F, -1.0F };
down = false;
}
// The stubs and a window of 1280 x 720 for one case, and the real ones
// back after it, whatever it did: no focus left on a button either.
struct HeadlessUi {
HeadlessUi() {
rmp::ui::detail::set_measure_provider(measure_stub);
rmp::ui::detail::set_pointer_provider(pointer_stub);
rmp::ui::detail::set_test_viewport(1280, 720);
}
HeadlessUi(const HeadlessUi &) = delete;
HeadlessUi &operator=(const HeadlessUi &) = delete;
~HeadlessUi() {
rmp::ui::focus("");
rmp::ui::detail::set_measure_provider(rmp::ui::detail::measure_with_raylib);
rmp::ui::detail::set_pointer_provider(rmp::ui::detail::pointer_from_raylib);
rmp::ui::detail::set_test_viewport(0, 0);
}
};
void draw_menu() {
rmp::ui::begin();
rmp::ui::button("Play");
rmp::ui::button("Quit");
rmp::ui::end();
}
} // namespace
TEST_CASE_FIXTURE(HeadlessUi, "Play is above Quit") {
// Twice: the first frame has nothing laid out before it to hit-test against.
draw_menu();
draw_menu();
Clay_BoundingBox play{};
Clay_BoundingBox quit{};
REQUIRE(rmp::ui::detail::bounds_of("Play", 0, 0, &play));
REQUIRE(rmp::ui::detail::bounds_of("Quit", 0, 0, &quit));
CHECK(play.y + play.height <= quit.y);
}Such a case can go in two places, and they are not the same:
- In
a
tests/ui_<what>_test.cppofunit_test, written as above. Its cases run shuffled among every other test of the framework, so the fixture puts the real providers back and leaves nothing behind it — no focus, no frame with something in front, no report.HeadlessUiintests/ui_overlay_test.cppis the whole of such a fixture, the navigation and the reports included. - In
tests/ui_layout_test.cpp, a program of its own whosemain()puts the stubs in place once, for every case: there a case is the drawing and the checks, with no fixture. Its cases run in the order they are written, each in the interface the one before it left, and the last one — Clay's ceiling on elements — leaves it unable to lay anything out again, so a new case goes before that one. It is where a layout is checked at many window sizes:rmp test layoutlays the menu out at four.
rmp test layout
cmake --preset debug -DBUILD_UI_TESTS=ON
cmake --build --preset debug --target ui_layout_test
./build/debug/ui_layout_test -tc="*dropdown*"With
no window there is nothing drawn, so what only drawing can show — the backdrop's blur, a shader
built for a phone's GPU — is tests/ui_render_test.cpp's: a hidden window on a real
GPU, the frame read back. rmp test ui-render runs it; CI runs it under a virtual
display.
Seen red first#
The framework's rule is that a test you have not seen go red is not a test, it is a hope with a name. A test that has only ever passed may be testing nothing: a check on the wrong variable, a case the build never compiled, a seam the code under test does not read. The only proof that it can fail is to watch it fail on the mistake it is for.
- Write the test before the fix, or take the fix out for a moment.
- Run it, and read the failure. It has to fail at the check you wrote, saying what you meant it to say — not a compile error, not a crash somewhere else, not a different check.
- Put the fix in, and see the same test pass.
- Say in the commit message how it was seen red.
When the fix is already written, take it out of the one file it is in and put it back, without touching anything else in the working tree:
git stash push -- src/rmp/app/clock.cpp
rmp test unit
git stash popWhat deserves a test is everything a header says the code does. A promise in a header comment with no test that would fail without it is not a feature yet: the framework once said for two phases that a scene collides against its map's solid tiles, and nothing did.
And what deserves a case is every input: for every option, the valid values, every invalid one, the wrong type, the empty one, and the combination that cannot work. A check that only ever sees plausible input has not been tested. For inputs nobody would think to write by hand, a property or a fuzz target looks for them.
A test that is a check on the repository — a gate — is seen red the same way, by planting the mistake it exists for: Coverage and the gates says how.
Tests of the tools#
The
Python in tools/ is tested by tests/<tool>_test.py, with the standard
library's unittest. Every such module has to be found by the pattern of a stage of
rmp test, and a test of the command fails on one that is not: a file of tests no stage
runs passes in silence, everywhere, for good. A new module either matches a pattern a stage already
has, or comes with its stage.
rmp test configure
python3 -m unittest discover -s tests -p configure_test.py -k ConfigureLineTest -vA
test loads the tool it tests by its path, under the name tools.<name>, as
load_tool() in tests/campaign_test.py does. That is the name mutation
testing records a test's reach under: a test that imported the tool as plain
<name> reaches nothing a mutant can be checked against.
A
rejection of tools/configure.py is a case of its own in
tests/configure_test.py: every combination of the .toml that cannot work
is refused with the line it is on and a reason, and every refusal has a test that sees it
fire.
In a game: tests/game/#
A
game made with rmp new keeps its own tests in tests/game/. Every
.cpp there is built with doctest and with everything in the game's src/
but main.cpp into one program, game_test, which runs with no window. The
framework runs the same folder against the small game in its own src/, the copy every
game starts from, so a test a new game would fail on its first day fails in the framework first.
rmp test unit
./build/debug/game_test -tc="*menu*"A game's test drives the game the way the framework would — the delta handed to a
hook, the seed of rmp::random, the input devices through the seam above — and reads
what the game keeps.
Testing has the file a game starts with.
After the test#
- Framework code added or tested:
rmp test coverage, whose floors only rise — Coverage. - Anything that parses, casts or frees touched:
rmp test sanitize, the unit and layout tests again under gcc's sanitizers, which instrument differently and warn about other things. - A parser touched:
rmp test fuzz, every committed input replayed. - The public API touched:
rmp test examples, every example built, booted and played.