TExcelTAD

Test Fixtures

Some tests need something prepared first: a database created, a server started, a temporary directory filled with sample files. And that something must be cleaned up afterwards, even when tests fail. CTest models this with fixtures: tests that set up or clean up a named resource, and tests that require it.

Property On which test Meaning
FIXTURES_SETUP <name> the setup test runs before any test requiring <name>
FIXTURES_CLEANUP <name> the cleanup test runs after all tests requiring <name> (whether they passed or not)
FIXTURES_REQUIRED <name> the tests that need it pulls in setup and cleanup automatically
RESOURCE_LOCK <name> tests sharing something never run at the same time as other tests locking the same name

The key difference from DEPENDS (which only orders tests that are already selected): selecting one test that requires a fixture also runs that fixture's setup and cleanup tests, and if the setup fails, the dependent tests are not run at all.

A database fixture

bash · try it yourself
mkdir -p dbtests && cd dbtests
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(DbTests LANGUAGES NONE)
enable_testing()
set(db ${CMAKE_CURRENT_BINARY_DIR}/test.db)

add_test(NAME db.create  COMMAND sh -c "printf 'ada\\ngrace\\n' > ${db} && echo created")
add_test(NAME db.drop    COMMAND sh -c "rm -f ${db} && echo dropped")
add_test(NAME users.count COMMAND sh -c "test $(wc -l < ${db}) -eq 2")
add_test(NAME users.find  COMMAND sh -c "grep -q grace ${db}")
add_test(NAME math.unrelated COMMAND true)

set_tests_properties(db.create PROPERTIES FIXTURES_SETUP Db)
set_tests_properties(db.drop   PROPERTIES FIXTURES_CLEANUP Db)
set_tests_properties(users.count users.find PROPERTIES FIXTURES_REQUIRED Db RESOURCE_LOCK db_file)
CM
cmake -S . -B build --log-level=NOTICE > /dev/null
cd build
echo "=== all tests"
ctest 2>&1 | grep -E 'Test +#|tests passed'
echo "=== only users.find: setup and cleanup come along"
ctest -R users.find 2>&1 | grep -E 'Test +#|tests passed'
echo "=== -FA: exclude fixture tests that weren't selected"
ctest -R users.find -FA '.*' 2>&1 | grep -E 'Test +#|tests passed|Failed'
=== all tests
1/5 Test #1: db.create ........................   Passed    0.00 sec
2/5 Test #3: users.count ......................   Passed    0.00 sec
3/5 Test #4: users.find .......................   Passed    0.00 sec
4/5 Test #2: db.drop ..........................   Passed    0.00 sec
5/5 Test #5: math.unrelated ...................   Passed    0.00 sec
100% tests passed out of 5
=== only users.find: setup and cleanup come along
1/3 Test #1: db.create ........................   Passed    0.00 sec
2/3 Test #4: users.find .......................   Passed    0.00 sec
3/3 Test #2: db.drop ..........................   Passed    0.00 sec
100% tests passed out of 3
=== -FA: exclude fixture tests that weren't selected
1/1 Test #4: users.find .......................***Failed    0.00 sec
0% tests passed, 1 tests failed out of 1
	  4 - users.find (Failed)
  • In the full run, CTest ordered db.create first and db.drop after the last user of the fixture, although db.drop was registered before the user tests.
  • ctest -R users.find selected one test, and CTest added db.create and db.drop around it.
  • -FA <regex> (--fixture-exclude-any) skips adding setup/cleanup for matching fixtures, for when you've already prepared the resource by hand. Without the database, users.find fails. -FS and -FC exclude only setups or only cleanups.

When setup fails

bash · try it yourself
mkdir -p broken && cd broken
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Broken LANGUAGES NONE)
enable_testing()
add_test(NAME server.start COMMAND sh -c "echo 'port 8080 already in use'; exit 1")
add_test(NAME api.get      COMMAND true)
add_test(NAME api.post     COMMAND true)
add_test(NAME server.stop  COMMAND sh -c "echo stopping")
set_tests_properties(server.start PROPERTIES FIXTURES_SETUP Server)
set_tests_properties(server.stop  PROPERTIES FIXTURES_CLEANUP Server)
set_tests_properties(api.get api.post PROPERTIES FIXTURES_REQUIRED Server)
CM
cmake -S . -B build --log-level=NOTICE > /dev/null
ctest --test-dir build 2>&1 | grep -E 'Test +#|tests passed|Not Run|Failed|required'
1/4 Test #1: server.start .....................***Failed    0.00 sec
Failed test dependencies: server.start
2/4 Test #2: api.get ..........................***Not Run   0.00 sec
Failed test dependencies: server.start
3/4 Test #3: api.post .........................***Not Run   0.00 sec
4/4 Test #4: server.stop ......................   Passed    0.00 sec
25% tests passed, 3 tests failed out of 4
	  1 - server.start (Failed)
	  2 - api.get (Not Run)
	  3 - api.post (Not Run)

The API tests were not run (reported as Not Run, which still counts as a failure of the run) instead of failing with confusing connection errors, CTest named the failed dependency, and the cleanup still ran. The failure report points straight at the real cause: the setup test.

Fixtures in parallel runs

With ctest -j N, tests requiring the same fixture can run in parallel with each other (setup and cleanup still bracket them). If they share something that can't be used concurrently, like the single test.db file above, add a RESOURCE_LOCK with a shared name, as the first example did. For hardware or limited resources ("2 GPUs"), CTest also has resource allocation (RESOURCE_GROUPS plus a resource spec file), which hands each test a specific slot.

A model of the scheduling rule

What does CTest add when you select some tests? This model applies the fixture rule to the selection:

js · try it yourself
const tests = {
  'db.create':   { setup: ['Db'] },
  'db.drop':     { cleanup: ['Db'] },
  'users.count': { requires: ['Db'] },
  'users.find':  { requires: ['Db'] },
  'math.unrelated': {},
};
const order = Object.keys(tests);

function plan(selected) {
  const chosen = new Set(selected);
  for (const name of selected) {
    for (const fx of tests[name].requires ?? []) {
      for (const [other, t] of Object.entries(tests)) {
        if (t.setup?.includes(fx) || t.cleanup?.includes(fx)) chosen.add(other);
      }
    }
  }
  // setups first, then normal tests, then cleanups (registration order inside each group)
  const phase = (n) => (tests[n].setup ? 0 : tests[n].cleanup ? 2 : 1);
  return order.filter((n) => chosen.has(n)).sort((a, b) => phase(a) - phase(b));
}

console.log('-R users.find   ->', plan(['users.find']).join(', '));
console.log('-R math         ->', plan(['math.unrelated']).join(', '));
console.log('all             ->', plan(order).join(', '));
-R users.find   -> db.create, users.find, db.drop
-R math         -> math.unrelated
all             -> db.create, users.count, users.find, math.unrelated, db.drop

(The real scheduler is finer-grained: a cleanup runs as soon as the last test requiring its fixture is done, which is why the real run above put db.drop before math.unrelated.)

Test yourself

ctest -R users.find selects one test that has FIXTURES_REQUIRED Db. What runs?

  1. Only users.find
  2. The Db setup test, users.find, then the Db cleanup test
  3. Every test
  4. Only the setup test

The fixture's setup test fails. What happens to the tests requiring the fixture?

  1. They run anyway
  2. They are not run, and the cleanup still runs
  3. ctest stops immediately without cleanup
  4. They are retried

Two tests use the same file and must not run at the same time under ctest -j 8. Which property?

  1. DEPENDS
  2. RUN_SERIAL on every test in the project
  3. RESOURCE_LOCK <same name> on both
  4. FIXTURES_CLEANUP