In Catch2, how does a TEST_CASE containing several SECTIONs execute, and why does each section start from fresh setup?
answer
- sections replace fixtures
- the case re-runs from the top
- one leaf section per run
- parents re-entered once per leaf
basics
~20 sCatch2 runs a TEST_CASE once per leaf SECTION, each time from the top. Each run repeats the setup and enters exactly one leaf, so every section sees freshly built locals; a parent section is entered once per leaf beneath it.
solid answer
~50 sA `SECTION` is not a function Catch2 calls; it is a block inside one function that the runner decides to enter or skip. On each **run** of the test case, Catch2 executes the body from the top, enters the first section that has not finished, and skips every other section once that leaf has run. It then repeats the whole case until every leaf section has run once. So local variables declared above the sections, a stack built from `{1, 2, 3}` for instance, are constructed fresh for each section, and nothing one section does to them leaks into a sibling. Nested sections form a tree walked depth-first: a parent is entered once for each leaf beneath it, and its code runs that many times. Code after the sections also runs on every pass. A failed `REQUIRE` ends only the current run; the remaining sections still get theirs.
code
cpp · 27 lines#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include <vector>
static int setups = 0;
TEST_CASE("stack push and pop", "[stack]") {
std::vector<int> stack{1, 2, 3}; // a stack built on vector
++setups;
std::cout << "setup #" << setups << '\n';
SECTION("push grows the stack") {
stack.push_back(4);
REQUIRE(stack.size() == 4);
}
SECTION("pop shrinks the stack") {
stack.pop_back();
REQUIRE(stack.size() == 2);
SECTION("pop again") {
stack.pop_back();
REQUIRE(stack.size() == 1);
}
SECTION("then push") {
stack.push_back(9);
REQUIRE(stack.back() == 9);
}
}
std::cout << "after sections, size " << stack.size() << '\n';
}go deeper
Recall that each section starts from the setup at the top of the test case and that sibling sections do not see each other's changes.
Explain the run loop: one leaf per run, parents entered once per leaf, and count runs for a nested example without hesitation.
Spot the costs and traps in review: expensive setup multiplied by the leaf count, statics and external state that survive runs, and failures that end only one run.
Weigh sections against fixture classes for a codebase: readability of nested paths, setup cost per leaf, and a team rule on nesting depth.
## Sections instead of fixture classes Many test frameworks share setup through a fixture class with set-up and tear-down methods. Catch2 supports that style, but its preferred mechanism is the **section**: setup is ordinary code at the top of a `TEST_CASE`, and each scenario that uses it is a `SECTION` block below. Teardown is ordinary scope exit, so the destructors of the locals do the cleaning. The trick that makes this work is that Catch2 **re-enters the test case** instead of calling sections like functions. ## The re-entry model A **leaf section** is a section with no sections inside it. Catch2 executes a test case as a series of **runs** (the documentation also calls them partial runs): 1. Start the test case function from its first line, so all setup above the sections executes. 2. Enter the first section, in source order, whose subtree still has an unfinished leaf. 3. When that leaf completes, skip every further section encountered in this run. 4. Let the function return, executing any code after the sections and destroying the locals. 5. If any leaf has not run yet, go back to step 1. The tutorial states the rule directly: each run through a test case executes one, and only one, leaf section. ## A worked example The stack below is a `std::vector<int>` built with three elements. One leaf pushes; a parent section pops and holds two nested leaves. ```cpp TEST_CASE("stack push and pop", "[stack]") { std::vector<int> stack{1, 2, 3}; SECTION("push grows the stack") { stack.push_back(4); REQUIRE(stack.size() == 4); } SECTION("pop shrinks the stack") { stack.pop_back(); REQUIRE(stack.size() == 2); SECTION("pop again") { stack.pop_back(); REQUIRE(stack.size() == 1); } SECTION("then push") { stack.push_back(9); REQUIRE(stack.back() == 9); } } } ``` There are three leaves, so there are **three runs**: | Run | Path entered | Stack at end of run | |---|---|---| | 1 | push grows the stack | 4 elements | | 2 | pop shrinks the stack, nested pop again | 1 element | | 3 | pop shrinks the stack, nested then push | 3 elements | The vector is constructed three times, and the parent section's `pop_back` runs twice, once for each nested leaf. Each leaf starts from a vector holding exactly `{1, 2, 3}` because it is a new object in a new run, not a copy restored by the framework. ## Nesting is a tree walked depth-first Sections can nest as deeply as the compiler allows. The documentation describes them as a tree of paths through the test, walked depth-first, with each path visiting exactly one leaf. Two consequences follow: - A parent section's code runs once **per leaf beneath it**, so expensive work in a parent is multiplied. - Shared steps belong in the parent and the differing steps in the children, which removes duplication without a fixture class. The tutorial's own advice is that nesting beyond about three levels is hard to follow. ## What does and does not reset - **Locals of the test case** are rebuilt each run; that is the whole mechanism. - **Code after the last section** executes on every run, because the function body continues after a skipped section. - **Static variables, globals, files and databases** are not reset. A `static int` counter incremented in the setup keeps counting across runs: with three leaves it ends at three. - **A failure ends only the current run.** If a `REQUIRE` fails inside the first leaf, that run is aborted, and Catch2 still re-enters the case for the remaining leaves. - **Sections are identified by name and source location.** That is why a plain `SECTION` inside a loop behaves surprisingly, a diagnosis covered separately. ## Sections compared with a fixture class | Concern | Sections | Fixture class | |---|---|---| | Where setup lives | Top of the test case | Constructor or set-up method | | Fresh state per scenario | Yes, by re-running the case | Yes, by a new object per test | | Sharing a partial path | Nested sections | A second fixture or a helper | | Cost | Setup repeats once per leaf | Construction repeats once per test | Both repeat the setup per scenario; sections simply keep it next to the scenarios, in one function, and let scenarios share a partial path.
- In Catch2, what happens to the remaining sections when a REQUIRE fails inside the first one?Only the current run ends. `REQUIRE` aborts the test case function, Catch2 records the failure against that section's path, and then re-enters the case from the top for the next unfinished leaf. In a two-section case whose first section fails, the second section still runs and can pass, and the summary shows the failure under the first section's name.
- Why does a static counter in a Catch2 test case's setup not reset between sections?Re-entry rebuilds only what the function's own execution builds: its automatic local variables. A `static` local, a global, a file or a database row outlives the call, so it accumulates across runs. Shared mutable state of that kind makes sections depend on each other, which is exactly what sections are meant to prevent.
- Catch2 runs all sibling SECTIONs one after another in a single pass.
- Each SECTION gets a copy of the state left by the previous one.
- Setup above the sections runs once per test case.
- A failing REQUIRE in one section skips the remaining sections.
- Code after the last SECTION runs only once.