提交 ce1d5a5e authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

Update Catch to 1.7.2

上级 93f65784
## Description
<!--
If your issue is a bugreport, this means describing what you did,
what did you want to happen and what actually did happen.
If your issue is a feature request, describe the feature and why do you
want it.
-->
### Steps to reproduce
<!--
This is only relevant for bug reports, but if you do have one,
please provide a minimal set of steps to reproduce the problem.
Usually this means providing a small and self-contained code using Catch
and specifying compiler flags/tools used if relevant.
-->
### Extra information
<!--
Fill in any extra information that might be important for your issue.
If your issue is a bugreport, definitely fill out at least the following.
-->
* Catch version: **v42.42.42**
* Operating System: **Joe's discount operating system**
* Compiler+version: **Hidden Dragon v1.2.3**
<!--
Please do not submit pull requests changing the `version.hpp`
or the single-include `catch.hpp` file, these are changed
only when a new release is made.
-->
## Description
<!--
Describe the what and the why of your pull request. Remember that these two
are usually a bit different. As an example, if you have made various changes
to decrease the number of new strings allocated, thats what. The why probably
was that you have a large set of tests and found that this speeds them up.
-->
## GitHub Issues
<!--
If this PR was motivated by some existing issues, reference them here.
If it is a simple bug-fix, please also add a line like 'Closes #123'
to your commit message, so that it is automatically closed.
If it is not, don't, as it might take several iterations for a feature
to be done properly. If in doubt, leave it open and reference it in the
PR itself, so that maintainers can decide.
-->
language: cpp language: cpp
sudo: false sudo: false
cache:
ccache: true
directories:
- $HOME/.ccache
env:
global:
- USE_CCACHE=1
- CCACHE_COMPRESS=1
- CCACHE_MAXSIZE=200M
- CCACHE_CPP2=1
matrix: matrix:
include: include:
# 1/ Linux Clang Builds # 1/ Linux Clang Builds
- os: linux
compiler: clang
addons: &clang34
apt:
sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test']
packages: ['clang']
env: COMPILER='clang++' BUILD_TYPE='Release' CPP11=0
- os: linux
compiler: clang
addons: *clang34
env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0
- os: linux - os: linux
compiler: clang compiler: clang
addons: &clang35 addons: &clang35
apt: apt:
sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test']
packages: ['clang-3.5'] packages: ['clang-3.5']
env: COMPILER='ccache clang++-3.5' BUILD_TYPE='Release' env: COMPILER='clang++-3.5' BUILD_TYPE='Release' CPP11=0
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang35 addons: *clang35
env: COMPILER='ccache clang++-3.5' BUILD_TYPE='Debug' env: COMPILER='clang++-3.5' BUILD_TYPE='Debug' CPP11=0
- os: linux - os: linux
...@@ -38,12 +38,12 @@ matrix: ...@@ -38,12 +38,12 @@ matrix:
apt: apt:
sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test']
packages: ['clang-3.6'] packages: ['clang-3.6']
env: COMPILER='ccache clang++-3.6' BUILD_TYPE='Release' env: COMPILER='clang++-3.6' BUILD_TYPE='Release' CPP11=0
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang36 addons: *clang36
env: COMPILER='ccache clang++-3.6' BUILD_TYPE='Debug' env: COMPILER='clang++-3.6' BUILD_TYPE='Debug' CPP11=0
- os: linux - os: linux
...@@ -52,12 +52,12 @@ matrix: ...@@ -52,12 +52,12 @@ matrix:
apt: apt:
sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test']
packages: ['clang-3.7'] packages: ['clang-3.7']
env: COMPILER='ccache clang++-3.7' BUILD_TYPE='Release' env: COMPILER='clang++-3.7' BUILD_TYPE='Release' CPP11=0
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang37 addons: *clang37
env: COMPILER='ccache clang++-3.7' BUILD_TYPE='Debug' env: COMPILER='clang++-3.7' BUILD_TYPE='Debug' CPP11=0
- os: linux - os: linux
...@@ -66,27 +66,55 @@ matrix: ...@@ -66,27 +66,55 @@ matrix:
apt: apt:
sources: ['llvm-toolchain-precise-3.8', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise-3.8', 'ubuntu-toolchain-r-test']
packages: ['clang-3.8'] packages: ['clang-3.8']
env: COMPILER='ccache clang++-3.8' BUILD_TYPE='Release' env: COMPILER='clang++-3.8' BUILD_TYPE='Release' CPP11=0
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang38 addons: *clang38
env: COMPILER='ccache clang++-3.8' BUILD_TYPE='Debug' env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' CPP11=0
# 2/ Linux GCC Builds # 2/ Linux GCC Builds
- os: linux
compiler: gcc
addons: &gcc44
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.4']
env: COMPILER='g++-4.4' BUILD_TYPE='Release' CPP11=0
- os: linux
compiler: gcc
addons: *gcc44
env: COMPILER='g++-4.4' BUILD_TYPE='Debug' CPP11=0
- os: linux
compiler: gcc
addons: &gcc47
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.7']
env: COMPILER='g++-4.7' BUILD_TYPE='Release' CPP11=0
- os: linux
compiler: gcc
addons: *gcc47
env: COMPILER='g++-4.7' BUILD_TYPE='Debug' CPP11=0
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: &gcc48 addons: &gcc48
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.8'] packages: ['g++-4.8']
env: COMPILER='ccache g++-4.8' BUILD_TYPE='Release' env: COMPILER='g++-4.8' BUILD_TYPE='Release' CPP11=0
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc48 addons: *gcc48
env: COMPILER='ccache g++-4.8' BUILD_TYPE='Debug' env: COMPILER='g++-4.8' BUILD_TYPE='Debug' CPP11=0
- os: linux - os: linux
...@@ -95,12 +123,12 @@ matrix: ...@@ -95,12 +123,12 @@ matrix:
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.9'] packages: ['g++-4.9']
env: COMPILER='ccache g++-4.9' BUILD_TYPE='Release' env: COMPILER='g++-4.9' BUILD_TYPE='Release' CPP11=0
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc49 addons: *gcc49
env: COMPILER='ccache g++-4.9' BUILD_TYPE='Debug' env: COMPILER='g++-4.9' BUILD_TYPE='Debug' CPP11=0
- os: linux - os: linux
...@@ -109,34 +137,76 @@ matrix: ...@@ -109,34 +137,76 @@ matrix:
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-5'] packages: ['g++-5']
env: COMPILER='ccache g++-5' BUILD_TYPE='Release' env: COMPILER='g++-5' BUILD_TYPE='Release' CPP11=0
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc5 addons: *gcc5
env: COMPILER='ccache g++-5' BUILD_TYPE='Debug' env: COMPILER='g++-5' BUILD_TYPE='Debug' CPP11=0
- os: linux
compiler: gcc
addons: &gcc6
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-6']
env: COMPILER='g++-6' BUILD_TYPE='Release' CPP11=0
- os: linux
compiler: gcc
addons: *gcc6
env: COMPILER='g++-6' BUILD_TYPE='Debug' CPP11=0
# 3a/ Linux C++11 GCC builds
- os: linux
compiler: gcc
addons: &gcc48
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.8']
env: COMPILER='g++-4.8' BUILD_TYPE='Release' CPP11=1
- os: linux
compiler: gcc
addons: *gcc48
env: COMPILER='g++-4.8' BUILD_TYPE='Debug' CPP11=1
# 3b/ Linux C++11 Clang builds
- os: linux
compiler: clang
addons: &clang38
apt:
sources: ['llvm-toolchain-precise-3.8', 'ubuntu-toolchain-r-test']
packages: ['clang-3.8']
env: COMPILER='clang++-3.8' BUILD_TYPE='Release' CPP11=1
- os: linux
compiler: clang
addons: *clang38
env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' CPP11=1
# 3/ OSX Clang Builds # 4/ OSX Clang Builds
- os: osx - os: osx
osx_image: xcode7 osx_image: xcode7.3
compiler: clang compiler: clang
env: COMPILER='ccache clang++' BUILD_TYPE='Debug' env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0
- os: osx - os: osx
osx_image: xcode7 osx_image: xcode7.3
compiler: clang compiler: clang
env: COMPILER='ccache clang++' BUILD_TYPE='Release' env: COMPILER='clang++' BUILD_TYPE='Release' CPP11=0
- os: osx - os: osx
osx_image: xcode8 osx_image: xcode8
compiler: clang compiler: clang
env: COMPILER='ccache clang++' BUILD_TYPE='Debug' env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0
- os: osx - os: osx
osx_image: xcode8 osx_image: xcode8
compiler: clang compiler: clang
env: COMPILER='ccache clang++' BUILD_TYPE='Release' env: COMPILER='clang++' BUILD_TYPE='Release' CPP11=0
install: install:
...@@ -145,17 +215,16 @@ install: ...@@ -145,17 +215,16 @@ install:
- | - |
if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then
CMAKE_URL="http://www.cmake.org/files/v3.3/cmake-3.3.2-Linux-x86_64.tar.gz" CMAKE_URL="http://www.cmake.org/files/v3.3/cmake-3.3.2-Linux-x86_64.tar.gz"
mkdir cmake && travis_retry wget --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake mkdir cmake && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake
export PATH=${DEPS_DIR}/cmake/bin:${PATH} export PATH=${DEPS_DIR}/cmake/bin:${PATH}
elif [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then elif [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then
which cmake || brew install cmake which cmake || brew install cmake
which ccache || brew install ccache
fi fi
before_script: before_script:
- export CXX=${COMPILER} - export CXX=${COMPILER}
- cd ${TRAVIS_BUILD_DIR} - cd ${TRAVIS_BUILD_DIR}
- cmake -H. -BBuild -DCMAKE_BUILD_TYPE=${BUILD_TYPE} - cmake -H. -BBuild -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -Wdev -DUSE_CPP11=${CPP11}
- cd Build - cd Build
script: script:
......
cmake_minimum_required(VERSION 2.8) cmake_minimum_required(VERSION 3.0)
project(CatchSelfTest) project(CatchSelfTest)
...@@ -7,36 +7,74 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON) ...@@ -7,36 +7,74 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
# define some folders # define some folders
set(CATCH_DIR ${CMAKE_CURRENT_SOURCE_DIR}) set(CATCH_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(SELF_TEST_DIR ${CATCH_DIR}/projects/SelfTest) set(SELF_TEST_DIR ${CATCH_DIR}/projects/SelfTest)
set(BENCHMARK_DIR ${CATCH_DIR}/projects/Benchmark)
set(HEADER_DIR ${CATCH_DIR}/include) set(HEADER_DIR ${CATCH_DIR}/include)
if(USE_CPP11) if(USE_CPP11)
## We can't turn this on by default, since it breaks on travis ## We can't turn this on by default, since it breaks on travis
message(STATUS "Enabling C++11") message(STATUS "Enabling C++11")
set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}") set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
elseif(USE_CPP14)
message(STATUS "Enabling C++14")
set(CMAKE_CXX_FLAGS "-std=c++14 ${CMAKE_CXX_FLAGS}")
endif() endif()
#checks that the given hard-coded list contains all headers + sources in the given folder
function(CheckFileList LIST_VAR FOLDER)
set(MESSAGE " should be added to the variable ${LIST_VAR}")
set(MESSAGE "${MESSAGE} in ${CMAKE_CURRENT_LIST_FILE}\n")
file(GLOB GLOBBED_LIST "${FOLDER}/*.cpp"
"${FOLDER}/*.hpp"
"${FOLDER}/*.h")
list(REMOVE_ITEM GLOBBED_LIST ${${LIST_VAR}})
foreach(EXTRA_ITEM ${GLOBBED_LIST})
string(REPLACE "${CATCH_DIR}/" "" RELATIVE_FILE_NAME "${EXTRA_ITEM}")
message(AUTHOR_WARNING "The file \"${RELATIVE_FILE_NAME}\"${MESSAGE}")
endforeach()
endfunction()
function(CheckFileListRec LIST_VAR FOLDER)
set(MESSAGE " should be added to the variable ${LIST_VAR}")
set(MESSAGE "${MESSAGE} in ${CMAKE_CURRENT_LIST_FILE}\n")
file(GLOB_RECURSE GLOBBED_LIST "${FOLDER}/*.cpp"
"${FOLDER}/*.hpp"
"${FOLDER}/*.h")
list(REMOVE_ITEM GLOBBED_LIST ${${LIST_VAR}})
foreach(EXTRA_ITEM ${GLOBBED_LIST})
string(REPLACE "${CATCH_DIR}/" "" RELATIVE_FILE_NAME "${EXTRA_ITEM}")
message(AUTHOR_WARNING "The file \"${RELATIVE_FILE_NAME}\"${MESSAGE}")
endforeach()
endfunction()
# define the sources of the self test # define the sources of the self test
# Please keep these ordered alphabetically
set(TEST_SOURCES set(TEST_SOURCES
${SELF_TEST_DIR}/ApproxTests.cpp ${SELF_TEST_DIR}/ApproxTests.cpp
${SELF_TEST_DIR}/BDDTests.cpp ${SELF_TEST_DIR}/BDDTests.cpp
${SELF_TEST_DIR}/ClassTests.cpp ${SELF_TEST_DIR}/ClassTests.cpp
${SELF_TEST_DIR}/CmdLineTests.cpp
${SELF_TEST_DIR}/CompilationTests.cpp
${SELF_TEST_DIR}/ConditionTests.cpp ${SELF_TEST_DIR}/ConditionTests.cpp
${SELF_TEST_DIR}/EnumToString.cpp
${SELF_TEST_DIR}/ExceptionTests.cpp ${SELF_TEST_DIR}/ExceptionTests.cpp
${SELF_TEST_DIR}/GeneratorTests.cpp ${SELF_TEST_DIR}/GeneratorTests.cpp
${SELF_TEST_DIR}/MessageTests.cpp ${SELF_TEST_DIR}/MessageTests.cpp
${SELF_TEST_DIR}/MiscTests.cpp ${SELF_TEST_DIR}/MiscTests.cpp
${SELF_TEST_DIR}/PartTrackerTests.cpp ${SELF_TEST_DIR}/PartTrackerTests.cpp
${SELF_TEST_DIR}/TagAliasTests.cpp
${SELF_TEST_DIR}/TestMain.cpp ${SELF_TEST_DIR}/TestMain.cpp
${SELF_TEST_DIR}/TrickyTests.cpp ${SELF_TEST_DIR}/ToStringGeneralTests.cpp
${SELF_TEST_DIR}/VariadicMacrosTests.cpp
${SELF_TEST_DIR}/EnumToString.cpp
${SELF_TEST_DIR}/ToStringPair.cpp ${SELF_TEST_DIR}/ToStringPair.cpp
${SELF_TEST_DIR}/ToStringTuple.cpp
${SELF_TEST_DIR}/ToStringVector.cpp ${SELF_TEST_DIR}/ToStringVector.cpp
${SELF_TEST_DIR}/ToStringWhich.cpp ${SELF_TEST_DIR}/ToStringWhich.cpp
${SELF_TEST_DIR}/ToStringTuple.cpp ${SELF_TEST_DIR}/TrickyTests.cpp
${SELF_TEST_DIR}/CmdLineTests.cpp ${SELF_TEST_DIR}/VariadicMacrosTests.cpp
${SELF_TEST_DIR}/TagAliasTests.cpp
) )
CheckFileList(TEST_SOURCES ${SELF_TEST_DIR})
# A set of impl files that just #include a single header
# Please keep these ordered alphabetically
set(IMPL_SOURCES set(IMPL_SOURCES
${SELF_TEST_DIR}/SurrogateCpps/catch_common.cpp ${SELF_TEST_DIR}/SurrogateCpps/catch_common.cpp
${SELF_TEST_DIR}/SurrogateCpps/catch_console_colour.cpp ${SELF_TEST_DIR}/SurrogateCpps/catch_console_colour.cpp
...@@ -56,13 +94,29 @@ set(IMPL_SOURCES ...@@ -56,13 +94,29 @@ set(IMPL_SOURCES
${SELF_TEST_DIR}/SurrogateCpps/catch_streambuf.cpp ${SELF_TEST_DIR}/SurrogateCpps/catch_streambuf.cpp
${SELF_TEST_DIR}/SurrogateCpps/catch_test_spec.cpp ${SELF_TEST_DIR}/SurrogateCpps/catch_test_spec.cpp
${SELF_TEST_DIR}/SurrogateCpps/catch_xmlwriter.cpp ${SELF_TEST_DIR}/SurrogateCpps/catch_xmlwriter.cpp
${SELF_TEST_DIR}/SurrogateCpps/catch_test_case_tracker.cpp
) )
CheckFileList(IMPL_SOURCES ${SELF_TEST_DIR}/SurrogateCpps)
# Specify the headers, too, so CLion recognises them as project files
set(HEADERS # Please keep these ordered alphabetically
set(TOP_LEVEL_HEADERS
${HEADER_DIR}/catch.hpp ${HEADER_DIR}/catch.hpp
${HEADER_DIR}/catch_session.hpp ${HEADER_DIR}/catch_session.hpp
${HEADER_DIR}/catch_with_main.hpp ${HEADER_DIR}/catch_with_main.hpp
)
CheckFileList(TOP_LEVEL_HEADERS ${HEADER_DIR})
# Please keep these ordered alphabetically
set(EXTERNAL_HEADERS
${HEADER_DIR}/external/clara.h
${HEADER_DIR}/external/tbc_text_format.h
)
CheckFileList(EXTERNAL_HEADERS ${HEADER_DIR}/external)
# Please keep these ordered alphabetically
set(INTERNAL_HEADERS
${HEADER_DIR}/internal/catch_approx.hpp ${HEADER_DIR}/internal/catch_approx.hpp
${HEADER_DIR}/internal/catch_assertionresult.h ${HEADER_DIR}/internal/catch_assertionresult.h
${HEADER_DIR}/internal/catch_assertionresult.hpp ${HEADER_DIR}/internal/catch_assertionresult.hpp
...@@ -141,12 +195,17 @@ set(HEADERS ...@@ -141,12 +195,17 @@ set(HEADERS
${HEADER_DIR}/internal/catch_tostring.h ${HEADER_DIR}/internal/catch_tostring.h
${HEADER_DIR}/internal/catch_tostring.hpp ${HEADER_DIR}/internal/catch_tostring.hpp
${HEADER_DIR}/internal/catch_totals.hpp ${HEADER_DIR}/internal/catch_totals.hpp
${HEADER_DIR}/internal/catch_type_traits.hpp
${HEADER_DIR}/internal/catch_version.h ${HEADER_DIR}/internal/catch_version.h
${HEADER_DIR}/internal/catch_version.hpp ${HEADER_DIR}/internal/catch_version.hpp
${HEADER_DIR}/internal/catch_wildcard_pattern.hpp ${HEADER_DIR}/internal/catch_wildcard_pattern.hpp
${HEADER_DIR}/internal/catch_windows_h_proxy.h
${HEADER_DIR}/internal/catch_xmlwriter.hpp ${HEADER_DIR}/internal/catch_xmlwriter.hpp
${HEADER_DIR}/external/clara.h )
${HEADER_DIR}/external/tbc_text_format.h CheckFileList(INTERNAL_HEADERS ${HEADER_DIR}/internal)
# Please keep these ordered alphabetically
set(REPORTER_HEADERS
${HEADER_DIR}/reporters/catch_reporter_bases.hpp ${HEADER_DIR}/reporters/catch_reporter_bases.hpp
${HEADER_DIR}/reporters/catch_reporter_compact.hpp ${HEADER_DIR}/reporters/catch_reporter_compact.hpp
${HEADER_DIR}/reporters/catch_reporter_console.hpp ${HEADER_DIR}/reporters/catch_reporter_console.hpp
...@@ -155,13 +214,43 @@ set(HEADERS ...@@ -155,13 +214,43 @@ set(HEADERS
${HEADER_DIR}/reporters/catch_reporter_teamcity.hpp ${HEADER_DIR}/reporters/catch_reporter_teamcity.hpp
${HEADER_DIR}/reporters/catch_reporter_xml.hpp ${HEADER_DIR}/reporters/catch_reporter_xml.hpp
) )
CheckFileList(REPORTER_HEADERS ${HEADER_DIR}/reporters)
# Specify the headers, too, so CLion recognises them as project files
set(HEADERS
${TOP_LEVEL_HEADERS}
${EXTERNAL_HEADERS}
${INTERNAL_HEADERS}
${REPORTER_HEADERS}
)
set(BENCH_SOURCES
${BENCHMARK_DIR}/BenchMain.cpp
${BENCHMARK_DIR}/StringificationBench.cpp
)
CheckFileList(BENCH_SOURCES ${BENCHMARK_DIR})
# Provide some groupings for IDEs
SOURCE_GROUP("Tests" FILES ${TEST_SOURCES}) SOURCE_GROUP("Tests" FILES ${TEST_SOURCES})
SOURCE_GROUP("Surrogates" FILES ${IMPL_SOURCES}) SOURCE_GROUP("Surrogates" FILES ${IMPL_SOURCES})
SOURCE_GROUP("Benchmarks" FILES ${BENCH_SOURCES})
# configure the executable # configure the executable
include_directories(${HEADER_DIR}) include_directories(${HEADER_DIR})
add_executable(SelfTest ${TEST_SOURCES} ${IMPL_SOURCES} ${HEADERS}) add_executable(SelfTest ${TEST_SOURCES} ${IMPL_SOURCES} ${HEADERS})
add_executable(Benchmark ${BENCH_SOURCES} ${HEADERS})
# Add desired warnings
if ( CMAKE_CXX_COMPILER_ID MATCHES "Clang|AppleClang|GNU" )
target_compile_options( SelfTest PRIVATE -Wall -Wextra )
target_compile_options( Benchmark PRIVATE -Wall -Wextra )
endif()
if ( CMAKE_CXX_COMPILER_ID MATCHES "MSVC" )
target_compile_options( SelfTest PRIVATE /W4 )
target_compile_options( Benchmark PRIVATE /W4 )
endif()
# configure unit tests via CTest # configure unit tests via CTest
enable_testing() enable_testing()
...@@ -172,3 +261,5 @@ set_tests_properties(ListTests PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ test c ...@@ -172,3 +261,5 @@ set_tests_properties(ListTests PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ test c
add_test(NAME ListTags COMMAND SelfTest --list-tags) add_test(NAME ListTags COMMAND SelfTest --list-tags)
set_tests_properties(ListTags PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ tags") set_tests_properties(ListTags PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ tags")
install(DIRECTORY "single_include/" DESTINATION "include/catch/")
![catch logo](catch-logo-small.png) ![catch logo](catch-logo-small.png)
*v1.6.0* *v1.7.2*
Build status (on Travis CI) [![Build Status](https://travis-ci.org/philsquared/Catch.svg?branch=master)](https://travis-ci.org/philsquared/Catch) Build status (on Travis CI) [![Build Status](https://travis-ci.org/philsquared/Catch.svg?branch=master)](https://travis-ci.org/philsquared/Catch)
<a href="https://raw.githubusercontent.com/philsquared/Catch/master/single_include/catch.hpp">The latest, single header, version can be downloaded directly using this link</a> <a href="https://github.com/philsquared/Catch/releases/download/v1.7.2/catch.hpp">The latest, single header, version can be downloaded directly using this link</a>
## What's the Catch? ## What's the Catch?
...@@ -20,3 +20,4 @@ This documentation comprises these three parts: ...@@ -20,3 +20,4 @@ This documentation comprises these three parts:
## More ## More
* Issues and bugs can be raised on the [Issue tracker on GitHub](https://github.com/philsquared/Catch/issues) * Issues and bugs can be raised on the [Issue tracker on GitHub](https://github.com/philsquared/Catch/issues)
* For discussion or questions please use [the dedicated Google Groups forum](https://groups.google.com/forum/?fromgroups#!forum/catch-forum) * For discussion or questions please use [the dedicated Google Groups forum](https://groups.google.com/forum/?fromgroups#!forum/catch-forum)
* See [who else is using Catch](docs/opensource-users.md)
...@@ -12,9 +12,11 @@ Before looking at this material be sure to read the [tutorial](tutorial.md) ...@@ -12,9 +12,11 @@ Before looking at this material be sure to read the [tutorial](tutorial.md)
* [Configuration](configuration.md) * [Configuration](configuration.md)
* [String Conversions](tostring.md) * [String Conversions](tostring.md)
* [Why are my tests slow to compile?](slow-compiles.md) * [Why are my tests slow to compile?](slow-compiles.md)
* [Known limitations](limitations.md)
Other Other
* [Why Catch?](why-catch.md) * [Why Catch?](why-catch.md)
* [Open Source Projects using Catch](opensource-users.md)
* [Contributing](contributing.md) * [Contributing](contributing.md)
* [Release Nodes](release-notes.md) * [Release Notes](release-notes.md)
\ No newline at end of file
...@@ -34,6 +34,15 @@ Example: ...@@ -34,6 +34,15 @@ Example:
REQUIRE_FALSE( thisReturnsFalse() ); 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 ### 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. 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.
...@@ -54,6 +63,11 @@ When dealing with very large or very small numbers it can be useful to specify a ...@@ -54,6 +63,11 @@ When dealing with very large or very small numbers it can be useful to specify a
## Exceptions ## Exceptions
* **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_ **)** * **CHECK_THROWS(** _expression_ **)**
...@@ -64,18 +78,41 @@ Expects that an exception (of any type) is be thrown during evaluation of the ex ...@@ -64,18 +78,41 @@ Expects that an exception (of any type) is be thrown during evaluation of the ex
Expects that an exception of the _specified type_ is thrown during evaluation of the expression. Expects that an exception of the _specified type_ is thrown during evaluation of the expression.
* **REQUIRE_NOTHROW(** _expression_ **)** and * **REQUIRE_THROWS_WITH(** _expression_, _string or string matcher_ **)** and
* **CHECK_NOTHROW(** _expression_ **)** * **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).
e.g.
```cpp
REQUIRE_THROWS_WITH( openThePodBayDoors(), Contains( "afraid" ) && Contains( "can't do that" ) );
REQUIRE_THROWS_WITH( dismantleHal(), "My mind is going" );
```
Expects that no exception is thrown during evaluation of the expression.
Please note that the `THROW` family of assertions expects to be passed a single expression, not a statement or series of statements. If you want to check a more complicated sequence of operations, you can use a C++11 lambda function.
```cpp
REQUIRE_NOTHROW([&](){
int i = 1;
int j = 2;
auto k = i + j;
if (k == 3) {
throw 1;
}
}());
```
## Matcher expressions ## Matcher expressions
To support Matchers a slightly different form is used. Matchers will be more fully documented elsewhere. *Note that Matchers are still at early stage development and are subject to change.* To support Matchers a slightly different form is used. Matchers will be more fully documented elsewhere. *Note that Matchers are still at early stage development and are subject to change.*
* **REQUIRE_THAT(** _lhs_, _matcher call_ **)** and * **REQUIRE_THAT(** _lhs_, _matcher expression_ **)** and
* **CHECK_THAT(** _lhs_, _matcher call_ **)** * **CHECK_THAT(** _lhs_, _matcher expression_ **)**
Currently only string matchers are implemented and consist of: `Contains`, `Equals`, `StartsWith` and `EndsWith`.
Matchers can be composed using `&&`, `||` and `!` operators.
--- ---
......
...@@ -69,7 +69,7 @@ ExternalProject_Add( ...@@ -69,7 +69,7 @@ ExternalProject_Add(
# Expose required variable (CATCH_INCLUDE_DIR) to parent scope # Expose required variable (CATCH_INCLUDE_DIR) to parent scope
ExternalProject_Get_Property(catch source_dir) ExternalProject_Get_Property(catch source_dir)
set(CATCH_INCLUDE_DIR ${source_dir}/include CACHE INTERNAL "Path to include folder for Catch") set(CATCH_INCLUDE_DIR ${source_dir}/single_include CACHE INTERNAL "Path to include folder for Catch")
``` ```
If you put it in, e.g., `${PROJECT_SRC_DIR}/${EXT_PROJECTS_DIR}/catch/`, you can use it in your project by adding the following to your root CMake file: If you put it in, e.g., `${PROJECT_SRC_DIR}/${EXT_PROJECTS_DIR}/catch/`, you can use it in your project by adding the following to your root CMake file:
......
...@@ -17,6 +17,9 @@ Click one of the followings links to take you straight to that option - or scrol ...@@ -17,6 +17,9 @@ Click one of the followings links to take you straight to that option - or scrol
<a href="#warnings"> ` -w, --warn`</a><br /> <a href="#warnings"> ` -w, --warn`</a><br />
<a href="#reporting-timings"> ` -d, --durations`</a><br /> <a href="#reporting-timings"> ` -d, --durations`</a><br />
<a href="#input-file"> ` -f, --input-file`</a><br /> <a href="#input-file"> ` -f, --input-file`</a><br />
<a href="#run-section"> ` -c, --section`</a><br />
<a href="#filenames-as-tags"> ` -#, --filenames-as-tags`</a><br />
</br> </br>
...@@ -66,6 +69,8 @@ A series of tags form an AND expression wheras a comma-separated sequence forms ...@@ -66,6 +69,8 @@ A series of tags form an AND expression wheras a comma-separated sequence forms
<pre>[one][two],[three]</pre> <pre>[one][two],[three]</pre>
This matches all tests tagged `[one]` and `[two]`, as well as all tests tagged `[three]` This matches all tests tagged `[one]` and `[two]`, as well as all tests tagged `[three]`
Test names containing special characters, such as `,` or `[` can specify them on the command line using `\`.
`\` also escapes itself.
<a id="choosing-a-reporter-to-use"></a> <a id="choosing-a-reporter-to-use"></a>
## Choosing a reporter to use ## Choosing a reporter to use
...@@ -88,7 +93,6 @@ The JUnit reporter is an xml format that follows the structure of the JUnit XML ...@@ -88,7 +93,6 @@ The JUnit reporter is an xml format that follows the structure of the JUnit XML
<pre>-b, --break</pre> <pre>-b, --break</pre>
In some IDEs (currently XCode and Visual Studio) it is possible for Catch to break into the debugger on a test failure. This can be very helpful during debug sessions - especially when there is more than one path through a particular test. In some IDEs (currently XCode and Visual Studio) it is possible for Catch to break into the debugger on a test failure. This can be very helpful during debug sessions - especially when there is more than one path through a particular test.
In addition to the command line option, ensure you have built your code with the DEBUG preprocessor symbol
<a id="showing-results-for-successful-tests"></a> <a id="showing-results-for-successful-tests"></a>
## Showing results for successful tests ## Showing results for successful tests
...@@ -215,6 +219,59 @@ In either case the actual value for the seed is printed as part of Catch's outpu ...@@ -215,6 +219,59 @@ In either case the actual value for the seed is printed as part of Catch's outpu
Prints the command line arguments to stdout Prints the command line arguments to stdout
<a id="run-section"></a>
## Specify the section to run
<pre>-s, --section &lt;section name&gt;</pre>
To limit execution to a specific section within a test case, use this option one or more times.
To narrow to sub-sections use multiple instances, where each subsequent instance specifies a deeper nesting level.
E.g. if you have:
<pre>
TEST_CASE( "Test" ) {
SECTION( "sa" ) {
SECTION( "sb" ) {
/*...*/
}
SECTION( "sc" ) {
/*...*/
}
}
SECTION( "sd" ) {
/*...*/
}
}
</pre>
Then you can run `sb` with:
<pre>./MyExe Test -c sa -c sb</pre>
Or run just `sd` with:
<pre>./MyExe Test -c sd</pre>
To run all of `sa`, including `sb` and `sc` use:
<pre>./MyExe Test -c sa</pre>
There are some limitations of this feature to be aware of:
- Code outside of sections being skipped will still be executed - e.g. any set-up code in the TEST_CASE before the
start of the first section.</br>
- At time of writing, wildcards are not supported in section names.
- If you specify a section without narrowing to a test case first then all test cases will be executed
(but only matching sections within them).
<a id="filenames-as-tags"></a>
## Filenames as tags
<pre>-#, --filenames-as-tags</pre>
When this option is used then every test is given an additional tag which is formed of the unqualified
filename it is found in, with any extension stripped, prefixed with the `#` character.
So, for example, tests within the file `~\Dev\MyProject\Ferrets.cpp` would be tagged `[#Ferrets]`.
--- ---
[Home](Readme.md) [Home](Readme.md)
# Commercial users of Catch
As well as [Open Source](opensource-users.md) users Catch is widely used within proprietary code bases too. Many companies like to keep this
information internal, and that's fine, but if you're more open it would be great if we could list the names of as
many organisations as possible that use Catch somewhere in their codebase. Enterprise environments often tend to be
far more conservative in their tool adoption - and being aware that other companies are using Catch can ease the
path in.
So if you are aware of Catch usage in your organisation, and are fairly confident there is no issue with sharing this
fact then please let us know - either directly, via a PR or [issue](https://github.com/philsquared/Catch/issues), or on the [forums](https://groups.google.com/forum/?fromgroups#!forum/catch-forum).
- Bloomberg
Catch is designed to "just work" as much as possible. For most people the only configuration needed is telling Catch which source file should host all the implementation code (```CATCH_CONFIG_MAIN```). Catch is designed to "just work" as much as possible. For most people the only configuration needed is telling Catch which source file should host all the implementation code (```CATCH_CONFIG_MAIN```).
Nonetheless there are still some occasions where finer control is needed. For these occasions Catch exposes a small set of macros for configuring how it is built. Nonetheless there are still some occasions where finer control is needed. For these occasions Catch exposes a set of macros for configuring how it is built.
# main()/ implementation # main()/ implementation
...@@ -62,6 +62,7 @@ This can be useful on certain platforms that do not provide ```std::cout``` and ...@@ -62,6 +62,7 @@ This can be useful on certain platforms that do not provide ```std::cout``` and
CATCH_CONFIG_CPP11_OVERRIDE // CATCH_OVERRIDE expands to override (for virtual function implementations) CATCH_CONFIG_CPP11_OVERRIDE // CATCH_OVERRIDE expands to override (for virtual function implementations)
CATCH_CONFIG_CPP11_UNIQUE_PTR // Use std::unique_ptr instead of std::auto_ptr CATCH_CONFIG_CPP11_UNIQUE_PTR // Use std::unique_ptr instead of std::auto_ptr
CATCH_CONFIG_CPP11_SHUFFLE // Use std::shuffle instead of std::random_shuffle CATCH_CONFIG_CPP11_SHUFFLE // Use std::shuffle instead of std::random_shuffle
CATCH_CONFIG_CPP11_TYPE_TRAITS // Use std::enable_if and <type_traits>
Catch has some basic compiler detection that will attempt to select the appropriate mix of these macros. However being incomplete - and often without access to the respective compilers - this detection tends to be conservative. Catch has some basic compiler detection that will attempt to select the appropriate mix of these macros. However being incomplete - and often without access to the respective compilers - this detection tends to be conservative.
So overriding control is given to the user. If a compiler supports a feature (and Catch does not already detect it) then one or more of these may be defined to enable it (or suppress it, in some cases). If you do do this please raise an issue, specifying your compiler version (ideally with an idea of how to detect it) and stating that it has such support. So overriding control is given to the user. If a compiler supports a feature (and Catch does not already detect it) then one or more of these may be defined to enable it (or suppress it, in some cases). If you do do this please raise an issue, specifying your compiler version (ideally with an idea of how to detect it) and stating that it has such support.
...@@ -69,6 +70,22 @@ You may also suppress any of these features by using the `_NO_` form, e.g. `CATC ...@@ -69,6 +70,22 @@ You may also suppress any of these features by using the `_NO_` form, e.g. `CATC
All C++11 support can be disabled with `CATCH_CONFIG_NO_CPP11` All C++11 support can be disabled with `CATCH_CONFIG_NO_CPP11`
# Other toggles
CATCH_CONFIG_COUNTER // Use __COUNTER__ to generate unique names for test cases
CATCH_CONFIG_WINDOWS_SEH // Enable SEH handling on Windows
Currently Catch enables `CATCH_CONFIG_WINDOWS_SEH` only when compiled with MSVC, because some versions of MinGW do not have the necessary Win32 API supports.
Just as with the C++11 conformance toggles, these toggles can be disabled by using `_NO_` form of the toggle, e.g. `CATCH_CONFIG_NO_WINDOWS_SEH`.
# Windows header clutter
On Windows Catch includes `windows.h`. To minimize global namespace clutter in the implementation file, it defines `NOMINMAX` and `WIN32_LEAN_AND_MEAN` before including it. You can control this behaviour via two macros:
CATCH_CONFIG_NO_NOMINMAX // Stops Catch from using NOMINMAX macro
CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN // Stops Catch from using WIN32_LEAN_AND_MEAN macro
--- ---
[Home](Readme.md) [Home](Readme.md)
\ No newline at end of file
# Known limitations
Catch has some known limitations, that we are not planning to change. Some of these are caused by our desire to support C++98 compilers, some of these are caused by our desire to keep Catch crossplatform, some exist because their priority is seen as low compared to the development effort they would need and some other yet are compiler/runtime bugs.
## Features
This section outlines some missing features, what is their status and their possible workarounds.
### Thread safe assertions
Because threading support in standard C++98 is limited (well, non-existent), assertion macros in Catch are not thread safe. This does not mean that you cannot use threads inside Catch's test, but that only single thread can interact with Catch's assertions and other macros.
This means that this is ok
```cpp
std::vector<std::thread> threads;
std::atomic<int> cnt{ 0 };
for (int i = 0; i < 4; ++i) {
threads.emplace_back([&]() {
++cnt; ++cnt; ++cnt; ++cnt;
});
}
for (auto& t : threads) { t.join(); }
REQUIRE(cnt == 16);
```
because only one thread passes the `REQUIRE` macro and this is not
```cpp
std::vector<std::thread> threads;
std::atomic<int> cnt{ 0 };
for (int i = 0; i < 4; ++i) {
threads.emplace_back([&]() {
++cnt; ++cnt; ++cnt; ++cnt;
CHECK(cnt == 16);
});
}
for (auto& t : threads) { t.join(); }
REQUIRE(cnt == 16);
```
_This limitation is highly unlikely to be lifted before Catch 2 is released._
### Process isolation in a test
Catch does not support running tests in isolated (forked) processes. While this might in the future, the fact that Windows does not support forking and only allows full-on process creation and the desire to keep code as similar as possible across platforms, mean that this is likely to take significant development time, that is not currently available.
### Running multiple tests in parallel
Catch's test execution is strictly serial. If you find yourself with a test suite that takes too long to run and you want to make it parallel, there are 2 feasible solutions
* You can split your tests into multiple binaries and then run these binaries in parallel.
* You can have Catch list contained test cases and then run the same test binary multiple times in parallel, passing each instance list of test cases it should run.
Both of these solutions have their problems, but should let you wring parallelism out of your test suite.
## 3rd party bugs
This section outlines known bugs in 3rd party components (this means compilers, standard libraries, standard runtimes).
### Visual Studio 2013 -- do-while loop withing range based for fails to compile (C2059)
There is a known bug in Visual Studio 2013 (VC 12), that causes compilation error if range based for is followed by an assertion macro, without enclosing the block in braces. This snippet is sufficient to trigger the error
```cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
TEST_CASE("Syntax error with VC12") {
for ( auto x : { 1 , 2, 3 } )
REQUIRE( x < 3.14 );
}
```
An easy workaround is possible, use braces:
```cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
TEST_CASE("No longer a syntax error with VC12") {
for ( auto x : { 1 , 2, 3 } ) {
REQUIRE( x < 3.14 );
}
}
```
### Visual Studio 2003 -- Syntax error caused by improperly expanded `__LINE__` macro
Older version of Visual Studio can have trouble compiling Catch, not expanding the `__LINE__` macro properly when recompiling the test binary. This is caused by Edit and Continue being on.
A workaround is to turn off Edit and Continue when compiling the test binary.
### Clang/G++ -- skipping leaf sections after an exception
Some versions of `libc++` and `libstdc++` (or their runtimes) have a bug with `std::uncaught_exception()` getting stuck returning `true` after rethrow, even if there are no active exceptions. One such case is this snippet, which skipped the sections "a" and "b", when compiled against `libcxxrt` from master
```cpp
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
TEST_CASE("a") {
CHECK_THROWS(throw 3);
}
TEST_CASE("b") {
int i = 0;
SECTION("a") { i = 1; }
SECTION("b") { i = 2; }
CHECK(i > 0);
}
```
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.
# Open Source projects using Catch
Catch is great for open source. With it's [liberal license](../LICENSE_1_0.txt) and single-header, dependency-free, distribution
it's easy to just drop the header into your project and start writing tests - what's not to like?
As a result Catch is now being used in many Open Source projects, including some quite well known ones.
This page is an attempt to track those projects. Obviously it can never be complete.
This effort largely relies on the maintainers of the projects themselves updating this page and submitting a PR
(or, if you prefer contact one of the maintainers of Catch directly, use the
[forums](https://groups.google.com/forum/?fromgroups#!forum/catch-forum)), or raise an [issue](https://github.com/philsquared/Catch/issues) to let us know).
Of course users of those projects might want to update this page too. That's fine - as long you're confident the project maintainers won't mind.
If you're an Open Source project maintainer and see your project listed here but would rather it wasn't -
just let us know via any of the previously mentioned means - although I'm sure there won't be many who feel that way.
Listing a project here does not imply endorsement and the plan is to keep these ordered alphabetically to avoid an implication of relative importance.
## Libraries & Frameworks
### [Azmq](https://github.com/zeromq/azmq)
Boost Asio style bindings for ZeroMQ
### [ChakraCore](https://github.com/Microsoft/ChakraCore)
The core part of the Chakra Javascript engine that powers Microsoft Edge
### [ChaiScript](https://github.com/ChaiScript/ChaiScript)
A, header-only, embedded scripting language designed from the ground up to directly target C++ and take advantage of modern C++ development techniques
### [Couchbase-lite-core](https://github.com/couchbase/couchbase-lite-core)
The next-generation core storage and query engine for Couchbase Lite/
### [JSON for Modern C++](https://github.com/nlohmann/json)
A, single-header, JSON parsing library that takes advantage of what C++ has to offer.
### [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
### [Ppconsul](https://github.com/oliora/ppconsul)
A C++ client library for Consul. Consul is a distributed tool for discovering and configuring services in your infrastructure
### [Reactive-Extensions/ RxCpp](https://github.com/Reactive-Extensions/RxCpp)
A library of algorithms for values-distributed-in-time
### [Trompeloeil](https://github.com/rollbear/trompeloeil)
A thread safe header only mocking framework for C++14
## Applications & Tools
### [MAME](https://github.com/mamedev/mame)
MAME originally stood for Multiple Arcade Machine Emulator
### [Standardese](https://github.com/foonathan/standardese)
Standardese aims to be a nextgen Doxygen
---
[Home](Readme.md)
...@@ -16,7 +16,7 @@ If you just need to have code that executes before and/ or after Catch this is t ...@@ -16,7 +16,7 @@ If you just need to have code that executes before and/ or after Catch this is t
#define CATCH_CONFIG_RUNNER #define CATCH_CONFIG_RUNNER
#include "catch.hpp" #include "catch.hpp"
int main( int argc, char* const argv[] ) int main( int argc, char* argv[] )
{ {
// global setup... // global setup...
...@@ -24,7 +24,7 @@ int main( int argc, char* const argv[] ) ...@@ -24,7 +24,7 @@ int main( int argc, char* const argv[] )
// global clean-up... // global clean-up...
return result; return ( result < 0xff ? result : 0xff );
} }
``` ```
...@@ -36,7 +36,7 @@ If you still want Catch to process the command line, but you want to programatic ...@@ -36,7 +36,7 @@ If you still want Catch to process the command line, but you want to programatic
#define CATCH_CONFIG_RUNNER #define CATCH_CONFIG_RUNNER
#include "catch.hpp" #include "catch.hpp"
int main( int argc, char* const argv[] ) int main( int argc, char* argv[] )
{ {
Catch::Session session; // There must be exactly one instance Catch::Session session; // There must be exactly one instance
...@@ -51,7 +51,11 @@ int main( int argc, char* const argv[] ) ...@@ -51,7 +51,11 @@ int main( int argc, char* const argv[] )
// overrides command line args // overrides command line args
// only do this if you know you need to // only do this if you know you need to
return session.run(); int numFailed = session.run();
// Note that on unices only the lower 8 bits are usually used, clamping
// the return value to 255 prevents false negative when some multiple
// of 256 tests has failed
return ( numFailed < 0xff ? numFailed : 0xff );
} }
``` ```
......
# 1.6.0 # 1.7.2
### Fixes and minor improvements
Xml:
(technically the first two are breaking changes but are also fixes and arguably break few if any people)
* C-escape control characters instead of XML encoding them (which requires XML 1.1)
* Revert XML output to XML 1.0
* Can provide stylesheet references by extending the XML reporter
* Added description and tags attribites to XML Reporter
* Tags are closed and the stream flushed more eagerly to avoid stdout interpolation
Other:
* `REQUIRE_THROWS_AS` now catches exception by `const&` and reports expected type
* In `SECTION`s the file/ line is now of the `SECTION`. not the `TEST_CASE`
* Added std:: qualification to some functions from C stdlib
* Removed use of RTTI (`dynamic_cast`) that had crept back in
* Silenced a few more warnings in different circumstances
* Travis improvements
# 1.7.1
### Fixes:
* Fixed inconsistency in defining `NOMINMAX` and `WIN32_LEAN_AND_MEAN` inside `catch.hpp`.
* Fixed SEH-related compilation error under older MinGW compilers, by making Windows SEH handling opt-in for compilers other than MSVC.
* For specifics, look into the [documentation](docs/configuration.md).
* Fixed compilation error under MinGW caused by improper compiler detection.
* Fixed XML reporter sometimes leaving an empty output file when a test ends with signal/structured exception.
* Fixed XML reporter not reporting captured stdout/stderr.
* Fixed possible infinite recursion in Windows SEH.
* Fixed possible compilation error caused by Catch's operator overloads being ambiguous in regards to user-defined templated operators.
# Older versions
Release notes were not maintained prior to v1.6.0, but you should be able to work them out from the Git history
## 1.7.0
### Features/ Changes:
* Catch now runs significantly faster for passing tests
* Microbenchmark focused on Catch's overhead went from ~3.4s to ~0.7s.
* Real world test using [JSON for Modern C++](https://github.com/nlohmann/json)'s test suite went from ~6m 25s to ~4m 14s.
* Catch can now run specific sections within test cases.
* For now the support is only basic (no wildcards or tags), for details see the [documentation](docs/command-line.md).
* Catch now supports SEH on Windows as well as signals on Linux.
* After receiving a signal, Catch reports failing assertion and then passes the signal onto the previous handler.
* Approx can be used to compare values against strong typedefs (available in C++11 mode only).
* Strong typedefs mean types that are explicitly convertible to double.
* CHECK macro no longer stops executing section if an exception happens.
* Certain characters (space, tab, etc) are now pretty printed.
* This means that a `char c = ' '; REQUIRE(c == '\t');` would be printed as `' ' == '\t'`, instead of ` == 9`.
### Fixes:
* Text formatting no longer attempts to access out-of-bounds characters under certain conditions.
* THROW family of assertions no longer trigger `-Wunused-value` on expressions containing explicit cast.
* Breaking into debugger under OS X works again and no longer required `DEBUG` to be defined.
* Compilation no longer breaks under certain compiler if a lambda is used inside assertion macro.
### Other:
* Catch's CMakeLists now defines install command.
* Catch's CMakeLists now generates projects with warnings enabled.
## 1.6.1
### Features/ Changes:
* Catch now supports breaking into debugger on Linux
### Fixes:
* Generators no longer leak memory (generators are still unsupported in general)
* JUnit reporter now reports UTC timestamps, instead of "tbd"
* `CHECK_THAT` macro is now properly defined as `CATCH_CHECK_THAT` when using `CATCH_` prefixed macros
### Other:
* Types with overloaded `&&` operator are no longer evaluated twice when used in an assertion macro.
* The use of `__COUNTER__` is supressed when Catch is parsed by CLion
* This change is not active when compiling a binary
* Approval tests can now be run on Windows
* CMake will now warn if a file is present in the `include` folder but not is not enumerated as part of the project
* Catch now defines `NOMINMAX` and `WIN32_LEAN_AND_MEAN` before including `windows.h`
* This can be disabled if needed, see [documentation](docs/configuration.md) for details.
## 1.6.0
### Cmake/ projects: ### Cmake/ projects:
* Moved CMakeLists.txt to root, made it friendlier for CLion and generating XCode and VS projects, and removed the manually maintained XCode and VS projects. * Moved CMakeLists.txt to root, made it friendlier for CLion and generating XCode and VS projects, and removed the manually maintained XCode and VS projects.
### Features/ Changes: ### Features/ Changes:
* Approx now supports >= and <= * Approx now supports `>=` and `<=`
* Can now use \ to escape chars in test names on command line * Can now use `\` to escape chars in test names on command line
* Standardize C++11 feature toggles * Standardize C++11 feature toggles
### Fixes: ### Fixes:
* Blue shell colour * Blue shell colour
* Missing argument to CATCH_CHECK_THROWS * Missing argument to `CATCH_CHECK_THROWS`
* Don't encode extended ASCII in XML * Don't encode extended ASCII in XML
* use std::shuffle on more compilers (fixes deprecation warning/error) * use `std::shuffle` on more compilers (fixes deprecation warning/error)
* Use __COUNTER__ more consistently (where available) * Use `__COUNTER__` more consistently (where available)
### Other: ### Other:
* Tweaks and changes to scripts - particularly for Approval test - to make them more portable * Tweaks and changes to scripts - particularly for Approval test - to make them more portable
# Older versions
Release notes were not maintained prior to v1.6.0, but you should be able to work them out from the Git history
--- ---
......
...@@ -17,6 +17,46 @@ Because Catch is implemented *entirely* in headers you might think that the whol ...@@ -17,6 +17,46 @@ Because Catch is implemented *entirely* in headers you might think that the whol
As a result the main source file *does* compile the whole of Catch every time! So it makes sense to dedicate this file to *only* ```#define```-ing the identifier and ```#include```-ing Catch (and implementing the runner code, if you're doing that). Keep all your test cases in other files. This way you won't pay the recompilation cost for the whole of Catch As a result the main source file *does* compile the whole of Catch every time! So it makes sense to dedicate this file to *only* ```#define```-ing the identifier and ```#include```-ing Catch (and implementing the runner code, if you're doing that). Keep all your test cases in other files. This way you won't pay the recompilation cost for the whole of Catch
## Practical example
Assume you have the `Factorial` function from the [tutorial](tutorial.md) in `factorial.cpp` (with forward declaration in `factorial.h`) and want to test it and keep the compile times down when adding new tests. Then you should have 2 files, `tests-main.cpp` and `tests-factorial.cpp`:
```cpp
// tests-main.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
```
```cpp
// tests-factorial.cpp
#include "catch.hpp"
#include "factorial.h"
TEST_CASE( "Factorials are computed", "[factorial]" ) {
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}
```
After compiling `tests-main.cpp` once, it is enough to link it with separately compiled `tests-factorial.cpp`. This means that adding more tests to `tests-factorial.cpp`, will not result in recompiling Catch's main and the resulting compilation times will decrease substantially.
```
$ g++ tests-main.cpp -c
$ g++ tests-main.o tests-factorial.cpp -o tests && ./tests -r compact
Passed 1 test case with 4 assertions.
```
Now, the next time we change the file `tests-factorial.cpp` (say we add `REQUIRE( Factorial(0) == 1)`), it is enough to recompile the tests instead of recompiling main as well:
```
$ g++ tests-main.o tests-factorial.cpp -o tests && ./tests -r compact
tests-factorial.cpp:11: failed: Factorial(0) == 1 for: 0 == 1
Failed 1 test case, failed 1 assertion.
```
--- ---
[Home](Readme.md) [Home](Readme.md)
\ No newline at end of file
...@@ -42,6 +42,8 @@ All tag names beginning with non-alphanumeric characters are reserved by Catch. ...@@ -42,6 +42,8 @@ All tag names beginning with non-alphanumeric characters are reserved by Catch.
* `[!mayfail]` - doesn't fail the test if any given assertion fails (but still reports it). This can be useful to flag a work-in-progress, or a known issue that you don't want to immediately fix but still want to track in the your tests. * `[!mayfail]` - doesn't fail the test if any given assertion fails (but still reports it). This can be useful to flag a work-in-progress, or a known issue that you don't want to immediately fix but still want to track in the your tests.
* `[!nonportable]` - Indicates that behaviour may vary between platforms or compilers.
* `[#<filename>]` - running with `-#` or `--filenames-as-tags` causes Catch to add the filename, prefixed with `#` (and with any extension stripped) as a tag. e.g. tests in testfile.cpp would all be tagged `[#testfile]`. * `[#<filename>]` - running with `-#` or `--filenames-as-tags` causes Catch to add the filename, prefixed with `#` (and with any extension stripped) as a tag. e.g. tests in testfile.cpp would all be tagged `[#testfile]`.
* `[@<alias>]` - tag aliases all begin with `@` (see below). * `[@<alias>]` - tag aliases all begin with `@` (see below).
......
...@@ -35,6 +35,10 @@ So what does Catch bring to the party that differentiates it from these? Apart f ...@@ -35,6 +35,10 @@ So what does Catch bring to the party that differentiates it from these? Apart f
* Implement test fixtures using Obj-C classes too (like OCUnit) * Implement test fixtures using Obj-C classes too (like OCUnit)
* Additional built in matchers that work with Obj-C types (e.g. string matchers) * Additional built in matchers that work with Obj-C types (e.g. string matchers)
## Who else is using Catch?
See the list of [open source projects using Catch](opensource-users.md).
See the [tutorial](tutorial.md) to get more of a taste of using CATCH in practice See the [tutorial](tutorial.md) to get more of a taste of using CATCH in practice
--- ---
......
...@@ -86,7 +86,7 @@ ...@@ -86,7 +86,7 @@
#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CATCH_CHECK_THROWS_WITH" ) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CATCH_CHECK_THROWS_WITH" )
#define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" ) #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" )
#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" ) #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" )
#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" ) #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" )
#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" )
......
...@@ -37,19 +37,16 @@ namespace Tbc { ...@@ -37,19 +37,16 @@ namespace Tbc {
TextAttributes() TextAttributes()
: initialIndent( std::string::npos ), : initialIndent( std::string::npos ),
indent( 0 ), indent( 0 ),
width( consoleWidth-1 ), width( consoleWidth-1 )
tabChar( '\t' )
{} {}
TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }
TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }
TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }
TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; }
std::size_t initialIndent; // indent of first line, or npos std::size_t initialIndent; // indent of first line, or npos
std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos
std::size_t width; // maximum width of text, including indent. Longer text will wrap std::size_t width; // maximum width of text, including indent. Longer text will wrap
char tabChar; // If this char is seen the indent is changed to current pos
}; };
class Text { class Text {
...@@ -57,63 +54,80 @@ namespace Tbc { ...@@ -57,63 +54,80 @@ namespace Tbc {
Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
: attr( _attr ) : attr( _attr )
{ {
std::string wrappableChars = " [({.,/|\\-"; const std::string wrappableBeforeChars = "[({<\t";
std::size_t indent = _attr.initialIndent != std::string::npos const std::string wrappableAfterChars = "])}>-,./|\\";
? _attr.initialIndent const std::string wrappableInsteadOfChars = " \n\r";
: _attr.indent; std::string indent = _attr.initialIndent != std::string::npos
std::string remainder = _str; ? std::string( _attr.initialIndent, ' ' )
: std::string( _attr.indent, ' ' );
typedef std::string::const_iterator iterator;
iterator it = _str.begin();
const iterator strEnd = _str.end();
while( it != strEnd ) {
while( !remainder.empty() ) {
if( lines.size() >= 1000 ) { if( lines.size() >= 1000 ) {
lines.push_back( "... message truncated due to excessive size" ); lines.push_back( "... message truncated due to excessive size" );
return; return;
} }
std::size_t tabPos = std::string::npos;
std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
std::size_t pos = remainder.find_first_of( '\n' );
if( pos <= width ) {
width = pos;
}
pos = remainder.find_last_of( _attr.tabChar, width );
if( pos != std::string::npos ) {
tabPos = pos;
if( remainder[width] == '\n' )
width--;
remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
}
if( width == remainder.size() ) {
spliceLine( indent, remainder, width ); std::string suffix;
} std::size_t width = (std::min)( static_cast<size_t>( strEnd-it ), _attr.width-static_cast<size_t>( indent.size() ) );
else if( remainder[width] == '\n' ) { iterator itEnd = it+width;
spliceLine( indent, remainder, width ); iterator itNext = _str.end();
if( width <= 1 || remainder.size() != 1 )
remainder = remainder.substr( 1 ); iterator itNewLine = std::find( it, itEnd, '\n' );
indent = _attr.indent; if( itNewLine != itEnd )
} itEnd = itNewLine;
else {
pos = remainder.find_last_of( wrappableChars, width ); if( itEnd != strEnd ) {
if( pos != std::string::npos && pos > 0 ) { bool foundWrapPoint = false;
spliceLine( indent, remainder, pos ); iterator findIt = itEnd;
if( remainder[0] == ' ' ) do {
remainder = remainder.substr( 1 ); if( wrappableAfterChars.find( *findIt ) != std::string::npos && findIt != itEnd ) {
itEnd = findIt+1;
itNext = findIt+1;
foundWrapPoint = true;
}
else if( findIt > it && wrappableBeforeChars.find( *findIt ) != std::string::npos ) {
itEnd = findIt;
itNext = findIt;
foundWrapPoint = true;
}
else if( wrappableInsteadOfChars.find( *findIt ) != std::string::npos ) {
itNext = findIt+1;
itEnd = findIt;
foundWrapPoint = true;
}
if( findIt == it )
break;
else
--findIt;
}
while( !foundWrapPoint );
if( !foundWrapPoint ) {
// No good wrap char, so we'll break mid word and add a hyphen
--itEnd;
itNext = itEnd;
suffix = "-";
} }
else { else {
spliceLine( indent, remainder, width-1 ); while( itEnd > it && wrappableInsteadOfChars.find( *(itEnd-1) ) != std::string::npos )
lines.back() += "-"; --itEnd;
} }
if( lines.size() == 1 )
indent = _attr.indent;
if( tabPos != std::string::npos )
indent += tabPos;
} }
lines.push_back( indent + std::string( it, itEnd ) + suffix );
if( indent.size() != _attr.indent )
indent = std::string( _attr.indent, ' ' );
it = itNext;
} }
} }
void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );
_remainder = _remainder.substr( _pos );
}
typedef std::vector<std::string>::const_iterator const_iterator; typedef std::vector<std::string>::const_iterator const_iterator;
...@@ -138,6 +152,7 @@ namespace Tbc { ...@@ -138,6 +152,7 @@ namespace Tbc {
return _stream; return _stream;
} }
private: private:
std::string str; std::string str;
TextAttributes attr; TextAttributes attr;
......
...@@ -13,6 +13,10 @@ ...@@ -13,6 +13,10 @@
#include <cmath> #include <cmath>
#include <limits> #include <limits>
#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
#include <type_traits>
#endif
namespace Catch { namespace Catch {
namespace Detail { namespace Detail {
...@@ -41,9 +45,56 @@ namespace Detail { ...@@ -41,9 +45,56 @@ namespace Detail {
return approx; return approx;
} }
#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator == ( const T& lhs, Approx const& rhs ) {
// Thanks to Richard Harris for his help refining this formula
auto lhs_v = double(lhs);
return std::fabs( lhs_v - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs_v), std::fabs(rhs.m_value) ) );
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator == ( Approx const& lhs, const T& rhs ) {
return operator==( rhs, lhs );
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator != ( T lhs, Approx const& rhs ) {
return !operator==( lhs, rhs );
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator != ( Approx const& lhs, T rhs ) {
return !operator==( rhs, lhs );
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator <= ( T lhs, Approx const& rhs )
{
return double(lhs) < rhs.m_value || lhs == rhs;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator <= ( Approx const& lhs, T rhs )
{
return lhs.m_value < double(rhs) || lhs == rhs;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator >= ( T lhs, Approx const& rhs )
{
return double(lhs) > rhs.m_value || lhs == rhs;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator >= ( Approx const& lhs, T rhs )
{
return lhs.m_value > double(rhs) || lhs == rhs;
}
#else
friend bool operator == ( double lhs, Approx const& rhs ) { friend bool operator == ( double lhs, Approx const& rhs ) {
// Thanks to Richard Harris for his help refining this formula // Thanks to Richard Harris for his help refining this formula
return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) ); return std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) );
} }
friend bool operator == ( Approx const& lhs, double rhs ) { friend bool operator == ( Approx const& lhs, double rhs ) {
...@@ -77,6 +128,7 @@ namespace Detail { ...@@ -77,6 +128,7 @@ namespace Detail {
{ {
return lhs.m_value > rhs || lhs == rhs; return lhs.m_value > rhs || lhs == rhs;
} }
#endif
Approx& epsilon( double newEpsilon ) { Approx& epsilon( double newEpsilon ) {
m_epsilon = newEpsilon; m_epsilon = newEpsilon;
......
...@@ -13,6 +13,27 @@ ...@@ -13,6 +13,27 @@
namespace Catch { namespace Catch {
struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
struct DecomposedExpression
{
virtual ~DecomposedExpression() {}
virtual bool isBinaryExpression() const {
return false;
}
virtual void reconstructExpression( std::string& dest ) const = 0;
// Only simple binary comparisons can be decomposed.
// If more complex check is required then wrap sub-expressions in parentheses.
template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( T const& );
template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( T const& );
template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( T const& );
template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( T const& );
template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator % ( T const& );
template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( T const& );
template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( T const& );
};
struct AssertionInfo struct AssertionInfo
{ {
AssertionInfo() {} AssertionInfo() {}
...@@ -29,11 +50,41 @@ namespace Catch { ...@@ -29,11 +50,41 @@ namespace Catch {
struct AssertionResultData struct AssertionResultData
{ {
AssertionResultData() : resultType( ResultWas::Unknown ) {} AssertionResultData() : decomposedExpression( CATCH_NULL )
, resultType( ResultWas::Unknown )
, negated( false )
, parenthesized( false ) {}
void negate( bool parenthesize ) {
negated = !negated;
parenthesized = parenthesize;
if( resultType == ResultWas::Ok )
resultType = ResultWas::ExpressionFailed;
else if( resultType == ResultWas::ExpressionFailed )
resultType = ResultWas::Ok;
}
std::string const& reconstructExpression() const {
if( decomposedExpression != CATCH_NULL ) {
decomposedExpression->reconstructExpression( reconstructedExpression );
if( parenthesized ) {
reconstructedExpression.insert( 0, 1, '(' );
reconstructedExpression.append( 1, ')' );
}
if( negated ) {
reconstructedExpression.insert( 0, 1, '!' );
}
decomposedExpression = CATCH_NULL;
}
return reconstructedExpression;
}
std::string reconstructedExpression; mutable DecomposedExpression const* decomposedExpression;
mutable std::string reconstructedExpression;
std::string message; std::string message;
ResultWas::OfType resultType; ResultWas::OfType resultType;
bool negated;
bool parenthesized;
}; };
class AssertionResult { class AssertionResult {
...@@ -60,6 +111,8 @@ namespace Catch { ...@@ -60,6 +111,8 @@ namespace Catch {
std::string getMessage() const; std::string getMessage() const;
SourceLineInfo getSourceInfo() const; SourceLineInfo getSourceInfo() const;
std::string getTestMacroName() const; std::string getTestMacroName() const;
void discardDecomposedExpression() const;
void expandDecomposedExpression() const;
protected: protected:
AssertionInfo m_info; AssertionInfo m_info;
......
...@@ -56,7 +56,7 @@ namespace Catch { ...@@ -56,7 +56,7 @@ namespace Catch {
std::string AssertionResult::getExpression() const { std::string AssertionResult::getExpression() const {
if( isFalseTest( m_info.resultDisposition ) ) if( isFalseTest( m_info.resultDisposition ) )
return "!" + m_info.capturedExpression; return '!' + m_info.capturedExpression;
else else
return m_info.capturedExpression; return m_info.capturedExpression;
} }
...@@ -72,7 +72,7 @@ namespace Catch { ...@@ -72,7 +72,7 @@ namespace Catch {
} }
std::string AssertionResult::getExpandedExpression() const { std::string AssertionResult::getExpandedExpression() const {
return m_resultData.reconstructedExpression; return m_resultData.reconstructExpression();
} }
std::string AssertionResult::getMessage() const { std::string AssertionResult::getMessage() const {
...@@ -86,6 +86,14 @@ namespace Catch { ...@@ -86,6 +86,14 @@ namespace Catch {
return m_info.macroName; return m_info.macroName;
} }
void AssertionResult::discardDecomposedExpression() const {
m_resultData.decomposedExpression = CATCH_NULL;
}
void AssertionResult::expandDecomposedExpression() const {
m_resultData.reconstructExpression();
}
} // end namespace Catch } // end namespace Catch
#endif // TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED #endif // TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
#include "catch_tostring.h" #include "catch_tostring.h"
#include "catch_interfaces_runner.h" #include "catch_interfaces_runner.h"
#include "catch_compiler_capabilities.h" #include "catch_compiler_capabilities.h"
#include "catch_type_traits.hpp"
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
...@@ -37,10 +38,11 @@ ...@@ -37,10 +38,11 @@
( __catchResult <= expr ).endExpression(); \ ( __catchResult <= expr ).endExpression(); \
} \ } \
catch( ... ) { \ catch( ... ) { \
__catchResult.useActiveException( Catch::ResultDisposition::Normal ); \ __catchResult.useActiveException( resultDisposition ); \
} \ } \
INTERNAL_CATCH_REACT( __catchResult ) \ INTERNAL_CATCH_REACT( __catchResult ) \
} while( Catch::isTrue( false && !!(expr) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look } while( Catch::isTrue( false && static_cast<bool>( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
// The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \ #define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \
...@@ -57,7 +59,7 @@ ...@@ -57,7 +59,7 @@
do { \ do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
try { \ try { \
expr; \ static_cast<void>(expr); \
__catchResult.captureResult( Catch::ResultWas::Ok ); \ __catchResult.captureResult( Catch::ResultWas::Ok ); \
} \ } \
catch( ... ) { \ catch( ... ) { \
...@@ -72,7 +74,7 @@ ...@@ -72,7 +74,7 @@
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \
if( __catchResult.allowThrows() ) \ if( __catchResult.allowThrows() ) \
try { \ try { \
expr; \ static_cast<void>(expr); \
__catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
} \ } \
catch( ... ) { \ catch( ... ) { \
...@@ -86,13 +88,13 @@ ...@@ -86,13 +88,13 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \ #define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \
do { \ do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr ", " #exceptionType, resultDisposition ); \
if( __catchResult.allowThrows() ) \ if( __catchResult.allowThrows() ) \
try { \ try { \
expr; \ static_cast<void>(expr); \
__catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
} \ } \
catch( exceptionType ) { \ catch( Catch::add_const<Catch::add_lvalue_reference<exceptionType>::type>::type ) { \
__catchResult.captureResult( Catch::ResultWas::Ok ); \ __catchResult.captureResult( Catch::ResultWas::Ok ); \
} \ } \
catch( ... ) { \ catch( ... ) { \
...@@ -132,13 +134,7 @@ ...@@ -132,13 +134,7 @@
do { \ do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \
try { \ try { \
std::string matcherAsString = (matcher).toString(); \ __catchResult.captureMatch( arg, matcher, #matcher ); \
__catchResult \
.setLhs( Catch::toString( arg ) ) \
.setRhs( matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString ) \
.setOp( "matches" ) \
.setResultType( (matcher).match( arg ) ); \
__catchResult.captureExpression(); \
} catch( ... ) { \ } catch( ... ) { \
__catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \
} \ } \
......
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
#include "catch_clara.h" #include "catch_clara.h"
#include <fstream> #include <fstream>
#include <ctime>
namespace Catch { namespace Catch {
...@@ -23,13 +24,14 @@ namespace Catch { ...@@ -23,13 +24,14 @@ namespace Catch {
config.abortAfter = x; config.abortAfter = x;
} }
inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); } inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); }
inline void addSectionToRun( ConfigData& config, std::string const& sectionName ) { config.sectionsToRun.push_back( sectionName ); }
inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); } inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); }
inline void addWarning( ConfigData& config, std::string const& _warning ) { inline void addWarning( ConfigData& config, std::string const& _warning ) {
if( _warning == "NoAssertions" ) if( _warning == "NoAssertions" )
config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions ); config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
else else
throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" ); throw std::runtime_error( "Unrecognised warning: '" + _warning + '\'' );
} }
inline void setOrder( ConfigData& config, std::string const& order ) { inline void setOrder( ConfigData& config, std::string const& order ) {
if( startsWith( "declared", order ) ) if( startsWith( "declared", order ) )
...@@ -39,7 +41,7 @@ namespace Catch { ...@@ -39,7 +41,7 @@ namespace Catch {
else if( startsWith( "random", order ) ) else if( startsWith( "random", order ) )
config.runOrder = RunTests::InRandomOrder; config.runOrder = RunTests::InRandomOrder;
else else
throw std::runtime_error( "Unrecognised ordering: '" + order + "'" ); throw std::runtime_error( "Unrecognised ordering: '" + order + '\'' );
} }
inline void setRngSeed( ConfigData& config, std::string const& seed ) { inline void setRngSeed( ConfigData& config, std::string const& seed ) {
if( seed == "time" ) { if( seed == "time" ) {
...@@ -50,7 +52,7 @@ namespace Catch { ...@@ -50,7 +52,7 @@ namespace Catch {
ss << seed; ss << seed;
ss >> config.rngSeed; ss >> config.rngSeed;
if( ss.fail() ) if( ss.fail() )
throw std::runtime_error( "Argment to --rng-seed should be the word 'time' or a number" ); throw std::runtime_error( "Argument to --rng-seed should be the word 'time' or a number" );
} }
} }
inline void setVerbosity( ConfigData& config, int level ) { inline void setVerbosity( ConfigData& config, int level ) {
...@@ -64,7 +66,7 @@ namespace Catch { ...@@ -64,7 +66,7 @@ namespace Catch {
} }
inline void setUseColour( ConfigData& config, std::string const& value ) { inline void setUseColour( ConfigData& config, std::string const& value ) {
std::string mode = toLower( value ); std::string mode = toLower( value );
if( mode == "yes" ) if( mode == "yes" )
config.useColour = UseColour::Yes; config.useColour = UseColour::Yes;
else if( mode == "no" ) else if( mode == "no" )
...@@ -85,10 +87,10 @@ namespace Catch { ...@@ -85,10 +87,10 @@ namespace Catch {
std::string line; std::string line;
while( std::getline( f, line ) ) { while( std::getline( f, line ) ) {
line = trim(line); line = trim(line);
if( !line.empty() && !startsWith( line, "#" ) ) { if( !line.empty() && !startsWith( line, '#' ) ) {
if( !startsWith( line, "\"" ) ) if( !startsWith( line, '"' ) )
line = "\"" + line + "\""; line = '"' + line + '"';
addTestOrTags( config, line + "," ); addTestOrTags( config, line + ',' );
} }
} }
} }
...@@ -176,6 +178,10 @@ namespace Catch { ...@@ -176,6 +178,10 @@ namespace Catch {
.describe( "adds a tag for the filename" ) .describe( "adds a tag for the filename" )
.bind( &ConfigData::filenamesAsTags ); .bind( &ConfigData::filenamesAsTags );
cli["-c"]["--section"]
.describe( "specify section to run" )
.bind( &addSectionToRun, "section name" );
// Less common commands which don't have a short form // Less common commands which don't have a short form
cli["--list-test-names-only"] cli["--list-test-names-only"]
.describe( "list all/matching test cases names only" ) .describe( "list all/matching test cases names only" )
...@@ -196,7 +202,7 @@ namespace Catch { ...@@ -196,7 +202,7 @@ namespace Catch {
cli["--force-colour"] cli["--force-colour"]
.describe( "force colourised output (deprecated)" ) .describe( "force colourised output (deprecated)" )
.bind( &forceColour ); .bind( &forceColour );
cli["--use-colour"] cli["--use-colour"]
.describe( "should output be colourised" ) .describe( "should output be colourised" )
.bind( &setUseColour, "yes|no" ); .bind( &setUseColour, "yes|no" );
......
...@@ -22,7 +22,6 @@ ...@@ -22,7 +22,6 @@
#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr ) #define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr )
#include <sstream> #include <sstream>
#include <stdexcept>
#include <algorithm> #include <algorithm>
#include "catch_compiler_capabilities.h" #include "catch_compiler_capabilities.h"
...@@ -79,7 +78,9 @@ namespace Catch { ...@@ -79,7 +78,9 @@ namespace Catch {
} }
bool startsWith( std::string const& s, std::string const& prefix ); bool startsWith( std::string const& s, std::string const& prefix );
bool startsWith( std::string const& s, char prefix );
bool endsWith( std::string const& s, std::string const& suffix ); bool endsWith( std::string const& s, std::string const& suffix );
bool endsWith( std::string const& s, char suffix );
bool contains( std::string const& s, std::string const& infix ); bool contains( std::string const& s, std::string const& infix );
void toLowerInPlace( std::string& s ); void toLowerInPlace( std::string& s );
std::string toLower( std::string const& s ); std::string toLower( std::string const& s );
...@@ -99,8 +100,8 @@ namespace Catch { ...@@ -99,8 +100,8 @@ namespace Catch {
SourceLineInfo(); SourceLineInfo();
SourceLineInfo( char const* _file, std::size_t _line ); SourceLineInfo( char const* _file, std::size_t _line );
SourceLineInfo( SourceLineInfo const& other );
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
SourceLineInfo(SourceLineInfo const& other) = default;
SourceLineInfo( SourceLineInfo && ) = default; SourceLineInfo( SourceLineInfo && ) = default;
SourceLineInfo& operator = ( SourceLineInfo const& ) = default; SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
SourceLineInfo& operator = ( SourceLineInfo && ) = default; SourceLineInfo& operator = ( SourceLineInfo && ) = default;
...@@ -109,7 +110,7 @@ namespace Catch { ...@@ -109,7 +110,7 @@ namespace Catch {
bool operator == ( SourceLineInfo const& other ) const; bool operator == ( SourceLineInfo const& other ) const;
bool operator < ( SourceLineInfo const& other ) const; bool operator < ( SourceLineInfo const& other ) const;
std::string file; char const* file;
std::size_t line; std::size_t line;
}; };
......
...@@ -10,19 +10,28 @@ ...@@ -10,19 +10,28 @@
#include "catch_common.h" #include "catch_common.h"
#include <cstring>
#include <cctype>
namespace Catch { namespace Catch {
bool startsWith( std::string const& s, std::string const& prefix ) { bool startsWith( std::string const& s, std::string const& prefix ) {
return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix; return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
}
bool startsWith( std::string const& s, char prefix ) {
return !s.empty() && s[0] == prefix;
} }
bool endsWith( std::string const& s, std::string const& suffix ) { bool endsWith( std::string const& s, std::string const& suffix ) {
return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix; return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
}
bool endsWith( std::string const& s, char suffix ) {
return !s.empty() && s[s.size()-1] == suffix;
} }
bool contains( std::string const& s, std::string const& infix ) { bool contains( std::string const& s, std::string const& infix ) {
return s.find( infix ) != std::string::npos; return s.find( infix ) != std::string::npos;
} }
char toLowerCh(char c) { char toLowerCh(char c) {
return static_cast<char>( ::tolower( c ) ); return static_cast<char>( std::tolower( c ) );
} }
void toLowerInPlace( std::string& s ) { void toLowerInPlace( std::string& s ) {
std::transform( s.begin(), s.end(), s.begin(), toLowerCh ); std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
...@@ -37,7 +46,7 @@ namespace Catch { ...@@ -37,7 +46,7 @@ namespace Catch {
std::string::size_type start = str.find_first_not_of( whitespaceChars ); std::string::size_type start = str.find_first_not_of( whitespaceChars );
std::string::size_type end = str.find_last_not_of( whitespaceChars ); std::string::size_type end = str.find_last_not_of( whitespaceChars );
return start != std::string::npos ? str.substr( start, 1+end-start ) : ""; return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
} }
bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
...@@ -60,29 +69,25 @@ namespace Catch { ...@@ -60,29 +69,25 @@ namespace Catch {
{} {}
std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
os << pluraliser.m_count << " " << pluraliser.m_label; os << pluraliser.m_count << ' ' << pluraliser.m_label;
if( pluraliser.m_count != 1 ) if( pluraliser.m_count != 1 )
os << "s"; os << 's';
return os; return os;
} }
SourceLineInfo::SourceLineInfo() : line( 0 ){} SourceLineInfo::SourceLineInfo() : file(""), line( 0 ){}
SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line )
: file( _file ), : file( _file ),
line( _line ) line( _line )
{} {}
SourceLineInfo::SourceLineInfo( SourceLineInfo const& other )
: file( other.file ),
line( other.line )
{}
bool SourceLineInfo::empty() const { bool SourceLineInfo::empty() const {
return file.empty(); return file[0] == '\0';
} }
bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const { bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const {
return line == other.line && file == other.file; return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
} }
bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const { bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const {
return line < other.line || ( line == other.line && file < other.file ); return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
} }
void seedRng( IConfig const& config ) { void seedRng( IConfig const& config ) {
...@@ -95,16 +100,16 @@ namespace Catch { ...@@ -95,16 +100,16 @@ namespace Catch {
std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
#ifndef __GNUG__ #ifndef __GNUG__
os << info.file << "(" << info.line << ")"; os << info.file << '(' << info.line << ')';
#else #else
os << info.file << ":" << info.line; os << info.file << ':' << info.line;
#endif #endif
return os; return os;
} }
void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) { void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) {
std::ostringstream oss; std::ostringstream oss;
oss << locationInfo << ": Internal Catch error: '" << message << "'"; oss << locationInfo << ": Internal Catch error: '" << message << '\'';
if( alwaysTrue() ) if( alwaysTrue() )
throw std::logic_error( oss.str() ); throw std::logic_error( oss.str() );
} }
......
...@@ -19,11 +19,14 @@ ...@@ -19,11 +19,14 @@
// CATCH_CONFIG_CPP11_LONG_LONG : is long long supported? // CATCH_CONFIG_CPP11_LONG_LONG : is long long supported?
// CATCH_CONFIG_CPP11_OVERRIDE : is override supported? // CATCH_CONFIG_CPP11_OVERRIDE : is override supported?
// CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) // CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr)
// CATCH_CONFIG_CPP11_SHUFFLE : is std::shuffle supported?
// CATCH_CONFIG_CPP11_TYPE_TRAITS : are type_traits and enable_if supported?
// CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? // CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported?
// CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? // CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported?
// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
// **************** // ****************
// Note to maintainers: if new toggles are added please document them // Note to maintainers: if new toggles are added please document them
// in configuration.md, too // in configuration.md, too
...@@ -107,6 +110,8 @@ ...@@ -107,6 +110,8 @@
// Visual C++ // Visual C++
#ifdef _MSC_VER #ifdef _MSC_VER
#define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
#if (_MSC_VER >= 1600) #if (_MSC_VER >= 1600)
# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
# define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
...@@ -116,6 +121,7 @@ ...@@ -116,6 +121,7 @@
#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT #define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
#define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE #define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
#define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
#endif #endif
#endif // _MSC_VER #endif // _MSC_VER
...@@ -184,6 +190,9 @@ ...@@ -184,6 +190,9 @@
# if !defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) # if !defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE)
# define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE # define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
# endif # endif
# if !defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS)
# define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
# endif
#endif // __cplusplus >= 201103L #endif // __cplusplus >= 201103L
...@@ -215,12 +224,21 @@ ...@@ -215,12 +224,21 @@
#if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11) #if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11)
# define CATCH_CONFIG_CPP11_UNIQUE_PTR # define CATCH_CONFIG_CPP11_UNIQUE_PTR
#endif #endif
#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) // Use of __COUNTER__ is suppressed if __JETBRAINS_IDE__ is #defined (meaning we're being parsed by a JetBrains IDE for
// analytics) because, at time of writing, __COUNTER__ is not properly handled by it.
// This does not affect compilation
#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__)
# define CATCH_CONFIG_COUNTER # define CATCH_CONFIG_COUNTER
#endif #endif
#if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11) #if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11)
# define CATCH_CONFIG_CPP11_SHUFFLE # define CATCH_CONFIG_CPP11_SHUFFLE
#endif #endif
# if defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_NO_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_NO_CPP11)
# define CATCH_CONFIG_CPP11_TYPE_TRAITS
# endif
#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
# define CATCH_CONFIG_WINDOWS_SEH
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
......
...@@ -16,8 +16,7 @@ ...@@ -16,8 +16,7 @@
#include <memory> #include <memory>
#include <vector> #include <vector>
#include <string> #include <string>
#include <iostream> #include <stdexcept>
#include <ctime>
#ifndef CATCH_CONFIG_CONSOLE_WIDTH #ifndef CATCH_CONFIG_CONSOLE_WIDTH
#define CATCH_CONFIG_CONSOLE_WIDTH 80 #define CATCH_CONFIG_CONSOLE_WIDTH 80
...@@ -74,6 +73,7 @@ namespace Catch { ...@@ -74,6 +73,7 @@ namespace Catch {
std::vector<std::string> reporterNames; std::vector<std::string> reporterNames;
std::vector<std::string> testsOrTags; std::vector<std::string> testsOrTags;
std::vector<std::string> sectionsToRun;
}; };
...@@ -99,8 +99,7 @@ namespace Catch { ...@@ -99,8 +99,7 @@ namespace Catch {
} }
} }
virtual ~Config() { virtual ~Config() {}
}
std::string const& getFilename() const { std::string const& getFilename() const {
return m_data.outputFilename ; return m_data.outputFilename ;
...@@ -113,27 +112,26 @@ namespace Catch { ...@@ -113,27 +112,26 @@ namespace Catch {
std::string getProcessName() const { return m_data.processName; } std::string getProcessName() const { return m_data.processName; }
bool shouldDebugBreak() const { return m_data.shouldDebugBreak; } std::vector<std::string> const& getReporterNames() const { return m_data.reporterNames; }
std::vector<std::string> const& getSectionsToRun() const CATCH_OVERRIDE { return m_data.sectionsToRun; }
std::vector<std::string> getReporterNames() const { return m_data.reporterNames; }
int abortAfter() const { return m_data.abortAfter; }
TestSpec const& testSpec() const { return m_testSpec; } virtual TestSpec const& testSpec() const CATCH_OVERRIDE { return m_testSpec; }
bool showHelp() const { return m_data.showHelp; } bool showHelp() const { return m_data.showHelp; }
bool showInvisibles() const { return m_data.showInvisibles; }
// IConfig interface // IConfig interface
virtual bool allowThrows() const { return !m_data.noThrow; } virtual bool allowThrows() const CATCH_OVERRIDE { return !m_data.noThrow; }
virtual std::ostream& stream() const { return m_stream->stream(); } virtual std::ostream& stream() const CATCH_OVERRIDE { return m_stream->stream(); }
virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } virtual std::string name() const CATCH_OVERRIDE { return m_data.name.empty() ? m_data.processName : m_data.name; }
virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; } virtual bool includeSuccessfulResults() const CATCH_OVERRIDE { return m_data.showSuccessfulTests; }
virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; } virtual bool warnAboutMissingAssertions() const CATCH_OVERRIDE { return m_data.warnings & WarnAbout::NoAssertions; }
virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; } virtual ShowDurations::OrNot showDurations() const CATCH_OVERRIDE { return m_data.showDurations; }
virtual RunTests::InWhatOrder runOrder() const { return m_data.runOrder; } virtual RunTests::InWhatOrder runOrder() const CATCH_OVERRIDE { return m_data.runOrder; }
virtual unsigned int rngSeed() const { return m_data.rngSeed; } virtual unsigned int rngSeed() const CATCH_OVERRIDE { return m_data.rngSeed; }
virtual UseColour::YesOrNo useColour() const { return m_data.useColour; } virtual UseColour::YesOrNo useColour() const CATCH_OVERRIDE { return m_data.useColour; }
virtual bool shouldDebugBreak() const CATCH_OVERRIDE { return m_data.shouldDebugBreak; }
virtual int abortAfter() const CATCH_OVERRIDE { return m_data.abortAfter; }
virtual bool showInvisibles() const CATCH_OVERRIDE { return m_data.showInvisibles; }
private: private:
......
...@@ -41,15 +41,7 @@ namespace Catch { ...@@ -41,15 +41,7 @@ namespace Catch {
#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
#ifndef NOMINMAX #include "catch_windows_h_proxy.h"
#define NOMINMAX
#endif
#ifdef __AFXDLL
#include <AfxWin.h>
#else
#include <windows.h>
#endif
namespace Catch { namespace Catch {
namespace { namespace {
......
...@@ -11,9 +11,6 @@ ...@@ -11,9 +11,6 @@
#include "catch_interfaces_generators.h" #include "catch_interfaces_generators.h"
#include "catch_ptr.hpp" #include "catch_ptr.hpp"
#include <memory>
#include <vector>
#include <stdlib.h>
namespace Catch { namespace Catch {
......
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
#include "catch_context.h" #include "catch_context.h"
#include "catch_stream.hpp" #include "catch_stream.hpp"
#include "catch_common.h"
namespace Catch { namespace Catch {
...@@ -21,6 +22,11 @@ namespace Catch { ...@@ -21,6 +22,11 @@ namespace Catch {
Context( Context const& ); Context( Context const& );
void operator=( Context const& ); void operator=( Context const& );
public:
virtual ~Context() {
deleteAllValues( m_generatorsByTestName );
}
public: // IContext public: // IContext
virtual IResultCapture* getResultCapture() { virtual IResultCapture* getResultCapture() {
return m_resultCapture; return m_resultCapture;
......
...@@ -23,27 +23,36 @@ namespace Catch{ ...@@ -23,27 +23,36 @@ namespace Catch{
// The following code snippet based on: // The following code snippet based on:
// http://cocoawithlove.com/2008/03/break-into-debugger.html // http://cocoawithlove.com/2008/03/break-into-debugger.html
#ifdef DEBUG #if defined(__ppc64__) || defined(__ppc__)
#if defined(__ppc64__) || defined(__ppc__) #define CATCH_TRAP() \
#define CATCH_BREAK_INTO_DEBUGGER() \ __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \
if( Catch::isDebuggerActive() ) { \ : : : "memory","r0","r3","r4" )
__asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ #else
: : : "memory","r0","r3","r4" ); \ #define CATCH_TRAP() __asm__("int $3\n" : : )
}
#else
#define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__("int $3\n" : : );}
#endif
#endif #endif
#elif defined(CATCH_PLATFORM_LINUX)
// If we can use inline assembler, do it because this allows us to break
// directly at the location of the failing check instead of breaking inside
// raise() called from it, i.e. one stack frame below.
#if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
#define CATCH_TRAP() asm volatile ("int $3")
#else // Fall back to the generic way.
#include <signal.h>
#define CATCH_TRAP() raise(SIGTRAP)
#endif
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
#define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); } #define CATCH_TRAP() __debugbreak()
#elif defined(__MINGW32__) #elif defined(__MINGW32__)
extern "C" __declspec(dllimport) void __stdcall DebugBreak(); extern "C" __declspec(dllimport) void __stdcall DebugBreak();
#define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); } #define CATCH_TRAP() DebugBreak()
#endif #endif
#ifndef CATCH_BREAK_INTO_DEBUGGER #ifdef CATCH_TRAP
#define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
#else
#define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
#endif #endif
#endif // TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED #endif // TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED
...@@ -11,8 +11,6 @@ ...@@ -11,8 +11,6 @@
#include "catch_debugger.h" #include "catch_debugger.h"
#include <iostream>
#ifdef CATCH_PLATFORM_MAC #ifdef CATCH_PLATFORM_MAC
#include <assert.h> #include <assert.h>
...@@ -61,6 +59,33 @@ ...@@ -61,6 +59,33 @@
} }
} // namespace Catch } // namespace Catch
#elif defined(CATCH_PLATFORM_LINUX)
#include <fstream>
#include <string>
namespace Catch{
// The standard POSIX way of detecting a debugger is to attempt to
// ptrace() the process, but this needs to be done from a child and not
// this process itself to still allow attaching to this process later
// if wanted, so is rather heavy. Under Linux we have the PID of the
// "debugger" (which doesn't need to be gdb, of course, it could also
// be strace, for example) in /proc/$PID/status, so just get it from
// there instead.
bool isDebuggerActive(){
std::ifstream in("/proc/self/status");
for( std::string line; std::getline(in, line); ) {
static const int PREFIX_LEN = 11;
if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
// We're traced if the PID is not 0 and no other PID starts
// with 0 digit, so it's enough to check for just a single
// character.
return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
}
}
return false;
}
} // namespace Catch
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
namespace Catch { namespace Catch {
...@@ -82,7 +107,9 @@ ...@@ -82,7 +107,9 @@
#endif // Platform #endif // Platform
#ifdef CATCH_PLATFORM_WINDOWS #ifdef CATCH_PLATFORM_WINDOWS
extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* );
#include "catch_windows_h_proxy.h"
namespace Catch { namespace Catch {
void writeToDebugConsole( std::string const& text ) { void writeToDebugConsole( std::string const& text ) {
::OutputDebugStringA( text.c_str() ); ::OutputDebugStringA( text.c_str() );
......
...@@ -12,7 +12,8 @@ ...@@ -12,7 +12,8 @@
// Standard C/C++ main entry point // Standard C/C++ main entry point
int main (int argc, char * argv[]) { int main (int argc, char * argv[]) {
return Catch::Session().run( argc, argv ); int result = Catch::Session().run( argc, argv );
return ( result < 0xff ? result : 0xff );
} }
#else // __OBJC__ #else // __OBJC__
...@@ -30,7 +31,7 @@ int main (int argc, char * const argv[]) { ...@@ -30,7 +31,7 @@ int main (int argc, char * const argv[]) {
[pool drain]; [pool drain];
#endif #endif
return result; return ( result < 0xff ? result : 0xff );
} }
#endif // __OBJC__ #endif // __OBJC__
......
...@@ -14,90 +14,155 @@ ...@@ -14,90 +14,155 @@
namespace Catch { namespace Catch {
// Wraps the LHS of an expression and captures the operator and RHS (if any) - template<typename LhsT, Internal::Operator Op, typename RhsT>
// wrapping them all in a ResultBuilder object class BinaryExpression;
template<typename T>
class ExpressionLhs { template<typename ArgT, typename MatcherT>
ExpressionLhs& operator = ( ExpressionLhs const& ); class MatchExpression;
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
ExpressionLhs& operator = ( ExpressionLhs && ) = delete;
# endif
// Wraps the LHS of an expression and overloads comparison operators
// for also capturing those and RHS (if any)
template<typename T>
class ExpressionLhs : public DecomposedExpression {
public: public:
ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ) {} ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ), m_truthy(false) {}
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
ExpressionLhs( ExpressionLhs const& ) = default;
ExpressionLhs( ExpressionLhs && ) = default;
# endif
template<typename RhsT> template<typename RhsT>
ResultBuilder& operator == ( RhsT const& rhs ) { BinaryExpression<T, Internal::IsEqualTo, RhsT const&>
operator == ( RhsT const& rhs ) {
return captureExpression<Internal::IsEqualTo>( rhs ); return captureExpression<Internal::IsEqualTo>( rhs );
} }
template<typename RhsT> template<typename RhsT>
ResultBuilder& operator != ( RhsT const& rhs ) { BinaryExpression<T, Internal::IsNotEqualTo, RhsT const&>
operator != ( RhsT const& rhs ) {
return captureExpression<Internal::IsNotEqualTo>( rhs ); return captureExpression<Internal::IsNotEqualTo>( rhs );
} }
template<typename RhsT> template<typename RhsT>
ResultBuilder& operator < ( RhsT const& rhs ) { BinaryExpression<T, Internal::IsLessThan, RhsT const&>
operator < ( RhsT const& rhs ) {
return captureExpression<Internal::IsLessThan>( rhs ); return captureExpression<Internal::IsLessThan>( rhs );
} }
template<typename RhsT> template<typename RhsT>
ResultBuilder& operator > ( RhsT const& rhs ) { BinaryExpression<T, Internal::IsGreaterThan, RhsT const&>
operator > ( RhsT const& rhs ) {
return captureExpression<Internal::IsGreaterThan>( rhs ); return captureExpression<Internal::IsGreaterThan>( rhs );
} }
template<typename RhsT> template<typename RhsT>
ResultBuilder& operator <= ( RhsT const& rhs ) { BinaryExpression<T, Internal::IsLessThanOrEqualTo, RhsT const&>
operator <= ( RhsT const& rhs ) {
return captureExpression<Internal::IsLessThanOrEqualTo>( rhs ); return captureExpression<Internal::IsLessThanOrEqualTo>( rhs );
} }
template<typename RhsT> template<typename RhsT>
ResultBuilder& operator >= ( RhsT const& rhs ) { BinaryExpression<T, Internal::IsGreaterThanOrEqualTo, RhsT const&>
operator >= ( RhsT const& rhs ) {
return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs ); return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs );
} }
ResultBuilder& operator == ( bool rhs ) { BinaryExpression<T, Internal::IsEqualTo, bool> operator == ( bool rhs ) {
return captureExpression<Internal::IsEqualTo>( rhs ); return captureExpression<Internal::IsEqualTo>( rhs );
} }
ResultBuilder& operator != ( bool rhs ) { BinaryExpression<T, Internal::IsNotEqualTo, bool> operator != ( bool rhs ) {
return captureExpression<Internal::IsNotEqualTo>( rhs ); return captureExpression<Internal::IsNotEqualTo>( rhs );
} }
void endExpression() { void endExpression() {
bool value = m_lhs ? true : false; m_truthy = m_lhs ? true : false;
m_rb m_rb
.setLhs( Catch::toString( value ) ) .setResultType( m_truthy )
.setResultType( value ) .endExpression( *this );
.endExpression();
} }
// Only simple binary expressions are allowed on the LHS. virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
// If more complex compositions are required then place the sub expression in parentheses dest = Catch::toString( m_truthy );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& ); }
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& );
private: private:
template<Internal::Operator Op, typename RhsT> template<Internal::Operator Op, typename RhsT>
ResultBuilder& captureExpression( RhsT const& rhs ) { BinaryExpression<T, Op, RhsT&> captureExpression( RhsT& rhs ) const {
return m_rb return BinaryExpression<T, Op, RhsT&>( m_rb, m_lhs, rhs );
.setResultType( Internal::compare<Op>( m_lhs, rhs ) ) }
.setLhs( Catch::toString( m_lhs ) )
.setRhs( Catch::toString( rhs ) ) template<Internal::Operator Op>
.setOp( Internal::OperatorTraits<Op>::getName() ); BinaryExpression<T, Op, bool> captureExpression( bool rhs ) const {
return BinaryExpression<T, Op, bool>( m_rb, m_lhs, rhs );
} }
private: private:
ResultBuilder& m_rb; ResultBuilder& m_rb;
T m_lhs; T m_lhs;
bool m_truthy;
};
template<typename LhsT, Internal::Operator Op, typename RhsT>
class BinaryExpression : public DecomposedExpression {
public:
BinaryExpression( ResultBuilder& rb, LhsT lhs, RhsT rhs )
: m_rb( rb ), m_lhs( lhs ), m_rhs( rhs ) {}
void endExpression() const {
m_rb
.setResultType( Internal::compare<Op>( m_lhs, m_rhs ) )
.endExpression( *this );
}
virtual bool isBinaryExpression() const CATCH_OVERRIDE {
return true;
}
virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
std::string lhs = Catch::toString( m_lhs );
std::string rhs = Catch::toString( m_rhs );
char delim = lhs.size() + rhs.size() < 40 &&
lhs.find('\n') == std::string::npos &&
rhs.find('\n') == std::string::npos ? ' ' : '\n';
dest.reserve( 7 + lhs.size() + rhs.size() );
// 2 for spaces around operator
// 2 for operator
// 2 for parentheses (conditionally added later)
// 1 for negation (conditionally added later)
dest = lhs;
dest += delim;
dest += Internal::OperatorTraits<Op>::getName();
dest += delim;
dest += rhs;
}
private:
ResultBuilder& m_rb;
LhsT m_lhs;
RhsT m_rhs;
};
template<typename ArgT, typename MatcherT>
class MatchExpression : public DecomposedExpression {
public:
MatchExpression( ArgT arg, MatcherT matcher, char const* matcherString )
: m_arg( arg ), m_matcher( matcher ), m_matcherString( matcherString ) {}
virtual bool isBinaryExpression() const CATCH_OVERRIDE {
return true;
}
virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
std::string matcherAsString = m_matcher.toString();
dest = Catch::toString( m_arg );
dest += ' ';
if( matcherAsString == Detail::unprintableString )
dest += m_matcherString;
else
dest += matcherAsString;
}
private:
ArgT m_arg;
MatcherT m_matcher;
char const* m_matcherString;
}; };
} // end namespace Catch } // end namespace Catch
......
...@@ -12,35 +12,105 @@ ...@@ -12,35 +12,105 @@
namespace Catch { namespace Catch {
// Report the error condition then exit the process // Report the error condition
inline void fatal( std::string const& message, int exitCode ) { inline void reportFatal( std::string const& message ) {
IContext& context = Catch::getCurrentContext(); IContext& context = Catch::getCurrentContext();
IResultCapture* resultCapture = context.getResultCapture(); IResultCapture* resultCapture = context.getResultCapture();
resultCapture->handleFatalErrorCondition( message ); resultCapture->handleFatalErrorCondition( message );
if( Catch::alwaysTrue() ) // avoids "no return" warnings
exit( exitCode );
} }
} // namespace Catch } // namespace Catch
#if defined ( CATCH_PLATFORM_WINDOWS ) ///////////////////////////////////////// #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
#include "catch_windows_h_proxy.h"
# if !defined ( CATCH_CONFIG_WINDOWS_SEH )
namespace Catch {
struct FatalConditionHandler {
void reset() {}
};
}
# else // CATCH_CONFIG_WINDOWS_SEH is defined
namespace Catch { namespace Catch {
struct SignalDefs { DWORD id; const char* name; };
extern SignalDefs signalDefs[];
// There is no 1-1 mapping between signals and windows exceptions.
// Windows can easily distinguish between SO and SigSegV,
// but SigInt, SigTerm, etc are handled differently.
SignalDefs signalDefs[] = {
{ EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
{ EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
{ EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
{ EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
};
struct FatalConditionHandler { struct FatalConditionHandler {
void reset() {}
}; static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
for (int i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
if (ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) {
reset();
reportFatal(signalDefs[i].name);
}
}
// If its not an exception we care about, pass it along.
// This stops us from eating debugger breaks etc.
return EXCEPTION_CONTINUE_SEARCH;
}
FatalConditionHandler() {
isSet = true;
// 32k seems enough for Catch to handle stack overflow,
// but the value was found experimentally, so there is no strong guarantee
guaranteeSize = 32 * 1024;
exceptionHandlerHandle = CATCH_NULL;
// Register as first handler in current chain
exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
// Pass in guarantee size to be filled
SetThreadStackGuarantee(&guaranteeSize);
}
static void reset() {
if (isSet) {
// Unregister handler and restore the old guarantee
RemoveVectoredExceptionHandler(exceptionHandlerHandle);
SetThreadStackGuarantee(&guaranteeSize);
exceptionHandlerHandle = CATCH_NULL;
isSet = false;
}
}
~FatalConditionHandler() {
reset();
}
private:
static bool isSet;
static ULONG guaranteeSize;
static PVOID exceptionHandlerHandle;
};
bool FatalConditionHandler::isSet = false;
ULONG FatalConditionHandler::guaranteeSize = 0;
PVOID FatalConditionHandler::exceptionHandlerHandle = CATCH_NULL;
} // namespace Catch } // namespace Catch
# endif // CATCH_CONFIG_WINDOWS_SEH
#else // Not Windows - assumed to be POSIX compatible ////////////////////////// #else // Not Windows - assumed to be POSIX compatible //////////////////////////
#include <signal.h> #include <signal.h>
namespace Catch { namespace Catch {
struct SignalDefs { int id; const char* name; }; struct SignalDefs {
int id;
const char* name;
};
extern SignalDefs signalDefs[]; extern SignalDefs signalDefs[];
SignalDefs signalDefs[] = { SignalDefs signalDefs[] = {
{ SIGINT, "SIGINT - Terminal interrupt signal" }, { SIGINT, "SIGINT - Terminal interrupt signal" },
...@@ -49,35 +119,68 @@ namespace Catch { ...@@ -49,35 +119,68 @@ namespace Catch {
{ SIGSEGV, "SIGSEGV - Segmentation violation signal" }, { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
{ SIGTERM, "SIGTERM - Termination request signal" }, { SIGTERM, "SIGTERM - Termination request signal" },
{ SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
}; };
struct FatalConditionHandler { struct FatalConditionHandler {
static bool isSet;
static struct sigaction oldSigActions [sizeof(signalDefs)/sizeof(SignalDefs)];
static stack_t oldSigStack;
static char altStackMem[SIGSTKSZ];
static void handleSignal( int sig ) { static void handleSignal( int sig ) {
for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) std::string name = "<unknown signal>";
if( sig == signalDefs[i].id ) for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
fatal( signalDefs[i].name, -sig ); SignalDefs &def = signalDefs[i];
fatal( "<unknown signal>", -sig ); if (sig == def.id) {
name = def.name;
break;
}
}
reset();
reportFatal(name);
raise( sig );
} }
FatalConditionHandler() : m_isSet( true ) { FatalConditionHandler() {
for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) isSet = true;
signal( signalDefs[i].id, handleSignal ); stack_t sigStack;
sigStack.ss_sp = altStackMem;
sigStack.ss_size = SIGSTKSZ;
sigStack.ss_flags = 0;
sigaltstack(&sigStack, &oldSigStack);
struct sigaction sa = { 0 };
sa.sa_handler = handleSignal;
sa.sa_flags = SA_ONSTACK;
for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
}
} }
~FatalConditionHandler() { ~FatalConditionHandler() {
reset(); reset();
} }
void reset() { static void reset() {
if( m_isSet ) { if( isSet ) {
for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
signal( signalDefs[i].id, SIG_DFL ); for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
m_isSet = false; sigaction(signalDefs[i].id, &oldSigActions[i], CATCH_NULL);
}
// Return the old stack
sigaltstack(&oldSigStack, CATCH_NULL);
isSet = false;
} }
} }
bool m_isSet;
}; };
bool FatalConditionHandler::isSet = false;
struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
stack_t FatalConditionHandler::oldSigStack = {};
char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
} // namespace Catch } // namespace Catch
#endif // not Windows #endif // not Windows
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
#ifndef TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED #ifndef TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
#define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED #define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
#include <iostream> #include <iosfwd>
#include <string> #include <string>
#include <vector> #include <vector>
...@@ -41,7 +41,7 @@ namespace Catch { ...@@ -41,7 +41,7 @@ namespace Catch {
Auto, Auto,
Yes, Yes,
No No
}; }; }; };
class TestSpec; class TestSpec;
...@@ -62,6 +62,8 @@ namespace Catch { ...@@ -62,6 +62,8 @@ namespace Catch {
virtual RunTests::InWhatOrder runOrder() const = 0; virtual RunTests::InWhatOrder runOrder() const = 0;
virtual unsigned int rngSeed() const = 0; virtual unsigned int rngSeed() const = 0;
virtual UseColour::YesOrNo useColour() const = 0; virtual UseColour::YesOrNo useColour() const = 0;
virtual std::vector<std::string> const& getSectionsToRun() const = 0;
}; };
} }
......
...@@ -21,7 +21,6 @@ ...@@ -21,7 +21,6 @@
#include <string> #include <string>
#include <ostream> #include <ostream>
#include <map> #include <map>
#include <assert.h>
namespace Catch namespace Catch
{ {
...@@ -248,7 +247,7 @@ namespace Catch ...@@ -248,7 +247,7 @@ namespace Catch
virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
virtual void skipTest( TestCaseInfo const& testInfo ) = 0; virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
virtual MultipleReporters* tryAsMulti() { return CATCH_NULL; } virtual MultipleReporters* tryAsMulti() { return CATCH_NULL; }
}; };
......
...@@ -51,9 +51,9 @@ namespace Catch { ...@@ -51,9 +51,9 @@ namespace Catch {
} }
if( !config.testSpec().hasFilters() ) if( !config.testSpec().hasFilters() )
Catch::cout() << pluralise( matchedTests, "test case" ) << "\n" << std::endl; Catch::cout() << pluralise( matchedTests, "test case" ) << '\n' << std::endl;
else else
Catch::cout() << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl; Catch::cout() << pluralise( matchedTests, "matching test case" ) << '\n' << std::endl;
return matchedTests; return matchedTests;
} }
...@@ -68,8 +68,8 @@ namespace Catch { ...@@ -68,8 +68,8 @@ namespace Catch {
++it ) { ++it ) {
matchedTests++; matchedTests++;
TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
if( startsWith( testCaseInfo.name, "#" ) ) if( startsWith( testCaseInfo.name, '#' ) )
Catch::cout() << "\"" << testCaseInfo.name << "\"" << std::endl; Catch::cout() << '"' << testCaseInfo.name << '"' << std::endl;
else else
Catch::cout() << testCaseInfo.name << std::endl; Catch::cout() << testCaseInfo.name << std::endl;
} }
...@@ -132,9 +132,9 @@ namespace Catch { ...@@ -132,9 +132,9 @@ namespace Catch {
.setInitialIndent( 0 ) .setInitialIndent( 0 )
.setIndent( oss.str().size() ) .setIndent( oss.str().size() )
.setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) ); .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) );
Catch::cout() << oss.str() << wrapper << "\n"; Catch::cout() << oss.str() << wrapper << '\n';
} }
Catch::cout() << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl; Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
return tagCounts.size(); return tagCounts.size();
} }
...@@ -153,9 +153,9 @@ namespace Catch { ...@@ -153,9 +153,9 @@ namespace Catch {
.setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) ); .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) );
Catch::cout() << " " Catch::cout() << " "
<< it->first << it->first
<< ":" << ':'
<< std::string( maxNameLen - it->first.size() + 2, ' ' ) << std::string( maxNameLen - it->first.size() + 2, ' ' )
<< wrapper << "\n"; << wrapper << '\n';
} }
Catch::cout() << std::endl; Catch::cout() << std::endl;
return factories.size(); return factories.size();
......
...@@ -184,7 +184,7 @@ namespace Matchers { ...@@ -184,7 +184,7 @@ namespace Matchers {
{ {
return m_caseSensitivity == CaseSensitive::No return m_caseSensitivity == CaseSensitive::No
? " (case insensitive)" ? " (case insensitive)"
: ""; : std::string();
} }
CaseSensitive::Choice m_caseSensitivity; CaseSensitive::Choice m_caseSensitivity;
std::string m_str; std::string m_str;
...@@ -202,7 +202,7 @@ namespace Matchers { ...@@ -202,7 +202,7 @@ namespace Matchers {
return m_data.m_str == m_data.adjustString( expr );; return m_data.m_str == m_data.adjustString( expr );;
} }
virtual std::string toString() const { virtual std::string toString() const {
return "equals: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); return "equals: \"" + m_data.m_str + '"' + m_data.toStringSuffix();
} }
CasedString m_data; CasedString m_data;
...@@ -219,7 +219,7 @@ namespace Matchers { ...@@ -219,7 +219,7 @@ namespace Matchers {
return m_data.adjustString( expr ).find( m_data.m_str ) != std::string::npos; return m_data.adjustString( expr ).find( m_data.m_str ) != std::string::npos;
} }
virtual std::string toString() const { virtual std::string toString() const {
return "contains: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); return "contains: \"" + m_data.m_str + '"' + m_data.toStringSuffix();
} }
CasedString m_data; CasedString m_data;
...@@ -237,7 +237,7 @@ namespace Matchers { ...@@ -237,7 +237,7 @@ namespace Matchers {
return startsWith( m_data.adjustString( expr ), m_data.m_str ); return startsWith( m_data.adjustString( expr ), m_data.m_str );
} }
virtual std::string toString() const { virtual std::string toString() const {
return "starts with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); return "starts with: \"" + m_data.m_str + '"' + m_data.toStringSuffix();
} }
CasedString m_data; CasedString m_data;
...@@ -254,7 +254,7 @@ namespace Matchers { ...@@ -254,7 +254,7 @@ namespace Matchers {
return endsWith( m_data.adjustString( expr ), m_data.m_str ); return endsWith( m_data.adjustString( expr ), m_data.m_str );
} }
virtual std::string toString() const { virtual std::string toString() const {
return "ends with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); return "ends with: \"" + m_data.m_str + '"' + m_data.toStringSuffix();
} }
CasedString m_data; CasedString m_data;
......
...@@ -9,7 +9,6 @@ ...@@ -9,7 +9,6 @@
#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED
#include "catch_common.h" #include "catch_common.h"
#include <ostream>
namespace Catch { namespace Catch {
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED
#include "catch_notimplemented_exception.h" #include "catch_notimplemented_exception.h"
#include <ostream> #include <sstream>
namespace Catch { namespace Catch {
......
...@@ -10,11 +10,19 @@ ...@@ -10,11 +10,19 @@
#define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED #define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED
#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
#define CATCH_PLATFORM_MAC # define CATCH_PLATFORM_MAC
#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#define CATCH_PLATFORM_IPHONE # define CATCH_PLATFORM_IPHONE
#elif defined(linux) || defined(__linux) || defined(__linux__)
# define CATCH_PLATFORM_LINUX
#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
#define CATCH_PLATFORM_WINDOWS # define CATCH_PLATFORM_WINDOWS
# if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
# define CATCH_DEFINES_NOMINMAX
# endif
# if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
# define CATCH_DEFINES_WIN32_LEAN_AND_MEAN
# endif
#endif #endif
#endif // TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED #endif // TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED
...@@ -74,7 +74,7 @@ namespace Catch { ...@@ -74,7 +74,7 @@ namespace Catch {
return new T( config ); return new T( config );
} }
virtual std::string getDescription() const { virtual std::string getDescription() const {
return ""; return std::string();
} }
}; };
......
...@@ -19,22 +19,20 @@ namespace Catch { ...@@ -19,22 +19,20 @@ namespace Catch {
template<typename T> class ExpressionLhs; template<typename T> class ExpressionLhs;
struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
struct CopyableStream { struct CopyableStream {
CopyableStream() {} CopyableStream() {}
CopyableStream( CopyableStream const& other ) { CopyableStream( CopyableStream const& other ) {
oss << other.oss.str(); oss << other.oss.str();
} }
CopyableStream& operator=( CopyableStream const& other ) { CopyableStream& operator=( CopyableStream const& other ) {
oss.str(""); oss.str(std::string());
oss << other.oss.str(); oss << other.oss.str();
return *this; return *this;
} }
std::ostringstream oss; std::ostringstream oss;
}; };
class ResultBuilder { class ResultBuilder : public DecomposedExpression {
public: public:
ResultBuilder( char const* macroName, ResultBuilder( char const* macroName,
SourceLineInfo const& lineInfo, SourceLineInfo const& lineInfo,
...@@ -52,19 +50,15 @@ namespace Catch { ...@@ -52,19 +50,15 @@ namespace Catch {
return *this; return *this;
} }
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& );
ResultBuilder& setResultType( ResultWas::OfType result ); ResultBuilder& setResultType( ResultWas::OfType result );
ResultBuilder& setResultType( bool result ); ResultBuilder& setResultType( bool result );
ResultBuilder& setLhs( std::string const& lhs );
ResultBuilder& setRhs( std::string const& rhs );
ResultBuilder& setOp( std::string const& op );
void endExpression(); void endExpression( DecomposedExpression const& expr );
virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE;
std::string reconstructExpression() const;
AssertionResult build() const; AssertionResult build() const;
AssertionResult build( DecomposedExpression const& expr ) const;
void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal ); void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal );
void captureResult( ResultWas::OfType resultType ); void captureResult( ResultWas::OfType resultType );
...@@ -76,14 +70,12 @@ namespace Catch { ...@@ -76,14 +70,12 @@ namespace Catch {
bool shouldDebugBreak() const; bool shouldDebugBreak() const;
bool allowThrows() const; bool allowThrows() const;
template<typename ArgT, typename MatcherT>
void captureMatch( ArgT const& arg, MatcherT const& matcher, char const* matcherString );
private: private:
AssertionInfo m_assertionInfo; AssertionInfo m_assertionInfo;
AssertionResultData m_data; AssertionResultData m_data;
struct ExprComponents {
ExprComponents() : testFalse( false ) {}
bool testFalse;
std::string lhs, rhs, op;
} m_exprComponents;
CopyableStream m_stream; CopyableStream m_stream;
bool m_shouldDebugBreak; bool m_shouldDebugBreak;
...@@ -106,6 +98,14 @@ namespace Catch { ...@@ -106,6 +98,14 @@ namespace Catch {
return ExpressionLhs<bool>( *this, value ); return ExpressionLhs<bool>( *this, value );
} }
template<typename ArgT, typename MatcherT>
inline void ResultBuilder::captureMatch( ArgT const& arg, MatcherT const& matcher,
char const* matcherString ) {
MatchExpression<ArgT const&, MatcherT const&> expr( arg, matcher, matcherString );
setResultType( matcher.match( arg ) );
endExpression( expr );
}
} // namespace Catch } // namespace Catch
#endif // TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED #endif // TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED
...@@ -41,22 +41,10 @@ namespace Catch { ...@@ -41,22 +41,10 @@ namespace Catch {
m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed;
return *this; return *this;
} }
ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) {
m_exprComponents.lhs = lhs;
return *this;
}
ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) {
m_exprComponents.rhs = rhs;
return *this;
}
ResultBuilder& ResultBuilder::setOp( std::string const& op ) {
m_exprComponents.op = op;
return *this;
}
void ResultBuilder::endExpression() { void ResultBuilder::endExpression( DecomposedExpression const& expr ) {
m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition ); AssertionResult result = build( expr );
captureExpression(); handleResult( result );
} }
void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) {
...@@ -69,6 +57,7 @@ namespace Catch { ...@@ -69,6 +57,7 @@ namespace Catch {
setResultType( resultType ); setResultType( resultType );
captureExpression(); captureExpression();
} }
void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) { void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) {
if( expectedMessage.empty() ) if( expectedMessage.empty() )
captureExpectedException( Matchers::Impl::Generic::AllOf<std::string>() ); captureExpectedException( Matchers::Impl::Generic::AllOf<std::string>() );
...@@ -78,7 +67,7 @@ namespace Catch { ...@@ -78,7 +67,7 @@ namespace Catch {
void ResultBuilder::captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher ) { void ResultBuilder::captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher ) {
assert( m_exprComponents.testFalse == false ); assert( !isFalseTest( m_assertionInfo.resultDisposition ) );
AssertionResultData data = m_data; AssertionResultData data = m_data;
data.resultType = ResultWas::Ok; data.resultType = ResultWas::Ok;
data.reconstructedExpression = m_assertionInfo.capturedExpression; data.reconstructedExpression = m_assertionInfo.capturedExpression;
...@@ -96,6 +85,7 @@ namespace Catch { ...@@ -96,6 +85,7 @@ namespace Catch {
AssertionResult result = build(); AssertionResult result = build();
handleResult( result ); handleResult( result );
} }
void ResultBuilder::handleResult( AssertionResult const& result ) void ResultBuilder::handleResult( AssertionResult const& result )
{ {
getResultCapture().assertionEnded( result ); getResultCapture().assertionEnded( result );
...@@ -107,6 +97,7 @@ namespace Catch { ...@@ -107,6 +97,7 @@ namespace Catch {
m_shouldThrow = true; m_shouldThrow = true;
} }
} }
void ResultBuilder::react() { void ResultBuilder::react() {
if( m_shouldThrow ) if( m_shouldThrow )
throw Catch::TestFailureException(); throw Catch::TestFailureException();
...@@ -117,43 +108,32 @@ namespace Catch { ...@@ -117,43 +108,32 @@ namespace Catch {
AssertionResult ResultBuilder::build() const AssertionResult ResultBuilder::build() const
{ {
assert( m_data.resultType != ResultWas::Unknown ); return build( *this );
}
// CAVEAT: The returned AssertionResult stores a pointer to the argument expr,
// a temporary DecomposedExpression, which in turn holds references to
// operands, possibly temporary as well.
// It should immediately be passed to handleResult; if the expression
// needs to be reported, its string expansion must be composed before
// the temporaries are destroyed.
AssertionResult ResultBuilder::build( DecomposedExpression const& expr ) const
{
assert( m_data.resultType != ResultWas::Unknown );
AssertionResultData data = m_data; AssertionResultData data = m_data;
// Flip bool results if testFalse is set // Flip bool results if FalseTest flag is set
if( m_exprComponents.testFalse ) { if( isFalseTest( m_assertionInfo.resultDisposition ) ) {
if( data.resultType == ResultWas::Ok ) data.negate( expr.isBinaryExpression() );
data.resultType = ResultWas::ExpressionFailed;
else if( data.resultType == ResultWas::ExpressionFailed )
data.resultType = ResultWas::Ok;
} }
data.message = m_stream.oss.str(); data.message = m_stream.oss.str();
data.reconstructedExpression = reconstructExpression(); data.decomposedExpression = &expr; // for lazy reconstruction
if( m_exprComponents.testFalse ) {
if( m_exprComponents.op == "" )
data.reconstructedExpression = "!" + data.reconstructedExpression;
else
data.reconstructedExpression = "!(" + data.reconstructedExpression + ")";
}
return AssertionResult( m_assertionInfo, data ); return AssertionResult( m_assertionInfo, data );
} }
std::string ResultBuilder::reconstructExpression() const {
if( m_exprComponents.op == "" ) void ResultBuilder::reconstructExpression( std::string& dest ) const {
return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.lhs; dest = m_assertionInfo.capturedExpression;
else if( m_exprComponents.op == "matches" )
return m_exprComponents.lhs + " " + m_exprComponents.rhs;
else if( m_exprComponents.op != "!" ) {
if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 &&
m_exprComponents.lhs.find("\n") == std::string::npos &&
m_exprComponents.rhs.find("\n") == std::string::npos )
return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs;
else
return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs;
}
else
return "{can't expand - use " + m_assertionInfo.macroName + "_FALSE( " + m_assertionInfo.capturedExpression.substr(1) + " ) instead of " + m_assertionInfo.macroName + "( " + m_assertionInfo.capturedExpression + " ) for better diagnostics}";
} }
} // end namespace Catch } // end namespace Catch
......
...@@ -97,10 +97,12 @@ namespace Catch { ...@@ -97,10 +97,12 @@ namespace Catch {
do { do {
m_trackerContext.startRun(); ITracker& rootTracker = m_trackerContext.startRun();
assert( rootTracker.isSectionTracker() );
static_cast<SectionTracker&>( rootTracker ).addInitialFilters( m_config->getSectionsToRun() );
do { do {
m_trackerContext.startCycle(); m_trackerContext.startCycle();
m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, testInfo.name ); m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( testInfo.name, testInfo.lineInfo ) );
runCurrentTest( redirectedCout, redirectedCerr ); runCurrentTest( redirectedCout, redirectedCerr );
} }
while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() ); while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() );
...@@ -146,7 +148,7 @@ namespace Catch { ...@@ -146,7 +148,7 @@ namespace Catch {
m_messages.clear(); m_messages.clear();
// Reset working state // Reset working state
m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); m_lastAssertionInfo = AssertionInfo( std::string(), m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition );
m_lastResult = result; m_lastResult = result;
} }
...@@ -155,10 +157,7 @@ namespace Catch { ...@@ -155,10 +157,7 @@ namespace Catch {
Counts& assertions Counts& assertions
) )
{ {
std::ostringstream oss; ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( sectionInfo.name, sectionInfo.lineInfo ) );
oss << sectionInfo.name << "@" << sectionInfo.lineInfo;
ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, oss.str() );
if( !sectionTracker.isOpen() ) if( !sectionTracker.isOpen() )
return false; return false;
m_activeSections.push_back( &sectionTracker ); m_activeSections.push_back( &sectionTracker );
...@@ -217,7 +216,7 @@ namespace Catch { ...@@ -217,7 +216,7 @@ namespace Catch {
virtual std::string getCurrentTestName() const { virtual std::string getCurrentTestName() const {
return m_activeTestCase return m_activeTestCase
? m_activeTestCase->getTestCaseInfo().name ? m_activeTestCase->getTestCaseInfo().name
: ""; : std::string();
} }
virtual const AssertionResult* getLastResult() const { virtual const AssertionResult* getLastResult() const {
...@@ -247,11 +246,11 @@ namespace Catch { ...@@ -247,11 +246,11 @@ namespace Catch {
deltaTotals.testCases.failed = 1; deltaTotals.testCases.failed = 1;
m_reporter->testCaseEnded( TestCaseStats( testInfo, m_reporter->testCaseEnded( TestCaseStats( testInfo,
deltaTotals, deltaTotals,
"", std::string(),
"", std::string(),
false ) ); false ) );
m_totals.testCases.failed++; m_totals.testCases.failed++;
testGroupEnded( "", m_totals, 1, 1 ); testGroupEnded( std::string(), m_totals, 1, 1 );
m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) );
} }
...@@ -270,7 +269,7 @@ namespace Catch { ...@@ -270,7 +269,7 @@ namespace Catch {
Counts prevAssertions = m_totals.assertions; Counts prevAssertions = m_totals.assertions;
double duration = 0; double duration = 0;
try { try {
m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal ); m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, std::string(), ResultDisposition::Normal );
seedRng( *m_config ); seedRng( *m_config );
......
...@@ -11,7 +11,6 @@ ...@@ -11,7 +11,6 @@
#include "catch_section.h" #include "catch_section.h"
#include "catch_capture.hpp" #include "catch_capture.hpp"
#include "catch_compiler_capabilities.h" #include "catch_compiler_capabilities.h"
#include "catch_timer.h"
namespace Catch { namespace Catch {
......
...@@ -11,6 +11,8 @@ ...@@ -11,6 +11,8 @@
#include "catch_common.h" #include "catch_common.h"
#include "catch_totals.hpp" #include "catch_totals.hpp"
#include <string>
namespace Catch { namespace Catch {
struct SectionInfo { struct SectionInfo {
......
...@@ -8,10 +8,7 @@ ...@@ -8,10 +8,7 @@
#ifndef TWOBLUECUBES_CATCH_SECTION_INFO_HPP_INCLUDED #ifndef TWOBLUECUBES_CATCH_SECTION_INFO_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_SECTION_INFO_HPP_INCLUDED #define TWOBLUECUBES_CATCH_SECTION_INFO_HPP_INCLUDED
#include "catch_common.h" #include "catch_section_info.h"
#include <map>
#include <string>
namespace Catch { namespace Catch {
......
...@@ -61,7 +61,7 @@ namespace Catch { ...@@ -61,7 +61,7 @@ namespace Catch {
m_ofs.open( filename.c_str() ); m_ofs.open( filename.c_str() );
if( m_ofs.fail() ) { if( m_ofs.fail() ) {
std::ostringstream oss; std::ostringstream oss;
oss << "Unable to open file: '" << filename << "'"; oss << "Unable to open file: '" << filename << '\'';
throw std::domain_error( oss.str() ); throw std::domain_error( oss.str() );
} }
} }
......
...@@ -11,9 +11,6 @@ ...@@ -11,9 +11,6 @@
#include "catch_tag_alias_registry.h" #include "catch_tag_alias_registry.h"
#include "catch_console_colour.hpp" #include "catch_console_colour.hpp"
#include <map>
#include <iostream>
namespace Catch { namespace Catch {
TagAliasRegistry::~TagAliasRegistry() {} TagAliasRegistry::~TagAliasRegistry() {}
...@@ -43,7 +40,7 @@ namespace Catch { ...@@ -43,7 +40,7 @@ namespace Catch {
void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) {
if( !startsWith( alias, "[@" ) || !endsWith( alias, "]" ) ) { if( !startsWith( alias, "[@" ) || !endsWith( alias, ']' ) ) {
std::ostringstream oss; std::ostringstream oss;
oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo; oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo;
throw std::domain_error( oss.str().c_str() ); throw std::domain_error( oss.str().c_str() );
...@@ -51,7 +48,7 @@ namespace Catch { ...@@ -51,7 +48,7 @@ namespace Catch {
if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) {
std::ostringstream oss; std::ostringstream oss;
oss << "error: tag alias, \"" << alias << "\" already registered.\n" oss << "error: tag alias, \"" << alias << "\" already registered.\n"
<< "\tFirst seen at " << find(alias)->lineInfo << "\n" << "\tFirst seen at " << find(alias)->lineInfo << '\n'
<< "\tRedefined at " << lineInfo; << "\tRedefined at " << lineInfo;
throw std::domain_error( oss.str().c_str() ); throw std::domain_error( oss.str().c_str() );
} }
......
...@@ -29,7 +29,8 @@ namespace Catch { ...@@ -29,7 +29,8 @@ namespace Catch {
IsHidden = 1 << 1, IsHidden = 1 << 1,
ShouldFail = 1 << 2, ShouldFail = 1 << 2,
MayFail = 1 << 3, MayFail = 1 << 3,
Throws = 1 << 4 Throws = 1 << 4,
NonPortable = 1 << 5
}; };
TestCaseInfo( std::string const& _name, TestCaseInfo( std::string const& _name,
......
...@@ -13,10 +13,12 @@ ...@@ -13,10 +13,12 @@
#include "catch_interfaces_testcase.h" #include "catch_interfaces_testcase.h"
#include "catch_common.h" #include "catch_common.h"
#include <cctype>
namespace Catch { namespace Catch {
inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
if( startsWith( tag, "." ) || if( startsWith( tag, '.' ) ||
tag == "hide" || tag == "hide" ||
tag == "!hide" ) tag == "!hide" )
return TestCaseInfo::IsHidden; return TestCaseInfo::IsHidden;
...@@ -26,11 +28,13 @@ namespace Catch { ...@@ -26,11 +28,13 @@ namespace Catch {
return TestCaseInfo::ShouldFail; return TestCaseInfo::ShouldFail;
else if( tag == "!mayfail" ) else if( tag == "!mayfail" )
return TestCaseInfo::MayFail; return TestCaseInfo::MayFail;
else if( tag == "!nonportable" )
return TestCaseInfo::NonPortable;
else else
return TestCaseInfo::None; return TestCaseInfo::None;
} }
inline bool isReservedTag( std::string const& tag ) { inline bool isReservedTag( std::string const& tag ) {
return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] ); return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
} }
inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
if( isReservedTag( tag ) ) { if( isReservedTag( tag ) ) {
...@@ -100,7 +104,7 @@ namespace Catch { ...@@ -100,7 +104,7 @@ namespace Catch {
std::ostringstream oss; std::ostringstream oss;
for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) { for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) {
oss << "[" << *it << "]"; oss << '[' << *it << ']';
std::string lcaseTag = toLower( *it ); std::string lcaseTag = toLower( *it );
testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
testCaseInfo.lcaseTags.insert( lcaseTag ); testCaseInfo.lcaseTags.insert( lcaseTag );
......
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
#include <vector> #include <vector>
#include <set> #include <set>
#include <sstream> #include <sstream>
#include <iostream>
#include <algorithm> #include <algorithm>
...@@ -78,7 +77,7 @@ namespace Catch { ...@@ -78,7 +77,7 @@ namespace Catch {
ss << Colour( Colour::Red ) ss << Colour( Colour::Red )
<< "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n" << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n"
<< "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n" << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << '\n'
<< "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl; << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl;
throw std::runtime_error(ss.str()); throw std::runtime_error(ss.str());
...@@ -110,7 +109,7 @@ namespace Catch { ...@@ -110,7 +109,7 @@ namespace Catch {
virtual void registerTest( TestCase const& testCase ) { virtual void registerTest( TestCase const& testCase ) {
std::string name = testCase.getTestCaseInfo().name; std::string name = testCase.getTestCaseInfo().name;
if( name == "" ) { if( name.empty() ) {
std::ostringstream oss; std::ostringstream oss;
oss << "Anonymous test case " << ++m_unnamedCount; oss << "Anonymous test case " << ++m_unnamedCount;
return registerTest( testCase.withName( oss.str() ) ); return registerTest( testCase.withName( oss.str() ) );
...@@ -159,7 +158,7 @@ namespace Catch { ...@@ -159,7 +158,7 @@ namespace Catch {
inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) { inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
std::string className = classOrQualifiedMethodName; std::string className = classOrQualifiedMethodName;
if( startsWith( className, "&" ) ) if( startsWith( className, '&' ) )
{ {
std::size_t lastColons = className.rfind( "::" ); std::size_t lastColons = className.rfind( "::" );
std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
......
...@@ -15,15 +15,27 @@ ...@@ -15,15 +15,27 @@
#include <string> #include <string>
#include <assert.h> #include <assert.h>
#include <vector> #include <vector>
#include <iterator>
#include <stdexcept>
namespace Catch { namespace Catch {
namespace TestCaseTracking { namespace TestCaseTracking {
struct NameAndLocation {
std::string name;
SourceLineInfo location;
NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
: name( _name ),
location( _location )
{}
};
struct ITracker : SharedImpl<> { struct ITracker : SharedImpl<> {
virtual ~ITracker(); virtual ~ITracker();
// static queries // static queries
virtual std::string name() const = 0; virtual NameAndLocation const& nameAndLocation() const = 0;
// dynamic queries // dynamic queries
virtual bool isComplete() const = 0; // Successfully completed or failed virtual bool isComplete() const = 0; // Successfully completed or failed
...@@ -39,15 +51,15 @@ namespace TestCaseTracking { ...@@ -39,15 +51,15 @@ namespace TestCaseTracking {
virtual void markAsNeedingAnotherRun() = 0; virtual void markAsNeedingAnotherRun() = 0;
virtual void addChild( Ptr<ITracker> const& child ) = 0; virtual void addChild( Ptr<ITracker> const& child ) = 0;
virtual ITracker* findChild( std::string const& name ) = 0; virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) = 0;
virtual void openChild() = 0; virtual void openChild() = 0;
// Debug/ checking // Debug/ checking
virtual bool isSectionTracker() const = 0; virtual bool isSectionTracker() const = 0;
virtual bool isIndexTracker() const = 0; virtual bool isIndexTracker() const = 0;
}; };
class TrackerContext { class TrackerContext {
enum RunState { enum RunState {
NotStarted, NotStarted,
...@@ -110,30 +122,32 @@ namespace TestCaseTracking { ...@@ -110,30 +122,32 @@ namespace TestCaseTracking {
Failed Failed
}; };
class TrackerHasName { class TrackerHasName {
std::string m_name; NameAndLocation m_nameAndLocation;
public: public:
TrackerHasName( std::string const& name ) : m_name( name ) {} TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
bool operator ()( Ptr<ITracker> const& tracker ) { bool operator ()( Ptr<ITracker> const& tracker ) {
return tracker->name() == m_name; return
tracker->nameAndLocation().name == m_nameAndLocation.name &&
tracker->nameAndLocation().location == m_nameAndLocation.location;
} }
}; };
typedef std::vector<Ptr<ITracker> > Children; typedef std::vector<Ptr<ITracker> > Children;
std::string m_name; NameAndLocation m_nameAndLocation;
TrackerContext& m_ctx; TrackerContext& m_ctx;
ITracker* m_parent; ITracker* m_parent;
Children m_children; Children m_children;
CycleState m_runState; CycleState m_runState;
public: public:
TrackerBase( std::string const& name, TrackerContext& ctx, ITracker* parent ) TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
: m_name( name ), : m_nameAndLocation( nameAndLocation ),
m_ctx( ctx ), m_ctx( ctx ),
m_parent( parent ), m_parent( parent ),
m_runState( NotStarted ) m_runState( NotStarted )
{} {}
virtual ~TrackerBase(); virtual ~TrackerBase();
virtual std::string name() const CATCH_OVERRIDE { virtual NameAndLocation const& nameAndLocation() const CATCH_OVERRIDE {
return m_name; return m_nameAndLocation;
} }
virtual bool isComplete() const CATCH_OVERRIDE { virtual bool isComplete() const CATCH_OVERRIDE {
return m_runState == CompletedSuccessfully || m_runState == Failed; return m_runState == CompletedSuccessfully || m_runState == Failed;
...@@ -153,8 +167,8 @@ namespace TestCaseTracking { ...@@ -153,8 +167,8 @@ namespace TestCaseTracking {
m_children.push_back( child ); m_children.push_back( child );
} }
virtual ITracker* findChild( std::string const& name ) CATCH_OVERRIDE { virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) CATCH_OVERRIDE {
Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( name ) ); Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
return( it != m_children.end() ) return( it != m_children.end() )
? it->get() ? it->get()
: CATCH_NULL; : CATCH_NULL;
...@@ -174,7 +188,7 @@ namespace TestCaseTracking { ...@@ -174,7 +188,7 @@ namespace TestCaseTracking {
virtual bool isSectionTracker() const CATCH_OVERRIDE { return false; } virtual bool isSectionTracker() const CATCH_OVERRIDE { return false; }
virtual bool isIndexTracker() const CATCH_OVERRIDE { return false; } virtual bool isIndexTracker() const CATCH_OVERRIDE { return false; }
void open() { void open() {
m_runState = Executing; m_runState = Executing;
moveToThis(); moveToThis();
...@@ -232,32 +246,56 @@ namespace TestCaseTracking { ...@@ -232,32 +246,56 @@ namespace TestCaseTracking {
}; };
class SectionTracker : public TrackerBase { class SectionTracker : public TrackerBase {
std::vector<std::string> m_filters;
public: public:
SectionTracker( std::string const& name, TrackerContext& ctx, ITracker* parent ) SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
: TrackerBase( name, ctx, parent ) : TrackerBase( nameAndLocation, ctx, parent )
{} {
if( parent ) {
while( !parent->isSectionTracker() )
parent = &parent->parent();
SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
addNextFilters( parentSection.m_filters );
}
}
virtual ~SectionTracker(); virtual ~SectionTracker();
virtual bool isSectionTracker() const CATCH_OVERRIDE { return true; } virtual bool isSectionTracker() const CATCH_OVERRIDE { return true; }
static SectionTracker& acquire( TrackerContext& ctx, std::string const& name ) { static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
SectionTracker* section = CATCH_NULL; SectionTracker* section = CATCH_NULL;
ITracker& currentTracker = ctx.currentTracker(); ITracker& currentTracker = ctx.currentTracker();
if( ITracker* childTracker = currentTracker.findChild( name ) ) { if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) {
assert( childTracker ); assert( childTracker );
assert( childTracker->isSectionTracker() ); assert( childTracker->isSectionTracker() );
section = static_cast<SectionTracker*>( childTracker ); section = static_cast<SectionTracker*>( childTracker );
} }
else { else {
section = new SectionTracker( name, ctx, &currentTracker ); section = new SectionTracker( nameAndLocation, ctx, &currentTracker );
currentTracker.addChild( section ); currentTracker.addChild( section );
} }
if( !ctx.completedCycle() && !section->isComplete() ) { if( !ctx.completedCycle() )
section->tryOpen();
return *section;
}
void tryOpen() {
if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
open();
}
section->open(); void addInitialFilters( std::vector<std::string> const& filters ) {
if( !filters.empty() ) {
m_filters.push_back(""); // Root - should never be consulted
m_filters.push_back(""); // Test Case - not a section filter
std::copy( filters.begin(), filters.end(), std::back_inserter( m_filters ) );
} }
return *section; }
void addNextFilters( std::vector<std::string> const& filters ) {
if( filters.size() > 1 )
std::copy( filters.begin()+1, filters.end(), std::back_inserter( m_filters ) );
} }
}; };
...@@ -265,26 +303,26 @@ namespace TestCaseTracking { ...@@ -265,26 +303,26 @@ namespace TestCaseTracking {
int m_size; int m_size;
int m_index; int m_index;
public: public:
IndexTracker( std::string const& name, TrackerContext& ctx, ITracker* parent, int size ) IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
: TrackerBase( name, ctx, parent ), : TrackerBase( nameAndLocation, ctx, parent ),
m_size( size ), m_size( size ),
m_index( -1 ) m_index( -1 )
{} {}
virtual ~IndexTracker(); virtual ~IndexTracker();
virtual bool isIndexTracker() const CATCH_OVERRIDE { return true; } virtual bool isIndexTracker() const CATCH_OVERRIDE { return true; }
static IndexTracker& acquire( TrackerContext& ctx, std::string const& name, int size ) { static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
IndexTracker* tracker = CATCH_NULL; IndexTracker* tracker = CATCH_NULL;
ITracker& currentTracker = ctx.currentTracker(); ITracker& currentTracker = ctx.currentTracker();
if( ITracker* childTracker = currentTracker.findChild( name ) ) { if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) {
assert( childTracker ); assert( childTracker );
assert( childTracker->isIndexTracker() ); assert( childTracker->isIndexTracker() );
tracker = static_cast<IndexTracker*>( childTracker ); tracker = static_cast<IndexTracker*>( childTracker );
} }
else { else {
tracker = new IndexTracker( name, ctx, &currentTracker, size ); tracker = new IndexTracker( nameAndLocation, ctx, &currentTracker, size );
currentTracker.addChild( tracker ); currentTracker.addChild( tracker );
} }
...@@ -312,7 +350,7 @@ namespace TestCaseTracking { ...@@ -312,7 +350,7 @@ namespace TestCaseTracking {
}; };
inline ITracker& TrackerContext::startRun() { inline ITracker& TrackerContext::startRun() {
m_rootTracker = new SectionTracker( "{root}", *this, CATCH_NULL ); m_rootTracker = new SectionTracker( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, CATCH_NULL );
m_currentTracker = CATCH_NULL; m_currentTracker = CATCH_NULL;
m_runState = Executing; m_runState = Executing;
return *m_rootTracker; return *m_rootTracker;
......
...@@ -87,6 +87,8 @@ namespace Catch { ...@@ -87,6 +87,8 @@ namespace Catch {
m_start = start; m_start = start;
} }
void escape() { void escape() {
if( m_mode == None )
m_start = m_pos;
m_mode = EscapedName; m_mode = EscapedName;
m_escapeChars.push_back( m_pos ); m_escapeChars.push_back( m_pos );
} }
...@@ -95,7 +97,7 @@ namespace Catch { ...@@ -95,7 +97,7 @@ namespace Catch {
void addPattern() { void addPattern() {
std::string token = subString(); std::string token = subString();
for( size_t i = 0; i < m_escapeChars.size(); ++i ) for( size_t i = 0; i < m_escapeChars.size(); ++i )
token = token.substr( 0, m_escapeChars[i] ) + token.substr( m_escapeChars[i]+1 ); token = token.substr( 0, m_escapeChars[i]-i ) + token.substr( m_escapeChars[i]+1-i );
m_escapeChars.clear(); m_escapeChars.clear();
if( startsWith( token, "exclude:" ) ) { if( startsWith( token, "exclude:" ) ) {
m_exclusion = true; m_exclusion = true;
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
#endif #endif
#ifdef CATCH_PLATFORM_WINDOWS #ifdef CATCH_PLATFORM_WINDOWS
#include <windows.h> #include "catch_windows_h_proxy.h"
#else #else
#include <sys/time.h> #include <sys/time.h>
#endif #endif
......
...@@ -69,7 +69,7 @@ std::string toString( std::string const& value ) { ...@@ -69,7 +69,7 @@ std::string toString( std::string const& value ) {
} }
} }
} }
return "\"" + s + "\""; return '"' + s + '"';
} }
std::string toString( std::wstring const& value ) { std::string toString( std::wstring const& value ) {
...@@ -90,19 +90,19 @@ std::string toString( char* const value ) { ...@@ -90,19 +90,19 @@ std::string toString( char* const value ) {
std::string toString( const wchar_t* const value ) std::string toString( const wchar_t* const value )
{ {
return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" ); return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" );
} }
std::string toString( wchar_t* const value ) std::string toString( wchar_t* const value )
{ {
return Catch::toString( static_cast<const wchar_t*>( value ) ); return Catch::toString( static_cast<const wchar_t*>( value ) );
} }
std::string toString( int value ) { std::string toString( int value ) {
std::ostringstream oss; std::ostringstream oss;
oss << value; oss << value;
if( value > Detail::hexThreshold ) if( value > Detail::hexThreshold )
oss << " (0x" << std::hex << value << ")"; oss << " (0x" << std::hex << value << ')';
return oss.str(); return oss.str();
} }
...@@ -110,7 +110,7 @@ std::string toString( unsigned long value ) { ...@@ -110,7 +110,7 @@ std::string toString( unsigned long value ) {
std::ostringstream oss; std::ostringstream oss;
oss << value; oss << value;
if( value > Detail::hexThreshold ) if( value > Detail::hexThreshold )
oss << " (0x" << std::hex << value << ")"; oss << " (0x" << std::hex << value << ')';
return oss.str(); return oss.str();
} }
...@@ -138,7 +138,7 @@ std::string toString( const double value ) { ...@@ -138,7 +138,7 @@ std::string toString( const double value ) {
return fpToString( value, 10 ); return fpToString( value, 10 );
} }
std::string toString( const float value ) { std::string toString( const float value ) {
return fpToString( value, 5 ) + "f"; return fpToString( value, 5 ) + 'f';
} }
std::string toString( bool value ) { std::string toString( bool value ) {
...@@ -146,9 +146,19 @@ std::string toString( bool value ) { ...@@ -146,9 +146,19 @@ std::string toString( bool value ) {
} }
std::string toString( char value ) { std::string toString( char value ) {
return value < ' ' if ( value == '\r' )
? toString( static_cast<unsigned int>( value ) ) return "'\\r'";
: Detail::makeString( value ); if ( value == '\f' )
return "'\\f'";
if ( value == '\n' )
return "'\\n'";
if ( value == '\t' )
return "'\\t'";
if ( '\0' <= value && value < ' ' )
return toString( static_cast<unsigned int>( value ) );
char chstr[] = "' '";
chstr[1] = value;
return chstr;
} }
std::string toString( signed char value ) { std::string toString( signed char value ) {
...@@ -164,14 +174,14 @@ std::string toString( long long value ) { ...@@ -164,14 +174,14 @@ std::string toString( long long value ) {
std::ostringstream oss; std::ostringstream oss;
oss << value; oss << value;
if( value > Detail::hexThreshold ) if( value > Detail::hexThreshold )
oss << " (0x" << std::hex << value << ")"; oss << " (0x" << std::hex << value << ')';
return oss.str(); return oss.str();
} }
std::string toString( unsigned long long value ) { std::string toString( unsigned long long value ) {
std::ostringstream oss; std::ostringstream oss;
oss << value; oss << value;
if( value > Detail::hexThreshold ) if( value > Detail::hexThreshold )
oss << " (0x" << std::hex << value << ")"; oss << " (0x" << std::hex << value << ')';
return oss.str(); return oss.str();
} }
#endif #endif
......
/*
* Created by Martin on 08/02/2017.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_CATCH_TYPE_TRAITS_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_TYPE_TRAITS_HPP_INCLUDED
#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
#include <type_traits>
#endif
namespace Catch {
#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
template <typename T>
using add_lvalue_reference = std::add_lvalue_reference<T>;
template <typename T>
using add_const = std::add_const<T>;
#else
template <typename T>
struct add_const {
typedef const T type;
};
template <typename T>
struct add_lvalue_reference {
typedef T& type;
};
template <typename T>
struct add_lvalue_reference<T&> {
typedef T& type;
};
// No && overload, because that is C++11, in which case we have
// proper type_traits implementation from the standard library
#endif
}
#endif // TWOBLUECUBES_CATCH_TYPE_TRAITS_HPP_INCLUDED
...@@ -26,18 +26,18 @@ namespace Catch { ...@@ -26,18 +26,18 @@ namespace Catch {
{} {}
std::ostream& operator << ( std::ostream& os, Version const& version ) { std::ostream& operator << ( std::ostream& os, Version const& version ) {
os << version.majorVersion << "." os << version.majorVersion << '.'
<< version.minorVersion << "." << version.minorVersion << '.'
<< version.patchNumber; << version.patchNumber;
if( !version.branchName.empty() ) { if( !version.branchName.empty() ) {
os << "-" << version.branchName os << '-' << version.branchName
<< "." << version.buildNumber; << '.' << version.buildNumber;
} }
return os; return os;
} }
Version libraryVersion( 1, 6, 0, "", 0 ); Version libraryVersion( 1, 7, 2, "", 0 );
} }
......
...@@ -10,6 +10,9 @@ ...@@ -10,6 +10,9 @@
#include "catch_common.h" #include "catch_common.h"
#include <stdexcept>
namespace Catch namespace Catch
{ {
class WildcardPattern { class WildcardPattern {
...@@ -27,11 +30,11 @@ namespace Catch ...@@ -27,11 +30,11 @@ namespace Catch
m_wildcard( NoWildcard ), m_wildcard( NoWildcard ),
m_pattern( adjustCase( pattern ) ) m_pattern( adjustCase( pattern ) )
{ {
if( startsWith( m_pattern, "*" ) ) { if( startsWith( m_pattern, '*' ) ) {
m_pattern = m_pattern.substr( 1 ); m_pattern = m_pattern.substr( 1 );
m_wildcard = WildcardAtStart; m_wildcard = WildcardAtStart;
} }
if( endsWith( m_pattern, "*" ) ) { if( endsWith( m_pattern, '*' ) ) {
m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd ); m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
} }
......
/*
* Created by Martin on 16/01/2017.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_CATCH_WINDOWS_H_PROXY_H_INCLUDED
#define TWOBLUECUBES_CATCH_WINDOWS_H_PROXY_H_INCLUDED
#ifdef CATCH_DEFINES_NOMINMAX
# define NOMINMAX
#endif
#ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#ifdef __AFXDLL
#include <AfxWin.h>
#else
#include <windows.h>
#endif
#ifdef CATCH_DEFINES_NOMINMAX
# undef NOMINMAX
#endif
#ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN
# undef WIN32_LEAN_AND_MEAN
#endif
#endif // TWOBLUECUBES_CATCH_WINDOWS_H_PROXY_H_INCLUDED
...@@ -57,8 +57,11 @@ namespace Catch { ...@@ -57,8 +57,11 @@ namespace Catch {
default: default:
// Escape control chars - based on contribution by @espenalb in PR #465 and // Escape control chars - based on contribution by @espenalb in PR #465 and
// by @mrpi PR #588 // by @mrpi PR #588
if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
os << "&#x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>( c ) << ';'; // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<int>( c );
}
else else
os << c; os << c;
} }
...@@ -112,20 +115,17 @@ namespace Catch { ...@@ -112,20 +115,17 @@ namespace Catch {
XmlWriter() XmlWriter()
: m_tagIsOpen( false ), : m_tagIsOpen( false ),
m_needsNewline( false ), m_needsNewline( false ),
m_os( &Catch::cout() ) m_os( Catch::cout() )
{ {
// We encode control characters, which requires writeDeclaration();
// XML 1.1
// see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
*m_os << "<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n";
} }
XmlWriter( std::ostream& os ) XmlWriter( std::ostream& os )
: m_tagIsOpen( false ), : m_tagIsOpen( false ),
m_needsNewline( false ), m_needsNewline( false ),
m_os( &os ) m_os( os )
{ {
*m_os << "<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n"; writeDeclaration();
} }
~XmlWriter() { ~XmlWriter() {
...@@ -136,7 +136,7 @@ namespace Catch { ...@@ -136,7 +136,7 @@ namespace Catch {
XmlWriter& startElement( std::string const& name ) { XmlWriter& startElement( std::string const& name ) {
ensureTagClosed(); ensureTagClosed();
newlineIfNecessary(); newlineIfNecessary();
stream() << m_indent << "<" << name; m_os << m_indent << '<' << name;
m_tags.push_back( name ); m_tags.push_back( name );
m_indent += " "; m_indent += " ";
m_tagIsOpen = true; m_tagIsOpen = true;
...@@ -153,24 +153,25 @@ namespace Catch { ...@@ -153,24 +153,25 @@ namespace Catch {
newlineIfNecessary(); newlineIfNecessary();
m_indent = m_indent.substr( 0, m_indent.size()-2 ); m_indent = m_indent.substr( 0, m_indent.size()-2 );
if( m_tagIsOpen ) { if( m_tagIsOpen ) {
stream() << "/>\n"; m_os << "/>";
m_tagIsOpen = false; m_tagIsOpen = false;
} }
else { else {
stream() << m_indent << "</" << m_tags.back() << ">\n"; m_os << m_indent << "</" << m_tags.back() << ">";
} }
m_os << std::endl;
m_tags.pop_back(); m_tags.pop_back();
return *this; return *this;
} }
XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) { XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) {
if( !name.empty() && !attribute.empty() ) if( !name.empty() && !attribute.empty() )
stream() << " " << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << "\""; m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
return *this; return *this;
} }
XmlWriter& writeAttribute( std::string const& name, bool attribute ) { XmlWriter& writeAttribute( std::string const& name, bool attribute ) {
stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\""; m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
return *this; return *this;
} }
...@@ -186,8 +187,8 @@ namespace Catch { ...@@ -186,8 +187,8 @@ namespace Catch {
bool tagWasOpen = m_tagIsOpen; bool tagWasOpen = m_tagIsOpen;
ensureTagClosed(); ensureTagClosed();
if( tagWasOpen && indent ) if( tagWasOpen && indent )
stream() << m_indent; m_os << m_indent;
stream() << XmlEncode( text ); m_os << XmlEncode( text );
m_needsNewline = true; m_needsNewline = true;
} }
return *this; return *this;
...@@ -195,39 +196,39 @@ namespace Catch { ...@@ -195,39 +196,39 @@ namespace Catch {
XmlWriter& writeComment( std::string const& text ) { XmlWriter& writeComment( std::string const& text ) {
ensureTagClosed(); ensureTagClosed();
stream() << m_indent << "<!--" << text << "-->"; m_os << m_indent << "<!--" << text << "-->";
m_needsNewline = true; m_needsNewline = true;
return *this; return *this;
} }
void writeStylesheetRef( std::string const& url ) {
m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
}
XmlWriter& writeBlankLine() { XmlWriter& writeBlankLine() {
ensureTagClosed(); ensureTagClosed();
stream() << "\n"; m_os << '\n';
return *this; return *this;
} }
void setStream( std::ostream& os ) { void ensureTagClosed() {
m_os = &os; if( m_tagIsOpen ) {
m_os << ">" << std::endl;
m_tagIsOpen = false;
}
} }
private: private:
XmlWriter( XmlWriter const& ); XmlWriter( XmlWriter const& );
void operator=( XmlWriter const& ); void operator=( XmlWriter const& );
std::ostream& stream() { void writeDeclaration() {
return *m_os; m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
}
void ensureTagClosed() {
if( m_tagIsOpen ) {
stream() << ">\n";
m_tagIsOpen = false;
}
} }
void newlineIfNecessary() { void newlineIfNecessary() {
if( m_needsNewline ) { if( m_needsNewline ) {
stream() << "\n"; m_os << std::endl;
m_needsNewline = false; m_needsNewline = false;
} }
} }
...@@ -236,7 +237,7 @@ namespace Catch { ...@@ -236,7 +237,7 @@ namespace Catch {
bool m_needsNewline; bool m_needsNewline;
std::vector<std::string> m_tags; std::vector<std::string> m_tags;
std::string m_indent; std::string m_indent;
std::ostream* m_os; std::ostream& m_os;
}; };
} }
......
...@@ -108,12 +108,12 @@ namespace Catch { ...@@ -108,12 +108,12 @@ namespace Catch {
struct BySectionInfo { struct BySectionInfo {
BySectionInfo( SectionInfo const& other ) : m_other( other ) {} BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
bool operator() ( Ptr<SectionNode> const& node ) const { bool operator() ( Ptr<SectionNode> const& node ) const {
return node->stats.sectionInfo.lineInfo == m_other.lineInfo; return node->stats.sectionInfo.lineInfo == m_other.lineInfo;
} }
private: private:
void operator=( BySectionInfo const& ); void operator=( BySectionInfo const& );
SectionInfo const& m_other; SectionInfo const& m_other;
}; };
...@@ -170,6 +170,12 @@ namespace Catch { ...@@ -170,6 +170,12 @@ namespace Catch {
assert( !m_sectionStack.empty() ); assert( !m_sectionStack.empty() );
SectionNode& sectionNode = *m_sectionStack.back(); SectionNode& sectionNode = *m_sectionStack.back();
sectionNode.assertions.push_back( assertionStats ); sectionNode.assertions.push_back( assertionStats );
// AssertionResult holds a pointer to a temporary DecomposedExpression,
// which getExpandedExpression() calls to build the expression string.
// Our section stack copy of the assertionResult will likely outlive the
// temporary, so it must be expanded or discarded now to avoid calling
// a destroyed object later.
prepareExpandedExpression( sectionNode.assertions.back().assertionResult );
return true; return true;
} }
virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE {
...@@ -204,6 +210,13 @@ namespace Catch { ...@@ -204,6 +210,13 @@ namespace Catch {
virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {} virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {}
virtual void prepareExpandedExpression( AssertionResult& result ) const {
if( result.isOk() )
result.discardDecomposedExpression();
else
result.expandDecomposedExpression();
}
Ptr<IConfig const> m_config; Ptr<IConfig const> m_config;
std::ostream& stream; std::ostream& stream;
std::vector<AssertionStats> m_assertions; std::vector<AssertionStats> m_assertions;
...@@ -224,7 +237,7 @@ namespace Catch { ...@@ -224,7 +237,7 @@ namespace Catch {
char const* getLineOfChars() { char const* getLineOfChars() {
static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
if( !*line ) { if( !*line ) {
memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
} }
return line; return line;
......
...@@ -34,7 +34,7 @@ namespace Catch { ...@@ -34,7 +34,7 @@ namespace Catch {
} }
virtual void noMatchingTestCases( std::string const& spec ) { virtual void noMatchingTestCases( std::string const& spec ) {
stream << "No test cases matched '" << spec << "'" << std::endl; stream << "No test cases matched '" << spec << '\'' << std::endl;
} }
virtual void assertionStarting( AssertionInfo const& ) { virtual void assertionStarting( AssertionInfo const& ) {
...@@ -61,7 +61,7 @@ namespace Catch { ...@@ -61,7 +61,7 @@ namespace Catch {
virtual void testRunEnded( TestRunStats const& _testRunStats ) { virtual void testRunEnded( TestRunStats const& _testRunStats ) {
printTotals( _testRunStats.totals ); printTotals( _testRunStats.totals );
stream << "\n" << std::endl; stream << '\n' << std::endl;
StreamingReporterBase::testRunEnded( _testRunStats ); StreamingReporterBase::testRunEnded( _testRunStats );
} }
...@@ -161,26 +161,26 @@ namespace Catch { ...@@ -161,26 +161,26 @@ namespace Catch {
void printSourceInfo() const { void printSourceInfo() const {
Colour colourGuard( Colour::FileName ); Colour colourGuard( Colour::FileName );
stream << result.getSourceInfo() << ":"; stream << result.getSourceInfo() << ':';
} }
void printResultType( Colour::Code colour, std::string passOrFail ) const { void printResultType( Colour::Code colour, std::string passOrFail ) const {
if( !passOrFail.empty() ) { if( !passOrFail.empty() ) {
{ {
Colour colourGuard( colour ); Colour colourGuard( colour );
stream << " " << passOrFail; stream << ' ' << passOrFail;
} }
stream << ":"; stream << ':';
} }
} }
void printIssue( std::string issue ) const { void printIssue( std::string issue ) const {
stream << " " << issue; stream << ' ' << issue;
} }
void printExpressionWas() { void printExpressionWas() {
if( result.hasExpression() ) { if( result.hasExpression() ) {
stream << ";"; stream << ';';
{ {
Colour colour( dimColour() ); Colour colour( dimColour() );
stream << " expression was:"; stream << " expression was:";
...@@ -191,7 +191,7 @@ namespace Catch { ...@@ -191,7 +191,7 @@ namespace Catch {
void printOriginalExpression() const { void printOriginalExpression() const {
if( result.hasExpression() ) { if( result.hasExpression() ) {
stream << " " << result.getExpression(); stream << ' ' << result.getExpression();
} }
} }
...@@ -207,7 +207,7 @@ namespace Catch { ...@@ -207,7 +207,7 @@ namespace Catch {
void printMessage() { void printMessage() {
if ( itMessage != messages.end() ) { if ( itMessage != messages.end() ) {
stream << " '" << itMessage->message << "'"; stream << " '" << itMessage->message << '\'';
++itMessage; ++itMessage;
} }
} }
...@@ -222,13 +222,13 @@ namespace Catch { ...@@ -222,13 +222,13 @@ namespace Catch {
{ {
Colour colourGuard( colour ); Colour colourGuard( colour );
stream << " with " << pluralise( N, "message" ) << ":"; stream << " with " << pluralise( N, "message" ) << ':';
} }
for(; itMessage != itEnd; ) { for(; itMessage != itEnd; ) {
// If this assertion is a warning ignore any INFO messages // If this assertion is a warning ignore any INFO messages
if( printInfoMessages || itMessage->type != ResultWas::Info ) { if( printInfoMessages || itMessage->type != ResultWas::Info ) {
stream << " '" << itMessage->message << "'"; stream << " '" << itMessage->message << '\'';
if ( ++itMessage != itEnd ) { if ( ++itMessage != itEnd ) {
Colour colourGuard( dimColour() ); Colour colourGuard( dimColour() );
stream << " and"; stream << " and";
...@@ -254,7 +254,7 @@ namespace Catch { ...@@ -254,7 +254,7 @@ namespace Catch {
// - green: Passed [both/all] N tests cases with M assertions. // - green: Passed [both/all] N tests cases with M assertions.
std::string bothOrAll( std::size_t count ) const { std::string bothOrAll( std::size_t count ) const {
return count == 1 ? "" : count == 2 ? "both " : "all " ; return count == 1 ? std::string() : count == 2 ? "both " : "all " ;
} }
void printTotals( const Totals& totals ) const { void printTotals( const Totals& totals ) const {
...@@ -265,12 +265,12 @@ namespace Catch { ...@@ -265,12 +265,12 @@ namespace Catch {
Colour colour( Colour::ResultError ); Colour colour( Colour::ResultError );
const std::string qualify_assertions_failed = const std::string qualify_assertions_failed =
totals.assertions.failed == totals.assertions.total() ? totals.assertions.failed == totals.assertions.total() ?
bothOrAll( totals.assertions.failed ) : ""; bothOrAll( totals.assertions.failed ) : std::string();
stream << stream <<
"Failed " << bothOrAll( totals.testCases.failed ) "Failed " << bothOrAll( totals.testCases.failed )
<< pluralise( totals.testCases.failed, "test case" ) << ", " << pluralise( totals.testCases.failed, "test case" ) << ", "
"failed " << qualify_assertions_failed << "failed " << qualify_assertions_failed <<
pluralise( totals.assertions.failed, "assertion" ) << "."; pluralise( totals.assertions.failed, "assertion" ) << '.';
} }
else if( totals.assertions.total() == 0 ) { else if( totals.assertions.total() == 0 ) {
stream << stream <<
...@@ -282,14 +282,14 @@ namespace Catch { ...@@ -282,14 +282,14 @@ namespace Catch {
Colour colour( Colour::ResultError ); Colour colour( Colour::ResultError );
stream << stream <<
"Failed " << pluralise( totals.testCases.failed, "test case" ) << ", " "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", "
"failed " << pluralise( totals.assertions.failed, "assertion" ) << "."; "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.';
} }
else { else {
Colour colour( Colour::ResultSuccess ); Colour colour( Colour::ResultSuccess );
stream << stream <<
"Passed " << bothOrAll( totals.testCases.passed ) "Passed " << bothOrAll( totals.testCases.passed )
<< pluralise( totals.testCases.passed, "test case" ) << << pluralise( totals.testCases.passed, "test case" ) <<
" with " << pluralise( totals.assertions.passed, "assertion" ) << "."; " with " << pluralise( totals.assertions.passed, "assertion" ) << '.';
} }
} }
}; };
......
...@@ -27,7 +27,7 @@ namespace Catch { ...@@ -27,7 +27,7 @@ namespace Catch {
} }
virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE {
stream << "No test cases matched '" << spec << "'" << std::endl; stream << "No test cases matched '" << spec << '\'' << std::endl;
} }
virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {
...@@ -69,12 +69,12 @@ namespace Catch { ...@@ -69,12 +69,12 @@ namespace Catch {
} }
if( m_headerPrinted ) { if( m_headerPrinted ) {
if( m_config->showDurations() == ShowDurations::Always ) if( m_config->showDurations() == ShowDurations::Always )
stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl; stream << "Completed in " << _sectionStats.durationInSeconds << 's' << std::endl;
m_headerPrinted = false; m_headerPrinted = false;
} }
else { else {
if( m_config->showDurations() == ShowDurations::Always ) if( m_config->showDurations() == ShowDurations::Always )
stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl; stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << 's' << std::endl;
} }
StreamingReporterBase::sectionEnded( _sectionStats ); StreamingReporterBase::sectionEnded( _sectionStats );
} }
...@@ -88,7 +88,7 @@ namespace Catch { ...@@ -88,7 +88,7 @@ namespace Catch {
printSummaryDivider(); printSummaryDivider();
stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
printTotals( _testGroupStats.totals ); printTotals( _testGroupStats.totals );
stream << "\n" << std::endl; stream << '\n' << std::endl;
} }
StreamingReporterBase::testGroupEnded( _testGroupStats ); StreamingReporterBase::testGroupEnded( _testGroupStats );
} }
...@@ -180,13 +180,13 @@ namespace Catch { ...@@ -180,13 +180,13 @@ namespace Catch {
printSourceInfo(); printSourceInfo();
if( stats.totals.assertions.total() > 0 ) { if( stats.totals.assertions.total() > 0 ) {
if( result.isOk() ) if( result.isOk() )
stream << "\n"; stream << '\n';
printResultType(); printResultType();
printOriginalExpression(); printOriginalExpression();
printReconstructedExpression(); printReconstructedExpression();
} }
else { else {
stream << "\n"; stream << '\n';
} }
printMessage(); printMessage();
} }
...@@ -203,25 +203,25 @@ namespace Catch { ...@@ -203,25 +203,25 @@ namespace Catch {
Colour colourGuard( Colour::OriginalExpression ); Colour colourGuard( Colour::OriginalExpression );
stream << " "; stream << " ";
stream << result.getExpressionInMacro(); stream << result.getExpressionInMacro();
stream << "\n"; stream << '\n';
} }
} }
void printReconstructedExpression() const { void printReconstructedExpression() const {
if( result.hasExpandedExpression() ) { if( result.hasExpandedExpression() ) {
stream << "with expansion:\n"; stream << "with expansion:\n";
Colour colourGuard( Colour::ReconstructedExpression ); Colour colourGuard( Colour::ReconstructedExpression );
stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n"; stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << '\n';
} }
} }
void printMessage() const { void printMessage() const {
if( !messageLabel.empty() ) if( !messageLabel.empty() )
stream << messageLabel << ":" << "\n"; stream << messageLabel << ':' << '\n';
for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end(); for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end();
it != itEnd; it != itEnd;
++it ) { ++it ) {
// If this assertion is a warning ignore any INFO messages // If this assertion is a warning ignore any INFO messages
if( printInfoMessages || it->type != ResultWas::Info ) if( printInfoMessages || it->type != ResultWas::Info )
stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n"; stream << Text( it->message, TextAttributes().setIndent(2) ) << '\n';
} }
} }
void printSourceInfo() const { void printSourceInfo() const {
...@@ -253,7 +253,7 @@ namespace Catch { ...@@ -253,7 +253,7 @@ namespace Catch {
} }
} }
void lazyPrintRunInfo() { void lazyPrintRunInfo() {
stream << "\n" << getLineOfChars<'~'>() << "\n"; stream << '\n' << getLineOfChars<'~'>() << '\n';
Colour colour( Colour::SecondaryText ); Colour colour( Colour::SecondaryText );
stream << currentTestRunInfo->name stream << currentTestRunInfo->name
<< " is a Catch v" << libraryVersion << " host application.\n" << " is a Catch v" << libraryVersion << " host application.\n"
...@@ -284,22 +284,22 @@ namespace Catch { ...@@ -284,22 +284,22 @@ namespace Catch {
printHeaderString( it->name, 2 ); printHeaderString( it->name, 2 );
} }
SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
if( !lineInfo.empty() ){ if( !lineInfo.empty() ){
stream << getLineOfChars<'-'>() << "\n"; stream << getLineOfChars<'-'>() << '\n';
Colour colourGuard( Colour::FileName ); Colour colourGuard( Colour::FileName );
stream << lineInfo << "\n"; stream << lineInfo << '\n';
} }
stream << getLineOfChars<'.'>() << "\n" << std::endl; stream << getLineOfChars<'.'>() << '\n' << std::endl;
} }
void printClosedHeader( std::string const& _name ) { void printClosedHeader( std::string const& _name ) {
printOpenHeader( _name ); printOpenHeader( _name );
stream << getLineOfChars<'.'>() << "\n"; stream << getLineOfChars<'.'>() << '\n';
} }
void printOpenHeader( std::string const& _name ) { void printOpenHeader( std::string const& _name ) {
stream << getLineOfChars<'-'>() << "\n"; stream << getLineOfChars<'-'>() << '\n';
{ {
Colour colourGuard( Colour::Headers ); Colour colourGuard( Colour::Headers );
printHeaderString( _name ); printHeaderString( _name );
...@@ -316,7 +316,7 @@ namespace Catch { ...@@ -316,7 +316,7 @@ namespace Catch {
i = 0; i = 0;
stream << Text( _string, TextAttributes() stream << Text( _string, TextAttributes()
.setIndent( indent+i) .setIndent( indent+i)
.setInitialIndent( indent ) ) << "\n"; .setInitialIndent( indent ) ) << '\n';
} }
struct SummaryColumn { struct SummaryColumn {
...@@ -331,9 +331,9 @@ namespace Catch { ...@@ -331,9 +331,9 @@ namespace Catch {
std::string row = oss.str(); std::string row = oss.str();
for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) { for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) {
while( it->size() < row.size() ) while( it->size() < row.size() )
*it = " " + *it; *it = ' ' + *it;
while( it->size() > row.size() ) while( it->size() > row.size() )
row = " " + row; row = ' ' + row;
} }
rows.push_back( row ); rows.push_back( row );
return *this; return *this;
...@@ -353,8 +353,8 @@ namespace Catch { ...@@ -353,8 +353,8 @@ namespace Catch {
stream << Colour( Colour::ResultSuccess ) << "All tests passed"; stream << Colour( Colour::ResultSuccess ) << "All tests passed";
stream << " (" stream << " ("
<< pluralise( totals.assertions.passed, "assertion" ) << " in " << pluralise( totals.assertions.passed, "assertion" ) << " in "
<< pluralise( totals.testCases.passed, "test case" ) << ")" << pluralise( totals.testCases.passed, "test case" ) << ')'
<< "\n"; << '\n';
} }
else { else {
...@@ -389,10 +389,10 @@ namespace Catch { ...@@ -389,10 +389,10 @@ namespace Catch {
else if( value != "0" ) { else if( value != "0" ) {
stream << Colour( Colour::LightGrey ) << " | "; stream << Colour( Colour::LightGrey ) << " | ";
stream << Colour( it->colour ) stream << Colour( it->colour )
<< value << " " << it->label; << value << ' ' << it->label;
} }
} }
stream << "\n"; stream << '\n';
} }
static std::size_t makeRatio( std::size_t number, std::size_t total ) { static std::size_t makeRatio( std::size_t number, std::size_t total ) {
...@@ -428,10 +428,10 @@ namespace Catch { ...@@ -428,10 +428,10 @@ namespace Catch {
else { else {
stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' ); stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' );
} }
stream << "\n"; stream << '\n';
} }
void printSummaryDivider() { void printSummaryDivider() {
stream << getLineOfChars<'-'>() << "\n"; stream << getLineOfChars<'-'>() << '\n';
} }
private: private:
......
...@@ -18,6 +18,35 @@ ...@@ -18,6 +18,35 @@
namespace Catch { namespace Catch {
namespace {
std::string getCurrentTimestamp() {
// Beware, this is not reentrant because of backward compatibility issues
// Also, UTC only, again because of backward compatibility (%z is C++11)
time_t rawtime;
std::time(&rawtime);
const size_t timeStampSize = sizeof("2017-01-16T17:06:45Z");
#ifdef _MSC_VER
std::tm timeInfo = {};
gmtime_s(&timeInfo, &rawtime);
#else
std::tm* timeInfo;
timeInfo = std::gmtime(&rawtime);
#endif
char timeStamp[timeStampSize];
const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
#ifdef _MSC_VER
std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
#else
std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
#endif
return std::string(timeStamp);
}
}
class JunitReporter : public CumulativeReporterBase { class JunitReporter : public CumulativeReporterBase {
public: public:
JunitReporter( ReporterConfig const& _config ) JunitReporter( ReporterConfig const& _config )
...@@ -82,7 +111,7 @@ namespace Catch { ...@@ -82,7 +111,7 @@ namespace Catch {
xml.writeAttribute( "time", "" ); xml.writeAttribute( "time", "" );
else else
xml.writeAttribute( "time", suiteTime ); xml.writeAttribute( "time", suiteTime );
xml.writeAttribute( "timestamp", "tbd" ); // !TBD xml.writeAttribute( "timestamp", getCurrentTimestamp() );
// Write test cases // Write test cases
for( TestGroupNode::ChildNodes::const_iterator for( TestGroupNode::ChildNodes::const_iterator
...@@ -117,7 +146,7 @@ namespace Catch { ...@@ -117,7 +146,7 @@ namespace Catch {
SectionNode const& sectionNode ) { SectionNode const& sectionNode ) {
std::string name = trim( sectionNode.stats.sectionInfo.name ); std::string name = trim( sectionNode.stats.sectionInfo.name );
if( !rootName.empty() ) if( !rootName.empty() )
name = rootName + "/" + name; name = rootName + '/' + name;
if( !sectionNode.assertions.empty() || if( !sectionNode.assertions.empty() ||
!sectionNode.stdOut.empty() || !sectionNode.stdOut.empty() ||
...@@ -195,14 +224,14 @@ namespace Catch { ...@@ -195,14 +224,14 @@ namespace Catch {
std::ostringstream oss; std::ostringstream oss;
if( !result.getMessage().empty() ) if( !result.getMessage().empty() )
oss << result.getMessage() << "\n"; oss << result.getMessage() << '\n';
for( std::vector<MessageInfo>::const_iterator for( std::vector<MessageInfo>::const_iterator
it = stats.infoMessages.begin(), it = stats.infoMessages.begin(),
itEnd = stats.infoMessages.end(); itEnd = stats.infoMessages.end();
it != itEnd; it != itEnd;
++it ) ++it )
if( it->type == ResultWas::Info ) if( it->type == ResultWas::Info )
oss << it->message << "\n"; oss << it->message << '\n';
oss << "at " << result.getSourceInfo(); oss << "at " << result.getSourceInfo();
xml.writeText( oss.str(), false ); xml.writeText( oss.str(), false );
......
...@@ -118,11 +118,11 @@ public: // IStreamingReporter ...@@ -118,11 +118,11 @@ public: // IStreamingReporter
++it ) ++it )
(*it)->skipTest( testInfo ); (*it)->skipTest( testInfo );
} }
virtual MultipleReporters* tryAsMulti() CATCH_OVERRIDE { virtual MultipleReporters* tryAsMulti() CATCH_OVERRIDE {
return this; return this;
} }
}; };
Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter ) { Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter ) {
......
...@@ -32,6 +32,10 @@ namespace Catch { ...@@ -32,6 +32,10 @@ namespace Catch {
return "Reports test results as an XML document"; return "Reports test results as an XML document";
} }
virtual std::string getStylesheetRef() const {
return std::string();
}
public: // StreamingReporterBase public: // StreamingReporterBase
virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE { virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE {
...@@ -40,6 +44,9 @@ namespace Catch { ...@@ -40,6 +44,9 @@ namespace Catch {
virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE { virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE {
StreamingReporterBase::testRunStarting( testInfo ); StreamingReporterBase::testRunStarting( testInfo );
std::string stylesheetRef = getStylesheetRef();
if( !stylesheetRef.empty() )
m_xml.writeStylesheetRef( stylesheetRef );
m_xml.startElement( "Catch" ); m_xml.startElement( "Catch" );
if( !m_config->name().empty() ) if( !m_config->name().empty() )
m_xml.writeAttribute( "name", m_config->name() ); m_xml.writeAttribute( "name", m_config->name() );
...@@ -53,10 +60,14 @@ namespace Catch { ...@@ -53,10 +60,14 @@ namespace Catch {
virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
StreamingReporterBase::testCaseStarting(testInfo); StreamingReporterBase::testCaseStarting(testInfo);
m_xml.startElement( "TestCase" ).writeAttribute( "name", testInfo.name ); m_xml.startElement( "TestCase" )
.writeAttribute( "name", trim( testInfo.name ) )
.writeAttribute( "description", testInfo.description )
.writeAttribute( "tags", testInfo.tagsAsString );
if ( m_config->showDurations() == ShowDurations::Always ) if ( m_config->showDurations() == ShowDurations::Always )
m_testCaseTimer.start(); m_testCaseTimer.start();
m_xml.ensureTagClosed();
} }
virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
...@@ -65,6 +76,7 @@ namespace Catch { ...@@ -65,6 +76,7 @@ namespace Catch {
m_xml.startElement( "Section" ) m_xml.startElement( "Section" )
.writeAttribute( "name", trim( sectionInfo.name ) ) .writeAttribute( "name", trim( sectionInfo.name ) )
.writeAttribute( "description", sectionInfo.description ); .writeAttribute( "description", sectionInfo.description );
m_xml.ensureTagClosed();
} }
} }
...@@ -96,7 +108,7 @@ namespace Catch { ...@@ -96,7 +108,7 @@ namespace Catch {
if( assertionResult.hasExpression() ) { if( assertionResult.hasExpression() ) {
m_xml.startElement( "Expression" ) m_xml.startElement( "Expression" )
.writeAttribute( "success", assertionResult.succeeded() ) .writeAttribute( "success", assertionResult.succeeded() )
.writeAttribute( "type", assertionResult.getTestMacroName() ) .writeAttribute( "type", assertionResult.getTestMacroName() )
.writeAttribute( "filename", assertionResult.getSourceInfo().file ) .writeAttribute( "filename", assertionResult.getSourceInfo().file )
.writeAttribute( "line", assertionResult.getSourceInfo().line ); .writeAttribute( "line", assertionResult.getSourceInfo().line );
...@@ -164,6 +176,11 @@ namespace Catch { ...@@ -164,6 +176,11 @@ namespace Catch {
if ( m_config->showDurations() == ShowDurations::Always ) if ( m_config->showDurations() == ShowDurations::Always )
e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
if( !testCaseStats.stdOut.empty() )
m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
if( !testCaseStats.stdErr.empty() )
m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
m_xml.endElement(); m_xml.endElement();
} }
......
/*
* Created by Martin on 16/01/2017.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
/*
* Created by Martin on 16/01/2017.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "catch.hpp"
#include <vector>
///////////////////////////////////////////////////////////////////////////////
TEST_CASE("Successful tests -- REQUIRE", "[Success]") {
const size_t sz = 1 * 1024 * 1024;
std::vector<size_t> vec; vec.reserve(sz);
for (size_t i = 0; i < sz; ++i){
vec.push_back(i);
REQUIRE(vec.back() == i);
}
}
///////////////////////////////////////////////////////////////////////////////
TEST_CASE("Successful tests -- CHECK", "[Success]") {
const size_t sz = 1 * 1024 * 1024;
std::vector<size_t> vec; vec.reserve(sz);
for (size_t i = 0; i < sz; ++i){
vec.push_back(i);
CHECK(vec.back() == i);
}
}
///////////////////////////////////////////////////////////////////////////////
TEST_CASE("Unsuccessful tests -- CHECK", "[Failure]") {
const size_t sz = 1024 * 1024;
std::vector<size_t> vec; vec.reserve(sz);
for (size_t i = 0; i < sz; ++i){
vec.push_back(i);
CHECK(vec.size() == i);
}
}
This is very much a work in progress.
The past results are standardized to a developer's machine,
the benchmarking script is basic and there are only 3 benchmarks,
but this should get better in time. For now, at least there is something to go by.
Successful tests -- CHECK: median: 3.38116 (s), stddev: 0.11567366292001534 (s)
Successful tests -- REQUIRE: median: 3.479955 (s), stddev: 0.16295972890734556 (s)
Unsuccessful tests -- CHECK: median: 1.966895 (s), stddev: 0.06323488524716572 (s)
Successful tests -- CHECK: median: 1.30312 (s), stddev: 0.08759818557862176 (s)
Successful tests -- REQUIRE: median: 1.341535 (s), stddev: 0.1479193390143576 (s)
Unsuccessful tests -- CHECK: median: 1.967755 (s), stddev: 0.07921104121269959 (s)
Successful tests -- CHECK: median: 1.2982 (s), stddev: 0.019540648829214084 (s)
Successful tests -- REQUIRE: median: 1.30102 (s), stddev: 0.014758430547392974 (s)
Unsuccessful tests -- CHECK: median: 15.520199999999999 (s), stddev: 0.09536359426485094 (s)
Successful tests -- CHECK: median: 0.7689014999999999 (s), stddev: 0.02127512078801068 (s)
Successful tests -- REQUIRE: median: 0.772845 (s), stddev: 0.03011638381365052 (s)
Unsuccessful tests -- CHECK: median: 15.49 (s), stddev: 0.536088571143903 (s)
Successful tests -- CHECK: median: 0.775769 (s), stddev: 0.014802129132136525 (s)
Successful tests -- REQUIRE: median: 0.785235 (s), stddev: 0.03532672836834896 (s)
Unsuccessful tests -- CHECK: median: 15.156600000000001 (s), stddev: 0.2832375673450742 (s)
...@@ -140,3 +140,48 @@ TEST_CASE( "Approximate PI", "[Approx][PI]" ) ...@@ -140,3 +140,48 @@ TEST_CASE( "Approximate PI", "[Approx][PI]" )
REQUIRE( divide( 22, 7 ) == Approx( 3.141 ).epsilon( 0.001 ) ); REQUIRE( divide( 22, 7 ) == Approx( 3.141 ).epsilon( 0.001 ) );
REQUIRE( divide( 22, 7 ) != Approx( 3.141 ).epsilon( 0.0001 ) ); REQUIRE( divide( 22, 7 ) != Approx( 3.141 ).epsilon( 0.0001 ) );
} }
////////////////////////////////////////////////////////////////////////////////
#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
class StrongDoubleTypedef
{
double d_ = 0.0;
public:
explicit StrongDoubleTypedef(double d) : d_(d) {}
explicit operator double() const { return d_; }
};
inline std::ostream& operator<<( std::ostream& os, StrongDoubleTypedef td ) {
return os << "StrongDoubleTypedef(" << static_cast<double>(td) << ")";
}
TEST_CASE
(
"Comparison with explicitly convertible types",
"[Approx][c++11]"
)
{
StrongDoubleTypedef td(10.0);
REQUIRE(td == Approx(10.0));
REQUIRE(Approx(10.0) == td);
REQUIRE(td != Approx(11.0));
REQUIRE(Approx(11.0) != td);
REQUIRE(td <= Approx(10.0));
REQUIRE(td <= Approx(11.0));
REQUIRE(Approx(10.0) <= td);
REQUIRE(Approx(9.0) <= td);
REQUIRE(td >= Approx(9.0));
REQUIRE(td >= Approx(10.0));
REQUIRE(Approx(10.0) >= td);
REQUIRE(Approx(11.0) >= td);
}
#endif
////////////////////////////////////////////////////////////////////////////////
...@@ -88,10 +88,10 @@ struct Fixture ...@@ -88,10 +88,10 @@ struct Fixture
} }
SCENARIO_METHOD(Fixture, SCENARIO_METHOD(Fixture,
"BDD tests requiring Fixtures to provide commonly-accessed data or methods", "BDD tests requiring Fixtures to provide commonly-accessed data or methods",
"[bdd][fixtures]") { "[bdd][fixtures]") {
const int before(counter()); const int before(counter());
GIVEN("No operations precede me") { GIVEN("No operations precede me") {
REQUIRE(before == 0); REQUIRE(before == 0);
WHEN("We get the count") { WHEN("We get the count") {
const int after(counter()); const int after(counter());
......
...@@ -131,7 +131,7 @@ ExceptionTests.cpp:<line number> ...@@ -131,7 +131,7 @@ ExceptionTests.cpp:<line number>
............................................................................... ...............................................................................
ExceptionTests.cpp:<line number>: FAILED: ExceptionTests.cpp:<line number>: FAILED:
REQUIRE_THROWS_AS( throwCustom() ) REQUIRE_THROWS_AS( throwCustom(), std::exception )
due to unexpected exception with message: due to unexpected exception with message:
custom exception - not std custom exception - not std
...@@ -245,12 +245,12 @@ ExceptionTests.cpp:<line number> ...@@ -245,12 +245,12 @@ ExceptionTests.cpp:<line number>
............................................................................... ...............................................................................
ExceptionTests.cpp:<line number>: FAILED: ExceptionTests.cpp:<line number>: FAILED:
CHECK_THROWS_AS( thisThrows() ) CHECK_THROWS_AS( thisThrows(), std::string )
due to unexpected exception with message: due to unexpected exception with message:
expected exception expected exception
ExceptionTests.cpp:<line number>: FAILED: ExceptionTests.cpp:<line number>: FAILED:
CHECK_THROWS_AS( thisDoesntThrow() ) CHECK_THROWS_AS( thisDoesntThrow(), std::domain_error )
because no exception was thrown where one was expected: because no exception was thrown where one was expected:
ExceptionTests.cpp:<line number>: FAILED: ExceptionTests.cpp:<line number>: FAILED:
...@@ -584,11 +584,11 @@ MiscTests.cpp:<line number>: FAILED: ...@@ -584,11 +584,11 @@ MiscTests.cpp:<line number>: FAILED:
CHECK( s1 == s2 ) CHECK( s1 == s2 )
with expansion: with expansion:
"if ($b == 10) { "if ($b == 10) {
$a= 20; $a = 20;
}" }"
== ==
"if ($b == 10) { "if ($b == 10) {
$a = 20; $a = 20;
} }
" "
...@@ -613,8 +613,7 @@ due to unexpected exception with message: ...@@ -613,8 +613,7 @@ due to unexpected exception with message:
unexpected exception unexpected exception
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
When unchecked exceptions are thrown during a CHECK the test should abort and When unchecked exceptions are thrown during a CHECK the test should continue
fail
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
ExceptionTests.cpp:<line number> ExceptionTests.cpp:<line number>
............................................................................... ...............................................................................
...@@ -712,7 +711,7 @@ MiscTests.cpp:<line number>: FAILED: ...@@ -712,7 +711,7 @@ MiscTests.cpp:<line number>: FAILED:
with expansion: with expansion:
false false
------------------------------------------------------------------------------- spanner-------------------------------------------------------------------------------
just failure just failure
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
MessageTests.cpp:<line number> MessageTests.cpp:<line number>
...@@ -830,6 +829,6 @@ with expansion: ...@@ -830,6 +829,6 @@ with expansion:
"first" == "second" "first" == "second"
=============================================================================== ===============================================================================
test cases: 159 | 115 passed | 42 failed | 2 failed as expected test cases: 161 | 117 passed | 42 failed | 2 failed as expected
assertions: 909 | 813 passed | 78 failed | 18 failed as expected assertions: 932 | 836 passed | 78 failed | 18 failed as expected
...@@ -14,6 +14,40 @@ PASSED: ...@@ -14,6 +14,40 @@ PASSED:
with message: with message:
yay yay
-------------------------------------------------------------------------------
#542
-------------------------------------------------------------------------------
CompilationTests.cpp:<line number>
...............................................................................
CompilationTests.cpp:<line number>:
PASSED:
CHECK_THROWS_AS( throws_int(true), int )
CompilationTests.cpp:<line number>:
PASSED:
CHECK_THROWS_AS( throws_int(true), int& )
CompilationTests.cpp:<line number>:
PASSED:
CHECK_THROWS_AS( throws_int(true), const int )
CompilationTests.cpp:<line number>:
PASSED:
CHECK_THROWS_AS( throws_int(true), const int& )
-------------------------------------------------------------------------------
#809
-------------------------------------------------------------------------------
CompilationTests.cpp:<line number>
...............................................................................
CompilationTests.cpp:<line number>:
PASSED:
REQUIRE( 42 == f )
with expansion:
42 == {?}
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
'Not' checks that should fail 'Not' checks that should fail
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
...@@ -35,6 +69,6 @@ ConditionTests.cpp:<line number>: FAILED: ...@@ -35,6 +69,6 @@ ConditionTests.cpp:<line number>: FAILED:
CHECK_FALSE( true ) CHECK_FALSE( true )
=============================================================================== ===============================================================================
test cases: 2 | 1 passed | 1 failed test cases: 4 | 3 passed | 1 failed
assertions: 5 | 1 passed | 4 failed assertions: 10 | 6 passed | 4 failed
<?xml version="1.1" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<testsuites> <testsuitesspanner>
<testsuite name="<exe-name>" errors="13" failures="68" tests="912" hostname="tbd" time="{duration}" timestamp="tbd"> <testsuite name="<exe-name>" errors="13" failures="68" tests="935" hostname="tbd" time="{duration}" timestamp="{iso8601-timestamp}">
<testcase classname="global" name="# A test name that starts with a #" time="{duration}"/> <testcase classname="global" name="# A test name that starts with a #" time="{duration}"/>
<testcase classname="global" name="#542" time="{duration}"/>
<testcase classname="global" name="#809" time="{duration}"/>
<testcase classname="global" name="'Not' checks that should fail" time="{duration}"> <testcase classname="global" name="'Not' checks that should fail" time="{duration}">
<failure message="false != false" type="CHECK"> <failure message="false != false" type="CHECK">
ConditionTests.cpp:<line number> ConditionTests.cpp:<line number>
...@@ -80,6 +82,9 @@ ExceptionTests.cpp:<line number> ...@@ -80,6 +82,9 @@ ExceptionTests.cpp:<line number>
<testcase classname="Assertions then sections" name="A section" time="{duration}"/> <testcase classname="Assertions then sections" name="A section" time="{duration}"/>
<testcase classname="Assertions then sections" name="A section/Another section" time="{duration}"/> <testcase classname="Assertions then sections" name="A section/Another section" time="{duration}"/>
<testcase classname="Assertions then sections" name="A section/Another other section" time="{duration}"/> <testcase classname="Assertions then sections" name="A section/Another other section" time="{duration}"/>
<testcase classname="Character pretty printing" name="Specifically escaped" time="{duration}"/>
<testcase classname="Character pretty printing" name="General chars" time="{duration}"/>
<testcase classname="Character pretty printing" name="Low ASCII" time="{duration}"/>
<testcase classname="global" name="Comparing function pointers" time="{duration}"/> <testcase classname="global" name="Comparing function pointers" time="{duration}"/>
<testcase classname="global" name="Comparing member function pointers" time="{duration}"/> <testcase classname="global" name="Comparing member function pointers" time="{duration}"/>
<testcase classname="global" name="Comparisons between ints where one side is computed" time="{duration}"/> <testcase classname="global" name="Comparisons between ints where one side is computed" time="{duration}"/>
...@@ -97,7 +102,7 @@ ExceptionTests.cpp:<line number> ...@@ -97,7 +102,7 @@ ExceptionTests.cpp:<line number>
</error> </error>
</testcase> </testcase>
<testcase classname="global" name="Custom exceptions can be translated when testing for throwing as something else" time="{duration}"> <testcase classname="global" name="Custom exceptions can be translated when testing for throwing as something else" time="{duration}">
<error message="throwCustom()" type="REQUIRE_THROWS_AS"> <error message="throwCustom(), std::exception" type="REQUIRE_THROWS_AS">
custom exception - not std custom exception - not std
ExceptionTests.cpp:<line number> ExceptionTests.cpp:<line number>
</error> </error>
...@@ -167,11 +172,11 @@ MiscTests.cpp:<line number> ...@@ -167,11 +172,11 @@ MiscTests.cpp:<line number>
<testcase classname="Exception messages can be tested for" name="different case" time="{duration}"/> <testcase classname="Exception messages can be tested for" name="different case" time="{duration}"/>
<testcase classname="Exception messages can be tested for" name="wildcarded" time="{duration}"/> <testcase classname="Exception messages can be tested for" name="wildcarded" time="{duration}"/>
<testcase classname="global" name="Expected exceptions that don't throw or unexpected exceptions fail the test" time="{duration}"> <testcase classname="global" name="Expected exceptions that don't throw or unexpected exceptions fail the test" time="{duration}">
<error message="thisThrows()" type="CHECK_THROWS_AS"> <error message="thisThrows(), std::string" type="CHECK_THROWS_AS">
expected exception expected exception
ExceptionTests.cpp:<line number> ExceptionTests.cpp:<line number>
</error> </error>
<failure message="thisDoesntThrow()" type="CHECK_THROWS_AS"> <failure message="thisDoesntThrow(), std::domain_error" type="CHECK_THROWS_AS">
ExceptionTests.cpp:<line number> ExceptionTests.cpp:<line number>
</failure> </failure>
<error message="thisThrows()" type="CHECK_NOTHROW"> <error message="thisThrows()" type="CHECK_NOTHROW">
...@@ -242,7 +247,9 @@ ConditionTests.cpp:<line number> ...@@ -242,7 +247,9 @@ ConditionTests.cpp:<line number>
<testcase classname="Long strings can be wrapped" name="With newlines/Trailing newline" time="{duration}"/> <testcase classname="Long strings can be wrapped" name="With newlines/Trailing newline" time="{duration}"/>
<testcase classname="Long strings can be wrapped" name="With newlines/Wrapped once" time="{duration}"/> <testcase classname="Long strings can be wrapped" name="With newlines/Wrapped once" time="{duration}"/>
<testcase classname="Long strings can be wrapped" name="With newlines/Wrapped twice" time="{duration}"/> <testcase classname="Long strings can be wrapped" name="With newlines/Wrapped twice" time="{duration}"/>
<testcase classname="Long strings can be wrapped" name="With tabs" time="{duration}"/> <testcase classname="Long strings can be wrapped" name="With wrap-before/ after characters/No wrapping" time="{duration}"/>
<testcase classname="Long strings can be wrapped" name="With wrap-before/ after characters/Wrap before" time="{duration}"/>
<testcase classname="Long strings can be wrapped" name="With wrap-before/ after characters/Wrap after" time="{duration}"/>
<testcase classname="global" name="Long text is truncted" time="{duration}"/> <testcase classname="global" name="Long text is truncted" time="{duration}"/>
<testcase classname="global" name="ManuallyRegistered" time="{duration}"/> <testcase classname="global" name="ManuallyRegistered" time="{duration}"/>
<testcase classname="global" name="Matchers can be (AllOf) composed with the &amp;&amp; operator" time="{duration}"/> <testcase classname="global" name="Matchers can be (AllOf) composed with the &amp;&amp; operator" time="{duration}"/>
...@@ -500,7 +507,7 @@ unexpected exception ...@@ -500,7 +507,7 @@ unexpected exception
ExceptionTests.cpp:<line number> ExceptionTests.cpp:<line number>
</error> </error>
</testcase> </testcase>
<testcase classname="global" name="When unchecked exceptions are thrown during a CHECK the test should abort and fail" time="{duration}"> <testcase classname="global" name="When unchecked exceptions are thrown during a CHECK the test should continue" time="{duration}">
<error message="thisThrows() == 0" type="CHECK"> <error message="thisThrows() == 0" type="CHECK">
expected exception expected exception
ExceptionTests.cpp:<line number> ExceptionTests.cpp:<line number>
...@@ -652,8 +659,6 @@ TrickyTests.cpp:<line number> ...@@ -652,8 +659,6 @@ TrickyTests.cpp:<line number>
<testcase classname="global" name="toString( has_maker_and_toString )" time="{duration}"/> <testcase classname="global" name="toString( has_maker_and_toString )" time="{duration}"/>
<testcase classname="global" name="toString( has_toString )" time="{duration}"/> <testcase classname="global" name="toString( has_toString )" time="{duration}"/>
<testcase classname="global" name="toString( vectors&lt;has_maker )" time="{duration}"/> <testcase classname="global" name="toString( vectors&lt;has_maker )" time="{duration}"/>
<testcase classname="global" name="toString( vectors&lt;has_maker_and_toString )" time="{duration}"/>
<testcase classname="global" name="toString( vectors&lt;has_toString )" time="{duration}"/>
<testcase classname="global" name="toString(enum w/operator&lt;&lt;)" time="{duration}"/> <testcase classname="global" name="toString(enum w/operator&lt;&lt;)" time="{duration}"/>
<testcase classname="global" name="toString(enum)" time="{duration}"/> <testcase classname="global" name="toString(enum)" time="{duration}"/>
<testcase classname="global" name="vector&lt;int> -> toString" time="{duration}"/> <testcase classname="global" name="vector&lt;int> -> toString" time="{duration}"/>
......
/*
* Created by Martin on 17/02/2017.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "catch.hpp"
// This is a minimal example for an issue we have found in 1.7.0
struct foo {
int i;
};
template <typename T>
bool operator==(const T& val, foo f){
return val == f.i;
}
TEST_CASE("#809") {
foo f; f.i = 42;
REQUIRE(42 == f);
}
// ------------------------------------------------------------------
// REQUIRE_THROWS_AS was changed to catch exceptions by const&
// using type traits. This means that this should compile cleanly
// Provides indirection to prevent unreachable-code warnings
void throws_int(bool b) {
if (b) {
throw 1;
}
}
TEST_CASE("#542") {
CHECK_THROWS_AS(throws_int(true), int);
CHECK_THROWS_AS(throws_int(true), int&);
CHECK_THROWS_AS(throws_int(true), const int);
CHECK_THROWS_AS(throws_int(true), const int&);
}
...@@ -210,29 +210,29 @@ TEST_CASE( "Comparisons with int literals don't warn when mixing signed/ unsigne ...@@ -210,29 +210,29 @@ TEST_CASE( "Comparisons with int literals don't warn when mixing signed/ unsigne
TEST_CASE( "comparisons between int variables", "" ) TEST_CASE( "comparisons between int variables", "" )
{ {
long long_var = 1L; long long_var = 1L;
unsigned char unsigned_char_var = 1; unsigned char unsigned_char_var = 1;
unsigned short unsigned_short_var = 1; unsigned short unsigned_short_var = 1;
unsigned int unsigned_int_var = 1; unsigned int unsigned_int_var = 1;
unsigned long unsigned_long_var = 1L; unsigned long unsigned_long_var = 1L;
REQUIRE( long_var == unsigned_char_var ); REQUIRE( long_var == unsigned_char_var );
REQUIRE( long_var == unsigned_short_var ); REQUIRE( long_var == unsigned_short_var );
REQUIRE( long_var == unsigned_int_var ); REQUIRE( long_var == unsigned_int_var );
REQUIRE( long_var == unsigned_long_var ); REQUIRE( long_var == unsigned_long_var );
} }
TEST_CASE( "comparisons between const int variables", "" ) TEST_CASE( "comparisons between const int variables", "" )
{ {
const unsigned char unsigned_char_var = 1; const unsigned char unsigned_char_var = 1;
const unsigned short unsigned_short_var = 1; const unsigned short unsigned_short_var = 1;
const unsigned int unsigned_int_var = 1; const unsigned int unsigned_int_var = 1;
const unsigned long unsigned_long_var = 1L; const unsigned long unsigned_long_var = 1L;
REQUIRE( unsigned_char_var == 1 ); REQUIRE( unsigned_char_var == 1 );
REQUIRE( unsigned_short_var == 1 ); REQUIRE( unsigned_short_var == 1 );
REQUIRE( unsigned_int_var == 1 ); REQUIRE( unsigned_int_var == 1 );
REQUIRE( unsigned_long_var == 1 ); REQUIRE( unsigned_long_var == 1 );
} }
TEST_CASE( "Comparisons between unsigned ints and negative signed ints match c++ standard behaviour", "" ) TEST_CASE( "Comparisons between unsigned ints and negative signed ints match c++ standard behaviour", "" )
......
...@@ -458,10 +458,10 @@ TEST_CASE( "XmlEncode" ) { ...@@ -458,10 +458,10 @@ TEST_CASE( "XmlEncode" ) {
REQUIRE( encode( stringWithQuotes, Catch::XmlEncode::ForAttributes ) == "don't &quot;quote&quot; me on that" ); REQUIRE( encode( stringWithQuotes, Catch::XmlEncode::ForAttributes ) == "don't &quot;quote&quot; me on that" );
} }
SECTION( "string with control char (1)" ) { SECTION( "string with control char (1)" ) {
REQUIRE( encode( "[\x01]" ) == "[&#x01;]" ); REQUIRE( encode( "[\x01]" ) == "[\\x01]" );
} }
SECTION( "string with control char (x7F)" ) { SECTION( "string with control char (x7F)" ) {
REQUIRE( encode( "[\x7F]" ) == "[&#x7F;]" ); REQUIRE( encode( "[\x7F]" ) == "[\\x7F]" );
} }
} }
......
// This file is only here to verify (to the extent possible) the self sufficiency of the header
#include "internal/catch_test_case_tracker.hpp"
...@@ -196,13 +196,13 @@ TEST_CASE( "Process can be configured on command line", "[config][command-line]" ...@@ -196,13 +196,13 @@ TEST_CASE( "Process can be configured on command line", "[config][command-line]"
} }
SECTION( "use-colour", "") { SECTION( "use-colour", "") {
using Catch::UseColour; using Catch::UseColour;
SECTION( "without option", "" ) { SECTION( "without option", "" ) {
const char* argv[] = { "test" }; const char* argv[] = { "test" };
CHECK_NOTHROW( parseIntoConfig( argv, config ) ); CHECK_NOTHROW( parseIntoConfig( argv, config ) );
REQUIRE( config.useColour == UseColour::Auto ); REQUIRE( config.useColour == UseColour::Auto );
} }
...@@ -216,14 +216,14 @@ TEST_CASE( "Process can be configured on command line", "[config][command-line]" ...@@ -216,14 +216,14 @@ TEST_CASE( "Process can be configured on command line", "[config][command-line]"
SECTION( "yes", "" ) { SECTION( "yes", "" ) {
const char* argv[] = { "test", "--use-colour", "yes" }; const char* argv[] = { "test", "--use-colour", "yes" };
CHECK_NOTHROW( parseIntoConfig( argv, config ) ); CHECK_NOTHROW( parseIntoConfig( argv, config ) );
REQUIRE( config.useColour == UseColour::Yes ); REQUIRE( config.useColour == UseColour::Yes );
} }
SECTION( "no", "" ) { SECTION( "no", "" ) {
const char* argv[] = { "test", "--use-colour", "no" }; const char* argv[] = { "test", "--use-colour", "no" };
CHECK_NOTHROW( parseIntoConfig( argv, config ) ); CHECK_NOTHROW( parseIntoConfig( argv, config ) );
REQUIRE( config.useColour == UseColour::No ); REQUIRE( config.useColour == UseColour::No );
} }
...@@ -299,9 +299,10 @@ TEST_CASE( "Long strings can be wrapped", "[wrap]" ) { ...@@ -299,9 +299,10 @@ TEST_CASE( "Long strings can be wrapped", "[wrap]" ) {
CHECK( Text( testString, TextAttributes().setWidth( 10 ) ).toString() == testString ); CHECK( Text( testString, TextAttributes().setWidth( 10 ) ).toString() == testString );
} }
SECTION( "Trailing newline" , "" ) { SECTION( "Trailing newline" , "" ) {
CHECK( Text( "abcdef\n", TextAttributes().setWidth( 10 ) ).toString() == "abcdef\n" ); CHECK( Text( "abcdef\n", TextAttributes().setWidth( 10 ) ).toString() == "abcdef" );
CHECK( Text( "abcdef", TextAttributes().setWidth( 6 ) ).toString() == "abcdef" ); CHECK( Text( "abcdef", TextAttributes().setWidth( 6 ) ).toString() == "abcdef" );
CHECK( Text( "abcdef\n", TextAttributes().setWidth( 6 ) ).toString() == "abcdef\n" ); CHECK( Text( "abcdef\n", TextAttributes().setWidth( 6 ) ).toString() == "abcdef" );
CHECK( Text( "abcdef\n", TextAttributes().setWidth( 5 ) ).toString() == "abcd-\nef" );
} }
SECTION( "Wrapped once", "" ) { SECTION( "Wrapped once", "" ) {
CHECK( Text( testString, TextAttributes().setWidth( 9 ) ).toString() == "one two\nthree\nfour" ); CHECK( Text( testString, TextAttributes().setWidth( 9 ) ).toString() == "one two\nthree\nfour" );
...@@ -313,16 +314,23 @@ TEST_CASE( "Long strings can be wrapped", "[wrap]" ) { ...@@ -313,16 +314,23 @@ TEST_CASE( "Long strings can be wrapped", "[wrap]" ) {
} }
} }
SECTION( "With tabs", "" ) { SECTION( "With wrap-before/ after characters", "" ) {
std::string testString = "one,two(three) <here>";
// guide: 1234567890123456789
std::string testString = "one two \tthree four five six";
CHECK( Text( testString, TextAttributes().setWidth( 15 ) ).toString() SECTION( "No wrapping", "" ) {
== "one two three\n four\n five\n six" ); CHECK( Text( testString, TextAttributes().setWidth( 80 ) ).toString() == testString );
CHECK( Text( testString, TextAttributes().setWidth( 24 ) ).toString() == testString );
}
SECTION( "Wrap before", "" ) {
CHECK( Text( testString, TextAttributes().setWidth( 11 ) ).toString() == "one,two\n(three)\n<here>" );
}
SECTION( "Wrap after", "" ) {
CHECK( Text( testString, TextAttributes().setWidth( 6 ) ).toString() == "one,\ntwo\n(thre-\ne)\n<here>" );
CHECK( Text( testString, TextAttributes().setWidth( 5 ) ).toString() == "one,\ntwo\n(thr-\nee)\n<her-\ne>" );
CHECK( Text( testString, TextAttributes().setWidth( 4 ) ).toString() == "one,\ntwo\n(th-\nree)\n<he-\nre>" );
}
} }
} }
using namespace Catch; using namespace Catch;
......
...@@ -37,19 +37,21 @@ TEST_CASE( "toString( has_toString )", "[toString]" ) { ...@@ -37,19 +37,21 @@ TEST_CASE( "toString( has_toString )", "[toString]" ) {
} }
// Call the overload // Call the overload
TEST_CASE( "toString( has_maker )", "[toString]" ) { TEST_CASE( "toString( has_maker )", "toString]" ) {
has_maker item; has_maker item;
REQUIRE( Catch::toString( item ) == "StringMaker<has_maker>" ); REQUIRE( Catch::toString( item ) == "StringMaker<has_maker>" );
} }
// Call the overload // Call the overload
TEST_CASE( "toString( has_maker_and_toString )", "[toString]" ) { TEST_CASE( "toString( has_maker_and_toString )", "[.][toString]" ) {
has_maker_and_toString item; has_maker_and_toString item;
REQUIRE( Catch::toString( item ) == "toString( has_maker_and_toString )" ); REQUIRE( Catch::toString( item ) == "toString( has_maker_and_toString )" );
} }
// Vectors... // Vectors...
TEST_CASE( "toString( vectors<has_toString )", "[toString]" ) {
// Don't run this in approval tests as it is sensitive to two phase lookup differences
TEST_CASE( "toString( vectors<has_toString )", "[.][toString][!nonportable]" ) {
std::vector<has_toString> v(1); std::vector<has_toString> v(1);
// This invokes template<T> toString which actually gives us '{ ? }' // This invokes template<T> toString which actually gives us '{ ? }'
REQUIRE( Catch::toString( v ) == "{ {?} }" ); REQUIRE( Catch::toString( v ) == "{ {?} }" );
...@@ -61,7 +63,8 @@ TEST_CASE( "toString( vectors<has_maker )", "[toString]" ) { ...@@ -61,7 +63,8 @@ TEST_CASE( "toString( vectors<has_maker )", "[toString]" ) {
} }
TEST_CASE( "toString( vectors<has_maker_and_toString )", "[toString]" ) { // Don't run this in approval tests as it is sensitive to two phase lookup differences
TEST_CASE( "toString( vectors<has_maker_and_toString )", "[.][toString][!nonportable]" ) {
std::vector<has_maker_and_toString> v(1); std::vector<has_maker_and_toString> v(1);
// Note: This invokes the template<T> toString -> StringMaker // Note: This invokes the template<T> toString -> StringMaker
REQUIRE( Catch::toString( v ) == "{ StringMaker<has_maker_and_toString> }" ); REQUIRE( Catch::toString( v ) == "{ StringMaker<has_maker_and_toString> }" );
......
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论