Compare commits

...

43 Commits

Author SHA1 Message Date
5df88da16e 3.1.1 2022-10-17 19:57:58 +02:00
5cd8938905 Update explanation of REQUIRE_FALSE in docs/assertions.md 2022-10-17 15:13:00 +02:00
6a422bae0b Trim superfluous whitespace in docs 2022-10-17 15:02:45 +02:00
a07ac3f935 Rewrite explanation of problems with && and || in assertions 2022-10-17 12:36:02 +02:00
d8619f076b Fixup shard index docs
Closes #2547
2022-10-16 17:00:29 +02:00
95cd95e591 Add extra explanations to some items in docs/readme.md
This should make it easier for people to find what they need, e.g.
finding generators by looking for "value parameterized tests".
2022-10-15 23:50:20 +02:00
eb7397544c Bold section 'headings' in docs/readme.md 2022-10-15 23:50:18 +02:00
d1394a7064 Link to SECTIONS doc at top of test fixtures page.
I came here looking for a way to use a fixture. But what I really wanted was better done in the SECTION macro. Feels like a link right at the top would've made it clearer faster.
2022-10-15 16:59:52 +02:00
e94976ec9c Downgrade MacOS version in GHA 2022-10-15 13:06:50 +02:00
0c962d11b3 Centralize and update docs for floating point comparisons
The new docs mention that Approx is deprecated and should not be
used, and explain the reasons behind it.

Closes #1444
2022-10-15 11:02:58 +02:00
bdf30834eb Mute the sign conversion warning with explicit cast 2022-10-09 19:02:32 +02:00
728de353be improve -ffile-prefix-map detection (#2517)
the current implementation has two problems:
  * `clang-cl` does not know `-ffile-prefix-map`, but in CMake it is
    reported as "Clang", so the compiler will warn about an unknown
    compiler option.
  * XCode's clang in CMake is reported as "AppleClang", so it is not picked
    up as "Clang", so it is not passed `-ffile-prefix-map`, even though
    it supports it.

Also changed the map so that the normalized `__FILE__` paths are the same
as what the approval tests normalize paths into.

Co-authored-by: Martin Hořeňovský <martin.horenovsky@gmail.com>
2022-10-04 15:55:50 +02:00
0e139b73e4 add versioning to shared libs (#2516)
* add versioning to shared libs

Co-authored-by: Martin Hořeňovský <martin.horenovsky@gmail.com>
2022-10-04 15:49:09 +02:00
97313f9033 fix compilation on cygwin
Use std::char_traits<char>::find instead of strnlen for better
portability.
2022-10-04 10:50:18 +02:00
6a9bf2e0af meson cleanups with muon (#2539)
* meson: run through muon's fmt to fix formatting

* meson: switch arrays to files

Allows muon to alphabetically sort files. switch headers back to arrays
as split() can only be used on strings.

Signed-off-by: Rosen Penev <rosenp@gmail.com>
2022-10-03 17:23:38 +02:00
980c20694e Don't expose header windows.h in catch_all.hpp (#2526)
* Don't expose header windows.h in catch_all.hpp
* Fix generateAmalgamatedFiles.py
2022-10-03 15:36:37 +02:00
4db8b50aab Add support for building with Meson (#2530)
The Meson[1] build system makes it easier incorporate third-party
libaries into a project if they also build using Meson.

Let's add a minimal Meson build that's compatible with the CMake build,
along with a GitHub workflow to check that it builds and that at least
the simplest SelfTest runs.

The handling of catch_user_config.hpp is inspired by BUILD.bazel and
doesn't attempt to support any configuratons options. Such features
could be added later.

Meson strongly discourages using wildcards to specify sources, so the
source and header lists are copied from CMakeLists.txt.

Add a new test workflow to test the Meson builds. I was unable to get
these tests to pass with Ubuntu 20.04, so they use Ubuntu 22.04.

I'm neither a CMake nor a Meson expert, but the results seem to work for
me.

[1] https://mesonbuild.com/

Co-authored-by: Mike Crowe <mcrowe@brightsign.biz>
2022-10-01 23:28:30 +02:00
4a7cefe601 Unused variable removed 2022-09-28 16:02:10 +02:00
243cf71608 Make Bazel work with CATCH_CONFIG_SHARED_LIBRARY 2022-09-27 22:06:12 +02:00
4bb7e02a9c Bazel build: Update of skylib 2022-09-27 22:06:12 +02:00
97d0b1e00e Suppress clang-tidy warnings for TEMPLATE_TEST_CASE (#2536)
* Suppress clang-tidy *-avoid-c-arrays for TEMPLATE_TEST_CASE
* Made globalRegistrar `const` to avoid `cppcoreguidelines-avoid-non-const-global-variables`

Fixes #2095
2022-09-26 18:07:50 +02:00
c0e582e659 Fix building as shared library with MSVC. 2022-09-24 15:15:50 +02:00
0de60d8e7e Suppress -Wuseless-cast Warning
Fixes #2520.
2022-09-22 21:00:05 +02:00
d6bbd3fdef warning: storage class is not first
This pull request fixes the warning issued by `nvc++`
(the C++ compiler in Nvidia HPC SDK/PGI),
and is similar to pull request #1717.
2022-09-21 20:14:12 +02:00
98d37da03e Raise the minimum CMake version to 3.10 (#2523) 2022-09-16 17:56:00 +02:00
4b3defe4af Suppress warning "-Wstrict-aliasing" for GCC 5 and 6 2022-09-15 13:40:16 +02:00
c75430834d Add GCC 5 and GCC 6 to CI 2022-09-15 13:40:16 +02:00
359542d53e FileStream: enable automatic flushing
when a test executable is killed by a signal (e.g. when executed by
ctest with timeout), the reporter files are not flushed. this can lead
to incomplete (or empty) report files.
to avoid this we enable automatic flushing via `std::unitbuf`

compare #663
2022-09-11 23:49:15 +02:00
dea1a6abd9 Fix typos in docs (#2514) 2022-09-09 16:00:39 +02:00
32eae0ecce Add missing include for VxWorks build. (#2515)
`catch_sharding.hpp` was using `std::min` without including `<algorithm>`.
This worked on most platforms, but it wasn't transitively included in
the VxWorks toolchain.
2022-09-08 10:21:36 +02:00
4adf010549 Mention dynamic library stuff in the FAQ
Closes #2497
2022-09-03 22:31:29 +02:00
686468d185 Explain TU as translation unit where appropriate 2022-09-03 22:22:10 +02:00
7b2e7d623b Disable Bazel's env checking on UWP
UWP does not support environment variables and so it cannot
compile code using getenv.
2022-09-02 07:11:28 +02:00
3ca5cf32e5 Add CATCH_PLATFORM_WINDOWS_UWP detection macro 2022-09-02 07:10:38 +02:00
dc001fa935 Allow easy retrieval of RNG seed by the users
This makes it so that they don't need parallel RNG seed passing
infrastructure for randomized data generation (e.g. inputs for
benchmarks).
2022-08-18 23:23:18 +02:00
33e70194d3 Link to the randomized-shard-registration script from usage tips 2022-08-18 00:14:07 +02:00
9bb206fc61 Remove obsoleted sections of ci-and-misc.md 2022-08-18 00:05:55 +02:00
ab04e599e7 Improve v2->v3 migration docs 2022-08-18 00:02:33 +02:00
47d56f28a9 Fix compatibility with cmake 3.8 2022-08-04 00:09:02 +02:00
a118799631 Switch MacOS image to macos-12 in Github Actions
Also updated GCC version to GCC-11, which is packaged in the
runner image.
2022-08-03 23:54:49 +02:00
997a7d4165 Fix running the tests with shared library on Windows.
Without this fix, the test executable fails because it can not find
the dll of Catch2.
2022-07-25 21:07:49 +02:00
2b0fd854e2 Modify the install directories into convention. 2022-07-25 10:43:41 +02:00
a7dc85dd49 Use DYLD_LIBRARY_PATH on apple platforms. 2022-07-23 20:45:49 +02:00
66 changed files with 1189 additions and 337 deletions

View File

@ -1,4 +1,10 @@
build --enable_platform_specific_config
build:gcc9 --cxxopt=-std=c++2a
build:gcc11 --cxxopt=-std=c++2a
build:clang13 --cxxopt=-std=c++17
build:vs2019 --cxxopt=/std:c++17
build:vs2022 --cxxopt=/std:c++17
build:vs2022 --cxxopt=/std:c++17
build:windows --config=vs2022
build:linux --config=gcc11

View File

@ -0,0 +1,43 @@
name: Linux builds (basic) using meson build system
on: [push, pull_request]
jobs:
build:
name: meson ${{matrix.cxx}}, C++${{matrix.std}}, ${{matrix.build_type}}
runs-on: ubuntu-22.04
strategy:
matrix:
cxx:
- g++-11
- clang++-11
build_type: [debug, release]
std: [14, 17]
include:
- cxx: clang++-11
other_pkgs: clang-11
steps:
- uses: actions/checkout@v2
- name: Prepare environment
run: sudo apt-get install -y meson ninja-build ${{matrix.other_pkgs}}
- name: Configure build
env:
CXX: ${{matrix.cxx}}
CXXFLAGS: -std=c++${{matrix.std}} ${{matrix.cxxflags}}
# Note: $GITHUB_WORKSPACE is distinct from ${{runner.workspace}}.
# This is important
run: |
meson -Dbuildtype=${{matrix.build_type}} ${{runner.workspace}}/meson-build
- name: Build tests + lib
working-directory: ${{runner.workspace}}/meson-build
run: ninja
- name: Run tests
working-directory: ${{runner.workspace}}/meson-build
# Hardcode 2 cores we know are there
run: |
meson test --verbose

View File

@ -9,7 +9,8 @@ jobs:
strategy:
matrix:
cxx:
# - g++-6
- g++-5
- g++-6
- g++-7
- g++-8
- g++-9
@ -22,9 +23,10 @@ jobs:
build_type: [Debug, Release]
std: [14]
include:
# cannot be installed on ubuntu-20.04 be default?
# - cxx: g++-6
# other_pkgs: g++-6
- cxx: g++-5
other_pkgs: g++-5
- cxx: g++-6
other_pkgs: g++-6
- cxx: g++-7
other_pkgs: g++-7
- cxx: g++-8
@ -67,6 +69,12 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Add repositories for older GCC
run: |
sudo apt-add-repository 'deb http://azure.archive.ubuntu.com/ubuntu/ bionic main'
sudo apt-add-repository 'deb http://azure.archive.ubuntu.com/ubuntu/ bionic universe'
if: ${{ matrix.cxx == 'g++-5' || matrix.cxx == 'g++-6' }}
- name: Prepare environment
run: sudo apt-get install -y ninja-build ${{matrix.other_pkgs}}

View File

@ -4,11 +4,15 @@ on: [push, pull_request]
jobs:
build:
runs-on: macos-10.15
# macos-12 updated to a toolchain that crashes when linking the
# test binary. This seems to be a known bug in that version,
# and will eventually get fixed in an update. After that, we can go
# back to newer macos images.
runs-on: macos-11
strategy:
matrix:
cxx:
- g++-9
- g++-11
- clang++
build_type: [Debug, Release]
std: [14, 17]

1
.gitignore vendored
View File

@ -1,4 +1,5 @@
*.build
!meson.build
*.pbxuser
*.mode1v3
*.ncb

View File

@ -1,14 +1,13 @@
# Load the cc_library rule.
load("@rules_cc//cc:defs.bzl", "cc_library")
load("@bazel_skylib//rules:expand_template.bzl", "expand_template")
expand_template(
name = "catch_user_config",
out = "catch2/catch_user_config.hpp",
substitutions = {
"@CATCH_CONFIG_CONSOLE_WIDTH@": "80",
"@CATCH_CONFIG_DEFAULT_REPORTER@": "console",
"#cmakedefine CATCH_CONFIG_ANDROID_LOGWRITE": "",
"#cmakedefine CATCH_CONFIG_BAZEL_SUPPORT": "#define CATCH_CONFIG_BAZEL_SUPPORT",
"#cmakedefine CATCH_CONFIG_NO_COLOUR_WIN32": "",
"#cmakedefine CATCH_CONFIG_COLOUR_WIN32": "",
"#cmakedefine CATCH_CONFIG_COUNTER": "",
"#cmakedefine CATCH_CONFIG_CPP11_TO_STRING": "",
@ -30,6 +29,8 @@ expand_template(
"#cmakedefine CATCH_CONFIG_FALLBACK_STRINGIFIER @CATCH_CONFIG_FALLBACK_STRINGIFIER@": "",
"#cmakedefine CATCH_CONFIG_FAST_COMPILE": "",
"#cmakedefine CATCH_CONFIG_GLOBAL_NEXTAFTER": "",
"#cmakedefine CATCH_CONFIG_NO_ANDROID_LOGWRITE": "",
"#cmakedefine CATCH_CONFIG_NO_COLOUR_WIN32": "",
"#cmakedefine CATCH_CONFIG_NO_COUNTER": "",
"#cmakedefine CATCH_CONFIG_NO_CPP11_TO_STRING": "",
"#cmakedefine CATCH_CONFIG_NO_CPP17_BYTE": "",
@ -45,13 +46,11 @@ expand_template(
"#cmakedefine CATCH_CONFIG_NOSTDOUT": "",
"#cmakedefine CATCH_CONFIG_POSIX_SIGNALS": "",
"#cmakedefine CATCH_CONFIG_PREFIX_ALL": "",
"#cmakedefine CATCH_CONFIG_SHARED_LIBRARY": "",
"#cmakedefine CATCH_CONFIG_USE_ASYNC": "",
"#cmakedefine CATCH_CONFIG_WCHAR": "",
"#cmakedefine CATCH_CONFIG_WINDOWS_CRTDBG": "",
"#cmakedefine CATCH_CONFIG_WINDOWS_SEH": "",
"#cmakedefine CATCH_CONFIG_NO_ANDROID_LOGWRITE": "",
"@CATCH_CONFIG_DEFAULT_REPORTER@": "console",
"@CATCH_CONFIG_CONSOLE_WIDTH@": "80",
},
template = "src/catch2/catch_user_config.hpp.in",
)
@ -88,4 +87,4 @@ cc_library(
linkstatic = True,
visibility = ["//visibility:public"],
deps = [":catch2"],
)
)

View File

@ -67,6 +67,7 @@ set(_OtherConfigOptions
foreach(OptionName ${_OtherConfigOptions})
AddConfigOption(${OptionName})
endforeach()
set(CATCH_CONFIG_SHARED_LIBRARY ${BUILD_SHARED_LIBS})
set(CATCH_CONFIG_DEFAULT_REPORTER "console" CACHE STRING "Read docs/configuration.md for details. The name of the reporter should be without quotes.")
set(CATCH_CONFIG_CONSOLE_WIDTH "80" CACHE STRING "Read docs/configuration.md for details. Must form a valid integer literal.")

View File

@ -8,9 +8,10 @@
include(CheckCXXCompilerFlag)
function(add_cxx_flag_if_supported_to_targets flagname targets)
check_cxx_compiler_flag("${flagname}" HAVE_FLAG_${flagname})
string(MAKE_C_IDENTIFIER ${flagname} flag_identifier )
check_cxx_compiler_flag("${flagname}" HAVE_FLAG_${flag_identifier})
if (HAVE_FLAG_${flagname})
if (HAVE_FLAG_${flag_identifier})
foreach(target ${targets})
target_compile_options(${target} PUBLIC ${flagname})
endforeach()
@ -112,9 +113,8 @@ endfunction()
# Adds flags required for reproducible build to the target
# Currently only supports GCC and Clang
function(add_build_reproducibility_settings target)
# Make the build reproducible on versions of g++ and clang that supports -ffile-prefix-map
if(("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" AND NOT ${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 8) OR
("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" AND NOT ${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 10))
target_compile_options(${target} PRIVATE "-ffile-prefix-map=${CATCH_DIR}=.")
# Make the build reproducible on versions of g++ and clang that supports -ffile-prefix-map
if((CMAKE_CXX_COMPILER_ID STREQUAL "GNU") OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang"))
add_cxx_flag_if_supported_to_targets("-ffile-prefix-map=${CATCH_DIR}/=" "${target}")
endif()
endfunction()

View File

@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.5)
cmake_minimum_required(VERSION 3.10)
# detect if Catch is being bundled,
# disable testsuite in that case
@ -30,14 +30,8 @@ if (CMAKE_BINARY_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
message(FATAL_ERROR "Building in-source is not supported! Create a build dir and remove ${CMAKE_SOURCE_DIR}/CMakeCache.txt")
endif()
if(CMAKE_VERSION VERSION_GREATER 3.8)
# Enable IPO for CMake versions that support it
cmake_policy(SET CMP0069 NEW)
endif()
project(Catch2
VERSION 3.1.0 # CML version placeholder, don't delete
VERSION 3.1.1 # CML version placeholder, don't delete
LANGUAGES CXX
# HOMEPAGE_URL is not supported until CMake version 3.12, which
# we do not target yet.

View File

@ -1,14 +0,0 @@
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "bazel_skylib",
strip_prefix = "bazel-skylib-2a87d4a62af886fb320883aba102255aba87275e",
urls = [
"https://github.com/bazelbuild/bazel-skylib/archive/2a87d4a62af886fb320883aba102255aba87275e.tar.gz",
],
sha256 = "d847b08d6702d2779e9eb399b54ff8920fa7521dc45e3e53572d1d8907767de7",
)
load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
bazel_skylib_workspace()

15
WORKSPACE.bazel Normal file
View File

@ -0,0 +1,15 @@
workspace(name = "catch2")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "bazel_skylib",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz",
"https://github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz",
],
sha256 = "74d544d96f4a5bb630d465ca8bbcfe231e3594e5aae57e1edbf17a6eb3ca2506",
)
load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
bazel_skylib_workspace()

View File

@ -4,34 +4,35 @@
To get the most out of Catch2, start with the [tutorial](tutorial.md#top).
Once you're up and running consider the following reference material.
Writing tests:
**Writing tests:**
* [Assertion macros](assertions.md#top)
* [Matchers](matchers.md#top)
* [Matchers (asserting complex properties)](matchers.md#top)
* [Comparing floating point numbers](comparing-floating-point-numbers.md#top)
* [Logging macros](logging.md#top)
* [Test cases and sections](test-cases-and-sections.md#top)
* [Test fixtures](test-fixtures.md#top)
* [Reporters](reporters.md#top)
* [Reporters (output customization)](reporters.md#top)
* [Event Listeners](event-listeners.md#top)
* [Data Generators](generators.md#top)
* [Data Generators (value parameterized tests)](generators.md#top)
* [Other macros](other-macros.md#top)
* [Micro benchmarking](benchmarks.md#top)
Fine tuning:
**Fine tuning:**
* [Supplying your own main()](own-main.md#top)
* [Compile-time configuration](configuration.md#top)
* [String Conversions](tostring.md#top)
Running:
**Running:**
* [Command line](command-line.md#top)
Odds and ends:
**Odds and ends:**
* [Frequently Asked Questions (FAQ)](faq.md#top)
* [Best practices and other tips](usage-tips.md#top)
* [CMake integration](cmake-integration.md#top)
* [CI and other miscellaneous pieces](ci-and-misc.md#top)
* [Known limitations](limitations.md#top)
Other:
**Other:**
* [Why Catch2?](why-catch.md#top)
* [Migrating from v2 to v3](migrate-v2-to-v3.md#top)
* [Open Source Projects using Catch2](opensource-users.md#top)

View File

@ -3,6 +3,7 @@
**Contents**<br>
[Natural Expressions](#natural-expressions)<br>
[Floating point comparisons](#floating-point-comparisons)<br>
[Exceptions](#exceptions)<br>
[Matcher expressions](#matcher-expressions)<br>
[Thread Safety](#thread-safety)<br>
@ -19,7 +20,7 @@ Most of these macros come in two forms:
The ```REQUIRE``` family of macros tests an expression and aborts the test case if it fails.
The ```CHECK``` family are equivalent but execution continues in the same test case even if the assertion fails. This is useful if you have a series of essentially orthogonal assertions and it is useful to see all the results rather than stopping at the first failure.
* **REQUIRE(** _expression_ **)** and
* **REQUIRE(** _expression_ **)** and
* **CHECK(** _expression_ **)**
Evaluates the expression and records the result. If an exception is thrown, it is caught, reported, and counted as a failure. These are the macros you will use most of the time.
@ -31,98 +32,78 @@ CHECK( thisReturnsTrue() );
REQUIRE( i == 42 );
```
* **REQUIRE_FALSE(** _expression_ **)** and
Expressions prefixed with `!` cannot be decomposed. If you have a type
that is convertible to bool and you want to assert that it evaluates to
false, use the two forms below:
* **REQUIRE_FALSE(** _expression_ **)** and
* **CHECK_FALSE(** _expression_ **)**
Evaluates the expression and records the _logical NOT_ of the result. If an exception is thrown it is caught, reported, and counted as a failure.
(these forms exist as a workaround for the fact that ! prefixed expressions cannot be decomposed).
Note that there is no reason to use these forms for plain bool variables,
because there is no added value in decomposing them.
Example:
```
REQUIRE_FALSE( thisReturnsFalse() );
```
Do note that "overly complex" expressions cannot be decomposed and thus will not compile. This is done partly for practical reasons (to keep the underlying expression template machinery to minimum) and partly for philosophical reasons (assertions should be simple and deterministic).
Examples:
* `CHECK(a == 1 && b == 2);`
This expression is too complex because of the `&&` operator. If you want to check that 2 or more properties hold, you can either put the expression into parenthesis, which stops decomposition from working, or you need to decompose the expression into two assertions: `CHECK( a == 1 ); CHECK( b == 2);`
* `CHECK( a == 2 || b == 1 );`
This expression is too complex because of the `||` operator. If you want to check that one of several properties hold, you can put the expression into parenthesis (unlike with `&&`, expression decomposition into several `CHECK`s is not possible).
### Floating point comparisons
When comparing floating point numbers - especially if at least one of them has been computed - great care must be taken to allow for rounding errors and inexact representations.
Catch provides a way to perform tolerant comparisons of floating point values through use of a wrapper class called `Approx`. `Approx` can be used on either side of a comparison expression. It overloads the comparisons operators to take a tolerance into account. Here's a simple example:
```cpp
REQUIRE( performComputation() == Approx( 2.1 ) );
Status ret = someFunction();
REQUIRE_FALSE(ret); // ret must evaluate to false, and Catch2 will print
// out the value of ret if possibly
```
Catch also provides a user-defined literal for `Approx`; `_a`. It resides in
the `Catch::literals` namespace and can be used like so:
```cpp
using namespace Catch::literals;
REQUIRE( performComputation() == 2.1_a );
```
`Approx` is constructed with defaults that should cover most simple cases.
For the more complex cases, `Approx` provides 3 customization points:
### Other limitations
* __epsilon__ - epsilon serves to set the coefficient by which a result
can differ from `Approx`'s value before it is rejected.
_By default set to `std::numeric_limits<float>::epsilon()*100`._
* __margin__ - margin serves to set the the absolute value by which
a result can differ from `Approx`'s value before it is rejected.
_By default set to `0.0`._
* __scale__ - scale is used to change the magnitude of `Approx` for relative check.
_By default set to `0.0`._
Note that expressions containing either of the binary logical operators,
`&&` or `||`, cannot be decomposed and will not compile. The reason behind
this is that it is impossible to overload `&&` and `||` in a way that
keeps their short-circuiting semantics, and expression decomposition
relies on overloaded operators to work.
#### epsilon example
```cpp
Approx target = Approx(100).epsilon(0.01);
100.0 == target; // Obviously true
200.0 == target; // Obviously still false
100.5 == target; // True, because we set target to allow up to 1% difference
```
Simple example of an issue with overloading binary logical operators
is a common pointer idiom, `p && p->foo == 2`. Using the built-in `&&`
operator, `p` is only dereferenced if it is not null. With overloaded
`&&`, `p` is always dereferenced, thus causing a segfault if
`p == nullptr`.
#### margin example
```cpp
Approx target = Approx(100).margin(5);
100.0 == target; // Obviously true
200.0 == target; // Obviously still false
104.0 == target; // True, because we set target to allow absolute difference of at most 5
```
If you want to test expression that contains `&&` or `||`, you have two
options.
#### scale
Scale can be useful if the computation leading to the result worked
on different scale than is used by the results. Since allowed difference
between Approx's value and compared value is based primarily on Approx's value
(the allowed difference is computed as
`(Approx::scale + Approx::value) * epsilon`), the resulting comparison could
need rescaling to be correct.
1) Enclose it in parentheses. Parentheses force evaluation of the expression
before the expression decomposition can touch it, and thus it cannot
be used.
2) Rewrite the expression. `REQUIRE(a == 1 && b == 2)` can always be split
into `REQUIRE(a == 1); REQUIRE(b == 2);`. Alternatively, if this is a
common pattern in your tests, think about using [Matchers](#matcher-expressions).
instead. There is no simple rewrite rule for `||`, but I generally
believe that if you have `||` in your test expression, you should rethink
your tests.
## Floating point comparisons
Comparing floating point numbers is complex, and [so it has its own
documentation page](comparing-floating-point-numbers.md#top).
## Exceptions
* **REQUIRE_NOTHROW(** _expression_ **)** and
* **REQUIRE_NOTHROW(** _expression_ **)** and
* **CHECK_NOTHROW(** _expression_ **)**
Expects that no exception is thrown during evaluation of the expression.
* **REQUIRE_THROWS(** _expression_ **)** and
* **REQUIRE_THROWS(** _expression_ **)** and
* **CHECK_THROWS(** _expression_ **)**
Expects that an exception (of any type) is be thrown during evaluation of the expression.
* **REQUIRE_THROWS_AS(** _expression_, _exception type_ **)** and
* **REQUIRE_THROWS_AS(** _expression_, _exception type_ **)** and
* **CHECK_THROWS_AS(** _expression_, _exception type_ **)**
Expects that an exception of the _specified type_ is thrown during evaluation of the expression. Note that the _exception type_ is extended with `const&` and you should not include it yourself.
* **REQUIRE_THROWS_WITH(** _expression_, _string or string matcher_ **)** and
* **REQUIRE_THROWS_WITH(** _expression_, _string or string matcher_ **)** and
* **CHECK_THROWS_WITH(** _expression_, _string or string matcher_ **)**
Expects that an exception is thrown that, when converted to a string, matches the _string_ or _string matcher_ provided (see next section for Matchers).
@ -158,8 +139,8 @@ REQUIRE_NOTHROW([&](){
To support Matchers a slightly different form is used. Matchers have [their own documentation](matchers.md#top).
* **REQUIRE_THAT(** _lhs_, _matcher expression_ **)** and
* **CHECK_THAT(** _lhs_, _matcher expression_ **)**
* **REQUIRE_THAT(** _lhs_, _matcher expression_ **)** and
* **CHECK_THAT(** _lhs_, _matcher expression_ **)**
Matchers can be composed using `&&`, `||` and `!` operators.

View File

@ -1,13 +1,7 @@
<a id="top"></a>
# CI and other odd pieces
**Contents**<br>
[Continuous Integration systems](#continuous-integration-systems)<br>
[Other reporters](#other-reporters)<br>
[Low-level tools](#low-level-tools)<br>
[CMake](#cmake)<br>
This page talks about how Catch integrates with Continuous Integration
This page talks about how Catch integrates with Continuous Integration
Build Systems may refer to low-level tools, like CMake, or larger systems that run on servers, like Jenkins or TeamCity. This page will talk about both.
## Continuous Integration systems
@ -17,9 +11,9 @@ Probably the most important aspect to using Catch with a build server is the use
Two of these reporters are built in (XML and JUnit) and the third (TeamCity) is included as a separate header. It's possible that the other two may be split out in the future too - as that would make the core of Catch smaller for those that don't need them.
### XML Reporter
```-r xml```
```-r xml```
The XML Reporter writes in an XML format that is specific to Catch.
The XML Reporter writes in an XML format that is specific to Catch.
The advantage of this format is that it corresponds well to the way Catch works (especially the more unusual features, such as nested sections) and is a fully streaming format - that is it writes output as it goes, without having to store up all its results before it can start writing.
@ -34,19 +28,6 @@ The advantage of this format is that the JUnit Ant schema is widely understood b
The disadvantage is that this schema was designed to correspond to how JUnit works - and there is a significant mismatch with how Catch works. Additionally the format is not streamable (because opening elements hold counts of failed and passing tests as attributes) - so the whole test run must complete before it can be written.
## Other reporters
Other reporters are not part of the single-header distribution and need
to be downloaded and included separately. All reporters are stored in
`single_include` directory in the git repository, and are named
`catch_reporter_*.hpp`. For example, to use the TeamCity reporter you
need to download `single_include/catch_reporter_teamcity.hpp` and include
it after Catch itself.
```cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "catch_reporter_teamcity.hpp"
```
### TeamCity Reporter
```-r teamcity```
@ -69,19 +50,9 @@ Because of the incremental nature of Catch's test suites and ability to run spec
```-r sonarqube```
[SonarQube Generic Test Data](https://docs.sonarqube.org/latest/analysis/generic-test/) XML format for tests metrics.
## Low-level tools
### Precompiled headers (PCHs)
Catch offers prototypal support for being included in precompiled headers, but because of its single-header nature it does need some actions by the user:
* The precompiled header needs to define `CATCH_CONFIG_ALL_PARTS`
* The implementation file needs to
* undefine `TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED`
* define `CATCH_CONFIG_IMPL_ONLY`
* define `CATCH_CONFIG_MAIN` or `CATCH_CONFIG_RUNNER`
* include "catch.hpp" again
### CodeCoverage module (GCOV, LCOV...)
If you are using GCOV tool to get testing coverage of your code, and are not sure how to integrate it with CMake and Catch, there should be an external example over at https://github.com/fkromer/catch_cmake_coverage

View File

@ -112,7 +112,7 @@ catch_discover_tests()
```
#### Customization
`catch_discover_tests` can be given several extra argumets:
`catch_discover_tests` can be given several extra arguments:
```cmake
catch_discover_tests(target
[TEST_SPEC arg1...]

View File

@ -284,7 +284,7 @@ This option transforms tabs and newline characters into ```\t``` and ```\n``` re
<pre>-w, --warn &lt;warning name></pre>
You can think of Catch2's warnings as the equivalent of `-Werror` (`/WX`)
flag for C++ compilers. It turns some suspicious occurences, like a section
flag for C++ compilers. It turns some suspicious occurrences, like a section
without assertions, into errors. Because these might be intended, warnings
are not enabled by default, but user can opt in.
@ -313,7 +313,7 @@ When set to ```yes``` Catch will report the duration of each test case, in milli
> `--min-duration` was [introduced](https://github.com/catchorg/Catch2/pull/1910) in Catch2 2.13.0
When set, Catch will report the duration of each test case that took more
than &lt;value> seconds, in milliseconds. This option is overriden by both
than &lt;value> seconds, in milliseconds. This option is overridden by both
`-d yes` and `-d no`, so that either all durations are reported, or none
are.
@ -339,8 +339,8 @@ Test cases are ordered one of three ways:
### decl
Declaration order (this is the default order if no --order argument is provided).
Tests in the same TU are sorted using their declaration orders, different
TUs are in an implementation (linking) dependent order.
Tests in the same translation unit are sorted using their declaration orders,
different TUs are sorted in an implementation (linking) dependent order.
### lex
@ -548,7 +548,8 @@ starting at 0. The tests in the set given by
`--shard-index <#shard index to run>` will be executed. The default shard
count is `1`, and the default index to run is `0`.
_It is an error to specify a shard index greater than the number of shards._
_Shard index must be less than number of shards. As the name suggests,
it is treated as an index of the shard to run._
Sharding is useful when you want to split test execution across multiple
processes, as is done with the [Bazel test sharding](https://docs.bazel.build/versions/main/test-encyclopedia.html#test-sharding).
@ -570,7 +571,7 @@ tests still returns 0.
-v, --verbosity <quiet|normal|high>
```
Changing verbosity might change how much details Catch2's reporters output.
Changing verbosity might change how many details Catch2's reporters output.
However, you should consider changing the verbosity level as a _suggestion_.
Not all reporters support all verbosity levels, e.g. because the reporter's
format cannot meaningfully change. In that case, the verbosity level is

View File

@ -6,7 +6,7 @@ some of them that are willing to share this information.
If you want to add your organisation, please check that there is no issue
with you sharing this fact.
- Bloomberg
- [Bloomlife](https://bloomlife.com)
- [Inscopix Inc.](https://www.inscopix.com/)
@ -16,7 +16,7 @@ with you sharing this fact.
- [Nexus Software Systems](https://nexwebsites.com)
- [UX3D](https://ux3d.io)
- [King](https://king.com)
---

View File

@ -0,0 +1,192 @@
<a id="top"></a>
# Comparing floating point numbers with Catch2
If you are not deeply familiar with them, floating point numbers can be
unintuitive. This also applies to comparing floating point numbers for
(in)equality.
This page assumes that you have some understanding of both FP, and the
meaning of different kinds of comparisons, and only goes over what
functionality Catch2 provides to help you with comparing floating point
numbers. If you do not have this understanding, we recommend that you first
study up on floating point numbers and their comparisons, e.g. by [reading
this blog post](https://codingnest.com/the-little-things-comparing-floating-point-numbers/).
## Floating point matchers
```
#include <catch2/matchers/catch_matchers_floating.hpp
```
[Matchers](matchers.md#top) are the preferred way of comparing floating
point numbers in Catch2. We provide 3 of them:
* `WithinAbs(double target, double margin)`,
* `WithinRel(FloatingPoint target, FloatingPoint eps)`, and
* `WithinULP(FloatingPoint target, uint64_t maxUlpDiff)`.
> `WithinRel` matcher was introduced in Catch2 2.10.0
As with all matchers, you can combine multiple floating point matchers
in a single assertion. For example, to check that some computation matches
a known good value within 0.1% or is close enough (no different to 5
decimal places) to zero, we would write this assertion:
```cpp
REQUIRE_THAT( computation(input),
Catch::Matchers::WithinRel(expected, 0.001)
|| Catch::Matchers::WithinAbs(0, 0.000001) );
```
### WithinAbs
`WithinAbs` creates a matcher that accepts floating point numbers whose
difference with `target` is less-or-equal to the `margin`. Since `float`
can be converted to `double` without losing precision, only `double`
overload exists.
```cpp
REQUIRE_THAT(1.0, WithinAbs(1.2, 0.2));
REQUIRE_THAT(0.f, !WithinAbs(1.0, 0.5));
// Notice that infinity == infinity for WithinAbs
REQUIRE_THAT(INFINITY, WithinAbs(INFINITY, 0));
```
### WithinRel
`WithinRel` creates a matcher that accepts floating point numbers that
are _approximately equal_ to the `target` with a tolerance of `eps.`
Specifically, it matches if
`|arg - target| <= eps * max(|arg|, |target|)` holds. If you do not
specify `eps`, `std::numeric_limits<FloatingPoint>::epsilon * 100`
is used as the default.
```cpp
// Notice that WithinRel comparison is symmetric, unlike Approx's.
REQUIRE_THAT(1.0, WithinRel(1.1, 0.1));
REQUIRE_THAT(1.1, WithinRel(1.0, 0.1));
// Notice that inifnity == infinity for WithinRel
REQUIRE_THAT(INFINITY, WithinRel(INFINITY));
```
### WithinULP
`WithinULP` creates a matcher that accepts floating point numbers that
are no more than `maxUlpDiff`
[ULPs](https://en.wikipedia.org/wiki/Unit_in_the_last_place)
away from the `target` value. The short version of what this means
is that there is no more than `maxUlpDiff - 1` representable floating
point numbers between the argument for matching and the `target` value.
When using the ULP matcher in Catch2, it is important to keep in mind
that Catch2 interprets ULP distance slightly differently than
e.g. `std::nextafter` does.
Catch2's ULP calculation obeys these relations:
* `ulpDistance(-x, x) == 2 * ulpDistance(x, 0)`
* `ulpDistance(-0, 0) == 0` (due to the above)
* `ulpDistance(DBL_MAX, INFINITY) == 1`
* `ulpDistancE(NaN, x) == infinity`
**Important**: The WithinULP matcher requires the platform to use the
[IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) representation for
floating point numbers.
```cpp
REQUIRE_THAT( -0.f, WithinULP( 0.f, 0 ) );
```
## `Approx`
```
#include <catch2/catch_approx.hpp>
```
**We strongly recommend against using `Approx` when writing new code.**
You should be using floating point matchers instead.
Catch2 provides one more way to handle floating point comparisons. It is
`Approx`, a special type with overloaded comparison operators, that can
be used in standard assertions, e.g.
```cpp
REQUIRE(0.99999 == Catch::Approx(1));
```
`Approx` supports four comparison operators, `==`, `!=`, `<=`, `>=`, and can
also be used with strong typedefs over `double`s. It can be used for both
relative and margin comparisons by using its three customization points.
Note that the semantics of this is always that of an _or_, so if either
the relative or absolute margin comparison passes, then the whole comparison
passes.
The downside to `Approx` is that it has a couple of issues that we cannot
fix without breaking backwards compatibility. Because Catch2 also provides
complete set of matchers that implement different floating point comparison
methods, `Approx` is left as-is, is considered deprecated, and should
not be used in new code.
The issues are
* All internal computation is done in `double`s, leading to slightly
different results if the inputs were floats.
* `Approx`'s relative margin comparison is not symmetric. This means
that `Approx( 10 ).epsilon(0.1) != 11.1` but `Approx( 11.1 ).epsilon(0.1) == 10`.
* By default, `Approx` only uses relative margin comparison. This means
that `Approx(0) == X` only passes for `X == 0`.
### Approx details
If you still want/need to know more about `Approx`, read on.
Catch2 provides a UDL for `Approx`; `_a`. It resides in the `Catch::literals`
namespace, and can be used like this:
```cpp
using namespace Catch::literals;
REQUIRE( performComputation() == 2.1_a );
```
`Approx` has three customization points for the comparison:
* **epsilon** - epsilon sets the coefficient by which a result
can differ from `Approx`'s value before it is rejected.
_Defaults to `std::numeric_limits<float>::epsilon()*100`._
```cpp
Approx target = Approx(100).epsilon(0.01);
100.0 == target; // Obviously true
200.0 == target; // Obviously still false
100.5 == target; // True, because we set target to allow up to 1% difference
```
* **margin** - margin sets the absolute value by which
a result can differ from `Approx`'s value before it is rejected.
_Defaults to `0.0`._
```cpp
Approx target = Approx(100).margin(5);
100.0 == target; // Obviously true
200.0 == target; // Obviously still false
104.0 == target; // True, because we set target to allow absolute difference of at most 5
```
* **scale** - scale is used to change the magnitude of `Approx` for the relative check.
_By default, set to `0.0`._
Scale could be useful if the computation leading to the result worked
on a different scale than is used by the results. Approx's scale is added
to Approx's value when computing the allowed relative margin from the
Approx's value.
---
[Home](Readme.md#top)

View File

@ -19,7 +19,7 @@
Catch2 is designed to "just work" as much as possible, and most of the
configuration options below are changed automatically during compilation,
according to the detected environment. However, this detection can also
be overriden by users, using macros documented below, and/or CMake options
be overridden by users, using macros documented below, and/or CMake options
with the same name.
@ -98,7 +98,7 @@ is equivalent with the out-of-the-box experience.
## Bazel support
When `CATCH_CONFIG_BAZEL_SUPPORT` is defined or when `BAZEL_TEST=1` (which is set by the Bazel inside of a test environment),
When `CATCH_CONFIG_BAZEL_SUPPORT` is defined or when `BAZEL_TEST=1` (which is set by the Bazel inside of a test environment),
Catch2 will register a `JUnit` reporter writing to a path pointed by `XML_OUTPUT_FILE` provided by Bazel.
> `CATCH_CONFIG_BAZEL_SUPPORT` was [introduced](https://github.com/catchorg/Catch2/pull/2399) in Catch2 3.0.1.

View File

@ -125,7 +125,7 @@ information that you will need for updating Catch2's documentation, and
possibly some generic advise as well.
### Technicalities
### Technicalities
First, the technicalities:
@ -203,7 +203,7 @@ and so on.
Catch2 currently targets C++14 as the minimum supported C++ version.
Features from higher language versions should be used only sparingly,
when the benefits from using them outweight the maintenance overhead.
when the benefits from using them outweigh the maintenance overhead.
Example of good use of polyfilling features is our use of `conjunction`,
where if available we use `std::conjunction` and otherwise provide our

View File

@ -33,7 +33,7 @@ public:
CATCH_REGISTER_LISTENER(testRunListener)
```
_Note that you should not use any assertion macros within a Listener!_
_Note that you should not use any assertion macros within a Listener!_
[You can find the list of events that the listeners can react to on its
own page](reporter-events.md#top).

View File

@ -7,6 +7,8 @@
[Why cannot I derive from the built-in reporters?](#why-cannot-i-derive-from-the-built-in-reporters)<br>
[What is Catch2's ABI stability policy?](#what-is-catch2s-abi-stability-policy)<br>
[What is Catch2's API stability policy?](#what-is-catch2s-api-stability-policy)<br>
[Does Catch2 support running tests in parallel?](#does-catch2-support-running-tests-in-parallel)<br>
[Can I compile Catch2 into a dynamic library?](#can-i-compile-catch2-into-a-dynamic-library)<br>
## How do I run global setup/teardown only if tests will be run?
@ -23,7 +25,7 @@ depending on how often the cleanup needs to happen.
## Why cannot I derive from the built-in reporters?
They are not made to be overriden, in that we do not attempt to maintain
They are not made to be overridden, in that we do not attempt to maintain
a consistent internal state if a member function is overriden, and by
forbidding users from using them as a base class, we can refactor them
as needed later.
@ -57,6 +59,16 @@ runners easier. [See the relevant section in our page on best
practices](usage-tips.md#parallel-tests).
## Can I compile Catch2 into a dynamic library?
Yes, Catch2 supports the [standard CMake `BUILD_SHARED_LIBS`
option](https://cmake.org/cmake/help/latest/variable/BUILD_SHARED_LIBS.html).
However, the dynamic library support is provided as-is. Catch2 does not
provide API export annotations, and so you can only use it as a dynamic
library on platforms that default to public visibility, or with tooling
support to force export Catch2's API.
---
[Home](Readme.md#top)

View File

@ -99,7 +99,7 @@ Catch does not support running tests in isolated (forked) processes. While this
Catch2 keeps test execution in one process strictly serial, and there
are no plans to change this. If you find yourself with a test suite
that takes too long to run and yo uwant to make it parallel, you have
that takes too long to run and you want to make it parallel, you have
to run multiple processes side by side.
There are 2 basic ways to do that,
@ -171,7 +171,7 @@ TEST_CASE("b") {
}
```
If you are seeing a problem like this, i.e. a weird test paths that trigger only under Clang with `libc++`, or only under very specific version of `libstdc++`, it is very likely you are seeing this. The only known workaround is to use a fixed version of your standard library.
If you are seeing a problem like this, i.e. weird test paths that trigger only under Clang with `libc++`, or only under very specific version of `libstdc++`, it is very likely you are seeing this. The only known workaround is to use a fixed version of your standard library.
### libstdc++, `_GLIBCXX_DEBUG` macro and random ordering of tests

View File

@ -150,49 +150,8 @@ are:
> `WithinRel` matcher was introduced in Catch2 2.10.0
`WithinAbs` creates a matcher that accepts floating point numbers whose
difference with `target` is less than the `margin`.
`WithinULP` creates a matcher that accepts floating point numbers that
are no more than `maxUlpDiff`
[ULPs](https://en.wikipedia.org/wiki/Unit_in_the_last_place)
away from the `target` value. The short version of what this means
is that there is no more than `maxUlpDiff - 1` representeable floating
point numbers between the argument for matching and the `target` value.
**Important**: The WithinULP matcher requires the platform to use the
[IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) representation for
floating point numbers.
`WithinRel` creates a matcher that accepts floating point numbers that
are _approximately equal_ with the `target` with tolerance of `eps.`
Specifically, it matches if
`|arg - target| <= eps * max(|arg|, |target|)` holds. If you do not
specify `eps`, `std::numeric_limits<FloatingPoint>::epsilon * 100`
is used as the default.
In practice, you will often want to combine multiple of these matchers,
together for an assertion, because all 3 options have edge cases where
they behave differently than you would expect. As an example, under
the `WithinRel` matcher, a `0.` only ever matches a `0.` (or `-0.`),
regardless of the relative tolerance specified. Thus, if you want to
handle numbers that are "close enough to 0 to be 0", you have to combine
it with the `WithinAbs` matcher.
For example, to check that our computation matches known good value
within 0.1%, or is close enough (no different to 5 decimal places)
to zero, we would write this assertion:
```cpp
REQUIRE_THAT( computation(input),
Catch::Matchers::WithinRel(expected, 0.001)
|| Catch::Matchers::WithinAbs(0, 0.000001) );
```
> floating point matchers live in `catch2/matchers/catch_matchers_floating.hpp`
For more details, read [the docs on comparing floating point
numbers](comparing-floating-point-numbers.md#floating-point-matchers).
### Miscellaneous matchers
@ -224,7 +183,7 @@ The other miscellaneous matcher utility is exception matching.
#### Matching exceptions
Catch2 provides an utility macro for asserting that an expression
Catch2 provides a utility macro for asserting that an expression
throws exception of specific type, and that the exception has desired
properties. The macro is `REQUIRE_THROWS_MATCHES(expr, ExceptionType, Matcher)`.
@ -282,12 +241,12 @@ in which case a range is accepted if any of its elements is accepted
by the provided matcher.
`AllMatch`, `NoneMatch`, and `AnyMatch` match ranges for which either
all, none, or any of the contained elements matches the given matcher,
all, none, or any of the contained elements matches the given matcher,
respectively.
`AllTrue`, `NoneTrue`, and `AnyTrue` match ranges for which either
all, none, or any of the contained elements are `true`, respectively.
It works for ranges of `bool`s and ranges of elements (explicitly)
all, none, or any of the contained elements are `true`, respectively.
It works for ranges of `bool`s and ranges of elements (explicitly)
convertible to `bool`.
## Writing custom matchers (old style)
@ -368,7 +327,7 @@ style matchers arbitrarily.
To create a new-style matcher, you have to create your own type that
derives from `Catch::Matchers::MatcherGenericBase`. Your type has to
also provide two methods, `bool match( ... ) const` and overriden
also provide two methods, `bool match( ... ) const` and overridden
`std::string describe() const`.
Unlike with old-style matchers, there are no requirements on how

View File

@ -21,9 +21,10 @@ reduced by roughly 80%. The improved ease of maintenance also led to
various runtime performance improvements and the introduction of new features.
For details, look at [the release notes of 3.0.1](release-notes.md#301).
_Note that we still provide one header + one TU distribution but do
not consider it the primarily supported option. You should also expect
that the compilation times will be worse if you use this option._
_Note that we still provide one header + one translation unit (TU)
distribution but do not consider it the primarily supported option. You
should also expect that the compilation times will be worse if you use
this option._
## How to migrate projects from v2 to v3
@ -65,7 +66,9 @@ to piecemeal includes. You will likely want to start by including
[other notes](#other-notes) for further ideas)
## Other notes
* The main test include is now `<catch2/catch_test_macros.hpp>`
* Big "subparts" like Matchers, or Generators, have their own folder, and
also their own "big header", so if you just want to include all matchers,
you can include `<catch2/matchers/catch_matchers_all.hpp>`,
@ -73,11 +76,21 @@ or `<catch2/generators/catch_generators_all.hpp>`
## Things that can break during porting
* The namespace on Matchers were cleaned up, they are no longer first declared
deep within an internal namespace and then brought up. All Matchers now live
in `Catch::Matchers`.
* The reporter interfaces changed in a breaking manner. If you wrote custom
reporter or listener, you might need to modify them a bit.
* The namespaces of Matchers were flattened and cleaned up.
Matchers are no longer declared deep within an internal namespace and
then brought up into `Catch` namespace. All Matchers now live in the
`Catch::Matchers` namespace.
* The `Contains` string matcher was renamed to `ContainsSubstring`.
* The reporter interfaces changed in a breaking manner.
If you are using a custom reporter or listener, you will likely need to
modify them to conform to the new interfaces. Unlike before in v2,
the [interfaces](reporters.md#top) and the [events](reporter-events.md#top)
are now documented.
---

View File

@ -72,7 +72,7 @@ A header-only template engine for modern C++.
A C++17 template header-only library for the abstraction of memory access patterns.
### [libcluon](https://github.com/chrberger/libcluon)
A single-header-only library written in C++14 to glue distributed software components (UDP, TCP, shared memory) supporting natively Protobuf, LCM/ZCM, MsgPack, and JSON for dynamic message transformations in-between.
A single-header-only library written in C++14 to glue distributed software components (UDP, TCP, shared memory) supporting natively Protobuf, LCM/ZCM, MsgPack, and JSON for dynamic message transformations in-between.
### [MNMLSTC Core](https://github.com/mnmlstc/core)
A small and easy to use C++11 library that adds a functionality set that will be available in C++14 and later, as well as some useful additions.

View File

@ -2,6 +2,7 @@
# Release notes
**Contents**<br>
[3.1.1](#311)<br>
[3.1.0](#310)<br>
[3.0.1](#301)<br>
[2.13.7](#2137)<br>
@ -50,6 +51,39 @@
[Even Older versions](#even-older-versions)<br>
## 3.1.1
### Improvements
* Added `Catch::getSeed` function that user code can call to retrieve current rng-seed
* Better detection of compiler support for `-ffile-prefix-map` (#2517)
* Catch2's shared libraries now have `SOVERSION` set (#2516)
* `catch2/catch_all.hpp` convenience header no longer transitively includes `windows.h` (#2432, #2526)
### Fixes
* Fixed compilation on Universal Windows Platform
* Fixed compilation on VxWorks (#2515)
* Fixed compilation on Cygwin (#2540)
* Remove unused variable in reporter registration (#2538)
* Fixed some symbol visibility issues with dynamic library on Windows (#2527)
* Suppressed `-Wuseless-cast` warnings in `REQUIRE_THROWS*` macros (#2520, #2521)
* This was triggered when the potentially throwing expression evaluates to `void`
* Fixed "warning: storage class is not first" with `nvc++` (#2533)
* Fixed handling of `DL_PATHS` argument to `catch_discover_tests` on MacOS (#2483)
* Suppressed `*-avoid-c-arrays` clang-tidy warning in `TEMPLATE_TEST_CASE` (#2095, #2536)
### Miscellaneous
* Fixed CMake install step for Catch2 build as dynamic library (#2485)
* Raised minimum CMake version to 3.10 (#2523)
* Expect the minimum CMake version to increase once more in next few releases.
* Whole bunch of doc updates and fixes
* #1444, #2497, #2547, #2549, and more
* Added support for building Catch2 with Meson (#2530, #2539)
## 3.1.0
### Improvements

View File

@ -138,7 +138,7 @@ benchmarking itself fails.
> Introduced in Catch2 3.0.1.
Listings events are events that correspond to the test binary being
invoked with `--list-foo` flag.
invoked with `--list-foo` flag.
There are currently 3 listing events, one for reporters, one for tests,
and one for tags. Note that they are not exclusive to each other.

View File

@ -3,7 +3,7 @@
## Defining test fixtures
Although Catch allows you to group tests together as sections within a test case, 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:
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:
```c++
class UniqueTestsFixture {
@ -130,9 +130,9 @@ struct Template_Foo_2 {
};
TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(
Template_Fixture_2,
"A TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG based test run that succeeds",
"[class][template][product][nttp]",
Template_Fixture_2,
"A TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG based test run that succeeds",
"[class][template][product][nttp]",
((typename T, size_t S), T, S),
(std::array, Template_Foo_2),
((int,2), (float,6))) {

View File

@ -13,9 +13,10 @@
## Getting Catch2
Ideally you should be using Catch2 through its [CMake integration](cmake-integration.md#top).
Catch2 also provides pkg-config files and single TU distribution, but this
documentation will assume you are using CMake. If you are using single-TU
distribution instead, remember to replace the included header with `catch_amalgamated.hpp`.
Catch2 also provides pkg-config files and two file (header + cpp)
distribution, but this documentation will assume you are using CMake. If
you are using the two file distribution instead, remember to replace
the included header with `catch_amalgamated.hpp`.
## Writing tests
@ -99,7 +100,7 @@ before we move on.
It accepts a boolean expression, and uses expression templates to
internally decompose it, so that it can be individually stringified
on test failure.
On the last point, note that there are more testing macros available,
because not all useful checks can be expressed as a simple boolean
expression. As an example, checking that an expression throws an exception
@ -177,7 +178,7 @@ To continue on the vector example above, you could add a check that
}
```
Another way to look at sections is that they are a way to define a tree
Another way to look at sections is that they are a way to define a tree
of paths through the test. Each section represents a node, and the final
tree is walked in depth-first manner, with each path only visiting only
one leaf node.

View File

@ -47,7 +47,7 @@ Catch2 also supports [splitting tests in a binary into multiple
shards](command-line.md#test-sharding). This can be used by any test
runner to run batches of tests in parallel. Do note that when selecting
on the number of shards, you should have more shards than there are cores,
to avoid issues with long running tests getting accidentally grouped in
to avoid issues with long-running tests getting accidentally grouped in
the same shard, and causing long-tailed execution time.
**Note that naively composing sharding and random ordering of tests will break.**
@ -73,6 +73,11 @@ seed, e.g.
./tests --order rand --shard-index 2 --shard-count 3 --rng-seed 0xBEEF
```
Catch2 actually provides a helper to automatically register multiple shards
as CTest tests, with shared random seed that changes each CTest invocation.
For details look at the documentation of
[`CatchShardTests.cmake` CMake script](cmake-integration.md#catchshardtestscmake).
## Organizing tests into binaries

View File

@ -41,7 +41,7 @@ So what does Catch2 bring to the party that differentiates it from these? Apart
## Who else is using Catch2?
A whole lot of people. According to the 2021 Jetbrains C++ ecosystem survey,
A whole lot of people. According to the 2021 JetBrains C++ ecosystem survey,
about 11% of C++ programmers use Catch2 for unit testing, making it the
second most popular unit testing framework.

View File

@ -1,4 +1,4 @@
cmake_minimum_required( VERSION 3.5 )
cmake_minimum_required( VERSION 3.10 )
project( Catch2Examples LANGUAGES CXX )

View File

@ -17,6 +17,8 @@ set(tests)
if(WIN32)
set(dl_paths_variable_name PATH)
elseif(APPLE)
set(dl_paths_variable_name DYLD_LIBRARY_PATH)
else()
set(dl_paths_variable_name LD_LIBRARY_PATH)
endif()

View File

@ -5,8 +5,8 @@
// SPDX-License-Identifier: BSL-1.0
// Catch v3.1.0
// Generated: 2022-07-17 20:14:05.885021
// Catch v3.1.1
// Generated: 2022-10-17 18:47:22.400176
// ----------------------------------------------------------
// This file is an amalgamation of multiple different files.
// You probably shouldn't edit it directly.
@ -15,6 +15,28 @@
#include "catch_amalgamated.hpp"
#ifndef CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
#define CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
#if defined(CATCH_PLATFORM_WINDOWS)
// We might end up with the define made globally through the compiler,
// and we don't want to trigger warnings for this
#if !defined(NOMINMAX)
# define NOMINMAX
#endif
#if !defined(WIN32_LEAN_AND_MEAN)
# define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif // defined(CATCH_PLATFORM_WINDOWS)
#endif // CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
namespace Catch {
@ -488,8 +510,11 @@ namespace Catch {
namespace {
bool provideBazelReporterOutput() {
#ifdef CATCH_CONFIG_BAZEL_SUPPORT
#if defined(CATCH_CONFIG_BAZEL_SUPPORT)
return true;
#elif defined(CATCH_PLATFORM_WINDOWS_UWP)
// UWP does not support environment variables
return false;
#else
# if defined( _MSC_VER )
@ -554,6 +579,7 @@ namespace Catch {
} );
}
#if !defined(CATCH_PLATFORM_WINDOWS_UWP)
if(provideBazelReporterOutput()){
// Register a JUnit reporter for Bazel. Bazel sets an environment
// variable with the path to XML output. If this file is written to
@ -575,7 +601,7 @@ namespace Catch {
{ "junit", std::string( bazelOutputFilePtr ), {}, {} } );
}
}
#endif
// We now fixup the reporter specs to handle default output spec,
// default colour spec, etc
@ -659,6 +685,16 @@ namespace Catch {
namespace Catch {
std::uint32_t getSeed() {
return getCurrentContext().getConfig()->rngSeed();
}
}
#include <cassert>
#include <stack>
@ -882,7 +918,6 @@ namespace Catch {
multi->addListener(listener->create(config));
}
std::size_t reporterIdx = 0;
for ( auto const& reporterSpec : config->getProcessedReporterSpecs() ) {
multi->addReporter( createReporter(
reporterSpec.name,
@ -890,7 +925,6 @@ namespace Catch {
makeStream( reporterSpec.outputFilename ),
reporterSpec.colourMode,
reporterSpec.customOptions ) ) );
reporterIdx++;
}
return multi;
@ -1890,7 +1924,7 @@ namespace Catch {
}
Version const& libraryVersion() {
static Version version( 3, 1, 0, "", 0 );
static Version version( 3, 1, 1, "", 0 );
return version;
}
@ -3957,6 +3991,7 @@ namespace Detail {
FileStream( std::string const& filename ) {
m_ofs.open( filename.c_str() );
CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << '\'' );
m_ofs << std::unitbuf;
}
~FileStream() override = default;
public: // IStream
@ -7878,7 +7913,7 @@ private:
<< serializeFilters( m_config->getTestsOrTags() )
<< '\n';
}
m_stream << "RNG seed: " << m_config->rngSeed() << '\n';
m_stream << "RNG seed: " << getSeed() << '\n';
}
void CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
@ -8399,7 +8434,7 @@ void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
m_stream << m_colour->guardColour( Colour::BrightYellow ) << "Filters: "
<< serializeFilters( m_config->getTestsOrTags() ) << '\n';
}
m_stream << "Randomness seeded to: " << m_config->rngSeed() << '\n';
m_stream << "Randomness seeded to: " << getSeed() << '\n';
}
void ConsoleReporter::lazyPrint() {

View File

@ -5,8 +5,8 @@
// SPDX-License-Identifier: BSL-1.0
// Catch v3.1.0
// Generated: 2022-07-17 20:14:04.055157
// Catch v3.1.1
// Generated: 2022-10-17 18:47:20.510385
// ----------------------------------------------------------
// This file is an amalgamation of multiple different files.
// You probably shouldn't edit it directly.
@ -326,6 +326,10 @@ namespace Catch {
#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
# define CATCH_PLATFORM_WINDOWS
# if defined( WINAPI_FAMILY ) && ( WINAPI_FAMILY == WINAPI_FAMILY_APP )
# define CATCH_PLATFORM_WINDOWS_UWP
# endif
#endif
#endif // CATCH_PLATFORM_HPP_INCLUDED
@ -356,6 +360,9 @@ namespace Catch {
# define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
_Pragma( "GCC diagnostic ignored \"-Wunused-variable\"" )
# define CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
_Pragma( "GCC diagnostic ignored \"-Wuseless-cast\"" )
# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
#endif
@ -477,7 +484,7 @@ namespace Catch {
// Universal Windows platform does not support SEH
// Or console colours (or console at all...)
# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
# if defined(CATCH_PLATFORM_WINDOWS_UWP)
# define CATCH_INTERNAL_CONFIG_NO_COLOUR_WIN32
# else
# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
@ -638,6 +645,9 @@ namespace Catch {
#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
#endif
@ -679,6 +689,16 @@ namespace Catch {
# define CATCH_CONFIG_COLOUR_WIN32
#endif
#if defined( CATCH_CONFIG_SHARED_LIBRARY ) && defined( _MSC_VER ) && \
!defined( CATCH_CONFIG_STATIC )
# ifdef Catch2_EXPORTS
# define CATCH_EXPORT //__declspec( dllexport ) // not needed
# else
# define CATCH_EXPORT __declspec( dllimport )
# endif
#else
# define CATCH_EXPORT
#endif
#endif // CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
@ -686,6 +706,7 @@ namespace Catch {
#ifndef CATCH_CONTEXT_HPP_INCLUDED
#define CATCH_CONTEXT_HPP_INCLUDED
namespace Catch {
class IResultCapture;
@ -706,7 +727,7 @@ namespace Catch {
virtual void setConfig( IConfig const* config ) = 0;
private:
static IMutableContext *currentContext;
CATCH_EXPORT static IMutableContext* currentContext;
friend IMutableContext& getCurrentMutableContext();
friend void cleanUpContext();
static void createContext();
@ -1716,9 +1737,9 @@ namespace Catch {
template <typename> struct true_given : std::true_type {};
struct is_callable_tester {
template <typename Fun, typename... Args>
true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
static true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> test(int);
template <typename...>
std::false_type static test(...);
static std::false_type test(...);
};
template <typename T>
@ -2737,14 +2758,18 @@ namespace Catch {
template <typename U>
void destruct_on_exit(std::enable_if_t<!Destruct, U>* = nullptr) { }
T& stored_object() {
return *static_cast<T*>(static_cast<void*>(data));
}
#if defined( __GNUC__ ) && __GNUC__ <= 6
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
T& stored_object() { return *reinterpret_cast<T*>( data ); }
T const& stored_object() const {
return *static_cast<T const*>(static_cast<void const*>(data));
return *reinterpret_cast<T const*>( data );
}
#if defined( __GNUC__ ) && __GNUC__ <= 6
# pragma GCC diagnostic pop
#endif
alignas( T ) unsigned char data[sizeof( T )]{};
};
@ -2776,7 +2801,6 @@ namespace Catch {
#include <cstddef>
#include <type_traits>
#include <string>
#include <string.h>
@ -2939,6 +2963,13 @@ namespace Catch {
namespace Detail {
inline std::size_t catch_strnlen(const char *str, std::size_t n) {
auto ret = std::char_traits<char>::find(str, n, '\0');
if (ret != nullptr) {
return static_cast<std::size_t>(ret - str);
}
return n;
}
constexpr StringRef unprintableString = "{?}"_sr;
@ -3106,28 +3137,24 @@ namespace Catch {
template<size_t SZ>
struct StringMaker<char[SZ]> {
static std::string convert(char const* str) {
// Note that `strnlen` is not actually part of standard C++,
// but both POSIX and Windows cstdlib provide it.
return Detail::convertIntoString(
StringRef( str, strnlen( str, SZ ) ) );
StringRef( str, Detail::catch_strnlen( str, SZ ) ) );
}
};
template<size_t SZ>
struct StringMaker<signed char[SZ]> {
static std::string convert(signed char const* str) {
// See the plain `char const*` overload
auto reinterpreted = reinterpret_cast<char const*>(str);
return Detail::convertIntoString(
StringRef(reinterpreted, strnlen(reinterpreted, SZ)));
StringRef(reinterpreted, Detail::catch_strnlen(reinterpreted, SZ)));
}
};
template<size_t SZ>
struct StringMaker<unsigned char[SZ]> {
static std::string convert(unsigned char const* str) {
// See the plain `char const*` overload
auto reinterpreted = reinterpret_cast<char const*>(str);
return Detail::convertIntoString(
StringRef(reinterpreted, strnlen(reinterpreted, SZ)));
StringRef(reinterpreted, Detail::catch_strnlen(reinterpreted, SZ)));
}
};
@ -3194,13 +3221,13 @@ namespace Catch {
template<>
struct StringMaker<float> {
static std::string convert(float value);
static int precision;
CATCH_EXPORT static int precision;
};
template<>
struct StringMaker<double> {
static std::string convert(double value);
static int precision;
CATCH_EXPORT static int precision;
};
template <typename T>
@ -4271,6 +4298,19 @@ namespace Catch {
#endif // CATCH_CONFIG_HPP_INCLUDED
#ifndef CATCH_GET_RANDOM_SEED_HPP_INCLUDED
#define CATCH_GET_RANDOM_SEED_HPP_INCLUDED
#include <cstdint>
namespace Catch {
//! Returns Catch2's current RNG seed.
std::uint32_t getSeed();
}
#endif // CATCH_GET_RANDOM_SEED_HPP_INCLUDED
#ifndef CATCH_MESSAGE_HPP_INCLUDED
#define CATCH_MESSAGE_HPP_INCLUDED
@ -5642,7 +5682,10 @@ namespace Catch {
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
try { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
static_cast<void>(__VA_ARGS__); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
} \
catch( ... ) { \
@ -5657,7 +5700,10 @@ namespace Catch {
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
if( catchAssertionHandler.allowThrows() ) \
try { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
static_cast<void>(__VA_ARGS__); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( ... ) { \
@ -5674,7 +5720,10 @@ namespace Catch {
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
if( catchAssertionHandler.allowThrows() ) \
try { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
static_cast<void>(expr); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( exceptionType const& ) { \
@ -5697,7 +5746,10 @@ namespace Catch {
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
if( catchAssertionHandler.allowThrows() ) \
try { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
static_cast<void>(__VA_ARGS__); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( ... ) { \
@ -6447,12 +6499,12 @@ struct AutoReg : Detail::NonCopyable {
struct TestName{\
TestName(){\
size_t index = 0; \
constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
using expander = size_t[];\
constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; /* NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays,hicpp-avoid-c-arrays) */\
using expander = size_t[]; /* NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays,hicpp-avoid-c-arrays) */\
(void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
}\
};\
static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
static const int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
return 0;\
}();\
@ -7063,7 +7115,7 @@ namespace Catch {
#define CATCH_VERSION_MAJOR 3
#define CATCH_VERSION_MINOR 1
#define CATCH_VERSION_PATCH 0
#define CATCH_VERSION_PATCH 1
#endif // CATCH_VERSION_MACROS_HPP_INCLUDED
@ -9122,6 +9174,7 @@ namespace Catch {
#include <cmath>
#include <algorithm>
namespace Catch {
@ -9673,32 +9726,6 @@ namespace Catch {
#endif // CATCH_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED
#ifndef CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
#define CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
#if defined(CATCH_PLATFORM_WINDOWS)
// We might end up with the define made globally through the compiler,
// and we don't want to trigger warnings for this
#if !defined(NOMINMAX)
# define NOMINMAX
#endif
#if !defined(WIN32_LEAN_AND_MEAN)
# define WIN32_LEAN_AND_MEAN
#endif
#ifdef __AFXDLL
#include <AfxWin.h>
#else
#include <windows.h>
#endif
#endif // defined(CATCH_PLATFORM_WINDOWS)
#endif // CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
#ifndef CATCH_XMLWRITER_HPP_INCLUDED
#define CATCH_XMLWRITER_HPP_INCLUDED

17
meson.build Normal file
View File

@ -0,0 +1,17 @@
# Copyright Catch2 Authors
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# https://www.boost.org/LICENSE_1_0.txt)
# SPDX-License-Identifier: BSL-1.0
project(
'catch2',
'cpp',
version: '3.1.1', # CML version placeholder, don't delete
license: 'BSL-1.0',
meson_version: '>=0.49.0',
)
subdir('src/catch2')
subdir('tests')

View File

@ -137,6 +137,7 @@ set(INTERNAL_HEADERS
${SOURCES_DIR}/internal/catch_string_manip.hpp
${SOURCES_DIR}/internal/catch_stringref.hpp
${SOURCES_DIR}/catch_tag_alias.hpp
${SOURCES_DIR}/catch_get_random_seed.hpp
${SOURCES_DIR}/catch_tag_alias_autoregistrar.hpp
${SOURCES_DIR}/internal/catch_tag_alias_registry.hpp
${SOURCES_DIR}/catch_test_case_info.hpp
@ -230,6 +231,7 @@ set(IMPL_SOURCES
${SOURCES_DIR}/matchers/catch_matchers_predicate.cpp
${SOURCES_DIR}/matchers/internal/catch_matchers_impl.cpp
${SOURCES_DIR}/catch_tag_alias_autoregistrar.cpp
${SOURCES_DIR}/catch_get_random_seed.cpp
${SOURCES_DIR}/internal/catch_decomposer.cpp
${SOURCES_DIR}/internal/catch_errno_guard.cpp
${SOURCES_DIR}/internal/catch_lazy_expr.cpp
@ -299,7 +301,10 @@ if (ANDROID)
target_link_libraries(Catch2 INTERFACE log)
endif()
set_target_properties(Catch2 PROPERTIES DEBUG_POSTFIX "d")
set_target_properties(Catch2 PROPERTIES
DEBUG_POSTFIX "d"
VERSION ${PROJECT_VERSION}
SOVERSION ${PROJECT_VERSION})
# depend on bunch of C++11 and C++14 features to have C++14 enabled by default
target_compile_features(Catch2
@ -348,6 +353,8 @@ target_link_libraries(Catch2WithMain PUBLIC Catch2)
set_target_properties(Catch2WithMain
PROPERTIES
OUTPUT_NAME "Catch2Main"
VERSION ${PROJECT_VERSION}
SOVERSION ${PROJECT_VERSION}
)
set_target_properties(Catch2WithMain PROPERTIES DEBUG_POSTFIX "d")
@ -359,8 +366,12 @@ if (NOT_SUBPROJECT)
Catch2WithMain
EXPORT
Catch2Targets
DESTINATION
LIBRARY DESTINATION
${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION
${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION
${CMAKE_INSTALL_BINDIR}
)
@ -403,6 +414,10 @@ if (CATCH_BUILD_EXAMPLES OR CATCH_BUILD_EXTRA_TESTS)
$<BUILD_INTERFACE:${CMAKE_BINARY_DIR}/generated-includes>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
target_compile_definitions(Catch2_buildall_interface
INTERFACE
CATCH_CONFIG_STATIC
)
target_compile_features(Catch2_buildall_interface
INTERFACE
cxx_alignas

View File

@ -54,14 +54,18 @@ namespace Catch {
template <typename U>
void destruct_on_exit(std::enable_if_t<!Destruct, U>* = nullptr) { }
T& stored_object() {
return *static_cast<T*>(static_cast<void*>(data));
}
#if defined( __GNUC__ ) && __GNUC__ <= 6
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
T& stored_object() { return *reinterpret_cast<T*>( data ); }
T const& stored_object() const {
return *static_cast<T const*>(static_cast<void const*>(data));
return *reinterpret_cast<T const*>( data );
}
#if defined( __GNUC__ ) && __GNUC__ <= 6
# pragma GCC diagnostic pop
#endif
alignas( T ) unsigned char data[sizeof( T )]{};
};

View File

@ -27,6 +27,7 @@
#include <catch2/catch_assertion_info.hpp>
#include <catch2/catch_assertion_result.hpp>
#include <catch2/catch_config.hpp>
#include <catch2/catch_get_random_seed.hpp>
#include <catch2/catch_message.hpp>
#include <catch2/catch_section_info.hpp>
#include <catch2/catch_session.hpp>
@ -113,7 +114,6 @@
#include <catch2/internal/catch_unique_ptr.hpp>
#include <catch2/internal/catch_void_type.hpp>
#include <catch2/internal/catch_wildcard_pattern.hpp>
#include <catch2/internal/catch_windows_h_proxy.hpp>
#include <catch2/internal/catch_xmlwriter.hpp>
#include <catch2/matchers/catch_matchers_all.hpp>
#include <catch2/reporters/catch_reporters_all.hpp>

View File

@ -8,6 +8,7 @@
#include <catch2/catch_config.hpp>
#include <catch2/catch_user_config.hpp>
#include <catch2/internal/catch_enforce.hpp>
#include <catch2/internal/catch_platform.hpp>
#include <catch2/internal/catch_stringref.hpp>
#include <catch2/internal/catch_string_manip.hpp>
#include <catch2/internal/catch_test_spec_parser.hpp>
@ -15,8 +16,11 @@
namespace {
bool provideBazelReporterOutput() {
#ifdef CATCH_CONFIG_BAZEL_SUPPORT
#if defined(CATCH_CONFIG_BAZEL_SUPPORT)
return true;
#elif defined(CATCH_PLATFORM_WINDOWS_UWP)
// UWP does not support environment variables
return false;
#else
# if defined( _MSC_VER )
@ -81,6 +85,7 @@ namespace Catch {
} );
}
#if !defined(CATCH_PLATFORM_WINDOWS_UWP)
if(provideBazelReporterOutput()){
// Register a JUnit reporter for Bazel. Bazel sets an environment
// variable with the path to XML output. If this file is written to
@ -102,7 +107,7 @@ namespace Catch {
{ "junit", std::string( bazelOutputFilePtr ), {}, {} } );
}
}
#endif
// We now fixup the reporter specs to handle default output spec,
// default colour spec, etc

View File

@ -0,0 +1,18 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
#include <catch2/catch_get_random_seed.hpp>
#include <catch2/internal/catch_context.hpp>
#include <catch2/catch_config.hpp>
namespace Catch {
std::uint32_t getSeed() {
return getCurrentContext().getConfig()->rngSeed();
}
}

View File

@ -0,0 +1,18 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
#ifndef CATCH_GET_RANDOM_SEED_HPP_INCLUDED
#define CATCH_GET_RANDOM_SEED_HPP_INCLUDED
#include <cstdint>
namespace Catch {
//! Returns Catch2's current RNG seed.
std::uint32_t getSeed();
}
#endif // CATCH_GET_RANDOM_SEED_HPP_INCLUDED

View File

@ -61,7 +61,6 @@ namespace Catch {
multi->addListener(listener->create(config));
}
std::size_t reporterIdx = 0;
for ( auto const& reporterSpec : config->getProcessedReporterSpecs() ) {
multi->addReporter( createReporter(
reporterSpec.name,
@ -69,7 +68,6 @@ namespace Catch {
makeStream( reporterSpec.outputFilename ),
reporterSpec.colourMode,
reporterSpec.customOptions ) ) );
reporterIdx++;
}
return multi;

View File

@ -13,7 +13,6 @@
#include <cstddef>
#include <type_traits>
#include <string>
#include <string.h>
#include <catch2/internal/catch_compiler_capabilities.hpp>
#include <catch2/internal/catch_config_wchar.hpp>
@ -41,6 +40,13 @@ namespace Catch {
namespace Detail {
inline std::size_t catch_strnlen(const char *str, std::size_t n) {
auto ret = std::char_traits<char>::find(str, n, '\0');
if (ret != nullptr) {
return static_cast<std::size_t>(ret - str);
}
return n;
}
constexpr StringRef unprintableString = "{?}"_sr;
@ -208,28 +214,24 @@ namespace Catch {
template<size_t SZ>
struct StringMaker<char[SZ]> {
static std::string convert(char const* str) {
// Note that `strnlen` is not actually part of standard C++,
// but both POSIX and Windows cstdlib provide it.
return Detail::convertIntoString(
StringRef( str, strnlen( str, SZ ) ) );
StringRef( str, Detail::catch_strnlen( str, SZ ) ) );
}
};
template<size_t SZ>
struct StringMaker<signed char[SZ]> {
static std::string convert(signed char const* str) {
// See the plain `char const*` overload
auto reinterpreted = reinterpret_cast<char const*>(str);
return Detail::convertIntoString(
StringRef(reinterpreted, strnlen(reinterpreted, SZ)));
StringRef(reinterpreted, Detail::catch_strnlen(reinterpreted, SZ)));
}
};
template<size_t SZ>
struct StringMaker<unsigned char[SZ]> {
static std::string convert(unsigned char const* str) {
// See the plain `char const*` overload
auto reinterpreted = reinterpret_cast<char const*>(str);
return Detail::convertIntoString(
StringRef(reinterpreted, strnlen(reinterpreted, SZ)));
StringRef(reinterpreted, Detail::catch_strnlen(reinterpreted, SZ)));
}
};
@ -296,13 +298,13 @@ namespace Catch {
template<>
struct StringMaker<float> {
static std::string convert(float value);
static int precision;
CATCH_EXPORT static int precision;
};
template<>
struct StringMaker<double> {
static std::string convert(double value);
static int precision;
CATCH_EXPORT static int precision;
};
template <typename T>

View File

@ -181,6 +181,8 @@
#cmakedefine CATCH_CONFIG_PREFIX_ALL
#cmakedefine CATCH_CONFIG_WINDOWS_CRTDBG
#cmakedefine CATCH_CONFIG_SHARED_LIBRARY
// ------
// "Variable" defines, these have actual values

View File

@ -36,7 +36,7 @@ namespace Catch {
}
Version const& libraryVersion() {
static Version version( 3, 1, 0, "", 0 );
static Version version( 3, 1, 1, "", 0 );
return version;
}

View File

@ -10,6 +10,6 @@
#define CATCH_VERSION_MAJOR 3
#define CATCH_VERSION_MINOR 1
#define CATCH_VERSION_PATCH 0
#define CATCH_VERSION_PATCH 1
#endif // CATCH_VERSION_MACROS_HPP_INCLUDED

View File

@ -53,6 +53,9 @@
# define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
_Pragma( "GCC diagnostic ignored \"-Wunused-variable\"" )
# define CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
_Pragma( "GCC diagnostic ignored \"-Wuseless-cast\"" )
# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
#endif
@ -174,7 +177,7 @@
// Universal Windows platform does not support SEH
// Or console colours (or console at all...)
# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
# if defined(CATCH_PLATFORM_WINDOWS_UWP)
# define CATCH_INTERNAL_CONFIG_NO_COLOUR_WIN32
# else
# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
@ -335,6 +338,9 @@
#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
#endif
@ -376,5 +382,15 @@
# define CATCH_CONFIG_COLOUR_WIN32
#endif
#if defined( CATCH_CONFIG_SHARED_LIBRARY ) && defined( _MSC_VER ) && \
!defined( CATCH_CONFIG_STATIC )
# ifdef Catch2_EXPORTS
# define CATCH_EXPORT //__declspec( dllexport ) // not needed
# else
# define CATCH_EXPORT __declspec( dllimport )
# endif
#else
# define CATCH_EXPORT
#endif
#endif // CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED

View File

@ -8,6 +8,8 @@
#ifndef CATCH_CONTEXT_HPP_INCLUDED
#define CATCH_CONTEXT_HPP_INCLUDED
#include <catch2/internal/catch_compiler_capabilities.hpp>
namespace Catch {
class IResultCapture;
@ -28,7 +30,7 @@ namespace Catch {
virtual void setConfig( IConfig const* config ) = 0;
private:
static IMutableContext *currentContext;
CATCH_EXPORT static IMutableContext* currentContext;
friend IMutableContext& getCurrentMutableContext();
friend void cleanUpContext();
static void createContext();

View File

@ -78,6 +78,7 @@ namespace Detail {
FileStream( std::string const& filename ) {
m_ofs.open( filename.c_str() );
CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << '\'' );
m_ofs << std::unitbuf;
}
~FileStream() override = default;
public: // IStream

View File

@ -17,9 +17,9 @@ namespace Catch {
template <typename> struct true_given : std::true_type {};
struct is_callable_tester {
template <typename Fun, typename... Args>
true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
static true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> test(int);
template <typename...>
std::false_type static test(...);
static std::false_type test(...);
};
template <typename T>

View File

@ -24,6 +24,10 @@
#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
# define CATCH_PLATFORM_WINDOWS
# if defined( WINAPI_FAMILY ) && ( WINAPI_FAMILY == WINAPI_FAMILY_APP )
# define CATCH_PLATFORM_WINDOWS_UWP
# endif
#endif
#endif // CATCH_PLATFORM_HPP_INCLUDED

View File

@ -11,6 +11,7 @@
#include <catch2/catch_session.hpp>
#include <cmath>
#include <algorithm>
namespace Catch {

View File

@ -84,12 +84,12 @@
struct TestName{\
TestName(){\
size_t index = 0; \
constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
using expander = size_t[];\
constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; /* NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays,hicpp-avoid-c-arrays) */\
using expander = size_t[]; /* NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays,hicpp-avoid-c-arrays) */\
(void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
}\
};\
static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
static const int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
return 0;\
}();\

View File

@ -76,7 +76,10 @@
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
try { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
static_cast<void>(__VA_ARGS__); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
} \
catch( ... ) { \
@ -91,7 +94,10 @@
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
if( catchAssertionHandler.allowThrows() ) \
try { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
static_cast<void>(__VA_ARGS__); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( ... ) { \
@ -108,7 +114,10 @@
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
if( catchAssertionHandler.allowThrows() ) \
try { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
static_cast<void>(expr); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( exceptionType const& ) { \
@ -131,7 +140,10 @@
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
if( catchAssertionHandler.allowThrows() ) \
try { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
static_cast<void>(__VA_ARGS__); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( ... ) { \

View File

@ -21,11 +21,7 @@
# define WIN32_LEAN_AND_MEAN
#endif
#ifdef __AFXDLL
#include <AfxWin.h>
#else
#include <windows.h>
#endif
#endif // defined(CATCH_PLATFORM_WINDOWS)

357
src/catch2/meson.build Normal file
View File

@ -0,0 +1,357 @@
# Copyright Catch2 Authors
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# https://www.boost.org/LICENSE_1_0.txt)
# SPDX-License-Identifier: BSL-1.0
pkg = import('pkgconfig')
conf_data = configuration_data()
conf_data.set('CATCH_CONFIG_DEFAULT_REPORTER', 'console')
conf_data.set('CATCH_CONFIG_CONSOLE_WIDTH', '80')
configure_file(
input: 'catch_user_config.hpp.in',
output: 'catch_user_config.hpp',
format: 'cmake@',
install_dir: get_option('includedir') / 'catch2',
configuration: conf_data,
)
benchmark_headers = [
'benchmark/catch_benchmark.hpp',
'benchmark/catch_benchmark_all.hpp',
'benchmark/catch_chronometer.hpp',
'benchmark/catch_clock.hpp',
'benchmark/catch_constructor.hpp',
'benchmark/catch_environment.hpp',
'benchmark/catch_estimate.hpp',
'benchmark/catch_execution_plan.hpp',
'benchmark/catch_optimizer.hpp',
'benchmark/catch_outlier_classification.hpp',
'benchmark/catch_sample_analysis.hpp',
'benchmark/detail/catch_analyse.hpp',
'benchmark/detail/catch_benchmark_function.hpp',
'benchmark/detail/catch_complete_invoke.hpp',
'benchmark/detail/catch_estimate_clock.hpp',
'benchmark/detail/catch_measure.hpp',
'benchmark/detail/catch_repeat.hpp',
'benchmark/detail/catch_run_for_at_least.hpp',
'benchmark/detail/catch_stats.hpp',
'benchmark/detail/catch_timing.hpp',
]
benchmark_sources = files(
'benchmark/catch_chronometer.cpp',
'benchmark/detail/catch_benchmark_function.cpp',
'benchmark/detail/catch_run_for_at_least.cpp',
'benchmark/detail/catch_stats.cpp',
)
internal_headers = [
'generators/catch_generator_exception.hpp',
'generators/catch_generators.hpp',
'generators/catch_generators_adapters.hpp',
'generators/catch_generators_all.hpp',
'generators/catch_generators_random.hpp',
'generators/catch_generators_range.hpp',
'interfaces/catch_interfaces_all.hpp',
'interfaces/catch_interfaces_capture.hpp',
'interfaces/catch_interfaces_config.hpp',
'interfaces/catch_interfaces_enum_values_registry.hpp',
'interfaces/catch_interfaces_exception.hpp',
'interfaces/catch_interfaces_generatortracker.hpp',
'interfaces/catch_interfaces_registry_hub.hpp',
'interfaces/catch_interfaces_reporter.hpp',
'interfaces/catch_interfaces_reporter_factory.hpp',
'interfaces/catch_interfaces_reporter_registry.hpp',
'interfaces/catch_interfaces_tag_alias_registry.hpp',
'interfaces/catch_interfaces_testcase.hpp',
'internal/catch_assertion_handler.hpp',
'internal/catch_case_insensitive_comparisons.hpp',
'internal/catch_case_sensitive.hpp',
'internal/catch_clara.hpp',
'internal/catch_commandline.hpp',
'internal/catch_compiler_capabilities.hpp',
'internal/catch_config_android_logwrite.hpp',
'internal/catch_config_counter.hpp',
'internal/catch_config_uncaught_exceptions.hpp',
'internal/catch_config_wchar.hpp',
'internal/catch_console_colour.hpp',
'internal/catch_console_width.hpp',
'internal/catch_container_nonmembers.hpp',
'internal/catch_context.hpp',
'internal/catch_debug_console.hpp',
'internal/catch_debugger.hpp',
'internal/catch_decomposer.hpp',
'internal/catch_enforce.hpp',
'internal/catch_enum_values_registry.hpp',
'internal/catch_errno_guard.hpp',
'internal/catch_exception_translator_registry.hpp',
'internal/catch_fatal_condition_handler.hpp',
'internal/catch_floating_point_helpers.hpp',
'internal/catch_istream.hpp',
'internal/catch_lazy_expr.hpp',
'internal/catch_leak_detector.hpp',
'internal/catch_list.hpp',
'internal/catch_message_info.hpp',
'internal/catch_meta.hpp',
'internal/catch_move_and_forward.hpp',
'internal/catch_noncopyable.hpp',
'internal/catch_optional.hpp',
'internal/catch_output_redirect.hpp',
'internal/catch_platform.hpp',
'internal/catch_polyfills.hpp',
'internal/catch_preprocessor.hpp',
'internal/catch_preprocessor_remove_parens.hpp',
'internal/catch_random_number_generator.hpp',
'internal/catch_random_seed_generation.hpp',
'internal/catch_reporter_registry.hpp',
'internal/catch_reporter_spec_parser.hpp',
'internal/catch_result_type.hpp',
'internal/catch_reusable_string_stream.hpp',
'internal/catch_run_context.hpp',
'internal/catch_section.hpp',
'internal/catch_sharding.hpp',
'internal/catch_singletons.hpp',
'internal/catch_source_line_info.hpp',
'internal/catch_startup_exception_registry.hpp',
'internal/catch_stdstreams.hpp',
'internal/catch_stream_end_stop.hpp',
'internal/catch_string_manip.hpp',
'internal/catch_stringref.hpp',
'internal/catch_tag_alias_registry.hpp',
'internal/catch_template_test_registry.hpp',
'internal/catch_test_case_info_hasher.hpp',
'internal/catch_test_case_registry_impl.hpp',
'internal/catch_test_case_tracker.hpp',
'internal/catch_test_failure_exception.hpp',
'internal/catch_test_macro_impl.hpp',
'internal/catch_test_registry.hpp',
'internal/catch_test_spec_parser.hpp',
'internal/catch_textflow.hpp',
'internal/catch_to_string.hpp',
'internal/catch_uncaught_exceptions.hpp',
'internal/catch_unique_name.hpp',
'internal/catch_unique_ptr.hpp',
'internal/catch_void_type.hpp',
'internal/catch_wildcard_pattern.hpp',
'internal/catch_windows_h_proxy.hpp',
'internal/catch_xmlwriter.hpp',
'matchers/catch_matchers.hpp',
'matchers/catch_matchers_all.hpp',
'matchers/catch_matchers_container_properties.hpp',
'matchers/catch_matchers_contains.hpp',
'matchers/catch_matchers_exception.hpp',
'matchers/catch_matchers_floating_point.hpp',
'matchers/catch_matchers_predicate.hpp',
'matchers/catch_matchers_quantifiers.hpp',
'matchers/catch_matchers_string.hpp',
'matchers/catch_matchers_templated.hpp',
'matchers/catch_matchers_vector.hpp',
'matchers/internal/catch_matchers_impl.hpp',
'catch_all.hpp',
'catch_approx.hpp',
'catch_assertion_info.hpp',
'catch_assertion_result.hpp',
'catch_config.hpp',
'catch_get_random_seed.hpp',
'catch_message.hpp',
'catch_section_info.hpp',
'catch_session.hpp',
'catch_tag_alias.hpp',
'catch_tag_alias_autoregistrar.hpp',
'catch_template_test_macros.hpp',
'catch_test_case_info.hpp',
'catch_test_macros.hpp',
'catch_test_spec.hpp',
'catch_timer.hpp',
'catch_tostring.hpp',
'catch_totals.hpp',
'catch_translate_exception.hpp',
'catch_version.hpp',
'catch_version_macros.hpp',
]
internal_sources = files(
'generators/catch_generator_exception.cpp',
'generators/catch_generators.cpp',
'generators/catch_generators_random.cpp',
'interfaces/catch_interfaces_capture.cpp',
'interfaces/catch_interfaces_config.cpp',
'interfaces/catch_interfaces_exception.cpp',
'interfaces/catch_interfaces_generatortracker.cpp',
'interfaces/catch_interfaces_registry_hub.cpp',
'interfaces/catch_interfaces_reporter.cpp',
'interfaces/catch_interfaces_reporter_factory.cpp',
'interfaces/catch_interfaces_reporter_registry.cpp',
'interfaces/catch_interfaces_testcase.cpp',
'internal/catch_assertion_handler.cpp',
'internal/catch_case_insensitive_comparisons.cpp',
'internal/catch_clara.cpp',
'internal/catch_commandline.cpp',
'internal/catch_console_colour.cpp',
'internal/catch_context.cpp',
'internal/catch_debug_console.cpp',
'internal/catch_debugger.cpp',
'internal/catch_decomposer.cpp',
'internal/catch_enforce.cpp',
'internal/catch_enum_values_registry.cpp',
'internal/catch_errno_guard.cpp',
'internal/catch_exception_translator_registry.cpp',
'internal/catch_fatal_condition_handler.cpp',
'internal/catch_floating_point_helpers.cpp',
'internal/catch_istream.cpp',
'internal/catch_lazy_expr.cpp',
'internal/catch_leak_detector.cpp',
'internal/catch_list.cpp',
'internal/catch_message_info.cpp',
'internal/catch_output_redirect.cpp',
'internal/catch_polyfills.cpp',
'internal/catch_random_number_generator.cpp',
'internal/catch_random_seed_generation.cpp',
'internal/catch_reporter_registry.cpp',
'internal/catch_reporter_spec_parser.cpp',
'internal/catch_result_type.cpp',
'internal/catch_reusable_string_stream.cpp',
'internal/catch_run_context.cpp',
'internal/catch_section.cpp',
'internal/catch_singletons.cpp',
'internal/catch_source_line_info.cpp',
'internal/catch_startup_exception_registry.cpp',
'internal/catch_stdstreams.cpp',
'internal/catch_string_manip.cpp',
'internal/catch_stringref.cpp',
'internal/catch_tag_alias_registry.cpp',
'internal/catch_test_case_info_hasher.cpp',
'internal/catch_test_case_registry_impl.cpp',
'internal/catch_test_case_tracker.cpp',
'internal/catch_test_registry.cpp',
'internal/catch_test_spec_parser.cpp',
'internal/catch_textflow.cpp',
'internal/catch_uncaught_exceptions.cpp',
'internal/catch_wildcard_pattern.cpp',
'internal/catch_xmlwriter.cpp',
'matchers/catch_matchers.cpp',
'matchers/catch_matchers_container_properties.cpp',
'matchers/catch_matchers_exception.cpp',
'matchers/catch_matchers_floating_point.cpp',
'matchers/catch_matchers_predicate.cpp',
'matchers/catch_matchers_quantifiers.cpp',
'matchers/catch_matchers_string.cpp',
'matchers/catch_matchers_templated.cpp',
'matchers/internal/catch_matchers_impl.cpp',
'catch_approx.cpp',
'catch_assertion_result.cpp',
'catch_config.cpp',
'catch_get_random_seed.cpp',
'catch_message.cpp',
'catch_registry_hub.cpp',
'catch_session.cpp',
'catch_tag_alias_autoregistrar.cpp',
'catch_test_case_info.cpp',
'catch_test_spec.cpp',
'catch_timer.cpp',
'catch_tostring.cpp',
'catch_totals.cpp',
'catch_version.cpp',
)
reporter_headers = [
'reporters/catch_reporter_automake.hpp',
'reporters/catch_reporter_common_base.hpp',
'reporters/catch_reporter_compact.hpp',
'reporters/catch_reporter_console.hpp',
'reporters/catch_reporter_cumulative_base.hpp',
'reporters/catch_reporter_event_listener.hpp',
'reporters/catch_reporter_helpers.hpp',
'reporters/catch_reporter_junit.hpp',
'reporters/catch_reporter_multi.hpp',
'reporters/catch_reporter_registrars.hpp',
'reporters/catch_reporter_sonarqube.hpp',
'reporters/catch_reporter_streaming_base.hpp',
'reporters/catch_reporter_tap.hpp',
'reporters/catch_reporter_teamcity.hpp',
'reporters/catch_reporter_xml.hpp',
'reporters/catch_reporters_all.hpp',
]
reporter_sources = files(
'reporters/catch_reporter_automake.cpp',
'reporters/catch_reporter_common_base.cpp',
'reporters/catch_reporter_compact.cpp',
'reporters/catch_reporter_console.cpp',
'reporters/catch_reporter_cumulative_base.cpp',
'reporters/catch_reporter_event_listener.cpp',
'reporters/catch_reporter_helpers.cpp',
'reporters/catch_reporter_junit.cpp',
'reporters/catch_reporter_multi.cpp',
'reporters/catch_reporter_registrars.cpp',
'reporters/catch_reporter_sonarqube.cpp',
'reporters/catch_reporter_streaming_base.cpp',
'reporters/catch_reporter_tap.cpp',
'reporters/catch_reporter_teamcity.cpp',
'reporters/catch_reporter_xml.cpp',
)
headers = benchmark_headers + internal_headers + reporter_headers
sources = benchmark_sources + internal_sources + reporter_sources
# The headers must be installed with their full paths, which meson
# v0.63 supports using `preserve_path` for `install_headers`. We'd
# like to be compatible with Debian 11 (current stable) which has
# meson v0.56.2. Instead, let's use the technique from
# https://github.com/mesonbuild/meson/issues/14 with some tweaks to
# make it compatible with newer meson.
include_subdir = 'catch2'
foreach file : headers
file_path = file.split('/')
folder = ''
foreach path : file_path
if path != file_path[-1]
folder = folder / path
endif
endforeach
install_headers(file, subdir: join_paths(include_subdir, folder))
endforeach
catch2 = static_library(
'Catch2',
sources,
include_directories: '..',
install: true,
)
catch2_dep = declare_dependency(
link_with: catch2,
include_directories: '..',
)
pkg.generate(
catch2,
filebase: 'catch2',
description: 'A modern, C++-native, test framework for C++14 and above',
url: 'https://github.com/catchorg/Catch2',
)
catch2_with_main = static_library(
'Catch2Main',
'internal/catch_main.cpp',
link_with: catch2,
include_directories: '..',
install: true,
)
catch2_with_main_dep = declare_dependency(
link_with: [catch2, catch2_with_main],
include_directories: '..',
)
pkg.generate(
catch2_with_main,
filebase: 'catch2-with-main',
description: 'A modern, C++-native, test framework for C++14 and above (links in default main)',
requires: 'catch2 = ' + meson.project_version(),
)

View File

@ -7,6 +7,7 @@
// SPDX-License-Identifier: BSL-1.0
#include <catch2/reporters/catch_reporter_compact.hpp>
#include <catch2/catch_get_random_seed.hpp>
#include <catch2/catch_test_spec.hpp>
#include <catch2/reporters/catch_reporter_helpers.hpp>
#include <catch2/interfaces/catch_interfaces_config.hpp>
@ -261,7 +262,7 @@ private:
<< serializeFilters( m_config->getTestsOrTags() )
<< '\n';
}
m_stream << "RNG seed: " << m_config->rngSeed() << '\n';
m_stream << "RNG seed: " << getSeed() << '\n';
}
void CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {

View File

@ -19,6 +19,7 @@
#include <catch2/internal/catch_console_width.hpp>
#include <catch2/reporters/catch_reporter_helpers.hpp>
#include <catch2/internal/catch_move_and_forward.hpp>
#include <catch2/catch_get_random_seed.hpp>
#include <cstdio>
@ -500,7 +501,7 @@ void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
m_stream << m_colour->guardColour( Colour::BrightYellow ) << "Filters: "
<< serializeFilters( m_config->getTestsOrTags() ) << '\n';
}
m_stream << "Randomness seeded to: " << m_config->rngSeed() << '\n';
m_stream << "Randomness seeded to: " << getSeed() << '\n';
}
void ConsoleReporter::lazyPrint() {

View File

@ -146,6 +146,12 @@ include(CTest)
add_executable(SelfTest ${TEST_SOURCES})
target_link_libraries(SelfTest PRIVATE Catch2WithMain)
if (BUILD_SHARED_LIBS AND WIN32)
add_custom_command(TARGET SelfTest PRE_LINK
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:Catch2>
$<TARGET_FILE:Catch2WithMain> $<TARGET_FILE_DIR:SelfTest>
)
endif()
if (CATCH_ENABLE_COVERAGE)
set(ENABLE_COVERAGE ON CACHE BOOL "Enable coverage build." FORCE)

View File

@ -2,7 +2,7 @@
# Build extra tests.
#
cmake_minimum_required( VERSION 3.5 )
cmake_minimum_required( VERSION 3.10 )
project( Catch2ExtraTests LANGUAGES CXX )

71
tests/meson.build Normal file
View File

@ -0,0 +1,71 @@
# Copyright Catch2 Authors
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# https://www.boost.org/LICENSE_1_0.txt)
# SPDX-License-Identifier: BSL-1.0
# define the sources of the self test
# Please keep these ordered alphabetically
self_test_sources = files(
'SelfTest/IntrospectiveTests/Clara.tests.cpp',
'SelfTest/IntrospectiveTests/CmdLine.tests.cpp',
'SelfTest/IntrospectiveTests/CmdLineHelpers.tests.cpp',
'SelfTest/IntrospectiveTests/ColourImpl.tests.cpp',
'SelfTest/IntrospectiveTests/Details.tests.cpp',
'SelfTest/IntrospectiveTests/FloatingPoint.tests.cpp',
'SelfTest/IntrospectiveTests/GeneratorsImpl.tests.cpp',
'SelfTest/IntrospectiveTests/InternalBenchmark.tests.cpp',
'SelfTest/IntrospectiveTests/PartTracker.tests.cpp',
'SelfTest/IntrospectiveTests/RandomNumberGeneration.tests.cpp',
'SelfTest/IntrospectiveTests/Reporters.tests.cpp',
'SelfTest/IntrospectiveTests/Sharding.tests.cpp',
'SelfTest/IntrospectiveTests/Stream.tests.cpp',
'SelfTest/IntrospectiveTests/String.tests.cpp',
'SelfTest/IntrospectiveTests/StringManip.tests.cpp',
'SelfTest/IntrospectiveTests/Tag.tests.cpp',
'SelfTest/IntrospectiveTests/TestCaseInfoHasher.tests.cpp',
'SelfTest/IntrospectiveTests/TestSpecParser.tests.cpp',
'SelfTest/IntrospectiveTests/TextFlow.tests.cpp',
'SelfTest/IntrospectiveTests/ToString.tests.cpp',
'SelfTest/IntrospectiveTests/UniquePtr.tests.cpp',
'SelfTest/IntrospectiveTests/Xml.tests.cpp',
'SelfTest/TestRegistrations.cpp',
'SelfTest/TimingTests/Sleep.tests.cpp',
'SelfTest/UsageTests/Approx.tests.cpp',
'SelfTest/UsageTests/BDD.tests.cpp',
'SelfTest/UsageTests/Benchmark.tests.cpp',
'SelfTest/UsageTests/Class.tests.cpp',
'SelfTest/UsageTests/Compilation.tests.cpp',
'SelfTest/UsageTests/Condition.tests.cpp',
'SelfTest/UsageTests/Decomposition.tests.cpp',
'SelfTest/UsageTests/EnumToString.tests.cpp',
'SelfTest/UsageTests/Exception.tests.cpp',
'SelfTest/UsageTests/Generators.tests.cpp',
'SelfTest/UsageTests/Matchers.tests.cpp',
'SelfTest/UsageTests/MatchersRanges.tests.cpp',
'SelfTest/UsageTests/Message.tests.cpp',
'SelfTest/UsageTests/Misc.tests.cpp',
'SelfTest/UsageTests/ToStringByte.tests.cpp',
'SelfTest/UsageTests/ToStringChrono.tests.cpp',
'SelfTest/UsageTests/ToStringGeneral.tests.cpp',
'SelfTest/UsageTests/ToStringOptional.tests.cpp',
'SelfTest/UsageTests/ToStringPair.tests.cpp',
'SelfTest/UsageTests/ToStringTuple.tests.cpp',
'SelfTest/UsageTests/ToStringVariant.tests.cpp',
'SelfTest/UsageTests/ToStringVector.tests.cpp',
'SelfTest/UsageTests/ToStringWhich.tests.cpp',
'SelfTest/UsageTests/Tricky.tests.cpp',
'SelfTest/UsageTests/VariadicMacros.tests.cpp',
)
# This isn't as good as the CMake tests, but it proves that we've
# actually put something in the library files.
self_test = executable(
'SelfTest',
self_test_sources,
include_directories: '../src',
link_with: [catch2_with_main, catch2],
)
test('SelfTest', self_test)

View File

@ -120,7 +120,8 @@ def verify_convenience_header(folder):
# 4) Are all required headers present?
file_incs_set = set(file_incs)
for include in target_includes:
if include not in file_incs_set:
if (include not in file_incs_set and
include != 'catch2/internal/catch_windows_h_proxy.hpp'):
errors_found = True
print("'{}': missing include '{}'".format(header_name, include))

View File

@ -108,6 +108,7 @@ def generate_cpp():
with open(output_cpp, mode='w', encoding='utf-8') as cpp:
cpp.write(formatted_file_header(Version()))
cpp.write('\n#include "catch_amalgamated.hpp"\n')
concatenate_file(cpp, os.path.join(root_path, 'catch2/internal/catch_windows_h_proxy.hpp'), False)
for file in cpp_files:
concatenate_file(cpp, file, False)
print('Concatenated {} cpp files'.format(len(cpp_files)))

View File

@ -15,6 +15,7 @@ versionPath = os.path.join( rootPath, "catch_version.cpp" )
definePath = os.path.join(rootPath, 'catch_version_macros.hpp')
readmePath = os.path.join( catchPath, "README.md" )
cmakePath = os.path.join(catchPath, 'CMakeLists.txt')
mesonPath = os.path.join(catchPath, 'meson.build')
class Version:
def __init__(self):
@ -89,6 +90,16 @@ def updateCmakeFile(version):
file.write(replacementRegex.sub(replacement, line))
def updateMesonFile(version):
with open(mesonPath, 'rb') as file:
lines = file.readlines()
replacementRegex = re.compile(b'''version\s*:\s*'(\\d+.\\d+.\\d+)', # CML version placeholder, don't delete''')
replacement = '''version: '{0}', # CML version placeholder, don't delete'''.format(version.getVersionString()).encode('ascii')
with open(mesonPath, 'wb') as file:
for line in lines:
file.write(replacementRegex.sub(replacement, line))
def updateVersionDefine(version):
# First member of the tuple is the compiled regex object, the second is replacement if it matches
replacementRegexes = [(re.compile(b'#define CATCH_VERSION_MAJOR \\d+'),'#define CATCH_VERSION_MAJOR {}'.format(version.majorVersion).encode('ascii')),
@ -132,4 +143,5 @@ def performUpdates(version):
generateAmalgamatedFiles.generate_cpp()
updateCmakeFile(version)
updateMesonFile(version)
updateDocumentationVersionPlaceholders(version)