Skip to content

Commit

Permalink
TEST_CASE_PERSISTENT_FIXTURE: A new fixture macro for allowing persis…
Browse files Browse the repository at this point in the history
…tent fixtures throughout a TEST_CASE (#2885)

This PR introduces a new `TEST_CASE` macro called `TEST_CASE_PERSISTENT_FIXTURE`. `TEST_CASE_PERSISTENT_FIXTURE` offers the same functionality as `TEST_CASE_METHOD` except for one difference. The object on which the test method is invoked is only created once for all invocations of the test case. The object is created just after the `testCaseStarting` event is broadcast and the object is destroyed just before the `testCaseEnding` event is broadcast.

The main motivation for this new functionality is to allow `TEST_CASE`s to do expensive setup and teardown once per `TEST_CASE`, without having to resort to abusing event listeners or static function variables with manual initialization.


Implements #1602

---------

Co-authored-by: Martin Hořeňovský <[email protected]>
  • Loading branch information
KStocky and horenmar authored Aug 5, 2024
1 parent 33e24b1 commit f7cd0ba
Show file tree
Hide file tree
Showing 31 changed files with 643 additions and 62 deletions.
1 change: 1 addition & 0 deletions docs/cmake-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
[`CATCH_CONFIG_*` customization options in CMake](#catch_config_-customization-options-in-cmake)<br>
[Installing Catch2 from git repository](#installing-catch2-from-git-repository)<br>
[Installing Catch2 from vcpkg](#installing-catch2-from-vcpkg)<br>
[Installing Catch2 from Bazel](#installing-catch2-from-bazel)<br>

Because we use CMake to build Catch2, we also provide a couple of
integration points for our users.
Expand Down
1 change: 1 addition & 0 deletions docs/list-of-examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- Assertion: [REQUIRE, CHECK](../examples/030-Asn-Require-Check.cpp)
- Fixture: [Sections](../examples/100-Fix-Section.cpp)
- Fixture: [Class-based fixtures](../examples/110-Fix-ClassFixture.cpp)
- Fixture: [Persistent fixtures](../examples/111-Fix-PersistentFixture.cpp)
- BDD: [SCENARIO, GIVEN, WHEN, THEN](../examples/120-Bdd-ScenarioGivenWhenThen.cpp)
- Listener: [Listeners](../examples/210-Evt-EventListeners.cpp)
- Configuration: [Provide your own output streams](../examples/231-Cfg-OutputStreams.cpp)
Expand Down
24 changes: 0 additions & 24 deletions docs/other-macros.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,30 +93,6 @@ TEST_CASE("STATIC_CHECK showcase", "[traits]") {

## Test case related macros

* `METHOD_AS_TEST_CASE`

`METHOD_AS_TEST_CASE( member-function-pointer, description )` lets you
register a member function of a class as a Catch2 test case. The class
will be separately instantiated for each method registered in this way.

```cpp
class TestClass {
std::string s;

public:
TestClass()
:s( "hello" )
{}

void testCase() {
REQUIRE( s == "hello" );
}
};


METHOD_AS_TEST_CASE( TestClass::testCase, "Use class's method as a test case", "[class]" )
```
* `REGISTER_TEST_CASE`

`REGISTER_TEST_CASE( function, description )` let's you register
Expand Down
137 changes: 133 additions & 4 deletions docs/test-fixtures.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,30 @@
<a id="top"></a>
# Test fixtures

## Defining test fixtures
**Contents**<br>
[Non-Templated test fixtures](#non-templated-test-fixtures)<br>
[Templated test fixtures](#templated-test-fixtures)<br>
[Signature-based parameterised test fixtures](#signature-based-parametrised-test-fixtures)<br>
[Template fixtures with types specified in template type lists](#template-fixtures-with-types-specified-in-template-type-lists)<br>

Although Catch allows you to group tests together as [sections within a test case](test-cases-and-sections.md), it can still be convenient, sometimes, to group them using a more traditional test fixture. Catch fully supports this too. You define the test fixture as a simple structure:
## Non-Templated test fixtures

Although Catch2 allows you to group tests together as
[sections within a test case](test-cases-and-sections.md), it can still
be convenient, sometimes, to group them using a more traditional test.
Catch2 fully supports this too with 3 different macros for
non-templated test fixtures. They are:

| Macro | Description |
|----------|-------------|
|1. `TEST_CASE_METHOD(className, ...)`| Creates a uniquely named class which inherits from the class specified by `className`. The test function will be a member of this derived class. An instance of the derived class will be created for every partial run of the test case. |
|2. `METHOD_AS_TEST_CASE(member-function, ...)`| Uses `member-function` as the test function. An instance of the class will be created for each partial run of the test case. |
|3. `TEST_CASE_PERSISTENT_FIXTURE(className, ...)`| Creates a uniquely named class which inherits from the class specified by `className`. The test function will be a member of this derived class. An instance of the derived class will be created at the start of the test run. That instance will be destroyed once the entire test case has ended. |

### 1. `TEST_CASE_METHOD`


You define a `TEST_CASE_METHOD` test fixture as a simple structure:

```c++
class UniqueTestsFixture {
Expand All @@ -30,8 +51,116 @@ class UniqueTestsFixture {
}
```
The two test cases here will create uniquely-named derived classes of UniqueTestsFixture and thus can access the `getID()` protected method and `conn` member variables. This ensures that both the test cases are able to create a DBConnection using the same method (DRY principle) and that any ID's created are unique such that the order that tests are executed does not matter.
The two test cases here will create uniquely-named derived classes of
UniqueTestsFixture and thus can access the `getID()` protected method
and `conn` member variables. This ensures that both the test cases
are able to create a DBConnection using the same method
(DRY principle) and that any ID's created are unique such that the
order that tests are executed does not matter.
### 2. `METHOD_AS_TEST_CASE`
`METHOD_AS_TEST_CASE` lets you register a member function of a class
as a Catch2 test case. The class will be separately instantiated
for each method registered in this way.
```cpp
class TestClass {
std::string s;
public:
TestClass()
:s( "hello" )
{}
void testCase() {
REQUIRE( s == "hello" );
}
};
METHOD_AS_TEST_CASE( TestClass::testCase, "Use class's method as a test case", "[class]" )
```

This type of fixture is similar to [TEST_CASE_METHOD](#1-test_case_method) except in this
case it will directly use the provided class to create an object rather than a derived
class.

### 3. `TEST_CASE_PERSISTENT_FIXTURE`

> [Introduced](https://github.com/catchorg/Catch2/pull/2885) in Catch2 X.Y.Z

`TEST_CASE_PERSISTENT_FIXTURE` behaves in the same way as
[TEST_CASE_METHOD](#1-test_case_method) except that there will only be
one instance created throughout the entire run of a test case. To
demonstrate this have a look at the following example:

```cpp
class ClassWithExpensiveSetup {
public:
ClassWithExpensiveSetup() {
// expensive construction
std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
}

~ClassWithExpensiveSetup() noexcept {
// expensive destruction
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
}

int getInt() const { return 42; }
};

struct MyFixture {
mutable int myInt = 0;
ClassWithExpensiveSetup expensive;
};

TEST_CASE_PERSISTENT_FIXTURE( MyFixture, "Tests with MyFixture" ) {

const int val = myInt++;

SECTION( "First partial run" ) {
const auto otherValue = expensive.getInt();
REQUIRE( val == 0 );
REQUIRE( otherValue == 42 );
}

SECTION( "Second partial run" ) { REQUIRE( val == 1 ); }
}
```
This example demonstates two possible use-cases of this fixture type:
1. Improve test run times by reducing the amount of expensive and
redundant setup and tear-down required.
2. Reusing results from the previous partial run, in the current
partial run.
This test case will be executed twice as there are two leaf sections.
On the first run `val` will be `0` and on the second run `val` will be
`1`. This demonstrates that we were able to use the results of the
previous partial run in subsequent partial runs.
Additionally, we are simulating an expensive object using
`std::this_thread::sleep_for`, but real world use-cases could be:
1. Creating a D3D12/Vulkan device
2. Connecting to a database
3. Loading a file.
The fixture object (`MyFixture`) will be constructed just before the
test case begins, and it will be destroyed just after the test case
ends. Therefore, this expensive object will only be created and
destroyed once during the execution of this test case. If we had used
`TEST_CASE_METHOD`, `MyFixture` would have been created and destroyed
twice during the execution of this test case.
NOTE: The member function which runs the test case is `const`. Therefore
if you want to mutate any member of the fixture it must be marked as
`mutable` as shown in this example. This is to make it clear that
the initial state of the fixture is intended to mutate during the
execution of the test case.
## Templated test fixtures
Catch2 also provides `TEMPLATE_TEST_CASE_METHOD` and
`TEMPLATE_PRODUCT_TEST_CASE_METHOD` that can be used together
Expand Down Expand Up @@ -93,7 +222,7 @@ _While there is an upper limit on the number of types you can specify
in single `TEMPLATE_TEST_CASE_METHOD` or `TEMPLATE_PRODUCT_TEST_CASE_METHOD`,
the limit is very high and should not be encountered in practice._

## Signature-based parametrised test fixtures
## Signature-based parameterised test fixtures

> [Introduced](https://github.com/catchorg/Catch2/issues/1609) in Catch2 2.8.0.
Expand Down
74 changes: 74 additions & 0 deletions examples/111-Fix-PersistentFixture.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@

// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)

// SPDX-License-Identifier: BSL-1.0

// Fixture.cpp

// Catch2 has three ways to express fixtures:
// - Sections
// - Traditional class-based fixtures that are created and destroyed on every
// partial run
// - Traditional class-based fixtures that are created at the start of a test
// case and destroyed at the end of a test case (this file)

// main() provided by linkage to Catch2WithMain

#include <catch2/catch_test_macros.hpp>

#include <thread>

class ClassWithExpensiveSetup {
public:
ClassWithExpensiveSetup() {
// Imagine some really expensive set up here.
// e.g.
// setting up a D3D12/Vulkan Device,
// connecting to a database,
// loading a file
// etc etc etc
std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
}

~ClassWithExpensiveSetup() noexcept {
// We can do any clean up of the expensive class in the destructor
// e.g.
// destroy D3D12/Vulkan Device,
// disconnecting from a database,
// release file handle
// etc etc etc
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
}

int getInt() const { return 42; }
};

struct MyFixture {

// The test case member function is const.
// Therefore we need to mark any member of the fixture
// that needs to mutate as mutable.
mutable int myInt = 0;
ClassWithExpensiveSetup expensive;
};

// Only one object of type MyFixture will be instantiated for the run
// of this test case even though there are two leaf sections.
// This is useful if your test case requires an object that is
// expensive to create and could be reused for each partial run of the
// test case.
TEST_CASE_PERSISTENT_FIXTURE( MyFixture, "Tests with MyFixture" ) {

const int val = myInt++;

SECTION( "First partial run" ) {
const auto otherValue = expensive.getInt();
REQUIRE( val == 0 );
REQUIRE( otherValue == 42 );
}

SECTION( "Second partial run" ) { REQUIRE( val == 1 ); }
}
1 change: 1 addition & 0 deletions examples/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ set( SOURCES_IDIOMATIC_EXAMPLES
030-Asn-Require-Check.cpp
100-Fix-Section.cpp
110-Fix-ClassFixture.cpp
111-Fix-PersistentFixture.cpp
120-Bdd-ScenarioGivenWhenThen.cpp
210-Evt-EventListeners.cpp
232-Cfg-CustomMain.cpp
Expand Down
8 changes: 8 additions & 0 deletions src/catch2/catch_test_case_info.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,14 @@ namespace Catch {
TestCaseHandle(TestCaseInfo* info, ITestInvoker* invoker) :
m_info(info), m_invoker(invoker) {}

void prepareTestCase() const {
m_invoker->prepareTestCase();
}

void tearDownTestCase() const {
m_invoker->tearDownTestCase();
}

void invoke() const {
m_invoker->invoke();
}
Expand Down
4 changes: 4 additions & 0 deletions src/catch2/catch_test_macros.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
#define CATCH_TEST_CASE_PERSISTENT_FIXTURE( className, ... ) INTERNAL_CATCH_TEST_CASE_PERSISTENT_FIXTURE( className, __VA_ARGS__ )
#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
Expand Down Expand Up @@ -97,6 +98,7 @@
#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ))
#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ))
#define CATCH_METHOD_AS_TEST_CASE( method, ... )
#define CATCH_TEST_CASE_PERSISTENT_FIXTURE( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ))
#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
#define CATCH_SECTION( ... )
#define CATCH_DYNAMIC_SECTION( ... )
Expand Down Expand Up @@ -142,6 +144,7 @@
#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
#define TEST_CASE_PERSISTENT_FIXTURE( className, ... ) INTERNAL_CATCH_TEST_CASE_PERSISTENT_FIXTURE( className, __VA_ARGS__ )
#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
Expand Down Expand Up @@ -195,6 +198,7 @@
#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ), __VA_ARGS__)
#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ))
#define METHOD_AS_TEST_CASE( method, ... )
#define TEST_CASE_PERSISTENT_FIXTURE( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ), __VA_ARGS__)
#define REGISTER_TEST_CASE( Function, ... ) (void)(0)
#define SECTION( ... )
#define DYNAMIC_SECTION( ... )
Expand Down
2 changes: 2 additions & 0 deletions src/catch2/interfaces/catch_interfaces_test_invoker.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ namespace Catch {

class ITestInvoker {
public:
virtual void prepareTestCase();
virtual void tearDownTestCase();
virtual void invoke() const = 0;
virtual ~ITestInvoker(); // = default
};
Expand Down
2 changes: 2 additions & 0 deletions src/catch2/internal/catch_run_context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ namespace Catch {

auto const& testInfo = testCase.getTestCaseInfo();
m_reporter->testCaseStarting(testInfo);
testCase.prepareTestCase();
m_activeTestCase = &testCase;


Expand Down Expand Up @@ -254,6 +255,7 @@ namespace Catch {
deltaTotals.testCases.failed++;
}
m_totals.testCases += deltaTotals.testCases;
testCase.tearDownTestCase();
m_reporter->testCaseEnded(TestCaseStats(testInfo,
deltaTotals,
CATCH_MOVE(redirectedCout),
Expand Down
2 changes: 2 additions & 0 deletions src/catch2/internal/catch_test_registry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
#include <iterator>

namespace Catch {
void ITestInvoker::prepareTestCase() {}
void ITestInvoker::tearDownTestCase() {}
ITestInvoker::~ITestInvoker() = default;

namespace {
Expand Down
Loading

0 comments on commit f7cd0ba

Please sign in to comment.