mirror of
https://github.com/catchorg/Catch2.git
synced 2025-08-02 13:25:41 +02:00
Rename include/ to src/
This commit is contained in:
490
src/catch.hpp
Normal file
490
src/catch.hpp
Normal file
@@ -0,0 +1,490 @@
|
||||
/*
|
||||
* Created by Phil on 22/10/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd
|
||||
*
|
||||
* 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_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_HPP_INCLUDED
|
||||
|
||||
#define CATCH_VERSION_MAJOR 2
|
||||
#define CATCH_VERSION_MINOR 10
|
||||
#define CATCH_VERSION_PATCH 2
|
||||
|
||||
#ifdef __clang__
|
||||
# pragma clang system_header
|
||||
#elif defined __GNUC__
|
||||
# pragma GCC system_header
|
||||
#endif
|
||||
|
||||
#include "internal/catch_suppress_warnings.h"
|
||||
|
||||
#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
|
||||
# define CATCH_IMPL
|
||||
# define CATCH_CONFIG_ALL_PARTS
|
||||
#endif
|
||||
|
||||
// In the impl file, we want to have access to all parts of the headers
|
||||
// Can also be used to sanely support PCHs
|
||||
#if defined(CATCH_CONFIG_ALL_PARTS)
|
||||
# define CATCH_CONFIG_EXTERNAL_INTERFACES
|
||||
# if defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
# undef CATCH_CONFIG_DISABLE_MATCHERS
|
||||
# endif
|
||||
# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
|
||||
# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if !defined(CATCH_CONFIG_IMPL_ONLY)
|
||||
#include "internal/catch_platform.h"
|
||||
|
||||
#ifdef CATCH_IMPL
|
||||
# ifndef CLARA_CONFIG_MAIN
|
||||
# define CLARA_CONFIG_MAIN_NOT_DEFINED
|
||||
# define CLARA_CONFIG_MAIN
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#include "internal/catch_user_interfaces.h"
|
||||
#include "internal/catch_tag_alias_autoregistrar.h"
|
||||
#include "internal/catch_test_registry.h"
|
||||
#include "internal/catch_capture.hpp"
|
||||
#include "internal/catch_section.h"
|
||||
#include "internal/catch_interfaces_exception.h"
|
||||
#include "internal/catch_approx.h"
|
||||
#include "internal/catch_compiler_capabilities.h"
|
||||
#include "internal/catch_string_manip.h"
|
||||
|
||||
#ifndef CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#include "internal/catch_capture_matchers.h"
|
||||
#endif
|
||||
#include "internal/catch_generators.hpp"
|
||||
#include "internal/catch_generators_generic.hpp"
|
||||
#include "internal/catch_generators_specific.hpp"
|
||||
|
||||
// These files are included here so the single_include script doesn't put them
|
||||
// in the conditionally compiled sections
|
||||
#include "internal/catch_test_case_info.h"
|
||||
#include "internal/catch_interfaces_runner.h"
|
||||
|
||||
#ifdef __OBJC__
|
||||
#include "internal/catch_objc.hpp"
|
||||
#endif
|
||||
|
||||
// Benchmarking needs the externally-facing parts of reporters to work
|
||||
#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
#include "internal/catch_external_interfaces.h"
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
#include "internal/benchmark/catch_benchmark.hpp"
|
||||
#endif
|
||||
|
||||
#endif // ! CATCH_CONFIG_IMPL_ONLY
|
||||
|
||||
#ifdef CATCH_IMPL
|
||||
#include "internal/catch_impl.hpp"
|
||||
#endif
|
||||
|
||||
#ifdef CATCH_CONFIG_MAIN
|
||||
#include "internal/catch_default_main.hpp"
|
||||
#endif
|
||||
|
||||
|
||||
#if !defined(CATCH_CONFIG_IMPL_ONLY)
|
||||
|
||||
#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
|
||||
# undef CLARA_CONFIG_MAIN
|
||||
#endif
|
||||
|
||||
#if !defined(CATCH_CONFIG_DISABLE)
|
||||
//////
|
||||
// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
|
||||
#ifdef CATCH_CONFIG_PREFIX_ALL
|
||||
|
||||
#define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
|
||||
#define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
|
||||
|
||||
#define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
|
||||
#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
|
||||
#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
|
||||
#endif// CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
|
||||
|
||||
#define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
|
||||
#define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
|
||||
|
||||
#define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
|
||||
#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
|
||||
|
||||
#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
|
||||
#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
|
||||
#define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
|
||||
#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
|
||||
#define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
|
||||
|
||||
#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
|
||||
#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
|
||||
#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
|
||||
#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
|
||||
#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
|
||||
#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
|
||||
#define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
|
||||
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
|
||||
#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
|
||||
#else
|
||||
#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
|
||||
#endif
|
||||
|
||||
|
||||
#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
|
||||
#define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
|
||||
#define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
|
||||
#else
|
||||
#define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
|
||||
#define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
|
||||
#endif
|
||||
|
||||
|
||||
// "BDD-style" convenience wrappers
|
||||
#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
|
||||
#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
|
||||
#define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
|
||||
#define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
|
||||
#define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
|
||||
#define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
|
||||
#define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
|
||||
#define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
#define CATCH_BENCHMARK(...) \
|
||||
INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
|
||||
#define CATCH_BENCHMARK_ADVANCED(name) \
|
||||
INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
|
||||
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
|
||||
|
||||
// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
|
||||
#else
|
||||
|
||||
#define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
|
||||
#define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
|
||||
|
||||
#define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
|
||||
#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
|
||||
#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
|
||||
|
||||
#define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
|
||||
#define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
|
||||
|
||||
#define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
|
||||
#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
|
||||
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
|
||||
|
||||
#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
|
||||
#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
|
||||
#define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
|
||||
#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
|
||||
#define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
|
||||
|
||||
#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
|
||||
#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
|
||||
#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
|
||||
#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
|
||||
#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
|
||||
#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
|
||||
#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
|
||||
|
||||
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
|
||||
#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
|
||||
#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
|
||||
#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
|
||||
#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#else
|
||||
#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
|
||||
#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
|
||||
#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
|
||||
#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
|
||||
#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
|
||||
#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
|
||||
#endif
|
||||
|
||||
|
||||
#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
|
||||
#define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
|
||||
#define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
|
||||
#else
|
||||
#define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
|
||||
#define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
|
||||
|
||||
// "BDD-style" convenience wrappers
|
||||
#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
|
||||
#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
|
||||
|
||||
#define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
|
||||
#define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
|
||||
#define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
|
||||
#define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
|
||||
#define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
|
||||
#define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
#define BENCHMARK(...) \
|
||||
INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
|
||||
#define BENCHMARK_ADVANCED(name) \
|
||||
INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
|
||||
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
|
||||
|
||||
using Catch::Detail::Approx;
|
||||
|
||||
#else // CATCH_CONFIG_DISABLE
|
||||
|
||||
//////
|
||||
// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
|
||||
#ifdef CATCH_CONFIG_PREFIX_ALL
|
||||
|
||||
#define CATCH_REQUIRE( ... ) (void)(0)
|
||||
#define CATCH_REQUIRE_FALSE( ... ) (void)(0)
|
||||
|
||||
#define CATCH_REQUIRE_THROWS( ... ) (void)(0)
|
||||
#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
|
||||
#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
|
||||
#endif// CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
|
||||
|
||||
#define CATCH_CHECK( ... ) (void)(0)
|
||||
#define CATCH_CHECK_FALSE( ... ) (void)(0)
|
||||
#define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
|
||||
#define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
|
||||
#define CATCH_CHECK_NOFAIL( ... ) (void)(0)
|
||||
|
||||
#define CATCH_CHECK_THROWS( ... ) (void)(0)
|
||||
#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
|
||||
#define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#define CATCH_CHECK_NOTHROW( ... ) (void)(0)
|
||||
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
|
||||
|
||||
#define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
|
||||
#define CATCH_INFO( msg ) (void)(0)
|
||||
#define CATCH_UNSCOPED_INFO( msg ) (void)(0)
|
||||
#define CATCH_WARN( msg ) (void)(0)
|
||||
#define CATCH_CAPTURE( msg ) (void)(0)
|
||||
|
||||
#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
|
||||
#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
|
||||
#define CATCH_METHOD_AS_TEST_CASE( method, ... )
|
||||
#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
|
||||
#define CATCH_SECTION( ... )
|
||||
#define CATCH_DYNAMIC_SECTION( ... )
|
||||
#define CATCH_FAIL( ... ) (void)(0)
|
||||
#define CATCH_FAIL_CHECK( ... ) (void)(0)
|
||||
#define CATCH_SUCCEED( ... ) (void)(0)
|
||||
|
||||
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
|
||||
#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
|
||||
#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
|
||||
#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
|
||||
#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#else
|
||||
#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#endif
|
||||
|
||||
// "BDD-style" convenience wrappers
|
||||
#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
|
||||
#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
|
||||
#define CATCH_GIVEN( desc )
|
||||
#define CATCH_AND_GIVEN( desc )
|
||||
#define CATCH_WHEN( desc )
|
||||
#define CATCH_AND_WHEN( desc )
|
||||
#define CATCH_THEN( desc )
|
||||
#define CATCH_AND_THEN( desc )
|
||||
|
||||
#define CATCH_STATIC_REQUIRE( ... ) (void)(0)
|
||||
#define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
|
||||
|
||||
// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
|
||||
#else
|
||||
|
||||
#define REQUIRE( ... ) (void)(0)
|
||||
#define REQUIRE_FALSE( ... ) (void)(0)
|
||||
|
||||
#define REQUIRE_THROWS( ... ) (void)(0)
|
||||
#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
|
||||
#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#define REQUIRE_NOTHROW( ... ) (void)(0)
|
||||
|
||||
#define CHECK( ... ) (void)(0)
|
||||
#define CHECK_FALSE( ... ) (void)(0)
|
||||
#define CHECKED_IF( ... ) if (__VA_ARGS__)
|
||||
#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
|
||||
#define CHECK_NOFAIL( ... ) (void)(0)
|
||||
|
||||
#define CHECK_THROWS( ... ) (void)(0)
|
||||
#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
|
||||
#define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
#define CHECK_NOTHROW( ... ) (void)(0)
|
||||
|
||||
|
||||
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
|
||||
#define CHECK_THAT( arg, matcher ) (void)(0)
|
||||
|
||||
#define REQUIRE_THAT( arg, matcher ) (void)(0)
|
||||
#endif // CATCH_CONFIG_DISABLE_MATCHERS
|
||||
|
||||
#define INFO( msg ) (void)(0)
|
||||
#define UNSCOPED_INFO( msg ) (void)(0)
|
||||
#define WARN( msg ) (void)(0)
|
||||
#define CAPTURE( msg ) (void)(0)
|
||||
|
||||
#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
|
||||
#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
|
||||
#define METHOD_AS_TEST_CASE( method, ... )
|
||||
#define REGISTER_TEST_CASE( Function, ... ) (void)(0)
|
||||
#define SECTION( ... )
|
||||
#define DYNAMIC_SECTION( ... )
|
||||
#define FAIL( ... ) (void)(0)
|
||||
#define FAIL_CHECK( ... ) (void)(0)
|
||||
#define SUCCEED( ... ) (void)(0)
|
||||
|
||||
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
|
||||
#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
|
||||
#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
|
||||
#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
|
||||
#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#else
|
||||
#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
|
||||
#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
|
||||
#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
|
||||
#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
|
||||
#endif
|
||||
|
||||
#define STATIC_REQUIRE( ... ) (void)(0)
|
||||
#define STATIC_REQUIRE_FALSE( ... ) (void)(0)
|
||||
|
||||
#endif
|
||||
|
||||
#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
|
||||
|
||||
// "BDD-style" convenience wrappers
|
||||
#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
|
||||
#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
|
||||
|
||||
#define GIVEN( desc )
|
||||
#define AND_GIVEN( desc )
|
||||
#define WHEN( desc )
|
||||
#define AND_WHEN( desc )
|
||||
#define THEN( desc )
|
||||
#define AND_THEN( desc )
|
||||
|
||||
using Catch::Detail::Approx;
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
#endif // ! CATCH_CONFIG_IMPL_ONLY
|
||||
|
||||
#include "internal/catch_reenable_warnings.h"
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_HPP_INCLUDED
|
1268
src/external/clara.hpp
vendored
Normal file
1268
src/external/clara.hpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
122
src/internal/benchmark/catch_benchmark.hpp
Normal file
122
src/internal/benchmark/catch_benchmark.hpp
Normal file
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Benchmark
|
||||
#ifndef TWOBLUECUBES_CATCH_BENCHMARK_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_BENCHMARK_HPP_INCLUDED
|
||||
|
||||
#include "../catch_config.hpp"
|
||||
#include "../catch_context.h"
|
||||
#include "../catch_interfaces_reporter.h"
|
||||
#include "../catch_test_registry.h"
|
||||
|
||||
#include "catch_chronometer.hpp"
|
||||
#include "catch_clock.hpp"
|
||||
#include "catch_environment.hpp"
|
||||
#include "catch_execution_plan.hpp"
|
||||
#include "detail/catch_estimate_clock.hpp"
|
||||
#include "detail/catch_complete_invoke.hpp"
|
||||
#include "detail/catch_analyse.hpp"
|
||||
#include "detail/catch_benchmark_function.hpp"
|
||||
#include "detail/catch_run_for_at_least.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
struct Benchmark {
|
||||
Benchmark(std::string &&name)
|
||||
: name(std::move(name)) {}
|
||||
|
||||
template <class FUN>
|
||||
Benchmark(std::string &&name, FUN &&func)
|
||||
: fun(std::move(func)), name(std::move(name)) {}
|
||||
|
||||
template <typename Clock>
|
||||
ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
|
||||
auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
|
||||
auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
|
||||
auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
|
||||
int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
|
||||
return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
|
||||
}
|
||||
|
||||
template <typename Clock = default_clock>
|
||||
void run() {
|
||||
IConfigPtr cfg = getCurrentContext().getConfig();
|
||||
|
||||
auto env = Detail::measure_environment<Clock>();
|
||||
|
||||
getResultCapture().benchmarkPreparing(name);
|
||||
CATCH_TRY{
|
||||
auto plan = user_code([&] {
|
||||
return prepare<Clock>(*cfg, env);
|
||||
});
|
||||
|
||||
BenchmarkInfo info {
|
||||
name,
|
||||
plan.estimated_duration.count(),
|
||||
plan.iterations_per_sample,
|
||||
cfg->benchmarkSamples(),
|
||||
cfg->benchmarkResamples(),
|
||||
env.clock_resolution.mean.count(),
|
||||
env.clock_cost.mean.count()
|
||||
};
|
||||
|
||||
getResultCapture().benchmarkStarting(info);
|
||||
|
||||
auto samples = user_code([&] {
|
||||
return plan.template run<Clock>(*cfg, env);
|
||||
});
|
||||
|
||||
auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
|
||||
BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
|
||||
getResultCapture().benchmarkEnded(stats);
|
||||
|
||||
} CATCH_CATCH_ALL{
|
||||
if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
|
||||
std::rethrow_exception(std::current_exception());
|
||||
}
|
||||
}
|
||||
|
||||
// sets lambda to be used in fun *and* executes benchmark!
|
||||
template <typename Fun,
|
||||
typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
|
||||
Benchmark & operator=(Fun func) {
|
||||
fun = Detail::BenchmarkFunction(func);
|
||||
run();
|
||||
return *this;
|
||||
}
|
||||
|
||||
explicit operator bool() {
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
Detail::BenchmarkFunction fun;
|
||||
std::string name;
|
||||
};
|
||||
}
|
||||
} // namespace Catch
|
||||
|
||||
#define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
|
||||
#define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
|
||||
|
||||
#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
|
||||
if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
|
||||
BenchmarkName = [&](int benchmarkIndex)
|
||||
|
||||
#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
|
||||
if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
|
||||
BenchmarkName = [&]
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_BENCHMARK_HPP_INCLUDED
|
71
src/internal/benchmark/catch_chronometer.hpp
Normal file
71
src/internal/benchmark/catch_chronometer.hpp
Normal file
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// User-facing chronometer
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_CHRONOMETER_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CHRONOMETER_HPP_INCLUDED
|
||||
|
||||
#include "catch_clock.hpp"
|
||||
#include "catch_optimizer.hpp"
|
||||
#include "detail/catch_complete_invoke.hpp"
|
||||
#include "../catch_meta.hpp"
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
struct ChronometerConcept {
|
||||
virtual void start() = 0;
|
||||
virtual void finish() = 0;
|
||||
virtual ~ChronometerConcept() = default;
|
||||
};
|
||||
template <typename Clock>
|
||||
struct ChronometerModel final : public ChronometerConcept {
|
||||
void start() override { started = Clock::now(); }
|
||||
void finish() override { finished = Clock::now(); }
|
||||
|
||||
ClockDuration<Clock> elapsed() const { return finished - started; }
|
||||
|
||||
TimePoint<Clock> started;
|
||||
TimePoint<Clock> finished;
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
struct Chronometer {
|
||||
public:
|
||||
template <typename Fun>
|
||||
void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
|
||||
|
||||
int runs() const { return k; }
|
||||
|
||||
Chronometer(Detail::ChronometerConcept& meter, int k)
|
||||
: impl(&meter)
|
||||
, k(k) {}
|
||||
|
||||
private:
|
||||
template <typename Fun>
|
||||
void measure(Fun&& fun, std::false_type) {
|
||||
measure([&fun](int) { return fun(); }, std::true_type());
|
||||
}
|
||||
|
||||
template <typename Fun>
|
||||
void measure(Fun&& fun, std::true_type) {
|
||||
Detail::optimizer_barrier();
|
||||
impl->start();
|
||||
for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
|
||||
impl->finish();
|
||||
Detail::optimizer_barrier();
|
||||
}
|
||||
|
||||
Detail::ChronometerConcept* impl;
|
||||
int k;
|
||||
};
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CHRONOMETER_HPP_INCLUDED
|
40
src/internal/benchmark/catch_clock.hpp
Normal file
40
src/internal/benchmark/catch_clock.hpp
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Clocks
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_CLOCK_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CLOCK_HPP_INCLUDED
|
||||
|
||||
#include <chrono>
|
||||
#include <ratio>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
template <typename Clock>
|
||||
using ClockDuration = typename Clock::duration;
|
||||
template <typename Clock>
|
||||
using FloatDuration = std::chrono::duration<double, typename Clock::period>;
|
||||
|
||||
template <typename Clock>
|
||||
using TimePoint = typename Clock::time_point;
|
||||
|
||||
using default_clock = std::chrono::steady_clock;
|
||||
|
||||
template <typename Clock>
|
||||
struct now {
|
||||
TimePoint<Clock> operator()() const {
|
||||
return Clock::now();
|
||||
}
|
||||
};
|
||||
|
||||
using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CLOCK_HPP_INCLUDED
|
73
src/internal/benchmark/catch_constructor.hpp
Normal file
73
src/internal/benchmark/catch_constructor.hpp
Normal file
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Constructor and destructor helpers
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_CONSTRUCTOR_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CONSTRUCTOR_HPP_INCLUDED
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
namespace Catch {
|
||||
namespace Detail {
|
||||
template <typename T, bool Destruct>
|
||||
struct ObjectStorage
|
||||
{
|
||||
using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
|
||||
|
||||
ObjectStorage() : data() {}
|
||||
|
||||
ObjectStorage(const ObjectStorage& other)
|
||||
{
|
||||
new(&data) T(other.stored_object());
|
||||
}
|
||||
|
||||
ObjectStorage(ObjectStorage&& other)
|
||||
{
|
||||
new(&data) T(std::move(other.stored_object()));
|
||||
}
|
||||
|
||||
~ObjectStorage() { destruct_on_exit<T>(); }
|
||||
|
||||
template <typename... Args>
|
||||
void construct(Args&&... args)
|
||||
{
|
||||
new (&data) T(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <bool AllowManualDestruction = !Destruct>
|
||||
typename std::enable_if<AllowManualDestruction>::type destruct()
|
||||
{
|
||||
stored_object().~T();
|
||||
}
|
||||
|
||||
private:
|
||||
// If this is a constructor benchmark, destruct the underlying object
|
||||
template <typename U>
|
||||
void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
|
||||
// Otherwise, don't
|
||||
template <typename U>
|
||||
void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
|
||||
|
||||
T& stored_object()
|
||||
{
|
||||
return *static_cast<T*>(static_cast<void*>(&data));
|
||||
}
|
||||
|
||||
TStorage data;
|
||||
};
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
using storage_for = Detail::ObjectStorage<T, true>;
|
||||
|
||||
template <typename T>
|
||||
using destructable_object = Detail::ObjectStorage<T, false>;
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CONSTRUCTOR_HPP_INCLUDED
|
38
src/internal/benchmark/catch_environment.hpp
Normal file
38
src/internal/benchmark/catch_environment.hpp
Normal file
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Environment information
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_ENVIRONMENT_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_ENVIRONMENT_HPP_INCLUDED
|
||||
|
||||
#include "catch_clock.hpp"
|
||||
#include "catch_outlier_classification.hpp"
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
template <typename Duration>
|
||||
struct EnvironmentEstimate {
|
||||
Duration mean;
|
||||
OutlierClassification outliers;
|
||||
|
||||
template <typename Duration2>
|
||||
operator EnvironmentEstimate<Duration2>() const {
|
||||
return { mean, outliers };
|
||||
}
|
||||
};
|
||||
template <typename Clock>
|
||||
struct Environment {
|
||||
using clock_type = Clock;
|
||||
EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
|
||||
EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
|
||||
};
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_ENVIRONMENT_HPP_INCLUDED
|
31
src/internal/benchmark/catch_estimate.hpp
Normal file
31
src/internal/benchmark/catch_estimate.hpp
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Statistics estimates
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_ESTIMATE_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_ESTIMATE_HPP_INCLUDED
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
template <typename Duration>
|
||||
struct Estimate {
|
||||
Duration point;
|
||||
Duration lower_bound;
|
||||
Duration upper_bound;
|
||||
double confidence_interval;
|
||||
|
||||
template <typename Duration2>
|
||||
operator Estimate<Duration2>() const {
|
||||
return { point, lower_bound, upper_bound, confidence_interval };
|
||||
}
|
||||
};
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_ESTIMATE_HPP_INCLUDED
|
58
src/internal/benchmark/catch_execution_plan.hpp
Normal file
58
src/internal/benchmark/catch_execution_plan.hpp
Normal file
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Execution plan
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_EXECUTION_PLAN_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_EXECUTION_PLAN_HPP_INCLUDED
|
||||
|
||||
#include "../catch_config.hpp"
|
||||
#include "catch_clock.hpp"
|
||||
#include "catch_environment.hpp"
|
||||
#include "detail/catch_benchmark_function.hpp"
|
||||
#include "detail/catch_repeat.hpp"
|
||||
#include "detail/catch_run_for_at_least.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
template <typename Duration>
|
||||
struct ExecutionPlan {
|
||||
int iterations_per_sample;
|
||||
Duration estimated_duration;
|
||||
Detail::BenchmarkFunction benchmark;
|
||||
Duration warmup_time;
|
||||
int warmup_iterations;
|
||||
|
||||
template <typename Duration2>
|
||||
operator ExecutionPlan<Duration2>() const {
|
||||
return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
|
||||
}
|
||||
|
||||
template <typename Clock>
|
||||
std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
|
||||
// warmup a bit
|
||||
Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
|
||||
|
||||
std::vector<FloatDuration<Clock>> times;
|
||||
times.reserve(cfg.benchmarkSamples());
|
||||
std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
|
||||
Detail::ChronometerModel<Clock> model;
|
||||
this->benchmark(Chronometer(model, iterations_per_sample));
|
||||
auto sample_time = model.elapsed() - env.clock_cost.mean;
|
||||
if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
|
||||
return sample_time / iterations_per_sample;
|
||||
});
|
||||
return times;
|
||||
}
|
||||
};
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_EXECUTION_PLAN_HPP_INCLUDED
|
68
src/internal/benchmark/catch_optimizer.hpp
Normal file
68
src/internal/benchmark/catch_optimizer.hpp
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Hinting the optimizer
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_OPTIMIZER_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_OPTIMIZER_HPP_INCLUDED
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
# include <atomic> // atomic_thread_fence
|
||||
#endif
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
template <typename T>
|
||||
inline void keep_memory(T* p) {
|
||||
asm volatile("" : : "g"(p) : "memory");
|
||||
}
|
||||
inline void keep_memory() {
|
||||
asm volatile("" : : : "memory");
|
||||
}
|
||||
|
||||
namespace Detail {
|
||||
inline void optimizer_barrier() { keep_memory(); }
|
||||
} // namespace Detail
|
||||
#elif defined(_MSC_VER)
|
||||
|
||||
#pragma optimize("", off)
|
||||
template <typename T>
|
||||
inline void keep_memory(T* p) {
|
||||
// thanks @milleniumbug
|
||||
*reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
|
||||
}
|
||||
// TODO equivalent keep_memory()
|
||||
#pragma optimize("", on)
|
||||
|
||||
namespace Detail {
|
||||
inline void optimizer_barrier() {
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
#endif
|
||||
|
||||
template <typename T>
|
||||
inline void deoptimize_value(T&& x) {
|
||||
keep_memory(&x);
|
||||
}
|
||||
|
||||
template <typename Fn, typename... Args>
|
||||
inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
|
||||
deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
|
||||
}
|
||||
|
||||
template <typename Fn, typename... Args>
|
||||
inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
|
||||
std::forward<Fn>(fn) (std::forward<Args...>(args...));
|
||||
}
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_OPTIMIZER_HPP_INCLUDED
|
29
src/internal/benchmark/catch_outlier_classification.hpp
Normal file
29
src/internal/benchmark/catch_outlier_classification.hpp
Normal file
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Outlier information
|
||||
#ifndef TWOBLUECUBES_CATCH_OUTLIERS_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_OUTLIERS_HPP_INCLUDED
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
struct OutlierClassification {
|
||||
int samples_seen = 0;
|
||||
int low_severe = 0; // more than 3 times IQR below Q1
|
||||
int low_mild = 0; // 1.5 to 3 times IQR below Q1
|
||||
int high_mild = 0; // 1.5 to 3 times IQR above Q3
|
||||
int high_severe = 0; // more than 3 times IQR above Q3
|
||||
|
||||
int total() const {
|
||||
return low_severe + low_mild + high_mild + high_severe;
|
||||
}
|
||||
};
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_OUTLIERS_HPP_INCLUDED
|
50
src/internal/benchmark/catch_sample_analysis.hpp
Normal file
50
src/internal/benchmark/catch_sample_analysis.hpp
Normal file
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Benchmark results
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_BENCHMARK_RESULTS_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_BENCHMARK_RESULTS_HPP_INCLUDED
|
||||
|
||||
#include "catch_clock.hpp"
|
||||
#include "catch_estimate.hpp"
|
||||
#include "catch_outlier_classification.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <iterator>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
template <typename Duration>
|
||||
struct SampleAnalysis {
|
||||
std::vector<Duration> samples;
|
||||
Estimate<Duration> mean;
|
||||
Estimate<Duration> standard_deviation;
|
||||
OutlierClassification outliers;
|
||||
double outlier_variance;
|
||||
|
||||
template <typename Duration2>
|
||||
operator SampleAnalysis<Duration2>() const {
|
||||
std::vector<Duration2> samples2;
|
||||
samples2.reserve(samples.size());
|
||||
std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
|
||||
return {
|
||||
std::move(samples2),
|
||||
mean,
|
||||
standard_deviation,
|
||||
outliers,
|
||||
outlier_variance,
|
||||
};
|
||||
}
|
||||
};
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_BENCHMARK_RESULTS_HPP_INCLUDED
|
78
src/internal/benchmark/detail/catch_analyse.hpp
Normal file
78
src/internal/benchmark/detail/catch_analyse.hpp
Normal file
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Run and analyse one benchmark
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_DETAIL_ANALYSE_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DETAIL_ANALYSE_HPP_INCLUDED
|
||||
|
||||
#include "../catch_clock.hpp"
|
||||
#include "../catch_sample_analysis.hpp"
|
||||
#include "catch_stats.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
#include <vector>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
template <typename Duration, typename Iterator>
|
||||
SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
|
||||
if (!cfg.benchmarkNoAnalysis()) {
|
||||
std::vector<double> samples;
|
||||
samples.reserve(last - first);
|
||||
std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
|
||||
|
||||
auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
|
||||
auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
|
||||
|
||||
auto wrap_estimate = [](Estimate<double> e) {
|
||||
return Estimate<Duration> {
|
||||
Duration(e.point),
|
||||
Duration(e.lower_bound),
|
||||
Duration(e.upper_bound),
|
||||
e.confidence_interval,
|
||||
};
|
||||
};
|
||||
std::vector<Duration> samples2;
|
||||
samples2.reserve(samples.size());
|
||||
std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
|
||||
return {
|
||||
std::move(samples2),
|
||||
wrap_estimate(analysis.mean),
|
||||
wrap_estimate(analysis.standard_deviation),
|
||||
outliers,
|
||||
analysis.outlier_variance,
|
||||
};
|
||||
} else {
|
||||
std::vector<Duration> samples;
|
||||
samples.reserve(last - first);
|
||||
|
||||
Duration mean = Duration(0);
|
||||
int i = 0;
|
||||
for (auto it = first; it < last; ++it, ++i) {
|
||||
samples.push_back(Duration(*it));
|
||||
mean += Duration(*it);
|
||||
}
|
||||
mean /= i;
|
||||
|
||||
return {
|
||||
std::move(samples),
|
||||
Estimate<Duration>{mean, mean, mean, 0.0},
|
||||
Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
|
||||
OutlierClassification{},
|
||||
0.0
|
||||
};
|
||||
}
|
||||
}
|
||||
} // namespace Detail
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DETAIL_ANALYSE_HPP_INCLUDED
|
105
src/internal/benchmark/detail/catch_benchmark_function.hpp
Normal file
105
src/internal/benchmark/detail/catch_benchmark_function.hpp
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Dumb std::function implementation for consistent call overhead
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_DETAIL_BENCHMARK_FUNCTION_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DETAIL_BENCHMARK_FUNCTION_HPP_INCLUDED
|
||||
|
||||
#include "../catch_chronometer.hpp"
|
||||
#include "catch_complete_invoke.hpp"
|
||||
#include "../../catch_meta.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <memory>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
template <typename T>
|
||||
using Decay = typename std::decay<T>::type;
|
||||
template <typename T, typename U>
|
||||
struct is_related
|
||||
: std::is_same<Decay<T>, Decay<U>> {};
|
||||
|
||||
/// We need to reinvent std::function because every piece of code that might add overhead
|
||||
/// in a measurement context needs to have consistent performance characteristics so that we
|
||||
/// can account for it in the measurement.
|
||||
/// Implementations of std::function with optimizations that aren't always applicable, like
|
||||
/// small buffer optimizations, are not uncommon.
|
||||
/// This is effectively an implementation of std::function without any such optimizations;
|
||||
/// it may be slow, but it is consistently slow.
|
||||
struct BenchmarkFunction {
|
||||
private:
|
||||
struct callable {
|
||||
virtual void call(Chronometer meter) const = 0;
|
||||
virtual callable* clone() const = 0;
|
||||
virtual ~callable() = default;
|
||||
};
|
||||
template <typename Fun>
|
||||
struct model : public callable {
|
||||
model(Fun&& fun) : fun(std::move(fun)) {}
|
||||
model(Fun const& fun) : fun(fun) {}
|
||||
|
||||
model<Fun>* clone() const override { return new model<Fun>(*this); }
|
||||
|
||||
void call(Chronometer meter) const override {
|
||||
call(meter, is_callable<Fun(Chronometer)>());
|
||||
}
|
||||
void call(Chronometer meter, std::true_type) const {
|
||||
fun(meter);
|
||||
}
|
||||
void call(Chronometer meter, std::false_type) const {
|
||||
meter.measure(fun);
|
||||
}
|
||||
|
||||
Fun fun;
|
||||
};
|
||||
|
||||
struct do_nothing { void operator()() const {} };
|
||||
|
||||
template <typename T>
|
||||
BenchmarkFunction(model<T>* c) : f(c) {}
|
||||
|
||||
public:
|
||||
BenchmarkFunction()
|
||||
: f(new model<do_nothing>{ {} }) {}
|
||||
|
||||
template <typename Fun,
|
||||
typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
|
||||
BenchmarkFunction(Fun&& fun)
|
||||
: f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
|
||||
|
||||
BenchmarkFunction(BenchmarkFunction&& that)
|
||||
: f(std::move(that.f)) {}
|
||||
|
||||
BenchmarkFunction(BenchmarkFunction const& that)
|
||||
: f(that.f->clone()) {}
|
||||
|
||||
BenchmarkFunction& operator=(BenchmarkFunction&& that) {
|
||||
f = std::move(that.f);
|
||||
return *this;
|
||||
}
|
||||
|
||||
BenchmarkFunction& operator=(BenchmarkFunction const& that) {
|
||||
f.reset(that.f->clone());
|
||||
return *this;
|
||||
}
|
||||
|
||||
void operator()(Chronometer meter) const { f->call(meter); }
|
||||
|
||||
private:
|
||||
std::unique_ptr<callable> f;
|
||||
};
|
||||
} // namespace Detail
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DETAIL_BENCHMARK_FUNCTION_HPP_INCLUDED
|
69
src/internal/benchmark/detail/catch_complete_invoke.hpp
Normal file
69
src/internal/benchmark/detail/catch_complete_invoke.hpp
Normal file
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Invoke with a special case for void
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_DETAIL_COMPLETE_INVOKE_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DETAIL_COMPLETE_INVOKE_HPP_INCLUDED
|
||||
|
||||
#include "../../catch_enforce.h"
|
||||
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
template <typename T>
|
||||
struct CompleteType { using type = T; };
|
||||
template <>
|
||||
struct CompleteType<void> { struct type {}; };
|
||||
|
||||
template <typename T>
|
||||
using CompleteType_t = typename CompleteType<T>::type;
|
||||
|
||||
template <typename Result>
|
||||
struct CompleteInvoker {
|
||||
template <typename Fun, typename... Args>
|
||||
static Result invoke(Fun&& fun, Args&&... args) {
|
||||
return std::forward<Fun>(fun)(std::forward<Args>(args)...);
|
||||
}
|
||||
};
|
||||
template <>
|
||||
struct CompleteInvoker<void> {
|
||||
template <typename Fun, typename... Args>
|
||||
static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
|
||||
std::forward<Fun>(fun)(std::forward<Args>(args)...);
|
||||
return {};
|
||||
}
|
||||
};
|
||||
template <typename Sig>
|
||||
using ResultOf_t = typename std::result_of<Sig>::type;
|
||||
|
||||
// invoke and not return void :(
|
||||
template <typename Fun, typename... Args>
|
||||
CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
|
||||
return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
|
||||
} // namespace Detail
|
||||
|
||||
template <typename Fun>
|
||||
Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
|
||||
CATCH_TRY{
|
||||
return Detail::complete_invoke(std::forward<Fun>(fun));
|
||||
} CATCH_CATCH_ALL{
|
||||
getResultCapture().benchmarkFailed(translateActiveException());
|
||||
CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
|
||||
}
|
||||
}
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DETAIL_COMPLETE_INVOKE_HPP_INCLUDED
|
113
src/internal/benchmark/detail/catch_estimate_clock.hpp
Normal file
113
src/internal/benchmark/detail/catch_estimate_clock.hpp
Normal file
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Environment measurement
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_DETAIL_ESTIMATE_CLOCK_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DETAIL_ESTIMATE_CLOCK_HPP_INCLUDED
|
||||
|
||||
#include "../catch_clock.hpp"
|
||||
#include "../catch_environment.hpp"
|
||||
#include "catch_stats.hpp"
|
||||
#include "catch_measure.hpp"
|
||||
#include "catch_run_for_at_least.hpp"
|
||||
#include "../catch_clock.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
template <typename Clock>
|
||||
std::vector<double> resolution(int k) {
|
||||
std::vector<TimePoint<Clock>> times;
|
||||
times.reserve(k + 1);
|
||||
std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
|
||||
|
||||
std::vector<double> deltas;
|
||||
deltas.reserve(k);
|
||||
std::transform(std::next(times.begin()), times.end(), times.begin(),
|
||||
std::back_inserter(deltas),
|
||||
[](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
|
||||
|
||||
return deltas;
|
||||
}
|
||||
|
||||
const auto warmup_iterations = 10000;
|
||||
const auto warmup_time = std::chrono::milliseconds(100);
|
||||
const auto minimum_ticks = 1000;
|
||||
const auto warmup_seed = 10000;
|
||||
const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
|
||||
const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
|
||||
const auto clock_cost_estimation_tick_limit = 100000;
|
||||
const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
|
||||
const auto clock_cost_estimation_iterations = 10000;
|
||||
|
||||
template <typename Clock>
|
||||
int warmup() {
|
||||
return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
|
||||
.iterations;
|
||||
}
|
||||
template <typename Clock>
|
||||
EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
|
||||
auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
|
||||
.result;
|
||||
return {
|
||||
FloatDuration<Clock>(mean(r.begin(), r.end())),
|
||||
classify_outliers(r.begin(), r.end()),
|
||||
};
|
||||
}
|
||||
template <typename Clock>
|
||||
EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
|
||||
auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
|
||||
auto time_clock = [](int k) {
|
||||
return Detail::measure<Clock>([k] {
|
||||
for (int i = 0; i < k; ++i) {
|
||||
volatile auto ignored = Clock::now();
|
||||
(void)ignored;
|
||||
}
|
||||
}).elapsed;
|
||||
};
|
||||
time_clock(1);
|
||||
int iters = clock_cost_estimation_iterations;
|
||||
auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
|
||||
std::vector<double> times;
|
||||
int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
|
||||
times.reserve(nsamples);
|
||||
std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
|
||||
return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
|
||||
});
|
||||
return {
|
||||
FloatDuration<Clock>(mean(times.begin(), times.end())),
|
||||
classify_outliers(times.begin(), times.end()),
|
||||
};
|
||||
}
|
||||
|
||||
template <typename Clock>
|
||||
Environment<FloatDuration<Clock>> measure_environment() {
|
||||
static Environment<FloatDuration<Clock>>* env = nullptr;
|
||||
if (env) {
|
||||
return *env;
|
||||
}
|
||||
|
||||
auto iters = Detail::warmup<Clock>();
|
||||
auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
|
||||
auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
|
||||
|
||||
env = new Environment<FloatDuration<Clock>>{ resolution, cost };
|
||||
return *env;
|
||||
}
|
||||
} // namespace Detail
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DETAIL_ESTIMATE_CLOCK_HPP_INCLUDED
|
35
src/internal/benchmark/detail/catch_measure.hpp
Normal file
35
src/internal/benchmark/detail/catch_measure.hpp
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Measure
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_DETAIL_MEASURE_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DETAIL_MEASURE_HPP_INCLUDED
|
||||
|
||||
#include "../catch_clock.hpp"
|
||||
#include "catch_complete_invoke.hpp"
|
||||
#include "catch_timing.hpp"
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
template <typename Clock, typename Fun, typename... Args>
|
||||
TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
|
||||
auto start = Clock::now();
|
||||
auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
|
||||
auto end = Clock::now();
|
||||
auto delta = end - start;
|
||||
return { delta, std::forward<decltype(r)>(r), 1 };
|
||||
}
|
||||
} // namespace Detail
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DETAIL_MEASURE_HPP_INCLUDED
|
37
src/internal/benchmark/detail/catch_repeat.hpp
Normal file
37
src/internal/benchmark/detail/catch_repeat.hpp
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// repeat algorithm
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_DETAIL_REPEAT_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DETAIL_REPEAT_HPP_INCLUDED
|
||||
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
template <typename Fun>
|
||||
struct repeater {
|
||||
void operator()(int k) const {
|
||||
for (int i = 0; i < k; ++i) {
|
||||
fun();
|
||||
}
|
||||
}
|
||||
Fun fun;
|
||||
};
|
||||
template <typename Fun>
|
||||
repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
|
||||
return { std::forward<Fun>(fun) };
|
||||
}
|
||||
} // namespace Detail
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DETAIL_REPEAT_HPP_INCLUDED
|
65
src/internal/benchmark/detail/catch_run_for_at_least.hpp
Normal file
65
src/internal/benchmark/detail/catch_run_for_at_least.hpp
Normal file
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Run a function for a minimum amount of time
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED
|
||||
|
||||
#include "../catch_clock.hpp"
|
||||
#include "../catch_chronometer.hpp"
|
||||
#include "catch_measure.hpp"
|
||||
#include "catch_complete_invoke.hpp"
|
||||
#include "catch_timing.hpp"
|
||||
#include "../../catch_meta.hpp"
|
||||
|
||||
#include <utility>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
template <typename Clock, typename Fun>
|
||||
TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
|
||||
return Detail::measure<Clock>(fun, iters);
|
||||
}
|
||||
template <typename Clock, typename Fun>
|
||||
TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
|
||||
Detail::ChronometerModel<Clock> meter;
|
||||
auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
|
||||
|
||||
return { meter.elapsed(), std::move(result), iters };
|
||||
}
|
||||
|
||||
template <typename Clock, typename Fun>
|
||||
using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
|
||||
|
||||
struct optimized_away_error : std::exception {
|
||||
const char* what() const noexcept override {
|
||||
return "could not measure benchmark, maybe it was optimized away";
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Clock, typename Fun>
|
||||
TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
|
||||
auto iters = seed;
|
||||
while (iters < (1 << 30)) {
|
||||
auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
|
||||
|
||||
if (Timing.elapsed >= how_long) {
|
||||
return { Timing.elapsed, std::move(Timing.result), iters };
|
||||
}
|
||||
iters *= 2;
|
||||
}
|
||||
throw optimized_away_error{};
|
||||
}
|
||||
} // namespace Detail
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED
|
224
src/internal/benchmark/detail/catch_stats.cpp
Normal file
224
src/internal/benchmark/detail/catch_stats.cpp
Normal file
@@ -0,0 +1,224 @@
|
||||
/*
|
||||
* Created by Martin on 15/06/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Statistical analysis tools
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
|
||||
#include "catch_stats.hpp"
|
||||
|
||||
#include "../../catch_compiler_capabilities.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <random>
|
||||
|
||||
|
||||
#if defined(CATCH_CONFIG_USE_ASYNC)
|
||||
#include <future>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
double erf_inv(double x) {
|
||||
// Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
|
||||
double w, p;
|
||||
|
||||
w = -log((1.0 - x) * (1.0 + x));
|
||||
|
||||
if (w < 6.250000) {
|
||||
w = w - 3.125000;
|
||||
p = -3.6444120640178196996e-21;
|
||||
p = -1.685059138182016589e-19 + p * w;
|
||||
p = 1.2858480715256400167e-18 + p * w;
|
||||
p = 1.115787767802518096e-17 + p * w;
|
||||
p = -1.333171662854620906e-16 + p * w;
|
||||
p = 2.0972767875968561637e-17 + p * w;
|
||||
p = 6.6376381343583238325e-15 + p * w;
|
||||
p = -4.0545662729752068639e-14 + p * w;
|
||||
p = -8.1519341976054721522e-14 + p * w;
|
||||
p = 2.6335093153082322977e-12 + p * w;
|
||||
p = -1.2975133253453532498e-11 + p * w;
|
||||
p = -5.4154120542946279317e-11 + p * w;
|
||||
p = 1.051212273321532285e-09 + p * w;
|
||||
p = -4.1126339803469836976e-09 + p * w;
|
||||
p = -2.9070369957882005086e-08 + p * w;
|
||||
p = 4.2347877827932403518e-07 + p * w;
|
||||
p = -1.3654692000834678645e-06 + p * w;
|
||||
p = -1.3882523362786468719e-05 + p * w;
|
||||
p = 0.0001867342080340571352 + p * w;
|
||||
p = -0.00074070253416626697512 + p * w;
|
||||
p = -0.0060336708714301490533 + p * w;
|
||||
p = 0.24015818242558961693 + p * w;
|
||||
p = 1.6536545626831027356 + p * w;
|
||||
} else if (w < 16.000000) {
|
||||
w = sqrt(w) - 3.250000;
|
||||
p = 2.2137376921775787049e-09;
|
||||
p = 9.0756561938885390979e-08 + p * w;
|
||||
p = -2.7517406297064545428e-07 + p * w;
|
||||
p = 1.8239629214389227755e-08 + p * w;
|
||||
p = 1.5027403968909827627e-06 + p * w;
|
||||
p = -4.013867526981545969e-06 + p * w;
|
||||
p = 2.9234449089955446044e-06 + p * w;
|
||||
p = 1.2475304481671778723e-05 + p * w;
|
||||
p = -4.7318229009055733981e-05 + p * w;
|
||||
p = 6.8284851459573175448e-05 + p * w;
|
||||
p = 2.4031110387097893999e-05 + p * w;
|
||||
p = -0.0003550375203628474796 + p * w;
|
||||
p = 0.00095328937973738049703 + p * w;
|
||||
p = -0.0016882755560235047313 + p * w;
|
||||
p = 0.0024914420961078508066 + p * w;
|
||||
p = -0.0037512085075692412107 + p * w;
|
||||
p = 0.005370914553590063617 + p * w;
|
||||
p = 1.0052589676941592334 + p * w;
|
||||
p = 3.0838856104922207635 + p * w;
|
||||
} else {
|
||||
w = sqrt(w) - 5.000000;
|
||||
p = -2.7109920616438573243e-11;
|
||||
p = -2.5556418169965252055e-10 + p * w;
|
||||
p = 1.5076572693500548083e-09 + p * w;
|
||||
p = -3.7894654401267369937e-09 + p * w;
|
||||
p = 7.6157012080783393804e-09 + p * w;
|
||||
p = -1.4960026627149240478e-08 + p * w;
|
||||
p = 2.9147953450901080826e-08 + p * w;
|
||||
p = -6.7711997758452339498e-08 + p * w;
|
||||
p = 2.2900482228026654717e-07 + p * w;
|
||||
p = -9.9298272942317002539e-07 + p * w;
|
||||
p = 4.5260625972231537039e-06 + p * w;
|
||||
p = -1.9681778105531670567e-05 + p * w;
|
||||
p = 7.5995277030017761139e-05 + p * w;
|
||||
p = -0.00021503011930044477347 + p * w;
|
||||
p = -0.00013871931833623122026 + p * w;
|
||||
p = 1.0103004648645343977 + p * w;
|
||||
p = 4.8499064014085844221 + p * w;
|
||||
}
|
||||
return p * x;
|
||||
}
|
||||
|
||||
double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
|
||||
auto m = Catch::Benchmark::Detail::mean(first, last);
|
||||
double variance = std::accumulate(first, last, 0., [m](double a, double b) {
|
||||
double diff = b - m;
|
||||
return a + diff * diff;
|
||||
}) / (last - first);
|
||||
return std::sqrt(variance);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
|
||||
double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
|
||||
auto count = last - first;
|
||||
double idx = (count - 1) * k / static_cast<double>(q);
|
||||
int j = static_cast<int>(idx);
|
||||
double g = idx - j;
|
||||
std::nth_element(first, first + j, last);
|
||||
auto xj = first[j];
|
||||
if (g == 0) return xj;
|
||||
|
||||
auto xj1 = *std::min_element(first + (j + 1), last);
|
||||
return xj + g * (xj1 - xj);
|
||||
}
|
||||
|
||||
|
||||
double erfc_inv(double x) {
|
||||
return erf_inv(1.0 - x);
|
||||
}
|
||||
|
||||
double normal_quantile(double p) {
|
||||
static const double ROOT_TWO = std::sqrt(2.0);
|
||||
|
||||
double result = 0.0;
|
||||
assert(p >= 0 && p <= 1);
|
||||
if (p < 0 || p > 1) {
|
||||
return result;
|
||||
}
|
||||
|
||||
result = -erfc_inv(2.0 * p);
|
||||
// result *= normal distribution standard deviation (1.0) * sqrt(2)
|
||||
result *= /*sd * */ ROOT_TWO;
|
||||
// result += normal disttribution mean (0)
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
|
||||
double sb = stddev.point;
|
||||
double mn = mean.point / n;
|
||||
double mg_min = mn / 2.;
|
||||
double sg = std::min(mg_min / 4., sb / std::sqrt(n));
|
||||
double sg2 = sg * sg;
|
||||
double sb2 = sb * sb;
|
||||
|
||||
auto c_max = [n, mn, sb2, sg2](double x) -> double {
|
||||
double k = mn - x;
|
||||
double d = k * k;
|
||||
double nd = n * d;
|
||||
double k0 = -n * nd;
|
||||
double k1 = sb2 - n * sg2 + nd;
|
||||
double det = k1 * k1 - 4 * sg2 * k0;
|
||||
return (int)(-2. * k0 / (k1 + std::sqrt(det)));
|
||||
};
|
||||
|
||||
auto var_out = [n, sb2, sg2](double c) {
|
||||
double nc = n - c;
|
||||
return (nc / n) * (sb2 - nc * sg2);
|
||||
};
|
||||
|
||||
return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
|
||||
}
|
||||
|
||||
|
||||
bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
|
||||
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
|
||||
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
|
||||
static std::random_device entropy;
|
||||
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
|
||||
|
||||
auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
|
||||
|
||||
auto mean = &Detail::mean<std::vector<double>::iterator>;
|
||||
auto stddev = &standard_deviation;
|
||||
|
||||
#if defined(CATCH_CONFIG_USE_ASYNC)
|
||||
auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
|
||||
auto seed = entropy();
|
||||
return std::async(std::launch::async, [=] {
|
||||
std::mt19937 rng(seed);
|
||||
auto resampled = resample(rng, n_resamples, first, last, f);
|
||||
return bootstrap(confidence_level, first, last, resampled, f);
|
||||
});
|
||||
};
|
||||
|
||||
auto mean_future = Estimate(mean);
|
||||
auto stddev_future = Estimate(stddev);
|
||||
|
||||
auto mean_estimate = mean_future.get();
|
||||
auto stddev_estimate = stddev_future.get();
|
||||
#else
|
||||
auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
|
||||
auto seed = entropy();
|
||||
std::mt19937 rng(seed);
|
||||
auto resampled = resample(rng, n_resamples, first, last, f);
|
||||
return bootstrap(confidence_level, first, last, resampled, f);
|
||||
};
|
||||
|
||||
auto mean_estimate = Estimate(mean);
|
||||
auto stddev_estimate = Estimate(stddev);
|
||||
#endif // CATCH_USE_ASYNC
|
||||
|
||||
double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
|
||||
|
||||
return { mean_estimate, stddev_estimate, outlier_variance };
|
||||
}
|
||||
} // namespace Detail
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
|
158
src/internal/benchmark/detail/catch_stats.hpp
Normal file
158
src/internal/benchmark/detail/catch_stats.hpp
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Statistical analysis tools
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_DETAIL_ANALYSIS_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DETAIL_ANALYSIS_HPP_INCLUDED
|
||||
|
||||
#include "../catch_clock.hpp"
|
||||
#include "../catch_estimate.hpp"
|
||||
#include "../catch_outlier_classification.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
#include <numeric>
|
||||
#include <tuple>
|
||||
#include <cmath>
|
||||
#include <utility>
|
||||
#include <cstddef>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
namespace Detail {
|
||||
using sample = std::vector<double>;
|
||||
|
||||
double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
|
||||
|
||||
template <typename Iterator>
|
||||
OutlierClassification classify_outliers(Iterator first, Iterator last) {
|
||||
std::vector<double> copy(first, last);
|
||||
|
||||
auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
|
||||
auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
|
||||
auto iqr = q3 - q1;
|
||||
auto los = q1 - (iqr * 3.);
|
||||
auto lom = q1 - (iqr * 1.5);
|
||||
auto him = q3 + (iqr * 1.5);
|
||||
auto his = q3 + (iqr * 3.);
|
||||
|
||||
OutlierClassification o;
|
||||
for (; first != last; ++first) {
|
||||
auto&& t = *first;
|
||||
if (t < los) ++o.low_severe;
|
||||
else if (t < lom) ++o.low_mild;
|
||||
else if (t > his) ++o.high_severe;
|
||||
else if (t > him) ++o.high_mild;
|
||||
++o.samples_seen;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
template <typename Iterator>
|
||||
double mean(Iterator first, Iterator last) {
|
||||
auto count = last - first;
|
||||
double sum = std::accumulate(first, last, 0.);
|
||||
return sum / count;
|
||||
}
|
||||
|
||||
template <typename URng, typename Iterator, typename Estimator>
|
||||
sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
|
||||
auto n = last - first;
|
||||
std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
|
||||
|
||||
sample out;
|
||||
out.reserve(resamples);
|
||||
std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
|
||||
std::vector<double> resampled;
|
||||
resampled.reserve(n);
|
||||
std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
|
||||
return estimator(resampled.begin(), resampled.end());
|
||||
});
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
template <typename Estimator, typename Iterator>
|
||||
sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
|
||||
auto n = last - first;
|
||||
auto second = std::next(first);
|
||||
sample results;
|
||||
results.reserve(n);
|
||||
|
||||
for (auto it = first; it != last; ++it) {
|
||||
std::iter_swap(it, first);
|
||||
results.push_back(estimator(second, last));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
inline double normal_cdf(double x) {
|
||||
return std::erfc(-x / std::sqrt(2.0)) / 2.0;
|
||||
}
|
||||
|
||||
double erfc_inv(double x);
|
||||
|
||||
double normal_quantile(double p);
|
||||
|
||||
template <typename Iterator, typename Estimator>
|
||||
Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
|
||||
auto n_samples = last - first;
|
||||
|
||||
double point = estimator(first, last);
|
||||
// Degenerate case with a single sample
|
||||
if (n_samples == 1) return { point, point, point, confidence_level };
|
||||
|
||||
sample jack = jackknife(estimator, first, last);
|
||||
double jack_mean = mean(jack.begin(), jack.end());
|
||||
double sum_squares, sum_cubes;
|
||||
std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
|
||||
auto d = jack_mean - x;
|
||||
auto d2 = d * d;
|
||||
auto d3 = d2 * d;
|
||||
return { sqcb.first + d2, sqcb.second + d3 };
|
||||
});
|
||||
|
||||
double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
|
||||
int n = static_cast<int>(resample.size());
|
||||
double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
|
||||
// degenerate case with uniform samples
|
||||
if (prob_n == 0) return { point, point, point, confidence_level };
|
||||
|
||||
double bias = normal_quantile(prob_n);
|
||||
double z1 = normal_quantile((1. - confidence_level) / 2.);
|
||||
|
||||
auto cumn = [n](double x) -> int {
|
||||
return std::lround(normal_cdf(x) * n); };
|
||||
auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
|
||||
double b1 = bias + z1;
|
||||
double b2 = bias - z1;
|
||||
double a1 = a(b1);
|
||||
double a2 = a(b2);
|
||||
auto lo = std::max(cumn(a1), 0);
|
||||
auto hi = std::min(cumn(a2), n - 1);
|
||||
|
||||
return { point, resample[lo], resample[hi], confidence_level };
|
||||
}
|
||||
|
||||
double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
|
||||
|
||||
struct bootstrap_analysis {
|
||||
Estimate<double> mean;
|
||||
Estimate<double> standard_deviation;
|
||||
double outlier_variance;
|
||||
};
|
||||
|
||||
bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
|
||||
} // namespace Detail
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DETAIL_ANALYSIS_HPP_INCLUDED
|
33
src/internal/benchmark/detail/catch_timing.hpp
Normal file
33
src/internal/benchmark/detail/catch_timing.hpp
Normal file
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Created by Joachim on 16/04/2019.
|
||||
* Adapted from donated nonius code.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// Timing
|
||||
|
||||
#ifndef TWOBLUECUBES_CATCH_DETAIL_TIMING_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DETAIL_TIMING_HPP_INCLUDED
|
||||
|
||||
#include "../catch_clock.hpp"
|
||||
#include "catch_complete_invoke.hpp"
|
||||
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Catch {
|
||||
namespace Benchmark {
|
||||
template <typename Duration, typename Result>
|
||||
struct Timing {
|
||||
Duration elapsed;
|
||||
Result result;
|
||||
int iterations;
|
||||
};
|
||||
template <typename Clock, typename Sig>
|
||||
using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
|
||||
} // namespace Benchmark
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DETAIL_TIMING_HPP_INCLUDED
|
88
src/internal/catch_approx.cpp
Normal file
88
src/internal/catch_approx.cpp
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Created by Martin on 19/07/2017.
|
||||
* Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_approx.h"
|
||||
#include "catch_enforce.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace {
|
||||
|
||||
// Performs equivalent check of std::fabs(lhs - rhs) <= margin
|
||||
// But without the subtraction to allow for INFINITY in comparison
|
||||
bool marginComparison(double lhs, double rhs, double margin) {
|
||||
return (lhs + margin >= rhs) && (rhs + margin >= lhs);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
namespace Catch {
|
||||
namespace Detail {
|
||||
|
||||
Approx::Approx ( double value )
|
||||
: m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
|
||||
m_margin( 0.0 ),
|
||||
m_scale( 0.0 ),
|
||||
m_value( value )
|
||||
{}
|
||||
|
||||
Approx Approx::custom() {
|
||||
return Approx( 0 );
|
||||
}
|
||||
|
||||
Approx Approx::operator-() const {
|
||||
auto temp(*this);
|
||||
temp.m_value = -temp.m_value;
|
||||
return temp;
|
||||
}
|
||||
|
||||
|
||||
std::string Approx::toString() const {
|
||||
ReusableStringStream rss;
|
||||
rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
|
||||
return rss.str();
|
||||
}
|
||||
|
||||
bool Approx::equalityComparisonImpl(const double other) const {
|
||||
// First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
|
||||
// Thanks to Richard Harris for his help refining the scaled margin value
|
||||
return marginComparison(m_value, other, m_margin)
|
||||
|| marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
|
||||
}
|
||||
|
||||
void Approx::setMargin(double newMargin) {
|
||||
CATCH_ENFORCE(newMargin >= 0,
|
||||
"Invalid Approx::margin: " << newMargin << '.'
|
||||
<< " Approx::Margin has to be non-negative.");
|
||||
m_margin = newMargin;
|
||||
}
|
||||
|
||||
void Approx::setEpsilon(double newEpsilon) {
|
||||
CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
|
||||
"Invalid Approx::epsilon: " << newEpsilon << '.'
|
||||
<< " Approx::epsilon has to be in [0, 1]");
|
||||
m_epsilon = newEpsilon;
|
||||
}
|
||||
|
||||
} // end namespace Detail
|
||||
|
||||
namespace literals {
|
||||
Detail::Approx operator "" _a(long double val) {
|
||||
return Detail::Approx(val);
|
||||
}
|
||||
Detail::Approx operator "" _a(unsigned long long val) {
|
||||
return Detail::Approx(val);
|
||||
}
|
||||
} // end namespace literals
|
||||
|
||||
std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
} // end namespace Catch
|
132
src/internal/catch_approx.h
Normal file
132
src/internal/catch_approx.h
Normal file
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* Created by Phil on 28/04/2011.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_APPROX_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED
|
||||
|
||||
#include "catch_tostring.h"
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
namespace Catch {
|
||||
namespace Detail {
|
||||
|
||||
class Approx {
|
||||
private:
|
||||
bool equalityComparisonImpl(double other) const;
|
||||
// Validates the new margin (margin >= 0)
|
||||
// out-of-line to avoid including stdexcept in the header
|
||||
void setMargin(double margin);
|
||||
// Validates the new epsilon (0 < epsilon < 1)
|
||||
// out-of-line to avoid including stdexcept in the header
|
||||
void setEpsilon(double epsilon);
|
||||
|
||||
public:
|
||||
explicit Approx ( double value );
|
||||
|
||||
static Approx custom();
|
||||
|
||||
Approx operator-() const;
|
||||
|
||||
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
Approx operator()( T const& value ) {
|
||||
Approx approx( static_cast<double>(value) );
|
||||
approx.m_epsilon = m_epsilon;
|
||||
approx.m_margin = m_margin;
|
||||
approx.m_scale = m_scale;
|
||||
return approx;
|
||||
}
|
||||
|
||||
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
explicit Approx( T const& value ): Approx(static_cast<double>(value))
|
||||
{}
|
||||
|
||||
|
||||
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
friend bool operator == ( const T& lhs, Approx const& rhs ) {
|
||||
auto lhs_v = static_cast<double>(lhs);
|
||||
return rhs.equalityComparisonImpl(lhs_v);
|
||||
}
|
||||
|
||||
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 const& 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 const& rhs ) {
|
||||
return !operator==( rhs, lhs );
|
||||
}
|
||||
|
||||
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
friend bool operator <= ( T const& lhs, Approx const& rhs ) {
|
||||
return static_cast<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 const& rhs ) {
|
||||
return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
|
||||
}
|
||||
|
||||
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
friend bool operator >= ( T const& lhs, Approx const& rhs ) {
|
||||
return static_cast<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 const& rhs ) {
|
||||
return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
|
||||
}
|
||||
|
||||
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
Approx& epsilon( T const& newEpsilon ) {
|
||||
double epsilonAsDouble = static_cast<double>(newEpsilon);
|
||||
setEpsilon(epsilonAsDouble);
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
Approx& margin( T const& newMargin ) {
|
||||
double marginAsDouble = static_cast<double>(newMargin);
|
||||
setMargin(marginAsDouble);
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
Approx& scale( T const& newScale ) {
|
||||
m_scale = static_cast<double>(newScale);
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::string toString() const;
|
||||
|
||||
private:
|
||||
double m_epsilon;
|
||||
double m_margin;
|
||||
double m_scale;
|
||||
double m_value;
|
||||
};
|
||||
} // end namespace Detail
|
||||
|
||||
namespace literals {
|
||||
Detail::Approx operator "" _a(long double val);
|
||||
Detail::Approx operator "" _a(unsigned long long val);
|
||||
} // end namespace literals
|
||||
|
||||
template<>
|
||||
struct StringMaker<Catch::Detail::Approx> {
|
||||
static std::string convert(Catch::Detail::Approx const& value);
|
||||
};
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED
|
121
src/internal/catch_assertionhandler.cpp
Normal file
121
src/internal/catch_assertionhandler.cpp
Normal file
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* Created by Phil on 8/8/2017.
|
||||
* Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_assertionhandler.h"
|
||||
#include "catch_assertionresult.h"
|
||||
#include "catch_interfaces_runner.h"
|
||||
#include "catch_interfaces_config.h"
|
||||
#include "catch_context.h"
|
||||
#include "catch_debugger.h"
|
||||
#include "catch_interfaces_registry_hub.h"
|
||||
#include "catch_capture_matchers.h"
|
||||
#include "catch_run_context.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
namespace {
|
||||
auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
|
||||
expr.streamReconstructedExpression( os );
|
||||
return os;
|
||||
}
|
||||
}
|
||||
|
||||
LazyExpression::LazyExpression( bool isNegated )
|
||||
: m_isNegated( isNegated )
|
||||
{}
|
||||
|
||||
LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
|
||||
|
||||
LazyExpression::operator bool() const {
|
||||
return m_transientExpression != nullptr;
|
||||
}
|
||||
|
||||
auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
|
||||
if( lazyExpr.m_isNegated )
|
||||
os << "!";
|
||||
|
||||
if( lazyExpr ) {
|
||||
if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
|
||||
os << "(" << *lazyExpr.m_transientExpression << ")";
|
||||
else
|
||||
os << *lazyExpr.m_transientExpression;
|
||||
}
|
||||
else {
|
||||
os << "{** error - unchecked empty expression requested **}";
|
||||
}
|
||||
return os;
|
||||
}
|
||||
|
||||
AssertionHandler::AssertionHandler
|
||||
( StringRef const& macroName,
|
||||
SourceLineInfo const& lineInfo,
|
||||
StringRef capturedExpression,
|
||||
ResultDisposition::Flags resultDisposition )
|
||||
: m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
|
||||
m_resultCapture( getResultCapture() )
|
||||
{}
|
||||
|
||||
void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
|
||||
m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
|
||||
}
|
||||
void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
|
||||
m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
|
||||
}
|
||||
|
||||
auto AssertionHandler::allowThrows() const -> bool {
|
||||
return getCurrentContext().getConfig()->allowThrows();
|
||||
}
|
||||
|
||||
void AssertionHandler::complete() {
|
||||
setCompleted();
|
||||
if( m_reaction.shouldDebugBreak ) {
|
||||
|
||||
// If you find your debugger stopping you here then go one level up on the
|
||||
// call-stack for the code that caused it (typically a failed assertion)
|
||||
|
||||
// (To go back to the test and change execution, jump over the throw, next)
|
||||
CATCH_BREAK_INTO_DEBUGGER();
|
||||
}
|
||||
if (m_reaction.shouldThrow) {
|
||||
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
|
||||
throw Catch::TestFailureException();
|
||||
#else
|
||||
CATCH_ERROR( "Test failure requires aborting test!" );
|
||||
#endif
|
||||
}
|
||||
}
|
||||
void AssertionHandler::setCompleted() {
|
||||
m_completed = true;
|
||||
}
|
||||
|
||||
void AssertionHandler::handleUnexpectedInflightException() {
|
||||
m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
|
||||
}
|
||||
|
||||
void AssertionHandler::handleExceptionThrownAsExpected() {
|
||||
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
|
||||
}
|
||||
void AssertionHandler::handleExceptionNotThrownAsExpected() {
|
||||
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
|
||||
}
|
||||
|
||||
void AssertionHandler::handleUnexpectedExceptionNotThrown() {
|
||||
m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
|
||||
}
|
||||
|
||||
void AssertionHandler::handleThrowingCallSkipped() {
|
||||
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
|
||||
}
|
||||
|
||||
// This is the overload that takes a string and infers the Equals matcher from it
|
||||
// The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
|
||||
void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
|
||||
handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
|
||||
}
|
||||
|
||||
} // namespace Catch
|
88
src/internal/catch_assertionhandler.h
Normal file
88
src/internal/catch_assertionhandler.h
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Created by Phil on 8/8/2017.
|
||||
* Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_ASSERTIONHANDLER_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_ASSERTIONHANDLER_H_INCLUDED
|
||||
|
||||
#include "catch_assertioninfo.h"
|
||||
#include "catch_decomposer.h"
|
||||
#include "catch_interfaces_capture.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct TestFailureException{};
|
||||
struct AssertionResultData;
|
||||
struct IResultCapture;
|
||||
class RunContext;
|
||||
|
||||
class LazyExpression {
|
||||
friend class AssertionHandler;
|
||||
friend struct AssertionStats;
|
||||
friend class RunContext;
|
||||
|
||||
ITransientExpression const* m_transientExpression = nullptr;
|
||||
bool m_isNegated;
|
||||
public:
|
||||
LazyExpression( bool isNegated );
|
||||
LazyExpression( LazyExpression const& other );
|
||||
LazyExpression& operator = ( LazyExpression const& ) = delete;
|
||||
|
||||
explicit operator bool() const;
|
||||
|
||||
friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
|
||||
};
|
||||
|
||||
struct AssertionReaction {
|
||||
bool shouldDebugBreak = false;
|
||||
bool shouldThrow = false;
|
||||
};
|
||||
|
||||
class AssertionHandler {
|
||||
AssertionInfo m_assertionInfo;
|
||||
AssertionReaction m_reaction;
|
||||
bool m_completed = false;
|
||||
IResultCapture& m_resultCapture;
|
||||
|
||||
public:
|
||||
AssertionHandler
|
||||
( StringRef const& macroName,
|
||||
SourceLineInfo const& lineInfo,
|
||||
StringRef capturedExpression,
|
||||
ResultDisposition::Flags resultDisposition );
|
||||
~AssertionHandler() {
|
||||
if ( !m_completed ) {
|
||||
m_resultCapture.handleIncomplete( m_assertionInfo );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
template<typename T>
|
||||
void handleExpr( ExprLhs<T> const& expr ) {
|
||||
handleExpr( expr.makeUnaryExpr() );
|
||||
}
|
||||
void handleExpr( ITransientExpression const& expr );
|
||||
|
||||
void handleMessage(ResultWas::OfType resultType, StringRef const& message);
|
||||
|
||||
void handleExceptionThrownAsExpected();
|
||||
void handleUnexpectedExceptionNotThrown();
|
||||
void handleExceptionNotThrownAsExpected();
|
||||
void handleThrowingCallSkipped();
|
||||
void handleUnexpectedInflightException();
|
||||
|
||||
void complete();
|
||||
void setCompleted();
|
||||
|
||||
// query
|
||||
auto allowThrows() const -> bool;
|
||||
};
|
||||
|
||||
void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
|
||||
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_ASSERTIONHANDLER_H_INCLUDED
|
28
src/internal/catch_assertioninfo.h
Normal file
28
src/internal/catch_assertioninfo.h
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Created by Phil on 8/8/2017.
|
||||
* Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_ASSERTIONINFO_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_ASSERTIONINFO_H_INCLUDED
|
||||
|
||||
#include "catch_result_type.h"
|
||||
#include "catch_common.h"
|
||||
#include "catch_stringref.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct AssertionInfo {
|
||||
// AssertionInfo() = delete;
|
||||
|
||||
StringRef macroName;
|
||||
SourceLineInfo lineInfo;
|
||||
StringRef capturedExpression;
|
||||
ResultDisposition::Flags resultDisposition;
|
||||
};
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_ASSERTIONINFO_H_INCLUDED
|
104
src/internal/catch_assertionresult.cpp
Normal file
104
src/internal/catch_assertionresult.cpp
Normal file
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Created by Phil on 8/8/12
|
||||
* Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_assertionresult.h"
|
||||
|
||||
namespace Catch {
|
||||
AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
|
||||
lazyExpression(_lazyExpression),
|
||||
resultType(_resultType) {}
|
||||
|
||||
std::string AssertionResultData::reconstructExpression() const {
|
||||
|
||||
if( reconstructedExpression.empty() ) {
|
||||
if( lazyExpression ) {
|
||||
ReusableStringStream rss;
|
||||
rss << lazyExpression;
|
||||
reconstructedExpression = rss.str();
|
||||
}
|
||||
}
|
||||
return reconstructedExpression;
|
||||
}
|
||||
|
||||
AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
|
||||
: m_info( info ),
|
||||
m_resultData( data )
|
||||
{}
|
||||
|
||||
// Result was a success
|
||||
bool AssertionResult::succeeded() const {
|
||||
return Catch::isOk( m_resultData.resultType );
|
||||
}
|
||||
|
||||
// Result was a success, or failure is suppressed
|
||||
bool AssertionResult::isOk() const {
|
||||
return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
|
||||
}
|
||||
|
||||
ResultWas::OfType AssertionResult::getResultType() const {
|
||||
return m_resultData.resultType;
|
||||
}
|
||||
|
||||
bool AssertionResult::hasExpression() const {
|
||||
return !m_info.capturedExpression.empty();
|
||||
}
|
||||
|
||||
bool AssertionResult::hasMessage() const {
|
||||
return !m_resultData.message.empty();
|
||||
}
|
||||
|
||||
std::string AssertionResult::getExpression() const {
|
||||
// Possibly overallocating by 3 characters should be basically free
|
||||
std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
|
||||
if (isFalseTest(m_info.resultDisposition)) {
|
||||
expr += "!(";
|
||||
}
|
||||
expr += m_info.capturedExpression;
|
||||
if (isFalseTest(m_info.resultDisposition)) {
|
||||
expr += ')';
|
||||
}
|
||||
return expr;
|
||||
}
|
||||
|
||||
std::string AssertionResult::getExpressionInMacro() const {
|
||||
std::string expr;
|
||||
if( m_info.macroName.empty() )
|
||||
expr = static_cast<std::string>(m_info.capturedExpression);
|
||||
else {
|
||||
expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
|
||||
expr += m_info.macroName;
|
||||
expr += "( ";
|
||||
expr += m_info.capturedExpression;
|
||||
expr += " )";
|
||||
}
|
||||
return expr;
|
||||
}
|
||||
|
||||
bool AssertionResult::hasExpandedExpression() const {
|
||||
return hasExpression() && getExpandedExpression() != getExpression();
|
||||
}
|
||||
|
||||
std::string AssertionResult::getExpandedExpression() const {
|
||||
std::string expr = m_resultData.reconstructExpression();
|
||||
return expr.empty()
|
||||
? getExpression()
|
||||
: expr;
|
||||
}
|
||||
|
||||
std::string AssertionResult::getMessage() const {
|
||||
return m_resultData.message;
|
||||
}
|
||||
SourceLineInfo AssertionResult::getSourceInfo() const {
|
||||
return m_info.lineInfo;
|
||||
}
|
||||
|
||||
StringRef AssertionResult::getTestMacroName() const {
|
||||
return m_info.macroName;
|
||||
}
|
||||
|
||||
} // end namespace Catch
|
59
src/internal/catch_assertionresult.h
Normal file
59
src/internal/catch_assertionresult.h
Normal file
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Created by Phil on 28/10/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_ASSERTIONRESULT_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED
|
||||
|
||||
#include <string>
|
||||
#include "catch_assertioninfo.h"
|
||||
#include "catch_result_type.h"
|
||||
#include "catch_common.h"
|
||||
#include "catch_stringref.h"
|
||||
#include "catch_assertionhandler.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct AssertionResultData
|
||||
{
|
||||
AssertionResultData() = delete;
|
||||
|
||||
AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
|
||||
|
||||
std::string message;
|
||||
mutable std::string reconstructedExpression;
|
||||
LazyExpression lazyExpression;
|
||||
ResultWas::OfType resultType;
|
||||
|
||||
std::string reconstructExpression() const;
|
||||
};
|
||||
|
||||
class AssertionResult {
|
||||
public:
|
||||
AssertionResult() = delete;
|
||||
AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
|
||||
|
||||
bool isOk() const;
|
||||
bool succeeded() const;
|
||||
ResultWas::OfType getResultType() const;
|
||||
bool hasExpression() const;
|
||||
bool hasMessage() const;
|
||||
std::string getExpression() const;
|
||||
std::string getExpressionInMacro() const;
|
||||
bool hasExpandedExpression() const;
|
||||
std::string getExpandedExpression() const;
|
||||
std::string getMessage() const;
|
||||
SourceLineInfo getSourceInfo() const;
|
||||
StringRef getTestMacroName() const;
|
||||
|
||||
//protected:
|
||||
AssertionInfo m_info;
|
||||
AssertionResultData m_resultData;
|
||||
};
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED
|
158
src/internal/catch_capture.hpp
Normal file
158
src/internal/catch_capture.hpp
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Created by Phil on 18/10/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_CAPTURE_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED
|
||||
|
||||
#include "catch_assertionhandler.h"
|
||||
#include "catch_interfaces_capture.h"
|
||||
#include "catch_message.h"
|
||||
#include "catch_stringref.h"
|
||||
|
||||
#if !defined(CATCH_CONFIG_DISABLE)
|
||||
|
||||
#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
|
||||
#define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
|
||||
#else
|
||||
#define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Another way to speed-up compilation is to omit local try-catch for REQUIRE*
|
||||
// macros.
|
||||
#define INTERNAL_CATCH_TRY
|
||||
#define INTERNAL_CATCH_CATCH( capturer )
|
||||
|
||||
#else // CATCH_CONFIG_FAST_COMPILE
|
||||
|
||||
#define INTERNAL_CATCH_TRY try
|
||||
#define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
|
||||
|
||||
#endif
|
||||
|
||||
#define INTERNAL_CATCH_REACT( handler ) handler.complete();
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
|
||||
do { \
|
||||
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
|
||||
INTERNAL_CATCH_TRY { \
|
||||
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
|
||||
CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
|
||||
catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
|
||||
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
|
||||
} INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
|
||||
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
|
||||
} while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression 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( macroName, resultDisposition, ... ) \
|
||||
INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
|
||||
if( Catch::getResultCapture().lastAssertionPassed() )
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
|
||||
INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
|
||||
if( !Catch::getResultCapture().lastAssertionPassed() )
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
|
||||
do { \
|
||||
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
|
||||
try { \
|
||||
static_cast<void>(__VA_ARGS__); \
|
||||
catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
|
||||
} \
|
||||
catch( ... ) { \
|
||||
catchAssertionHandler.handleUnexpectedInflightException(); \
|
||||
} \
|
||||
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
|
||||
} while( false )
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
|
||||
do { \
|
||||
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
|
||||
if( catchAssertionHandler.allowThrows() ) \
|
||||
try { \
|
||||
static_cast<void>(__VA_ARGS__); \
|
||||
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
|
||||
} \
|
||||
catch( ... ) { \
|
||||
catchAssertionHandler.handleExceptionThrownAsExpected(); \
|
||||
} \
|
||||
else \
|
||||
catchAssertionHandler.handleThrowingCallSkipped(); \
|
||||
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
|
||||
} while( false )
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
|
||||
do { \
|
||||
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
|
||||
if( catchAssertionHandler.allowThrows() ) \
|
||||
try { \
|
||||
static_cast<void>(expr); \
|
||||
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
|
||||
} \
|
||||
catch( exceptionType const& ) { \
|
||||
catchAssertionHandler.handleExceptionThrownAsExpected(); \
|
||||
} \
|
||||
catch( ... ) { \
|
||||
catchAssertionHandler.handleUnexpectedInflightException(); \
|
||||
} \
|
||||
else \
|
||||
catchAssertionHandler.handleThrowingCallSkipped(); \
|
||||
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
|
||||
} while( false )
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
|
||||
do { \
|
||||
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
|
||||
catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
|
||||
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
|
||||
} while( false )
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
|
||||
auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
|
||||
varName.captureValues( 0, __VA_ARGS__ )
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_INFO( macroName, log ) \
|
||||
Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
|
||||
Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Although this is matcher-based, it can be used with just a string
|
||||
#define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
|
||||
do { \
|
||||
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
|
||||
if( catchAssertionHandler.allowThrows() ) \
|
||||
try { \
|
||||
static_cast<void>(__VA_ARGS__); \
|
||||
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
|
||||
} \
|
||||
catch( ... ) { \
|
||||
Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
|
||||
} \
|
||||
else \
|
||||
catchAssertionHandler.handleThrowingCallSkipped(); \
|
||||
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
|
||||
} while( false )
|
||||
|
||||
#endif // CATCH_CONFIG_DISABLE
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED
|
24
src/internal/catch_capture_matchers.cpp
Normal file
24
src/internal/catch_capture_matchers.cpp
Normal file
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Created by Phil on 9/8/2017.
|
||||
* Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_capture_matchers.h"
|
||||
#include "catch_interfaces_registry_hub.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
|
||||
|
||||
// This is the general overload that takes a any string matcher
|
||||
// There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
|
||||
// the Equals matcher (so the header does not mention matchers)
|
||||
void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
|
||||
std::string exceptionMessage = Catch::translateActiveException();
|
||||
MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
|
||||
handler.handleExpr( expr );
|
||||
}
|
||||
|
||||
} // namespace Catch
|
88
src/internal/catch_capture_matchers.h
Normal file
88
src/internal/catch_capture_matchers.h
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Created by Phil on 9/8/2017
|
||||
* Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_CAPTURE_MATCHERS_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CAPTURE_MATCHERS_HPP_INCLUDED
|
||||
|
||||
#include "catch_capture.hpp"
|
||||
#include "catch_matchers.h"
|
||||
#include "catch_matchers_exception.hpp"
|
||||
#include "catch_matchers_floating.h"
|
||||
#include "catch_matchers_generic.hpp"
|
||||
#include "catch_matchers_string.h"
|
||||
#include "catch_matchers_vector.h"
|
||||
#include "catch_stringref.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
template<typename ArgT, typename MatcherT>
|
||||
class MatchExpr : public ITransientExpression {
|
||||
ArgT const& m_arg;
|
||||
MatcherT m_matcher;
|
||||
StringRef m_matcherString;
|
||||
public:
|
||||
MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
|
||||
: ITransientExpression{ true, matcher.match( arg ) },
|
||||
m_arg( arg ),
|
||||
m_matcher( matcher ),
|
||||
m_matcherString( matcherString )
|
||||
{}
|
||||
|
||||
void streamReconstructedExpression( std::ostream &os ) const override {
|
||||
auto matcherAsString = m_matcher.toString();
|
||||
os << Catch::Detail::stringify( m_arg ) << ' ';
|
||||
if( matcherAsString == Detail::unprintableString )
|
||||
os << m_matcherString;
|
||||
else
|
||||
os << matcherAsString;
|
||||
}
|
||||
};
|
||||
|
||||
using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
|
||||
|
||||
void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
|
||||
|
||||
template<typename ArgT, typename MatcherT>
|
||||
auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
|
||||
return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
|
||||
}
|
||||
|
||||
} // namespace Catch
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
|
||||
do { \
|
||||
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
|
||||
INTERNAL_CATCH_TRY { \
|
||||
catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
|
||||
} INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
|
||||
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
|
||||
} while( false )
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
|
||||
do { \
|
||||
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
|
||||
if( catchAssertionHandler.allowThrows() ) \
|
||||
try { \
|
||||
static_cast<void>(__VA_ARGS__ ); \
|
||||
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
|
||||
} \
|
||||
catch( exceptionType const& ex ) { \
|
||||
catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
|
||||
} \
|
||||
catch( ... ) { \
|
||||
catchAssertionHandler.handleUnexpectedInflightException(); \
|
||||
} \
|
||||
else \
|
||||
catchAssertionHandler.handleThrowingCallSkipped(); \
|
||||
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
|
||||
} while( false )
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CAPTURE_MATCHERS_HPP_INCLUDED
|
38
src/internal/catch_clara.h
Normal file
38
src/internal/catch_clara.h
Normal file
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Created by Phil on 10/2/2014.
|
||||
* Copyright 2014 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_CLARA_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED
|
||||
|
||||
// Use Catch's value for console width (store Clara's off to the side, if present)
|
||||
#ifdef CLARA_CONFIG_CONSOLE_WIDTH
|
||||
#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
|
||||
#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
|
||||
#endif
|
||||
#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
|
||||
|
||||
#ifdef __clang__
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wweak-vtables"
|
||||
#pragma clang diagnostic ignored "-Wexit-time-destructors"
|
||||
#pragma clang diagnostic ignored "-Wshadow"
|
||||
#endif
|
||||
|
||||
#include "../external/clara.hpp"
|
||||
|
||||
#ifdef __clang__
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
// Restore Clara's value for console width, if present
|
||||
#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
|
||||
#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
|
||||
#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
|
||||
#endif
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CLARA_H_INCLUDED
|
220
src/internal/catch_commandline.cpp
Normal file
220
src/internal/catch_commandline.cpp
Normal file
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* Created by Phil on 02/11/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_commandline.h"
|
||||
|
||||
#include "catch_string_manip.h"
|
||||
|
||||
#include "catch_interfaces_registry_hub.h"
|
||||
#include "catch_interfaces_reporter.h"
|
||||
|
||||
#include <fstream>
|
||||
#include <ctime>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
clara::Parser makeCommandLineParser( ConfigData& config ) {
|
||||
|
||||
using namespace clara;
|
||||
|
||||
auto const setWarning = [&]( std::string const& warning ) {
|
||||
auto warningSet = [&]() {
|
||||
if( warning == "NoAssertions" )
|
||||
return WarnAbout::NoAssertions;
|
||||
|
||||
if ( warning == "NoTests" )
|
||||
return WarnAbout::NoTests;
|
||||
|
||||
return WarnAbout::Nothing;
|
||||
}();
|
||||
|
||||
if (warningSet == WarnAbout::Nothing)
|
||||
return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
|
||||
config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
|
||||
return ParserResult::ok( ParseResultType::Matched );
|
||||
};
|
||||
auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
|
||||
std::ifstream f( filename.c_str() );
|
||||
if( !f.is_open() )
|
||||
return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
|
||||
|
||||
std::string line;
|
||||
while( std::getline( f, line ) ) {
|
||||
line = trim(line);
|
||||
if( !line.empty() && !startsWith( line, '#' ) ) {
|
||||
if( !startsWith( line, '"' ) )
|
||||
line = '"' + line + '"';
|
||||
config.testsOrTags.push_back( line );
|
||||
config.testsOrTags.push_back( "," );
|
||||
|
||||
}
|
||||
}
|
||||
//Remove comma in the end
|
||||
if(!config.testsOrTags.empty())
|
||||
config.testsOrTags.erase( config.testsOrTags.end()-1 );
|
||||
|
||||
return ParserResult::ok( ParseResultType::Matched );
|
||||
};
|
||||
auto const setTestOrder = [&]( std::string const& order ) {
|
||||
if( startsWith( "declared", order ) )
|
||||
config.runOrder = RunTests::InDeclarationOrder;
|
||||
else if( startsWith( "lexical", order ) )
|
||||
config.runOrder = RunTests::InLexicographicalOrder;
|
||||
else if( startsWith( "random", order ) )
|
||||
config.runOrder = RunTests::InRandomOrder;
|
||||
else
|
||||
return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
|
||||
return ParserResult::ok( ParseResultType::Matched );
|
||||
};
|
||||
auto const setRngSeed = [&]( std::string const& seed ) {
|
||||
if( seed != "time" )
|
||||
return clara::detail::convertInto( seed, config.rngSeed );
|
||||
config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
|
||||
return ParserResult::ok( ParseResultType::Matched );
|
||||
};
|
||||
auto const setColourUsage = [&]( std::string const& useColour ) {
|
||||
auto mode = toLower( useColour );
|
||||
|
||||
if( mode == "yes" )
|
||||
config.useColour = UseColour::Yes;
|
||||
else if( mode == "no" )
|
||||
config.useColour = UseColour::No;
|
||||
else if( mode == "auto" )
|
||||
config.useColour = UseColour::Auto;
|
||||
else
|
||||
return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
|
||||
return ParserResult::ok( ParseResultType::Matched );
|
||||
};
|
||||
auto const setWaitForKeypress = [&]( std::string const& keypress ) {
|
||||
auto keypressLc = toLower( keypress );
|
||||
if( keypressLc == "start" )
|
||||
config.waitForKeypress = WaitForKeypress::BeforeStart;
|
||||
else if( keypressLc == "exit" )
|
||||
config.waitForKeypress = WaitForKeypress::BeforeExit;
|
||||
else if( keypressLc == "both" )
|
||||
config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
|
||||
else
|
||||
return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
|
||||
return ParserResult::ok( ParseResultType::Matched );
|
||||
};
|
||||
auto const setVerbosity = [&]( std::string const& verbosity ) {
|
||||
auto lcVerbosity = toLower( verbosity );
|
||||
if( lcVerbosity == "quiet" )
|
||||
config.verbosity = Verbosity::Quiet;
|
||||
else if( lcVerbosity == "normal" )
|
||||
config.verbosity = Verbosity::Normal;
|
||||
else if( lcVerbosity == "high" )
|
||||
config.verbosity = Verbosity::High;
|
||||
else
|
||||
return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
|
||||
return ParserResult::ok( ParseResultType::Matched );
|
||||
};
|
||||
auto const setReporter = [&]( std::string const& reporter ) {
|
||||
IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
|
||||
|
||||
auto lcReporter = toLower( reporter );
|
||||
auto result = factories.find( lcReporter );
|
||||
|
||||
if( factories.end() != result )
|
||||
config.reporterName = lcReporter;
|
||||
else
|
||||
return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
|
||||
return ParserResult::ok( ParseResultType::Matched );
|
||||
};
|
||||
|
||||
auto cli
|
||||
= ExeName( config.processName )
|
||||
| Help( config.showHelp )
|
||||
| Opt( config.listTests )
|
||||
["-l"]["--list-tests"]
|
||||
( "list all/matching test cases" )
|
||||
| Opt( config.listTags )
|
||||
["-t"]["--list-tags"]
|
||||
( "list all/matching tags" )
|
||||
| Opt( config.showSuccessfulTests )
|
||||
["-s"]["--success"]
|
||||
( "include successful tests in output" )
|
||||
| Opt( config.shouldDebugBreak )
|
||||
["-b"]["--break"]
|
||||
( "break into debugger on failure" )
|
||||
| Opt( config.noThrow )
|
||||
["-e"]["--nothrow"]
|
||||
( "skip exception tests" )
|
||||
| Opt( config.showInvisibles )
|
||||
["-i"]["--invisibles"]
|
||||
( "show invisibles (tabs, newlines)" )
|
||||
| Opt( config.outputFilename, "filename" )
|
||||
["-o"]["--out"]
|
||||
( "output filename" )
|
||||
| Opt( setReporter, "name" )
|
||||
["-r"]["--reporter"]
|
||||
( "reporter to use (defaults to console)" )
|
||||
| Opt( config.name, "name" )
|
||||
["-n"]["--name"]
|
||||
( "suite name" )
|
||||
| Opt( [&]( bool ){ config.abortAfter = 1; } )
|
||||
["-a"]["--abort"]
|
||||
( "abort at first failure" )
|
||||
| Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
|
||||
["-x"]["--abortx"]
|
||||
( "abort after x failures" )
|
||||
| Opt( setWarning, "warning name" )
|
||||
["-w"]["--warn"]
|
||||
( "enable warnings" )
|
||||
| Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
|
||||
["-d"]["--durations"]
|
||||
( "show test durations" )
|
||||
| Opt( loadTestNamesFromFile, "filename" )
|
||||
["-f"]["--input-file"]
|
||||
( "load test names to run from a file" )
|
||||
| Opt( config.filenamesAsTags )
|
||||
["-#"]["--filenames-as-tags"]
|
||||
( "adds a tag for the filename" )
|
||||
| Opt( config.sectionsToRun, "section name" )
|
||||
["-c"]["--section"]
|
||||
( "specify section to run" )
|
||||
| Opt( setVerbosity, "quiet|normal|high" )
|
||||
["-v"]["--verbosity"]
|
||||
( "set output verbosity" )
|
||||
| Opt( config.listReporters )
|
||||
["--list-reporters"]
|
||||
( "list all reporters" )
|
||||
| Opt( setTestOrder, "decl|lex|rand" )
|
||||
["--order"]
|
||||
( "test case order (defaults to decl)" )
|
||||
| Opt( setRngSeed, "'time'|number" )
|
||||
["--rng-seed"]
|
||||
( "set a specific seed for random numbers" )
|
||||
| Opt( setColourUsage, "yes|no" )
|
||||
["--use-colour"]
|
||||
( "should output be colourised" )
|
||||
| Opt( config.libIdentify )
|
||||
["--libidentify"]
|
||||
( "report name and version according to libidentify standard" )
|
||||
| Opt( setWaitForKeypress, "start|exit|both" )
|
||||
["--wait-for-keypress"]
|
||||
( "waits for a keypress before exiting" )
|
||||
| Opt( config.benchmarkSamples, "samples" )
|
||||
["--benchmark-samples"]
|
||||
( "number of samples to collect (default: 100)" )
|
||||
| Opt( config.benchmarkResamples, "resamples" )
|
||||
["--benchmark-resamples"]
|
||||
( "number of resamples for the bootstrap (default: 100000)" )
|
||||
| Opt( config.benchmarkConfidenceInterval, "confidence interval" )
|
||||
["--benchmark-confidence-interval"]
|
||||
( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
|
||||
| Opt( config.benchmarkNoAnalysis )
|
||||
["--benchmark-no-analysis"]
|
||||
( "perform only measurements; do not perform any analysis" )
|
||||
| Arg( config.testsOrTags, "test name|pattern|tags" )
|
||||
( "which test or tests to use" );
|
||||
|
||||
return cli;
|
||||
}
|
||||
|
||||
} // end namespace Catch
|
20
src/internal/catch_commandline.h
Normal file
20
src/internal/catch_commandline.h
Normal file
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Created by Phil on 02/11/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_COMMANDLINE_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED
|
||||
|
||||
#include "catch_config.hpp"
|
||||
#include "catch_clara.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
clara::Parser makeCommandLineParser( ConfigData& config );
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED
|
40
src/internal/catch_common.cpp
Normal file
40
src/internal/catch_common.cpp
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Created by Phil on 27/11/2013.
|
||||
* Copyright 2013 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_common.h"
|
||||
#include "catch_context.h"
|
||||
#include "catch_interfaces_config.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <ostream>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
|
||||
return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
|
||||
}
|
||||
bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
|
||||
// We can assume that the same file will usually have the same pointer.
|
||||
// Thus, if the pointers are the same, there is no point in calling the strcmp
|
||||
return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
|
||||
}
|
||||
|
||||
std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
|
||||
#ifndef __GNUG__
|
||||
os << info.file << '(' << info.line << ')';
|
||||
#else
|
||||
os << info.file << ':' << info.line;
|
||||
#endif
|
||||
return os;
|
||||
}
|
||||
|
||||
std::string StreamEndStop::operator+() const {
|
||||
return std::string();
|
||||
}
|
||||
|
||||
} // end namespace Catch
|
89
src/internal/catch_common.h
Normal file
89
src/internal/catch_common.h
Normal file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Created by Phil on 29/10/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_COMMON_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED
|
||||
|
||||
#include "catch_compiler_capabilities.h"
|
||||
|
||||
#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
|
||||
#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
|
||||
#ifdef CATCH_CONFIG_COUNTER
|
||||
# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
|
||||
#else
|
||||
# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
|
||||
#endif
|
||||
|
||||
#include <iosfwd>
|
||||
#include <string>
|
||||
#include <cstdint>
|
||||
|
||||
// We need a dummy global operator<< so we can bring it into Catch namespace later
|
||||
struct Catch_global_namespace_dummy {};
|
||||
std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct CaseSensitive { enum Choice {
|
||||
Yes,
|
||||
No
|
||||
}; };
|
||||
|
||||
class NonCopyable {
|
||||
NonCopyable( NonCopyable const& ) = delete;
|
||||
NonCopyable( NonCopyable && ) = delete;
|
||||
NonCopyable& operator = ( NonCopyable const& ) = delete;
|
||||
NonCopyable& operator = ( NonCopyable && ) = delete;
|
||||
protected:
|
||||
NonCopyable() noexcept = default;
|
||||
};
|
||||
|
||||
struct SourceLineInfo {
|
||||
|
||||
SourceLineInfo() = delete;
|
||||
constexpr SourceLineInfo( char const* _file, std::size_t _line ) noexcept:
|
||||
file( _file ),
|
||||
line( _line )
|
||||
{}
|
||||
|
||||
SourceLineInfo( SourceLineInfo const& other ) = default;
|
||||
SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
|
||||
SourceLineInfo( SourceLineInfo&& ) noexcept = default;
|
||||
SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
|
||||
|
||||
bool operator == ( SourceLineInfo const& other ) const noexcept;
|
||||
bool operator < ( SourceLineInfo const& other ) const noexcept;
|
||||
|
||||
char const* file;
|
||||
std::size_t line;
|
||||
};
|
||||
|
||||
std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
|
||||
|
||||
// Bring in operator<< from global namespace into Catch namespace
|
||||
// This is necessary because the overload of operator<< above makes
|
||||
// lookup stop at namespace Catch
|
||||
using ::operator<<;
|
||||
|
||||
// Use this in variadic streaming macros to allow
|
||||
// >> +StreamEndStop
|
||||
// as well as
|
||||
// >> stuff +StreamEndStop
|
||||
struct StreamEndStop {
|
||||
std::string operator+() const;
|
||||
};
|
||||
template<typename T>
|
||||
T const& operator + ( T const& value, StreamEndStop ) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
#define CATCH_INTERNAL_LINEINFO \
|
||||
::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_COMMON_H_INCLUDED
|
||||
|
358
src/internal/catch_compiler_capabilities.h
Normal file
358
src/internal/catch_compiler_capabilities.h
Normal file
@@ -0,0 +1,358 @@
|
||||
/*
|
||||
* Created by Phil on 15/04/2013.
|
||||
* Copyright 2013 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_COMPILER_CAPABILITIES_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
|
||||
|
||||
// Detect a number of compiler features - by compiler
|
||||
// The following features are defined:
|
||||
//
|
||||
// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
|
||||
// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
|
||||
// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
|
||||
// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
|
||||
// ****************
|
||||
// Note to maintainers: if new toggles are added please document them
|
||||
// in configuration.md, too
|
||||
// ****************
|
||||
|
||||
// In general each macro has a _NO_<feature name> form
|
||||
// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
|
||||
// Many features, at point of detection, define an _INTERNAL_ macro, so they
|
||||
// can be combined, en-mass, with the _NO_ forms later.
|
||||
|
||||
#include "catch_platform.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
|
||||
# define CATCH_CPP14_OR_GREATER
|
||||
# endif
|
||||
|
||||
# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
|
||||
# define CATCH_CPP17_OR_GREATER
|
||||
# endif
|
||||
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_CPP17_OR_GREATER)
|
||||
# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
|
||||
#endif
|
||||
|
||||
// We have to avoid both ICC and Clang, because they try to mask themselves
|
||||
// as gcc, and we want only GCC in this block
|
||||
#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC)
|
||||
# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
|
||||
# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
|
||||
#endif
|
||||
|
||||
#if defined(__clang__)
|
||||
|
||||
# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
|
||||
# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
|
||||
|
||||
# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
|
||||
_Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
|
||||
_Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
|
||||
|
||||
# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
|
||||
_Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
|
||||
|
||||
# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
|
||||
_Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
|
||||
|
||||
# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
|
||||
_Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
|
||||
|
||||
# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
|
||||
_Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
|
||||
|
||||
#endif // __clang__
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Assume that non-Windows platforms support posix signals by default
|
||||
#if !defined(CATCH_PLATFORM_WINDOWS)
|
||||
#define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
|
||||
#endif
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// We know some environments not to support full POSIX signals
|
||||
#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
|
||||
#define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
|
||||
#endif
|
||||
|
||||
#ifdef __OS400__
|
||||
# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
|
||||
# define CATCH_CONFIG_COLOUR_NONE
|
||||
#endif
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Android somehow still does not support std::to_string
|
||||
#if defined(__ANDROID__)
|
||||
# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
|
||||
# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
|
||||
#endif
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Not all Windows environments support SEH properly
|
||||
#if defined(__MINGW32__)
|
||||
# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
|
||||
#endif
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// PS4
|
||||
#if defined(__ORBIS__)
|
||||
# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
|
||||
#endif
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Cygwin
|
||||
#ifdef __CYGWIN__
|
||||
|
||||
// Required for some versions of Cygwin to declare gettimeofday
|
||||
// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
|
||||
# define _BSD_SOURCE
|
||||
// some versions of cygwin (most) do not support std::to_string. Use the libstd check.
|
||||
// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
|
||||
# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
|
||||
&& !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
|
||||
|
||||
# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
|
||||
|
||||
# endif
|
||||
#endif // __CYGWIN__
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Visual C++
|
||||
#if defined(_MSC_VER)
|
||||
|
||||
# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
|
||||
# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
|
||||
|
||||
# if _MSC_VER >= 1900 // Visual Studio 2015 or newer
|
||||
# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
|
||||
# endif
|
||||
|
||||
// Universal Windows platform does not support SEH
|
||||
// Or console colours (or console at all...)
|
||||
# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
|
||||
# define CATCH_CONFIG_COLOUR_NONE
|
||||
# else
|
||||
# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
|
||||
# endif
|
||||
|
||||
// MSVC traditional preprocessor needs some workaround for __VA_ARGS__
|
||||
// _MSVC_TRADITIONAL == 0 means new conformant preprocessor
|
||||
// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
|
||||
# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
|
||||
# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
|
||||
# endif
|
||||
#endif // _MSC_VER
|
||||
|
||||
#if defined(_REENTRANT) || defined(_MSC_VER)
|
||||
// Enable async processing, as -pthread is specified or no additional linking is required
|
||||
# define CATCH_INTERNAL_CONFIG_USE_ASYNC
|
||||
#endif // _MSC_VER
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Check if we are compiled with -fno-exceptions or equivalent
|
||||
#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
|
||||
# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
|
||||
#endif
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// DJGPP
|
||||
#ifdef __DJGPP__
|
||||
# define CATCH_INTERNAL_CONFIG_NO_WCHAR
|
||||
#endif // __DJGPP__
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Embarcadero C++Build
|
||||
#if defined(__BORLANDC__)
|
||||
#define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
|
||||
#endif
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Use of __COUNTER__ is suppressed during code analysis in
|
||||
// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
|
||||
// handled by it.
|
||||
// Otherwise all supported compilers support COUNTER macro,
|
||||
// but user still might want to turn it off
|
||||
#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
|
||||
#define CATCH_INTERNAL_CONFIG_COUNTER
|
||||
#endif
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// RTX is a special version of Windows that is real time.
|
||||
// This means that it is detected as Windows, but does not provide
|
||||
// the same set of capabilities as real Windows does.
|
||||
#if defined(UNDER_RTSS) || defined(RTX64_BUILD)
|
||||
#define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
|
||||
#define CATCH_INTERNAL_CONFIG_NO_ASYNC
|
||||
#define CATCH_CONFIG_COLOUR_NONE
|
||||
#endif
|
||||
|
||||
#if defined(__UCLIBC__)
|
||||
#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
|
||||
#endif
|
||||
|
||||
// Various stdlib support checks that require __has_include
|
||||
#if defined(__has_include)
|
||||
// Check if string_view is available and usable
|
||||
#if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
|
||||
# define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
|
||||
#endif
|
||||
|
||||
// Check if optional is available and usable
|
||||
# if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
|
||||
# define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
|
||||
# endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
|
||||
|
||||
// Check if byte is available and usable
|
||||
# if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
|
||||
# define CATCH_INTERNAL_CONFIG_CPP17_BYTE
|
||||
# endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
|
||||
|
||||
// Check if variant is available and usable
|
||||
# if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
|
||||
# if defined(__clang__) && (__clang_major__ < 8)
|
||||
// work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
|
||||
// fix should be in clang 8, workaround in libstdc++ 8.2
|
||||
# include <ciso646>
|
||||
# if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
|
||||
# define CATCH_CONFIG_NO_CPP17_VARIANT
|
||||
# else
|
||||
# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
|
||||
# endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
|
||||
# else
|
||||
# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
|
||||
# endif // defined(__clang__) && (__clang_major__ < 8)
|
||||
# endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
|
||||
#endif // defined(__has_include)
|
||||
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
|
||||
# define CATCH_CONFIG_COUNTER
|
||||
#endif
|
||||
#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
|
||||
# define CATCH_CONFIG_WINDOWS_SEH
|
||||
#endif
|
||||
// This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
|
||||
#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
|
||||
# define CATCH_CONFIG_POSIX_SIGNALS
|
||||
#endif
|
||||
// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
|
||||
#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
|
||||
# define CATCH_CONFIG_WCHAR
|
||||
#endif
|
||||
|
||||
#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
|
||||
# define CATCH_CONFIG_CPP11_TO_STRING
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
|
||||
# define CATCH_CONFIG_CPP17_OPTIONAL
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
|
||||
# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
|
||||
# define CATCH_CONFIG_CPP17_STRING_VIEW
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
|
||||
# define CATCH_CONFIG_CPP17_VARIANT
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
|
||||
# define CATCH_CONFIG_CPP17_BYTE
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
|
||||
# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
|
||||
# define CATCH_CONFIG_NEW_CAPTURE
|
||||
#endif
|
||||
|
||||
#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
|
||||
# define CATCH_CONFIG_DISABLE_EXCEPTIONS
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
|
||||
# define CATCH_CONFIG_POLYFILL_ISNAN
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
|
||||
# define CATCH_CONFIG_USE_ASYNC
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
|
||||
# define CATCH_CONFIG_ANDROID_LOGWRITE
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
|
||||
# define CATCH_CONFIG_GLOBAL_NEXTAFTER
|
||||
#endif
|
||||
|
||||
|
||||
// Even if we do not think the compiler has that warning, we still have
|
||||
// to provide a macro that can be used by the code.
|
||||
#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
|
||||
# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
|
||||
#endif
|
||||
#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
|
||||
# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
|
||||
#endif
|
||||
#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
|
||||
# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
|
||||
#endif
|
||||
#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
|
||||
# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
|
||||
#endif
|
||||
#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
|
||||
# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
|
||||
#endif
|
||||
#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
|
||||
# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
|
||||
# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
|
||||
#elif defined(__clang__) && (__clang_major__ < 5)
|
||||
# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
|
||||
#endif
|
||||
|
||||
#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
|
||||
# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
|
||||
#define CATCH_TRY if ((true))
|
||||
#define CATCH_CATCH_ALL if ((false))
|
||||
#define CATCH_CATCH_ANON(type) if ((false))
|
||||
#else
|
||||
#define CATCH_TRY try
|
||||
#define CATCH_CATCH_ALL catch (...)
|
||||
#define CATCH_CATCH_ANON(type) catch (type)
|
||||
#endif
|
||||
|
||||
#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
|
||||
#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
|
||||
#endif
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
|
||||
|
83
src/internal/catch_config.cpp
Normal file
83
src/internal/catch_config.cpp
Normal file
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Created by Martin on 19/07/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_config.hpp"
|
||||
#include "catch_enforce.h"
|
||||
#include "catch_stringref.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
Config::Config( ConfigData const& data )
|
||||
: m_data( data ),
|
||||
m_stream( openStream() )
|
||||
{
|
||||
// We need to trim filter specs to avoid trouble with superfluous
|
||||
// whitespace (esp. important for bdd macros, as those are manually
|
||||
// aligned with whitespace).
|
||||
|
||||
for (auto& elem : m_data.testsOrTags) {
|
||||
elem = trim(elem);
|
||||
}
|
||||
for (auto& elem : m_data.sectionsToRun) {
|
||||
elem = trim(elem);
|
||||
}
|
||||
|
||||
TestSpecParser parser(ITagAliasRegistry::get());
|
||||
if (!m_data.testsOrTags.empty()) {
|
||||
m_hasTestFilters = true;
|
||||
for (auto const& testOrTags : m_data.testsOrTags) {
|
||||
parser.parse(testOrTags);
|
||||
}
|
||||
}
|
||||
m_testSpec = parser.testSpec();
|
||||
}
|
||||
|
||||
std::string const& Config::getFilename() const {
|
||||
return m_data.outputFilename ;
|
||||
}
|
||||
|
||||
bool Config::listTests() const { return m_data.listTests; }
|
||||
bool Config::listTags() const { return m_data.listTags; }
|
||||
bool Config::listReporters() const { return m_data.listReporters; }
|
||||
|
||||
std::string Config::getProcessName() const { return m_data.processName; }
|
||||
std::string const& Config::getReporterName() const { return m_data.reporterName; }
|
||||
|
||||
std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
|
||||
std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
|
||||
|
||||
TestSpec const& Config::testSpec() const { return m_testSpec; }
|
||||
bool Config::hasTestFilters() const { return m_hasTestFilters; }
|
||||
|
||||
bool Config::showHelp() const { return m_data.showHelp; }
|
||||
|
||||
// IConfig interface
|
||||
bool Config::allowThrows() const { return !m_data.noThrow; }
|
||||
std::ostream& Config::stream() const { return m_stream->stream(); }
|
||||
std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
|
||||
bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
|
||||
bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
|
||||
bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
|
||||
ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
|
||||
RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
|
||||
unsigned int Config::rngSeed() const { return m_data.rngSeed; }
|
||||
UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
|
||||
bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
|
||||
int Config::abortAfter() const { return m_data.abortAfter; }
|
||||
bool Config::showInvisibles() const { return m_data.showInvisibles; }
|
||||
Verbosity Config::verbosity() const { return m_data.verbosity; }
|
||||
|
||||
bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
|
||||
int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
|
||||
double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
|
||||
unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
|
||||
|
||||
IStream const* Config::openStream() {
|
||||
return Catch::makeStream(m_data.outputFilename);
|
||||
}
|
||||
|
||||
} // end namespace Catch
|
127
src/internal/catch_config.hpp
Normal file
127
src/internal/catch_config.hpp
Normal file
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Created by Phil on 08/11/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_CONFIG_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED
|
||||
|
||||
#include "catch_test_spec_parser.h"
|
||||
#include "catch_interfaces_config.h"
|
||||
|
||||
// Libstdc++ doesn't like incomplete classes for unique_ptr
|
||||
#include "catch_stream.h"
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
#ifndef CATCH_CONFIG_CONSOLE_WIDTH
|
||||
#define CATCH_CONFIG_CONSOLE_WIDTH 80
|
||||
#endif
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct IStream;
|
||||
|
||||
struct ConfigData {
|
||||
bool listTests = false;
|
||||
bool listTags = false;
|
||||
bool listReporters = false;
|
||||
|
||||
bool showSuccessfulTests = false;
|
||||
bool shouldDebugBreak = false;
|
||||
bool noThrow = false;
|
||||
bool showHelp = false;
|
||||
bool showInvisibles = false;
|
||||
bool filenamesAsTags = false;
|
||||
bool libIdentify = false;
|
||||
|
||||
int abortAfter = -1;
|
||||
unsigned int rngSeed = 0;
|
||||
|
||||
bool benchmarkNoAnalysis = false;
|
||||
unsigned int benchmarkSamples = 100;
|
||||
double benchmarkConfidenceInterval = 0.95;
|
||||
unsigned int benchmarkResamples = 100000;
|
||||
|
||||
Verbosity verbosity = Verbosity::Normal;
|
||||
WarnAbout::What warnings = WarnAbout::Nothing;
|
||||
ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
|
||||
RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
|
||||
UseColour::YesOrNo useColour = UseColour::Auto;
|
||||
WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
|
||||
|
||||
std::string outputFilename;
|
||||
std::string name;
|
||||
std::string processName;
|
||||
#ifndef CATCH_CONFIG_DEFAULT_REPORTER
|
||||
#define CATCH_CONFIG_DEFAULT_REPORTER "console"
|
||||
#endif
|
||||
std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
|
||||
#undef CATCH_CONFIG_DEFAULT_REPORTER
|
||||
|
||||
std::vector<std::string> testsOrTags;
|
||||
std::vector<std::string> sectionsToRun;
|
||||
};
|
||||
|
||||
|
||||
class Config : public IConfig {
|
||||
public:
|
||||
|
||||
Config() = default;
|
||||
Config( ConfigData const& data );
|
||||
virtual ~Config() = default;
|
||||
|
||||
std::string const& getFilename() const;
|
||||
|
||||
bool listTests() const;
|
||||
bool listTags() const;
|
||||
bool listReporters() const;
|
||||
|
||||
std::string getProcessName() const;
|
||||
std::string const& getReporterName() const;
|
||||
|
||||
std::vector<std::string> const& getTestsOrTags() const override;
|
||||
std::vector<std::string> const& getSectionsToRun() const override;
|
||||
|
||||
TestSpec const& testSpec() const override;
|
||||
bool hasTestFilters() const override;
|
||||
|
||||
bool showHelp() const;
|
||||
|
||||
// IConfig interface
|
||||
bool allowThrows() const override;
|
||||
std::ostream& stream() const override;
|
||||
std::string name() const override;
|
||||
bool includeSuccessfulResults() const override;
|
||||
bool warnAboutMissingAssertions() const override;
|
||||
bool warnAboutNoTests() const override;
|
||||
ShowDurations::OrNot showDurations() const override;
|
||||
RunTests::InWhatOrder runOrder() const override;
|
||||
unsigned int rngSeed() const override;
|
||||
UseColour::YesOrNo useColour() const override;
|
||||
bool shouldDebugBreak() const override;
|
||||
int abortAfter() const override;
|
||||
bool showInvisibles() const override;
|
||||
Verbosity verbosity() const override;
|
||||
bool benchmarkNoAnalysis() const override;
|
||||
int benchmarkSamples() const override;
|
||||
double benchmarkConfidenceInterval() const override;
|
||||
unsigned int benchmarkResamples() const override;
|
||||
|
||||
private:
|
||||
|
||||
IStream const* openStream();
|
||||
ConfigData m_data;
|
||||
|
||||
std::unique_ptr<IStream const> m_stream;
|
||||
TestSpec m_testSpec;
|
||||
bool m_hasTestFilters = false;
|
||||
};
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED
|
243
src/internal/catch_console_colour.cpp
Normal file
243
src/internal/catch_console_colour.cpp
Normal file
@@ -0,0 +1,243 @@
|
||||
/*
|
||||
* Created by Phil on 25/2/2012.
|
||||
* Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
|
||||
#if defined(__clang__)
|
||||
# pragma clang diagnostic push
|
||||
# pragma clang diagnostic ignored "-Wexit-time-destructors"
|
||||
#endif
|
||||
|
||||
|
||||
#include "catch_console_colour.h"
|
||||
#include "catch_enforce.h"
|
||||
#include "catch_errno_guard.h"
|
||||
#include "catch_interfaces_config.h"
|
||||
#include "catch_stream.h"
|
||||
#include "catch_context.h"
|
||||
#include "catch_platform.h"
|
||||
#include "catch_debugger.h"
|
||||
#include "catch_windows_h_proxy.h"
|
||||
|
||||
#include <sstream>
|
||||
|
||||
namespace Catch {
|
||||
namespace {
|
||||
|
||||
struct IColourImpl {
|
||||
virtual ~IColourImpl() = default;
|
||||
virtual void use( Colour::Code _colourCode ) = 0;
|
||||
};
|
||||
|
||||
struct NoColourImpl : IColourImpl {
|
||||
void use( Colour::Code ) {}
|
||||
|
||||
static IColourImpl* instance() {
|
||||
static NoColourImpl s_instance;
|
||||
return &s_instance;
|
||||
}
|
||||
};
|
||||
|
||||
} // anon namespace
|
||||
} // namespace Catch
|
||||
|
||||
#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
|
||||
# ifdef CATCH_PLATFORM_WINDOWS
|
||||
# define CATCH_CONFIG_COLOUR_WINDOWS
|
||||
# else
|
||||
# define CATCH_CONFIG_COLOUR_ANSI
|
||||
# endif
|
||||
#endif
|
||||
|
||||
|
||||
#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
|
||||
|
||||
namespace Catch {
|
||||
namespace {
|
||||
|
||||
class Win32ColourImpl : public IColourImpl {
|
||||
public:
|
||||
Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
|
||||
{
|
||||
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
|
||||
GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
|
||||
originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
|
||||
originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
|
||||
}
|
||||
|
||||
void use( Colour::Code _colourCode ) override {
|
||||
switch( _colourCode ) {
|
||||
case Colour::None: return setTextAttribute( originalForegroundAttributes );
|
||||
case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
|
||||
case Colour::Red: return setTextAttribute( FOREGROUND_RED );
|
||||
case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
|
||||
case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
|
||||
case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
|
||||
case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
|
||||
case Colour::Grey: return setTextAttribute( 0 );
|
||||
|
||||
case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
|
||||
case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
|
||||
case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
|
||||
case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
|
||||
case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
|
||||
|
||||
case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
|
||||
|
||||
default:
|
||||
CATCH_ERROR( "Unknown colour requested" );
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void setTextAttribute( WORD _textAttribute ) {
|
||||
SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
|
||||
}
|
||||
HANDLE stdoutHandle;
|
||||
WORD originalForegroundAttributes;
|
||||
WORD originalBackgroundAttributes;
|
||||
};
|
||||
|
||||
IColourImpl* platformColourInstance() {
|
||||
static Win32ColourImpl s_instance;
|
||||
|
||||
IConfigPtr config = getCurrentContext().getConfig();
|
||||
UseColour::YesOrNo colourMode = config
|
||||
? config->useColour()
|
||||
: UseColour::Auto;
|
||||
if( colourMode == UseColour::Auto )
|
||||
colourMode = UseColour::Yes;
|
||||
return colourMode == UseColour::Yes
|
||||
? &s_instance
|
||||
: NoColourImpl::instance();
|
||||
}
|
||||
|
||||
} // end anon namespace
|
||||
} // end namespace Catch
|
||||
|
||||
#elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Catch {
|
||||
namespace {
|
||||
|
||||
// use POSIX/ ANSI console terminal codes
|
||||
// Thanks to Adam Strzelecki for original contribution
|
||||
// (http://github.com/nanoant)
|
||||
// https://github.com/philsquared/Catch/pull/131
|
||||
class PosixColourImpl : public IColourImpl {
|
||||
public:
|
||||
void use( Colour::Code _colourCode ) override {
|
||||
switch( _colourCode ) {
|
||||
case Colour::None:
|
||||
case Colour::White: return setColour( "[0m" );
|
||||
case Colour::Red: return setColour( "[0;31m" );
|
||||
case Colour::Green: return setColour( "[0;32m" );
|
||||
case Colour::Blue: return setColour( "[0;34m" );
|
||||
case Colour::Cyan: return setColour( "[0;36m" );
|
||||
case Colour::Yellow: return setColour( "[0;33m" );
|
||||
case Colour::Grey: return setColour( "[1;30m" );
|
||||
|
||||
case Colour::LightGrey: return setColour( "[0;37m" );
|
||||
case Colour::BrightRed: return setColour( "[1;31m" );
|
||||
case Colour::BrightGreen: return setColour( "[1;32m" );
|
||||
case Colour::BrightWhite: return setColour( "[1;37m" );
|
||||
case Colour::BrightYellow: return setColour( "[1;33m" );
|
||||
|
||||
case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
|
||||
default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
|
||||
}
|
||||
}
|
||||
static IColourImpl* instance() {
|
||||
static PosixColourImpl s_instance;
|
||||
return &s_instance;
|
||||
}
|
||||
|
||||
private:
|
||||
void setColour( const char* _escapeCode ) {
|
||||
getCurrentContext().getConfig()->stream()
|
||||
<< '\033' << _escapeCode;
|
||||
}
|
||||
};
|
||||
|
||||
bool useColourOnPlatform() {
|
||||
return
|
||||
#ifdef CATCH_PLATFORM_MAC
|
||||
!isDebuggerActive() &&
|
||||
#endif
|
||||
#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
|
||||
isatty(STDOUT_FILENO)
|
||||
#else
|
||||
false
|
||||
#endif
|
||||
;
|
||||
}
|
||||
IColourImpl* platformColourInstance() {
|
||||
ErrnoGuard guard;
|
||||
IConfigPtr config = getCurrentContext().getConfig();
|
||||
UseColour::YesOrNo colourMode = config
|
||||
? config->useColour()
|
||||
: UseColour::Auto;
|
||||
if( colourMode == UseColour::Auto )
|
||||
colourMode = useColourOnPlatform()
|
||||
? UseColour::Yes
|
||||
: UseColour::No;
|
||||
return colourMode == UseColour::Yes
|
||||
? PosixColourImpl::instance()
|
||||
: NoColourImpl::instance();
|
||||
}
|
||||
|
||||
} // end anon namespace
|
||||
} // end namespace Catch
|
||||
|
||||
#else // not Windows or ANSI ///////////////////////////////////////////////
|
||||
|
||||
namespace Catch {
|
||||
|
||||
static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // Windows/ ANSI/ None
|
||||
|
||||
namespace Catch {
|
||||
|
||||
Colour::Colour( Code _colourCode ) { use( _colourCode ); }
|
||||
Colour::Colour( Colour&& rhs ) noexcept {
|
||||
m_moved = rhs.m_moved;
|
||||
rhs.m_moved = true;
|
||||
}
|
||||
Colour& Colour::operator=( Colour&& rhs ) noexcept {
|
||||
m_moved = rhs.m_moved;
|
||||
rhs.m_moved = true;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Colour::~Colour(){ if( !m_moved ) use( None ); }
|
||||
|
||||
void Colour::use( Code _colourCode ) {
|
||||
static IColourImpl* impl = platformColourInstance();
|
||||
// Strictly speaking, this cannot possibly happen.
|
||||
// However, under some conditions it does happen (see #1626),
|
||||
// and this change is small enough that we can let practicality
|
||||
// triumph over purity in this case.
|
||||
if (impl != NULL) {
|
||||
impl->use( _colourCode );
|
||||
}
|
||||
}
|
||||
|
||||
std::ostream& operator << ( std::ostream& os, Colour const& ) {
|
||||
return os;
|
||||
}
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#if defined(__clang__)
|
||||
# pragma clang diagnostic pop
|
||||
#endif
|
||||
|
69
src/internal/catch_console_colour.h
Normal file
69
src/internal/catch_console_colour.h
Normal file
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Created by Phil on 25/2/2012.
|
||||
* Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_CONSOLE_COLOUR_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED
|
||||
|
||||
#include "catch_common.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct Colour {
|
||||
enum Code {
|
||||
None = 0,
|
||||
|
||||
White,
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
Cyan,
|
||||
Yellow,
|
||||
Grey,
|
||||
|
||||
Bright = 0x10,
|
||||
|
||||
BrightRed = Bright | Red,
|
||||
BrightGreen = Bright | Green,
|
||||
LightGrey = Bright | Grey,
|
||||
BrightWhite = Bright | White,
|
||||
BrightYellow = Bright | Yellow,
|
||||
|
||||
// By intention
|
||||
FileName = LightGrey,
|
||||
Warning = BrightYellow,
|
||||
ResultError = BrightRed,
|
||||
ResultSuccess = BrightGreen,
|
||||
ResultExpectedFailure = Warning,
|
||||
|
||||
Error = BrightRed,
|
||||
Success = Green,
|
||||
|
||||
OriginalExpression = Cyan,
|
||||
ReconstructedExpression = BrightYellow,
|
||||
|
||||
SecondaryText = LightGrey,
|
||||
Headers = White
|
||||
};
|
||||
|
||||
// Use constructed object for RAII guard
|
||||
Colour( Code _colourCode );
|
||||
Colour( Colour&& other ) noexcept;
|
||||
Colour& operator=( Colour&& other ) noexcept;
|
||||
~Colour();
|
||||
|
||||
// Use static method for one-shot changes
|
||||
static void use( Code _colourCode );
|
||||
|
||||
private:
|
||||
bool m_moved = false;
|
||||
};
|
||||
|
||||
std::ostream& operator << ( std::ostream& os, Colour const& );
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED
|
70
src/internal/catch_context.cpp
Normal file
70
src/internal/catch_context.cpp
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Created by Phil on 31/12/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_context.h"
|
||||
#include "catch_common.h"
|
||||
#include "catch_random_number_generator.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
class Context : public IMutableContext, NonCopyable {
|
||||
|
||||
public: // IContext
|
||||
IResultCapture* getResultCapture() override {
|
||||
return m_resultCapture;
|
||||
}
|
||||
IRunner* getRunner() override {
|
||||
return m_runner;
|
||||
}
|
||||
|
||||
IConfigPtr const& getConfig() const override {
|
||||
return m_config;
|
||||
}
|
||||
|
||||
~Context() override;
|
||||
|
||||
public: // IMutableContext
|
||||
void setResultCapture( IResultCapture* resultCapture ) override {
|
||||
m_resultCapture = resultCapture;
|
||||
}
|
||||
void setRunner( IRunner* runner ) override {
|
||||
m_runner = runner;
|
||||
}
|
||||
void setConfig( IConfigPtr const& config ) override {
|
||||
m_config = config;
|
||||
}
|
||||
|
||||
friend IMutableContext& getCurrentMutableContext();
|
||||
|
||||
private:
|
||||
IConfigPtr m_config;
|
||||
IRunner* m_runner = nullptr;
|
||||
IResultCapture* m_resultCapture = nullptr;
|
||||
};
|
||||
|
||||
IMutableContext *IMutableContext::currentContext = nullptr;
|
||||
|
||||
void IMutableContext::createContext()
|
||||
{
|
||||
currentContext = new Context();
|
||||
}
|
||||
|
||||
void cleanUpContext() {
|
||||
delete IMutableContext::currentContext;
|
||||
IMutableContext::currentContext = nullptr;
|
||||
}
|
||||
IContext::~IContext() = default;
|
||||
IMutableContext::~IMutableContext() = default;
|
||||
Context::~Context() = default;
|
||||
|
||||
|
||||
SimplePcg32& rng() {
|
||||
static SimplePcg32 s_rng;
|
||||
return s_rng;
|
||||
}
|
||||
|
||||
}
|
64
src/internal/catch_context.h
Normal file
64
src/internal/catch_context.h
Normal file
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Created by Phil on 31/12/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_CONTEXT_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct IResultCapture;
|
||||
struct IRunner;
|
||||
struct IConfig;
|
||||
struct IMutableContext;
|
||||
|
||||
using IConfigPtr = std::shared_ptr<IConfig const>;
|
||||
|
||||
struct IContext
|
||||
{
|
||||
virtual ~IContext();
|
||||
|
||||
virtual IResultCapture* getResultCapture() = 0;
|
||||
virtual IRunner* getRunner() = 0;
|
||||
virtual IConfigPtr const& getConfig() const = 0;
|
||||
};
|
||||
|
||||
struct IMutableContext : IContext
|
||||
{
|
||||
virtual ~IMutableContext();
|
||||
virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
|
||||
virtual void setRunner( IRunner* runner ) = 0;
|
||||
virtual void setConfig( IConfigPtr const& config ) = 0;
|
||||
|
||||
private:
|
||||
static IMutableContext *currentContext;
|
||||
friend IMutableContext& getCurrentMutableContext();
|
||||
friend void cleanUpContext();
|
||||
static void createContext();
|
||||
};
|
||||
|
||||
inline IMutableContext& getCurrentMutableContext()
|
||||
{
|
||||
if( !IMutableContext::currentContext )
|
||||
IMutableContext::createContext();
|
||||
// NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
|
||||
return *IMutableContext::currentContext;
|
||||
}
|
||||
|
||||
inline IContext& getCurrentContext()
|
||||
{
|
||||
return getCurrentMutableContext();
|
||||
}
|
||||
|
||||
void cleanUpContext();
|
||||
|
||||
class SimplePcg32;
|
||||
SimplePcg32& rng();
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED
|
41
src/internal/catch_debug_console.cpp
Normal file
41
src/internal/catch_debug_console.cpp
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Created by Martin on 29/08/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_debug_console.h"
|
||||
#include "catch_compiler_capabilities.h"
|
||||
#include "catch_stream.h"
|
||||
#include "catch_platform.h"
|
||||
#include "catch_windows_h_proxy.h"
|
||||
|
||||
#if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
|
||||
#include <android/log.h>
|
||||
|
||||
namespace Catch {
|
||||
void writeToDebugConsole( std::string const& text ) {
|
||||
__android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
|
||||
}
|
||||
}
|
||||
|
||||
#elif defined(CATCH_PLATFORM_WINDOWS)
|
||||
|
||||
namespace Catch {
|
||||
void writeToDebugConsole( std::string const& text ) {
|
||||
::OutputDebugStringA( text.c_str() );
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
namespace Catch {
|
||||
void writeToDebugConsole( std::string const& text ) {
|
||||
// !TBD: Need a version for Mac/ XCode and other IDEs
|
||||
Catch::cout() << text;
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Platform
|
17
src/internal/catch_debug_console.h
Normal file
17
src/internal/catch_debug_console.h
Normal file
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Created by Martin on 29/08/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_DEBUG_CONSOLE_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DEBUG_CONSOLE_H_INCLUDED
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Catch {
|
||||
void writeToDebugConsole( std::string const& text );
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DEBUG_CONSOLE_H_INCLUDED
|
123
src/internal/catch_debugger.cpp
Normal file
123
src/internal/catch_debugger.cpp
Normal file
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Created by Phil on 27/12/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_debugger.h"
|
||||
#include "catch_errno_guard.h"
|
||||
#include "catch_stream.h"
|
||||
#include "catch_platform.h"
|
||||
|
||||
#ifdef CATCH_PLATFORM_MAC
|
||||
|
||||
# include <assert.h>
|
||||
# include <stdbool.h>
|
||||
# include <sys/types.h>
|
||||
# include <unistd.h>
|
||||
# include <cstddef>
|
||||
# include <ostream>
|
||||
|
||||
#ifdef __apple_build_version__
|
||||
// These headers will only compile with AppleClang (XCode)
|
||||
// For other compilers (Clang, GCC, ... ) we need to exclude them
|
||||
# include <sys/sysctl.h>
|
||||
#endif
|
||||
|
||||
namespace Catch {
|
||||
#ifdef __apple_build_version__
|
||||
// The following function is taken directly from the following technical note:
|
||||
// https://developer.apple.com/library/archive/qa/qa1361/_index.html
|
||||
|
||||
// Returns true if the current process is being debugged (either
|
||||
// running under the debugger or has a debugger attached post facto).
|
||||
bool isDebuggerActive(){
|
||||
int mib[4];
|
||||
struct kinfo_proc info;
|
||||
std::size_t size;
|
||||
|
||||
// Initialize the flags so that, if sysctl fails for some bizarre
|
||||
// reason, we get a predictable result.
|
||||
|
||||
info.kp_proc.p_flag = 0;
|
||||
|
||||
// Initialize mib, which tells sysctl the info we want, in this case
|
||||
// we're looking for information about a specific process ID.
|
||||
|
||||
mib[0] = CTL_KERN;
|
||||
mib[1] = KERN_PROC;
|
||||
mib[2] = KERN_PROC_PID;
|
||||
mib[3] = getpid();
|
||||
|
||||
// Call sysctl.
|
||||
|
||||
size = sizeof(info);
|
||||
if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
|
||||
Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// We're being debugged if the P_TRACED flag is set.
|
||||
|
||||
return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
|
||||
}
|
||||
#else
|
||||
bool isDebuggerActive() {
|
||||
// We need to find another way to determine this for non-appleclang compilers on macOS
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
} // 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(){
|
||||
// Libstdc++ has a bug, where std::ifstream sets errno to 0
|
||||
// This way our users can properly assert over errno values
|
||||
ErrnoGuard guard;
|
||||
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)
|
||||
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
|
||||
namespace Catch {
|
||||
bool isDebuggerActive() {
|
||||
return IsDebuggerPresent() != 0;
|
||||
}
|
||||
}
|
||||
#elif defined(__MINGW32__)
|
||||
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
|
||||
namespace Catch {
|
||||
bool isDebuggerActive() {
|
||||
return IsDebuggerPresent() != 0;
|
||||
}
|
||||
}
|
||||
#else
|
||||
namespace Catch {
|
||||
bool isDebuggerActive() { return false; }
|
||||
}
|
||||
#endif // Platform
|
46
src/internal/catch_debugger.h
Normal file
46
src/internal/catch_debugger.h
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Created by Phil on 3/12/2013.
|
||||
* Copyright 2013 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_DEBUGGER_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED
|
||||
|
||||
#include "catch_platform.h"
|
||||
|
||||
namespace Catch {
|
||||
bool isDebuggerActive();
|
||||
}
|
||||
|
||||
#ifdef CATCH_PLATFORM_MAC
|
||||
|
||||
#define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
|
||||
|
||||
#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") /* NOLINT */
|
||||
#else // Fall back to the generic way.
|
||||
#include <signal.h>
|
||||
|
||||
#define CATCH_TRAP() raise(SIGTRAP)
|
||||
#endif
|
||||
#elif defined(_MSC_VER)
|
||||
#define CATCH_TRAP() __debugbreak()
|
||||
#elif defined(__MINGW32__)
|
||||
extern "C" __declspec(dllimport) void __stdcall DebugBreak();
|
||||
#define CATCH_TRAP() DebugBreak()
|
||||
#endif
|
||||
|
||||
#ifdef CATCH_TRAP
|
||||
#define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
|
||||
#else
|
||||
#define CATCH_BREAK_INTO_DEBUGGER() []{}()
|
||||
#endif
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED
|
24
src/internal/catch_decomposer.cpp
Normal file
24
src/internal/catch_decomposer.cpp
Normal file
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Created by Phil Nash on 8/8/2017.
|
||||
* Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_decomposer.h"
|
||||
#include "catch_config.hpp"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
ITransientExpression::~ITransientExpression() = default;
|
||||
|
||||
void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
|
||||
if( lhs.size() + rhs.size() < 40 &&
|
||||
lhs.find('\n') == std::string::npos &&
|
||||
rhs.find('\n') == std::string::npos )
|
||||
os << lhs << " " << op << " " << rhs;
|
||||
else
|
||||
os << lhs << "\n" << op << "\n" << rhs;
|
||||
}
|
||||
}
|
247
src/internal/catch_decomposer.h
Normal file
247
src/internal/catch_decomposer.h
Normal file
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* Created by Phil Nash on 8/8/2017.
|
||||
* Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_DECOMPOSER_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DECOMPOSER_H_INCLUDED
|
||||
|
||||
#include "catch_tostring.h"
|
||||
#include "catch_stringref.h"
|
||||
#include "catch_meta.hpp"
|
||||
|
||||
#include <iosfwd>
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable:4389) // '==' : signed/unsigned mismatch
|
||||
#pragma warning(disable:4018) // more "signed/unsigned mismatch"
|
||||
#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
|
||||
#pragma warning(disable:4180) // qualifier applied to function type has no meaning
|
||||
#pragma warning(disable:4800) // Forcing result to true or false
|
||||
#endif
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct ITransientExpression {
|
||||
auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
|
||||
auto getResult() const -> bool { return m_result; }
|
||||
virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
|
||||
|
||||
ITransientExpression( bool isBinaryExpression, bool result )
|
||||
: m_isBinaryExpression( isBinaryExpression ),
|
||||
m_result( result )
|
||||
{}
|
||||
|
||||
// We don't actually need a virtual destructor, but many static analysers
|
||||
// complain if it's not here :-(
|
||||
virtual ~ITransientExpression();
|
||||
|
||||
bool m_isBinaryExpression;
|
||||
bool m_result;
|
||||
|
||||
};
|
||||
|
||||
void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
|
||||
|
||||
template<typename LhsT, typename RhsT>
|
||||
class BinaryExpr : public ITransientExpression {
|
||||
LhsT m_lhs;
|
||||
StringRef m_op;
|
||||
RhsT m_rhs;
|
||||
|
||||
void streamReconstructedExpression( std::ostream &os ) const override {
|
||||
formatReconstructedExpression
|
||||
( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
|
||||
}
|
||||
|
||||
public:
|
||||
BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
|
||||
: ITransientExpression{ true, comparisonResult },
|
||||
m_lhs( lhs ),
|
||||
m_op( op ),
|
||||
m_rhs( rhs )
|
||||
{}
|
||||
|
||||
template<typename T>
|
||||
auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<T>::value,
|
||||
"chained comparisons are not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<T>::value,
|
||||
"chained comparisons are not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<T>::value,
|
||||
"chained comparisons are not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<T>::value,
|
||||
"chained comparisons are not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<T>::value,
|
||||
"chained comparisons are not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<T>::value,
|
||||
"chained comparisons are not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<T>::value,
|
||||
"chained comparisons are not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<T>::value,
|
||||
"chained comparisons are not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
};
|
||||
|
||||
template<typename LhsT>
|
||||
class UnaryExpr : public ITransientExpression {
|
||||
LhsT m_lhs;
|
||||
|
||||
void streamReconstructedExpression( std::ostream &os ) const override {
|
||||
os << Catch::Detail::stringify( m_lhs );
|
||||
}
|
||||
|
||||
public:
|
||||
explicit UnaryExpr( LhsT lhs )
|
||||
: ITransientExpression{ false, static_cast<bool>(lhs) },
|
||||
m_lhs( lhs )
|
||||
{}
|
||||
};
|
||||
|
||||
|
||||
// Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
|
||||
template<typename LhsT, typename RhsT>
|
||||
auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
|
||||
template<typename T>
|
||||
auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
|
||||
template<typename T>
|
||||
auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
|
||||
template<typename T>
|
||||
auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
|
||||
template<typename T>
|
||||
auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
|
||||
|
||||
template<typename LhsT, typename RhsT>
|
||||
auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
|
||||
template<typename T>
|
||||
auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
|
||||
template<typename T>
|
||||
auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
|
||||
template<typename T>
|
||||
auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
|
||||
template<typename T>
|
||||
auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
|
||||
|
||||
|
||||
template<typename LhsT>
|
||||
class ExprLhs {
|
||||
LhsT m_lhs;
|
||||
public:
|
||||
explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
|
||||
|
||||
template<typename RhsT>
|
||||
auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
|
||||
}
|
||||
auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
|
||||
return { m_lhs == rhs, m_lhs, "==", rhs };
|
||||
}
|
||||
|
||||
template<typename RhsT>
|
||||
auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
|
||||
}
|
||||
auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
|
||||
return { m_lhs != rhs, m_lhs, "!=", rhs };
|
||||
}
|
||||
|
||||
template<typename RhsT>
|
||||
auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
|
||||
}
|
||||
template<typename RhsT>
|
||||
auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
|
||||
}
|
||||
template<typename RhsT>
|
||||
auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
|
||||
}
|
||||
template<typename RhsT>
|
||||
auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
|
||||
}
|
||||
|
||||
template<typename RhsT>
|
||||
auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<RhsT>::value,
|
||||
"operator&& is not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
template<typename RhsT>
|
||||
auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
|
||||
static_assert(always_false<RhsT>::value,
|
||||
"operator|| is not supported inside assertions, "
|
||||
"wrap the expression inside parentheses, or decompose it");
|
||||
}
|
||||
|
||||
auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
|
||||
return UnaryExpr<LhsT>{ m_lhs };
|
||||
}
|
||||
};
|
||||
|
||||
void handleExpression( ITransientExpression const& expr );
|
||||
|
||||
template<typename T>
|
||||
void handleExpression( ExprLhs<T> const& expr ) {
|
||||
handleExpression( expr.makeUnaryExpr() );
|
||||
}
|
||||
|
||||
struct Decomposer {
|
||||
template<typename T>
|
||||
auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
|
||||
return ExprLhs<T const&>{ lhs };
|
||||
}
|
||||
|
||||
auto operator <=( bool value ) -> ExprLhs<bool> {
|
||||
return ExprLhs<bool>{ value };
|
||||
}
|
||||
};
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DECOMPOSER_H_INCLUDED
|
46
src/internal/catch_default_main.hpp
Normal file
46
src/internal/catch_default_main.hpp
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Created by Phil on 20/05/2011.
|
||||
* Copyright 2011 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_DEFAULT_MAIN_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED
|
||||
|
||||
#include "catch_session.h"
|
||||
|
||||
#ifndef __OBJC__
|
||||
|
||||
#if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
|
||||
// Standard C/C++ Win32 Unicode wmain entry point
|
||||
extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
|
||||
#else
|
||||
// Standard C/C++ main entry point
|
||||
int main (int argc, char * argv[]) {
|
||||
#endif
|
||||
|
||||
return Catch::Session().run( argc, argv );
|
||||
}
|
||||
|
||||
#else // __OBJC__
|
||||
|
||||
// Objective-C entry point
|
||||
int main (int argc, char * const argv[]) {
|
||||
#if !CATCH_ARC_ENABLED
|
||||
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
|
||||
#endif
|
||||
|
||||
Catch::registerTestMethods();
|
||||
int result = Catch::Session().run( argc, (char**)argv );
|
||||
|
||||
#if !CATCH_ARC_ENABLED
|
||||
[pool drain];
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif // __OBJC__
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED
|
40
src/internal/catch_enforce.cpp
Normal file
40
src/internal/catch_enforce.cpp
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Created by Martin on 03/09/2018.
|
||||
*
|
||||
* 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_enforce.h"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
|
||||
namespace Catch {
|
||||
#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
|
||||
[[noreturn]]
|
||||
void throw_exception(std::exception const& e) {
|
||||
Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
|
||||
<< "The message was: " << e.what() << '\n';
|
||||
std::terminate();
|
||||
}
|
||||
#endif
|
||||
|
||||
[[noreturn]]
|
||||
void throw_logic_error(std::string const& msg) {
|
||||
throw_exception(std::logic_error(msg));
|
||||
}
|
||||
|
||||
[[noreturn]]
|
||||
void throw_domain_error(std::string const& msg) {
|
||||
throw_exception(std::domain_error(msg));
|
||||
}
|
||||
|
||||
[[noreturn]]
|
||||
void throw_runtime_error(std::string const& msg) {
|
||||
throw_exception(std::runtime_error(msg));
|
||||
}
|
||||
|
||||
|
||||
|
||||
} // namespace Catch;
|
53
src/internal/catch_enforce.h
Normal file
53
src/internal/catch_enforce.h
Normal file
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Created by Martin on 01/08/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_ENFORCE_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_ENFORCE_H_INCLUDED
|
||||
|
||||
#include "catch_common.h"
|
||||
#include "catch_compiler_capabilities.h"
|
||||
#include "catch_stream.h"
|
||||
|
||||
#include <exception>
|
||||
|
||||
namespace Catch {
|
||||
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
|
||||
template <typename Ex>
|
||||
[[noreturn]]
|
||||
void throw_exception(Ex const& e) {
|
||||
throw e;
|
||||
}
|
||||
#else // ^^ Exceptions are enabled // Exceptions are disabled vv
|
||||
[[noreturn]]
|
||||
void throw_exception(std::exception const& e);
|
||||
#endif
|
||||
|
||||
[[noreturn]]
|
||||
void throw_logic_error(std::string const& msg);
|
||||
[[noreturn]]
|
||||
void throw_domain_error(std::string const& msg);
|
||||
[[noreturn]]
|
||||
void throw_runtime_error(std::string const& msg);
|
||||
|
||||
} // namespace Catch;
|
||||
|
||||
#define CATCH_MAKE_MSG(...) \
|
||||
(Catch::ReusableStringStream() << __VA_ARGS__).str()
|
||||
|
||||
#define CATCH_INTERNAL_ERROR(...) \
|
||||
Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
|
||||
|
||||
#define CATCH_ERROR(...) \
|
||||
Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
|
||||
|
||||
#define CATCH_RUNTIME_ERROR(...) \
|
||||
Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
|
||||
|
||||
#define CATCH_ENFORCE( condition, ... ) \
|
||||
do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
|
||||
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_ENFORCE_H_INCLUDED
|
75
src/internal/catch_enum_values_registry.cpp
Normal file
75
src/internal/catch_enum_values_registry.cpp
Normal file
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Created by Phil on 4/4/2019.
|
||||
* Copyright 2019 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_enum_values_registry.h"
|
||||
#include "catch_string_manip.h"
|
||||
#include "catch_stream.h"
|
||||
|
||||
#include <map>
|
||||
#include <cassert>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
|
||||
|
||||
namespace Detail {
|
||||
|
||||
namespace {
|
||||
// Extracts the actual name part of an enum instance
|
||||
// In other words, it returns the Blue part of Bikeshed::Colour::Blue
|
||||
StringRef extractInstanceName(StringRef enumInstance) {
|
||||
// Find last occurence of ":"
|
||||
size_t name_start = enumInstance.size();
|
||||
while (name_start > 0 && enumInstance[name_start - 1] != ':') {
|
||||
--name_start;
|
||||
}
|
||||
return enumInstance.substr(name_start, enumInstance.size() - name_start);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<StringRef> parseEnums( StringRef enums ) {
|
||||
auto enumValues = splitStringRef( enums, ',' );
|
||||
std::vector<StringRef> parsed;
|
||||
parsed.reserve( enumValues.size() );
|
||||
for( auto const& enumValue : enumValues ) {
|
||||
parsed.push_back(trim(extractInstanceName(enumValue)));
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
EnumInfo::~EnumInfo() {}
|
||||
|
||||
StringRef EnumInfo::lookup( int value ) const {
|
||||
for( auto const& valueToName : m_values ) {
|
||||
if( valueToName.first == value )
|
||||
return valueToName.second;
|
||||
}
|
||||
return "{** unexpected enum value **}"_sr;
|
||||
}
|
||||
|
||||
std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
|
||||
std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
|
||||
enumInfo->m_name = enumName;
|
||||
enumInfo->m_values.reserve( values.size() );
|
||||
|
||||
const auto valueNames = Catch::Detail::parseEnums( allValueNames );
|
||||
assert( valueNames.size() == values.size() );
|
||||
std::size_t i = 0;
|
||||
for( auto value : values )
|
||||
enumInfo->m_values.push_back({ value, valueNames[i++] });
|
||||
|
||||
return enumInfo;
|
||||
}
|
||||
|
||||
EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
|
||||
m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
|
||||
return *m_enumInfos.back();
|
||||
}
|
||||
|
||||
} // Detail
|
||||
} // Catch
|
||||
|
35
src/internal/catch_enum_values_registry.h
Normal file
35
src/internal/catch_enum_values_registry.h
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Created by Phil on 4/4/2019.
|
||||
* Copyright 2019 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_ENUMVALUESREGISTRY_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_ENUMVALUESREGISTRY_H_INCLUDED
|
||||
|
||||
#include "catch_interfaces_enum_values_registry.h"
|
||||
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
namespace Detail {
|
||||
|
||||
std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
|
||||
|
||||
class EnumValuesRegistry : public IMutableEnumValuesRegistry {
|
||||
|
||||
std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
|
||||
|
||||
EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
|
||||
};
|
||||
|
||||
std::vector<StringRef> parseEnums( StringRef enums );
|
||||
|
||||
} // Detail
|
||||
|
||||
} // Catch
|
||||
|
||||
#endif //TWOBLUECUBES_CATCH_ENUMVALUESREGISTRY_H_INCLUDED
|
15
src/internal/catch_errno_guard.cpp
Normal file
15
src/internal/catch_errno_guard.cpp
Normal file
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Created by Martin on 06/03/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_errno_guard.h"
|
||||
|
||||
#include <cerrno>
|
||||
|
||||
namespace Catch {
|
||||
ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
|
||||
ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
|
||||
}
|
22
src/internal/catch_errno_guard.h
Normal file
22
src/internal/catch_errno_guard.h
Normal file
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Created by Martin on 06/03/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_ERRNO_GUARD_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_ERRNO_GUARD_H_INCLUDED
|
||||
|
||||
namespace Catch {
|
||||
|
||||
class ErrnoGuard {
|
||||
public:
|
||||
ErrnoGuard();
|
||||
~ErrnoGuard();
|
||||
private:
|
||||
int m_oldErrno;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_ERRNO_GUARD_H_INCLUDED
|
89
src/internal/catch_exception_translator_registry.cpp
Normal file
89
src/internal/catch_exception_translator_registry.cpp
Normal file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Created by Phil on 20/04/2011.
|
||||
* Copyright 2011 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_exception_translator_registry.h"
|
||||
#include "catch_assertionhandler.h"
|
||||
#include "catch_compiler_capabilities.h"
|
||||
#include "catch_enforce.h"
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import "Foundation/Foundation.h"
|
||||
#endif
|
||||
|
||||
namespace Catch {
|
||||
|
||||
ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
|
||||
}
|
||||
|
||||
void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
|
||||
m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
|
||||
}
|
||||
|
||||
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
|
||||
std::string ExceptionTranslatorRegistry::translateActiveException() const {
|
||||
try {
|
||||
#ifdef __OBJC__
|
||||
// In Objective-C try objective-c exceptions first
|
||||
@try {
|
||||
return tryTranslators();
|
||||
}
|
||||
@catch (NSException *exception) {
|
||||
return Catch::Detail::stringify( [exception description] );
|
||||
}
|
||||
#else
|
||||
// Compiling a mixed mode project with MSVC means that CLR
|
||||
// exceptions will be caught in (...) as well. However, these
|
||||
// do not fill-in std::current_exception and thus lead to crash
|
||||
// when attempting rethrow.
|
||||
// /EHa switch also causes structured exceptions to be caught
|
||||
// here, but they fill-in current_exception properly, so
|
||||
// at worst the output should be a little weird, instead of
|
||||
// causing a crash.
|
||||
if (std::current_exception() == nullptr) {
|
||||
return "Non C++ exception. Possibly a CLR exception.";
|
||||
}
|
||||
return tryTranslators();
|
||||
#endif
|
||||
}
|
||||
catch( TestFailureException& ) {
|
||||
std::rethrow_exception(std::current_exception());
|
||||
}
|
||||
catch( std::exception& ex ) {
|
||||
return ex.what();
|
||||
}
|
||||
catch( std::string& msg ) {
|
||||
return msg;
|
||||
}
|
||||
catch( const char* msg ) {
|
||||
return msg;
|
||||
}
|
||||
catch(...) {
|
||||
return "Unknown exception";
|
||||
}
|
||||
}
|
||||
|
||||
std::string ExceptionTranslatorRegistry::tryTranslators() const {
|
||||
if (m_translators.empty()) {
|
||||
std::rethrow_exception(std::current_exception());
|
||||
} else {
|
||||
return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
|
||||
}
|
||||
}
|
||||
|
||||
#else // ^^ Exceptions are enabled // Exceptions are disabled vv
|
||||
std::string ExceptionTranslatorRegistry::translateActiveException() const {
|
||||
CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
|
||||
}
|
||||
|
||||
std::string ExceptionTranslatorRegistry::tryTranslators() const {
|
||||
CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
}
|
30
src/internal/catch_exception_translator_registry.h
Normal file
30
src/internal/catch_exception_translator_registry.h
Normal file
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Created by Phil on 20/04/2011.
|
||||
* Copyright 2011 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
|
||||
|
||||
#include "catch_interfaces_exception.h"
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
|
||||
public:
|
||||
~ExceptionTranslatorRegistry();
|
||||
virtual void registerTranslator( const IExceptionTranslator* translator );
|
||||
std::string translateActiveException() const override;
|
||||
std::string tryTranslators() const;
|
||||
|
||||
private:
|
||||
std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
|
20
src/internal/catch_external_interfaces.h
Normal file
20
src/internal/catch_external_interfaces.h
Normal file
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Created by Martin on 17/08/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_EXTERNAL_INTERFACES_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_EXTERNAL_INTERFACES_H_INCLUDED
|
||||
|
||||
#include "../reporters/catch_reporter_bases.hpp"
|
||||
#include "catch_console_colour.h"
|
||||
#include "catch_reporter_registrars.hpp"
|
||||
|
||||
// Allow users to base their work off existing reporters
|
||||
#include "../reporters/catch_reporter_compact.h"
|
||||
#include "../reporters/catch_reporter_console.h"
|
||||
#include "../reporters/catch_reporter_junit.h"
|
||||
#include "../reporters/catch_reporter_xml.h"
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_EXTERNAL_INTERFACES_H_INCLUDED
|
176
src/internal/catch_fatal_condition.cpp
Normal file
176
src/internal/catch_fatal_condition.cpp
Normal file
@@ -0,0 +1,176 @@
|
||||
/*
|
||||
* Created by Phil on 21/08/2014
|
||||
* Copyright 2014 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_fatal_condition.h"
|
||||
|
||||
#include "catch_context.h"
|
||||
#include "catch_interfaces_capture.h"
|
||||
|
||||
#if defined(__GNUC__)
|
||||
# pragma GCC diagnostic push
|
||||
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
|
||||
#endif
|
||||
|
||||
#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
|
||||
|
||||
namespace {
|
||||
// Report the error condition
|
||||
void reportFatal( char const * const message ) {
|
||||
Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
|
||||
}
|
||||
}
|
||||
|
||||
#endif // signals/SEH handling
|
||||
|
||||
#if defined( CATCH_CONFIG_WINDOWS_SEH )
|
||||
|
||||
namespace Catch {
|
||||
struct SignalDefs { DWORD id; const char* name; };
|
||||
|
||||
// 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.
|
||||
static SignalDefs signalDefs[] = {
|
||||
{ static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
|
||||
{ static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
|
||||
{ static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
|
||||
{ static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
|
||||
};
|
||||
|
||||
LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
|
||||
for (auto const& def : signalDefs) {
|
||||
if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
|
||||
reportFatal(def.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::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 = nullptr;
|
||||
// Register as first handler in current chain
|
||||
exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
|
||||
// Pass in guarantee size to be filled
|
||||
SetThreadStackGuarantee(&guaranteeSize);
|
||||
}
|
||||
|
||||
void FatalConditionHandler::reset() {
|
||||
if (isSet) {
|
||||
RemoveVectoredExceptionHandler(exceptionHandlerHandle);
|
||||
SetThreadStackGuarantee(&guaranteeSize);
|
||||
exceptionHandlerHandle = nullptr;
|
||||
isSet = false;
|
||||
}
|
||||
}
|
||||
|
||||
FatalConditionHandler::~FatalConditionHandler() {
|
||||
reset();
|
||||
}
|
||||
|
||||
bool FatalConditionHandler::isSet = false;
|
||||
ULONG FatalConditionHandler::guaranteeSize = 0;
|
||||
PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
|
||||
|
||||
|
||||
} // namespace Catch
|
||||
|
||||
#elif defined( CATCH_CONFIG_POSIX_SIGNALS )
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct SignalDefs {
|
||||
int id;
|
||||
const char* name;
|
||||
};
|
||||
|
||||
// 32kb for the alternate stack seems to be sufficient. However, this value
|
||||
// is experimentally determined, so that's not guaranteed.
|
||||
static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
|
||||
|
||||
static SignalDefs signalDefs[] = {
|
||||
{ SIGINT, "SIGINT - Terminal interrupt signal" },
|
||||
{ SIGILL, "SIGILL - Illegal instruction signal" },
|
||||
{ SIGFPE, "SIGFPE - Floating point error signal" },
|
||||
{ SIGSEGV, "SIGSEGV - Segmentation violation signal" },
|
||||
{ SIGTERM, "SIGTERM - Termination request signal" },
|
||||
{ SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
|
||||
};
|
||||
|
||||
|
||||
void FatalConditionHandler::handleSignal( int sig ) {
|
||||
char const * name = "<unknown signal>";
|
||||
for (auto const& def : signalDefs) {
|
||||
if (sig == def.id) {
|
||||
name = def.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
reset();
|
||||
reportFatal(name);
|
||||
raise( sig );
|
||||
}
|
||||
|
||||
FatalConditionHandler::FatalConditionHandler() {
|
||||
isSet = true;
|
||||
stack_t sigStack;
|
||||
sigStack.ss_sp = altStackMem;
|
||||
sigStack.ss_size = sigStackSize;
|
||||
sigStack.ss_flags = 0;
|
||||
sigaltstack(&sigStack, &oldSigStack);
|
||||
struct sigaction sa = { };
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
void FatalConditionHandler::reset() {
|
||||
if( isSet ) {
|
||||
// Set signals back to previous values -- hopefully nobody overwrote them in the meantime
|
||||
for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
|
||||
sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
|
||||
}
|
||||
// Return the old stack
|
||||
sigaltstack(&oldSigStack, nullptr);
|
||||
isSet = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool FatalConditionHandler::isSet = false;
|
||||
struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
|
||||
stack_t FatalConditionHandler::oldSigStack = {};
|
||||
char FatalConditionHandler::altStackMem[sigStackSize] = {};
|
||||
|
||||
|
||||
} // namespace Catch
|
||||
|
||||
#else
|
||||
|
||||
namespace Catch {
|
||||
void FatalConditionHandler::reset() {}
|
||||
}
|
||||
|
||||
#endif // signals/SEH handling
|
||||
|
||||
#if defined(__GNUC__)
|
||||
# pragma GCC diagnostic pop
|
||||
#endif
|
69
src/internal/catch_fatal_condition.h
Normal file
69
src/internal/catch_fatal_condition.h
Normal file
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Created by Phil on 21/08/2014
|
||||
* Copyright 2014 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_FATAL_CONDITION_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED
|
||||
|
||||
#include "catch_platform.h"
|
||||
#include "catch_compiler_capabilities.h"
|
||||
#include "catch_windows_h_proxy.h"
|
||||
|
||||
|
||||
#if defined( CATCH_CONFIG_WINDOWS_SEH )
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct FatalConditionHandler {
|
||||
|
||||
static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
|
||||
FatalConditionHandler();
|
||||
static void reset();
|
||||
~FatalConditionHandler();
|
||||
|
||||
private:
|
||||
static bool isSet;
|
||||
static ULONG guaranteeSize;
|
||||
static PVOID exceptionHandlerHandle;
|
||||
};
|
||||
|
||||
} // namespace Catch
|
||||
|
||||
#elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
|
||||
|
||||
#include <signal.h>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct FatalConditionHandler {
|
||||
|
||||
static bool isSet;
|
||||
static struct sigaction oldSigActions[];
|
||||
static stack_t oldSigStack;
|
||||
static char altStackMem[];
|
||||
|
||||
static void handleSignal( int sig );
|
||||
|
||||
FatalConditionHandler();
|
||||
~FatalConditionHandler();
|
||||
static void reset();
|
||||
};
|
||||
|
||||
} // namespace Catch
|
||||
|
||||
|
||||
#else
|
||||
|
||||
namespace Catch {
|
||||
struct FatalConditionHandler {
|
||||
void reset();
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED
|
32
src/internal/catch_generators.cpp
Normal file
32
src/internal/catch_generators.cpp
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Created by Phil Nash on 15/6/2018.
|
||||
*
|
||||
* 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_generators.hpp"
|
||||
#include "catch_random_number_generator.h"
|
||||
#include "catch_interfaces_capture.h"
|
||||
|
||||
#include <limits>
|
||||
#include <set>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
IGeneratorTracker::~IGeneratorTracker() {}
|
||||
|
||||
const char* GeneratorException::what() const noexcept {
|
||||
return m_msg;
|
||||
}
|
||||
|
||||
namespace Generators {
|
||||
|
||||
GeneratorUntypedBase::~GeneratorUntypedBase() {}
|
||||
|
||||
auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
|
||||
return getResultCapture().acquireGeneratorTracker( lineInfo );
|
||||
}
|
||||
|
||||
} // namespace Generators
|
||||
} // namespace Catch
|
213
src/internal/catch_generators.hpp
Normal file
213
src/internal/catch_generators.hpp
Normal file
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* Created by Phil Nash on 15/6/2018.
|
||||
*
|
||||
* 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_GENERATORS_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED
|
||||
|
||||
#include "catch_interfaces_generatortracker.h"
|
||||
#include "catch_common.h"
|
||||
#include "catch_enforce.h"
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <cassert>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
#include <exception>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
class GeneratorException : public std::exception {
|
||||
const char* const m_msg = "";
|
||||
|
||||
public:
|
||||
GeneratorException(const char* msg):
|
||||
m_msg(msg)
|
||||
{}
|
||||
|
||||
const char* what() const noexcept override final;
|
||||
};
|
||||
|
||||
namespace Generators {
|
||||
|
||||
// !TBD move this into its own location?
|
||||
namespace pf{
|
||||
template<typename T, typename... Args>
|
||||
std::unique_ptr<T> make_unique( Args&&... args ) {
|
||||
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
struct IGenerator : GeneratorUntypedBase {
|
||||
virtual ~IGenerator() = default;
|
||||
|
||||
// Returns the current element of the generator
|
||||
//
|
||||
// \Precondition The generator is either freshly constructed,
|
||||
// or the last call to `next()` returned true
|
||||
virtual T const& get() const = 0;
|
||||
using type = T;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
class SingleValueGenerator final : public IGenerator<T> {
|
||||
T m_value;
|
||||
public:
|
||||
SingleValueGenerator(T const& value) : m_value( value ) {}
|
||||
SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
|
||||
|
||||
T const& get() const override {
|
||||
return m_value;
|
||||
}
|
||||
bool next() override {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
class FixedValuesGenerator final : public IGenerator<T> {
|
||||
static_assert(!std::is_same<T, bool>::value,
|
||||
"FixedValuesGenerator does not support bools because of std::vector<bool>"
|
||||
"specialization, use SingleValue Generator instead.");
|
||||
std::vector<T> m_values;
|
||||
size_t m_idx = 0;
|
||||
public:
|
||||
FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
|
||||
|
||||
T const& get() const override {
|
||||
return m_values[m_idx];
|
||||
}
|
||||
bool next() override {
|
||||
++m_idx;
|
||||
return m_idx < m_values.size();
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class GeneratorWrapper final {
|
||||
std::unique_ptr<IGenerator<T>> m_generator;
|
||||
public:
|
||||
GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
|
||||
m_generator(std::move(generator))
|
||||
{}
|
||||
T const& get() const {
|
||||
return m_generator->get();
|
||||
}
|
||||
bool next() {
|
||||
return m_generator->next();
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
GeneratorWrapper<T> value(T&& value) {
|
||||
return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
|
||||
}
|
||||
template <typename T>
|
||||
GeneratorWrapper<T> values(std::initializer_list<T> values) {
|
||||
return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
class Generators : public IGenerator<T> {
|
||||
std::vector<GeneratorWrapper<T>> m_generators;
|
||||
size_t m_current = 0;
|
||||
|
||||
void populate(GeneratorWrapper<T>&& generator) {
|
||||
m_generators.emplace_back(std::move(generator));
|
||||
}
|
||||
void populate(T&& val) {
|
||||
m_generators.emplace_back(value(std::move(val)));
|
||||
}
|
||||
template<typename U>
|
||||
void populate(U&& val) {
|
||||
populate(T(std::move(val)));
|
||||
}
|
||||
template<typename U, typename... Gs>
|
||||
void populate(U&& valueOrGenerator, Gs... moreGenerators) {
|
||||
populate(std::forward<U>(valueOrGenerator));
|
||||
populate(std::forward<Gs>(moreGenerators)...);
|
||||
}
|
||||
|
||||
public:
|
||||
template <typename... Gs>
|
||||
Generators(Gs... moreGenerators) {
|
||||
m_generators.reserve(sizeof...(Gs));
|
||||
populate(std::forward<Gs>(moreGenerators)...);
|
||||
}
|
||||
|
||||
T const& get() const override {
|
||||
return m_generators[m_current].get();
|
||||
}
|
||||
|
||||
bool next() override {
|
||||
if (m_current >= m_generators.size()) {
|
||||
return false;
|
||||
}
|
||||
const bool current_status = m_generators[m_current].next();
|
||||
if (!current_status) {
|
||||
++m_current;
|
||||
}
|
||||
return m_current < m_generators.size();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template<typename... Ts>
|
||||
GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
|
||||
return values<std::tuple<Ts...>>( tuples );
|
||||
}
|
||||
|
||||
// Tag type to signal that a generator sequence should convert arguments to a specific type
|
||||
template <typename T>
|
||||
struct as {};
|
||||
|
||||
template<typename T, typename... Gs>
|
||||
auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
|
||||
return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
|
||||
}
|
||||
template<typename T>
|
||||
auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
|
||||
return Generators<T>(std::move(generator));
|
||||
}
|
||||
template<typename T, typename... Gs>
|
||||
auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
|
||||
return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
|
||||
}
|
||||
template<typename T, typename U, typename... Gs>
|
||||
auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
|
||||
return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
|
||||
}
|
||||
|
||||
auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
|
||||
|
||||
template<typename L>
|
||||
// Note: The type after -> is weird, because VS2015 cannot parse
|
||||
// the expression used in the typedef inside, when it is in
|
||||
// return type. Yeah.
|
||||
auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
|
||||
using UnderlyingType = typename decltype(generatorExpression())::type;
|
||||
|
||||
IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
|
||||
if (!tracker.hasGenerator()) {
|
||||
tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
|
||||
}
|
||||
|
||||
auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
|
||||
return generator.get();
|
||||
}
|
||||
|
||||
} // namespace Generators
|
||||
} // namespace Catch
|
||||
|
||||
#define GENERATE( ... ) \
|
||||
Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
|
||||
#define GENERATE_COPY( ... ) \
|
||||
Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
|
||||
#define GENERATE_REF( ... ) \
|
||||
Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED
|
237
src/internal/catch_generators_generic.hpp
Normal file
237
src/internal/catch_generators_generic.hpp
Normal file
@@ -0,0 +1,237 @@
|
||||
/*
|
||||
* Created by Martin on 23/2/2019.
|
||||
*
|
||||
* 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_GENERATORS_GENERIC_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_GENERATORS_GENERIC_HPP_INCLUDED
|
||||
|
||||
#include "catch_generators.hpp"
|
||||
#include "catch_meta.hpp"
|
||||
|
||||
namespace Catch {
|
||||
namespace Generators {
|
||||
|
||||
template <typename T>
|
||||
class TakeGenerator : public IGenerator<T> {
|
||||
GeneratorWrapper<T> m_generator;
|
||||
size_t m_returned = 0;
|
||||
size_t m_target;
|
||||
public:
|
||||
TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
|
||||
m_generator(std::move(generator)),
|
||||
m_target(target)
|
||||
{
|
||||
assert(target != 0 && "Empty generators are not allowed");
|
||||
}
|
||||
T const& get() const override {
|
||||
return m_generator.get();
|
||||
}
|
||||
bool next() override {
|
||||
++m_returned;
|
||||
if (m_returned >= m_target) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto success = m_generator.next();
|
||||
// If the underlying generator does not contain enough values
|
||||
// then we cut short as well
|
||||
if (!success) {
|
||||
m_returned = m_target;
|
||||
}
|
||||
return success;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
|
||||
return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
|
||||
}
|
||||
|
||||
|
||||
template <typename T, typename Predicate>
|
||||
class FilterGenerator : public IGenerator<T> {
|
||||
GeneratorWrapper<T> m_generator;
|
||||
Predicate m_predicate;
|
||||
public:
|
||||
template <typename P = Predicate>
|
||||
FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
|
||||
m_generator(std::move(generator)),
|
||||
m_predicate(std::forward<P>(pred))
|
||||
{
|
||||
if (!m_predicate(m_generator.get())) {
|
||||
// It might happen that there are no values that pass the
|
||||
// filter. In that case we throw an exception.
|
||||
auto has_initial_value = next();
|
||||
if (!has_initial_value) {
|
||||
Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
T const& get() const override {
|
||||
return m_generator.get();
|
||||
}
|
||||
|
||||
bool next() override {
|
||||
bool success = m_generator.next();
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
|
||||
return success;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename T, typename Predicate>
|
||||
GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
|
||||
return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class RepeatGenerator : public IGenerator<T> {
|
||||
static_assert(!std::is_same<T, bool>::value,
|
||||
"RepeatGenerator currently does not support bools"
|
||||
"because of std::vector<bool> specialization");
|
||||
GeneratorWrapper<T> m_generator;
|
||||
mutable std::vector<T> m_returned;
|
||||
size_t m_target_repeats;
|
||||
size_t m_current_repeat = 0;
|
||||
size_t m_repeat_index = 0;
|
||||
public:
|
||||
RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
|
||||
m_generator(std::move(generator)),
|
||||
m_target_repeats(repeats)
|
||||
{
|
||||
assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
|
||||
}
|
||||
|
||||
T const& get() const override {
|
||||
if (m_current_repeat == 0) {
|
||||
m_returned.push_back(m_generator.get());
|
||||
return m_returned.back();
|
||||
}
|
||||
return m_returned[m_repeat_index];
|
||||
}
|
||||
|
||||
bool next() override {
|
||||
// There are 2 basic cases:
|
||||
// 1) We are still reading the generator
|
||||
// 2) We are reading our own cache
|
||||
|
||||
// In the first case, we need to poke the underlying generator.
|
||||
// If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
|
||||
if (m_current_repeat == 0) {
|
||||
const auto success = m_generator.next();
|
||||
if (!success) {
|
||||
++m_current_repeat;
|
||||
}
|
||||
return m_current_repeat < m_target_repeats;
|
||||
}
|
||||
|
||||
// In the second case, we need to move indices forward and check that we haven't run up against the end
|
||||
++m_repeat_index;
|
||||
if (m_repeat_index == m_returned.size()) {
|
||||
m_repeat_index = 0;
|
||||
++m_current_repeat;
|
||||
}
|
||||
return m_current_repeat < m_target_repeats;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
|
||||
return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
|
||||
}
|
||||
|
||||
template <typename T, typename U, typename Func>
|
||||
class MapGenerator : public IGenerator<T> {
|
||||
// TBD: provide static assert for mapping function, for friendly error message
|
||||
GeneratorWrapper<U> m_generator;
|
||||
Func m_function;
|
||||
// To avoid returning dangling reference, we have to save the values
|
||||
T m_cache;
|
||||
public:
|
||||
template <typename F2 = Func>
|
||||
MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
|
||||
m_generator(std::move(generator)),
|
||||
m_function(std::forward<F2>(function)),
|
||||
m_cache(m_function(m_generator.get()))
|
||||
{}
|
||||
|
||||
T const& get() const override {
|
||||
return m_cache;
|
||||
}
|
||||
bool next() override {
|
||||
const auto success = m_generator.next();
|
||||
if (success) {
|
||||
m_cache = m_function(m_generator.get());
|
||||
}
|
||||
return success;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
|
||||
GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
|
||||
return GeneratorWrapper<T>(
|
||||
pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
|
||||
);
|
||||
}
|
||||
|
||||
template <typename T, typename U, typename Func>
|
||||
GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
|
||||
return GeneratorWrapper<T>(
|
||||
pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
|
||||
);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class ChunkGenerator final : public IGenerator<std::vector<T>> {
|
||||
std::vector<T> m_chunk;
|
||||
size_t m_chunk_size;
|
||||
GeneratorWrapper<T> m_generator;
|
||||
bool m_used_up = false;
|
||||
public:
|
||||
ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
|
||||
m_chunk_size(size), m_generator(std::move(generator))
|
||||
{
|
||||
m_chunk.reserve(m_chunk_size);
|
||||
if (m_chunk_size != 0) {
|
||||
m_chunk.push_back(m_generator.get());
|
||||
for (size_t i = 1; i < m_chunk_size; ++i) {
|
||||
if (!m_generator.next()) {
|
||||
Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
|
||||
}
|
||||
m_chunk.push_back(m_generator.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<T> const& get() const override {
|
||||
return m_chunk;
|
||||
}
|
||||
bool next() override {
|
||||
m_chunk.clear();
|
||||
for (size_t idx = 0; idx < m_chunk_size; ++idx) {
|
||||
if (!m_generator.next()) {
|
||||
return false;
|
||||
}
|
||||
m_chunk.push_back(m_generator.get());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
|
||||
return GeneratorWrapper<std::vector<T>>(
|
||||
pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
|
||||
);
|
||||
}
|
||||
|
||||
} // namespace Generators
|
||||
} // namespace Catch
|
||||
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_GENERATORS_GENERIC_HPP_INCLUDED
|
175
src/internal/catch_generators_specific.hpp
Normal file
175
src/internal/catch_generators_specific.hpp
Normal file
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
* Created by Martin on 15/6/2018.
|
||||
*
|
||||
* 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_GENERATORS_SPECIFIC_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_GENERATORS_SPECIFIC_HPP_INCLUDED
|
||||
|
||||
#include "catch_context.h"
|
||||
#include "catch_generators.hpp"
|
||||
#include "catch_interfaces_config.h"
|
||||
#include "catch_random_number_generator.h"
|
||||
|
||||
#include <random>
|
||||
|
||||
namespace Catch {
|
||||
namespace Generators {
|
||||
|
||||
template <typename Float>
|
||||
class RandomFloatingGenerator final : public IGenerator<Float> {
|
||||
Catch::SimplePcg32& m_rng;
|
||||
std::uniform_real_distribution<Float> m_dist;
|
||||
Float m_current_number;
|
||||
public:
|
||||
|
||||
RandomFloatingGenerator(Float a, Float b):
|
||||
m_rng(rng()),
|
||||
m_dist(a, b) {
|
||||
static_cast<void>(next());
|
||||
}
|
||||
|
||||
Float const& get() const override {
|
||||
return m_current_number;
|
||||
}
|
||||
bool next() override {
|
||||
m_current_number = m_dist(m_rng);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Integer>
|
||||
class RandomIntegerGenerator final : public IGenerator<Integer> {
|
||||
Catch::SimplePcg32& m_rng;
|
||||
std::uniform_int_distribution<Integer> m_dist;
|
||||
Integer m_current_number;
|
||||
public:
|
||||
|
||||
RandomIntegerGenerator(Integer a, Integer b):
|
||||
m_rng(rng()),
|
||||
m_dist(a, b) {
|
||||
static_cast<void>(next());
|
||||
}
|
||||
|
||||
Integer const& get() const override {
|
||||
return m_current_number;
|
||||
}
|
||||
bool next() override {
|
||||
m_current_number = m_dist(m_rng);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// TODO: Ideally this would be also constrained against the various char types,
|
||||
// but I don't expect users to run into that in practice.
|
||||
template <typename T>
|
||||
typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
|
||||
GeneratorWrapper<T>>::type
|
||||
random(T a, T b) {
|
||||
return GeneratorWrapper<T>(
|
||||
pf::make_unique<RandomIntegerGenerator<T>>(a, b)
|
||||
);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
typename std::enable_if<std::is_floating_point<T>::value,
|
||||
GeneratorWrapper<T>>::type
|
||||
random(T a, T b) {
|
||||
return GeneratorWrapper<T>(
|
||||
pf::make_unique<RandomFloatingGenerator<T>>(a, b)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
template <typename T>
|
||||
class RangeGenerator final : public IGenerator<T> {
|
||||
T m_current;
|
||||
T m_end;
|
||||
T m_step;
|
||||
bool m_positive;
|
||||
|
||||
public:
|
||||
RangeGenerator(T const& start, T const& end, T const& step):
|
||||
m_current(start),
|
||||
m_end(end),
|
||||
m_step(step),
|
||||
m_positive(m_step > T(0))
|
||||
{
|
||||
assert(m_current != m_end && "Range start and end cannot be equal");
|
||||
assert(m_step != T(0) && "Step size cannot be zero");
|
||||
assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
|
||||
}
|
||||
|
||||
RangeGenerator(T const& start, T const& end):
|
||||
RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
|
||||
{}
|
||||
|
||||
T const& get() const override {
|
||||
return m_current;
|
||||
}
|
||||
|
||||
bool next() override {
|
||||
m_current += m_step;
|
||||
return (m_positive) ? (m_current < m_end) : (m_current > m_end);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
|
||||
static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
|
||||
return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
GeneratorWrapper<T> range(T const& start, T const& end) {
|
||||
static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
|
||||
return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
|
||||
}
|
||||
|
||||
|
||||
template <typename T>
|
||||
class IteratorGenerator final : public IGenerator<T> {
|
||||
static_assert(!std::is_same<T, bool>::value,
|
||||
"IteratorGenerator currently does not support bools"
|
||||
"because of std::vector<bool> specialization");
|
||||
|
||||
std::vector<T> m_elems;
|
||||
size_t m_current = 0;
|
||||
public:
|
||||
template <typename InputIterator, typename InputSentinel>
|
||||
IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
|
||||
if (m_elems.empty()) {
|
||||
Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
|
||||
}
|
||||
}
|
||||
|
||||
T const& get() const override {
|
||||
return m_elems[m_current];
|
||||
}
|
||||
|
||||
bool next() override {
|
||||
++m_current;
|
||||
return m_current != m_elems.size();
|
||||
}
|
||||
};
|
||||
|
||||
template <typename InputIterator,
|
||||
typename InputSentinel,
|
||||
typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
|
||||
GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
|
||||
return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
|
||||
}
|
||||
|
||||
template <typename Container,
|
||||
typename ResultType = typename Container::value_type>
|
||||
GeneratorWrapper<ResultType> from_range(Container const& cnt) {
|
||||
return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
|
||||
}
|
||||
|
||||
|
||||
} // namespace Generators
|
||||
} // namespace Catch
|
||||
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_GENERATORS_SPECIFIC_HPP_INCLUDED
|
33
src/internal/catch_impl.hpp
Normal file
33
src/internal/catch_impl.hpp
Normal file
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Created by Phil on 5/8/2012.
|
||||
* Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_IMPL_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED
|
||||
|
||||
#ifdef __clang__
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wweak-vtables"
|
||||
#endif
|
||||
|
||||
// Keep these here for external reporters
|
||||
#include "catch_test_spec.h"
|
||||
#include "catch_test_case_tracker.h"
|
||||
|
||||
#include "catch_leak_detector.h"
|
||||
|
||||
// Cpp files will be included in the single-header file here
|
||||
// ~*~* CATCH_CPP_STITCH_PLACE *~*~
|
||||
|
||||
namespace Catch {
|
||||
LeakDetector leakDetector;
|
||||
}
|
||||
|
||||
#ifdef __clang__
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED
|
5
src/internal/catch_interfaces_capture.cpp
Normal file
5
src/internal/catch_interfaces_capture.cpp
Normal file
@@ -0,0 +1,5 @@
|
||||
#include "catch_interfaces_capture.h"
|
||||
|
||||
namespace Catch {
|
||||
IResultCapture::~IResultCapture() = default;
|
||||
}
|
100
src/internal/catch_interfaces_capture.h
Normal file
100
src/internal/catch_interfaces_capture.h
Normal file
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Created by Phil on 07/01/2011.
|
||||
* Copyright 2011 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACES_CAPTURE_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
|
||||
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
|
||||
#include "catch_stringref.h"
|
||||
#include "catch_result_type.h"
|
||||
|
||||
namespace Catch {
|
||||
|
||||
class AssertionResult;
|
||||
struct AssertionInfo;
|
||||
struct SectionInfo;
|
||||
struct SectionEndInfo;
|
||||
struct MessageInfo;
|
||||
struct MessageBuilder;
|
||||
struct Counts;
|
||||
struct AssertionReaction;
|
||||
struct SourceLineInfo;
|
||||
|
||||
struct ITransientExpression;
|
||||
struct IGeneratorTracker;
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
struct BenchmarkInfo;
|
||||
template <typename Duration = std::chrono::duration<double, std::nano>>
|
||||
struct BenchmarkStats;
|
||||
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
|
||||
|
||||
struct IResultCapture {
|
||||
|
||||
virtual ~IResultCapture();
|
||||
|
||||
virtual bool sectionStarted( SectionInfo const& sectionInfo,
|
||||
Counts& assertions ) = 0;
|
||||
virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
|
||||
virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
|
||||
|
||||
virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
virtual void benchmarkPreparing( std::string const& name ) = 0;
|
||||
virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
|
||||
virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
|
||||
virtual void benchmarkFailed( std::string const& error ) = 0;
|
||||
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
|
||||
|
||||
virtual void pushScopedMessage( MessageInfo const& message ) = 0;
|
||||
virtual void popScopedMessage( MessageInfo const& message ) = 0;
|
||||
|
||||
virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
|
||||
|
||||
virtual void handleFatalErrorCondition( StringRef message ) = 0;
|
||||
|
||||
virtual void handleExpr
|
||||
( AssertionInfo const& info,
|
||||
ITransientExpression const& expr,
|
||||
AssertionReaction& reaction ) = 0;
|
||||
virtual void handleMessage
|
||||
( AssertionInfo const& info,
|
||||
ResultWas::OfType resultType,
|
||||
StringRef const& message,
|
||||
AssertionReaction& reaction ) = 0;
|
||||
virtual void handleUnexpectedExceptionNotThrown
|
||||
( AssertionInfo const& info,
|
||||
AssertionReaction& reaction ) = 0;
|
||||
virtual void handleUnexpectedInflightException
|
||||
( AssertionInfo const& info,
|
||||
std::string const& message,
|
||||
AssertionReaction& reaction ) = 0;
|
||||
virtual void handleIncomplete
|
||||
( AssertionInfo const& info ) = 0;
|
||||
virtual void handleNonExpr
|
||||
( AssertionInfo const &info,
|
||||
ResultWas::OfType resultType,
|
||||
AssertionReaction &reaction ) = 0;
|
||||
|
||||
|
||||
|
||||
virtual bool lastAssertionPassed() = 0;
|
||||
virtual void assertionPassed() = 0;
|
||||
|
||||
// Deprecated, do not use:
|
||||
virtual std::string getCurrentTestName() const = 0;
|
||||
virtual const AssertionResult* getLastResult() const = 0;
|
||||
virtual void exceptionEarlyReported() = 0;
|
||||
};
|
||||
|
||||
IResultCapture& getResultCapture();
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
|
5
src/internal/catch_interfaces_config.cpp
Normal file
5
src/internal/catch_interfaces_config.cpp
Normal file
@@ -0,0 +1,5 @@
|
||||
#include "catch_interfaces_config.h"
|
||||
|
||||
namespace Catch {
|
||||
IConfig::~IConfig() = default;
|
||||
}
|
89
src/internal/catch_interfaces_config.h
Normal file
89
src/internal/catch_interfaces_config.h
Normal file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Created by Phil on 05/06/2012.
|
||||
* Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACES_CONFIG_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
|
||||
|
||||
#include "catch_common.h"
|
||||
#include "catch_option.hpp"
|
||||
|
||||
#include <iosfwd>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
enum class Verbosity {
|
||||
Quiet = 0,
|
||||
Normal,
|
||||
High
|
||||
};
|
||||
|
||||
struct WarnAbout { enum What {
|
||||
Nothing = 0x00,
|
||||
NoAssertions = 0x01,
|
||||
NoTests = 0x02
|
||||
}; };
|
||||
|
||||
struct ShowDurations { enum OrNot {
|
||||
DefaultForReporter,
|
||||
Always,
|
||||
Never
|
||||
}; };
|
||||
struct RunTests { enum InWhatOrder {
|
||||
InDeclarationOrder,
|
||||
InLexicographicalOrder,
|
||||
InRandomOrder
|
||||
}; };
|
||||
struct UseColour { enum YesOrNo {
|
||||
Auto,
|
||||
Yes,
|
||||
No
|
||||
}; };
|
||||
struct WaitForKeypress { enum When {
|
||||
Never,
|
||||
BeforeStart = 1,
|
||||
BeforeExit = 2,
|
||||
BeforeStartAndExit = BeforeStart | BeforeExit
|
||||
}; };
|
||||
|
||||
class TestSpec;
|
||||
|
||||
struct IConfig : NonCopyable {
|
||||
|
||||
virtual ~IConfig();
|
||||
|
||||
virtual bool allowThrows() const = 0;
|
||||
virtual std::ostream& stream() const = 0;
|
||||
virtual std::string name() const = 0;
|
||||
virtual bool includeSuccessfulResults() const = 0;
|
||||
virtual bool shouldDebugBreak() const = 0;
|
||||
virtual bool warnAboutMissingAssertions() const = 0;
|
||||
virtual bool warnAboutNoTests() const = 0;
|
||||
virtual int abortAfter() const = 0;
|
||||
virtual bool showInvisibles() const = 0;
|
||||
virtual ShowDurations::OrNot showDurations() const = 0;
|
||||
virtual TestSpec const& testSpec() const = 0;
|
||||
virtual bool hasTestFilters() const = 0;
|
||||
virtual std::vector<std::string> const& getTestsOrTags() const = 0;
|
||||
virtual RunTests::InWhatOrder runOrder() const = 0;
|
||||
virtual unsigned int rngSeed() const = 0;
|
||||
virtual UseColour::YesOrNo useColour() const = 0;
|
||||
virtual std::vector<std::string> const& getSectionsToRun() const = 0;
|
||||
virtual Verbosity verbosity() const = 0;
|
||||
|
||||
virtual bool benchmarkNoAnalysis() const = 0;
|
||||
virtual int benchmarkSamples() const = 0;
|
||||
virtual double benchmarkConfidenceInterval() const = 0;
|
||||
virtual unsigned int benchmarkResamples() const = 0;
|
||||
};
|
||||
|
||||
using IConfigPtr = std::shared_ptr<IConfig const>;
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
|
46
src/internal/catch_interfaces_enum_values_registry.h
Normal file
46
src/internal/catch_interfaces_enum_values_registry.h
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Created by Phil on 4/4/2019.
|
||||
* Copyright 2019 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACESENUMVALUESREGISTRY_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACESENUMVALUESREGISTRY_H_INCLUDED
|
||||
|
||||
#include "catch_stringref.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
namespace Detail {
|
||||
struct EnumInfo {
|
||||
StringRef m_name;
|
||||
std::vector<std::pair<int, StringRef>> m_values;
|
||||
|
||||
~EnumInfo();
|
||||
|
||||
StringRef lookup( int value ) const;
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
struct IMutableEnumValuesRegistry {
|
||||
virtual ~IMutableEnumValuesRegistry();
|
||||
|
||||
virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
|
||||
|
||||
template<typename E>
|
||||
Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
|
||||
static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
|
||||
std::vector<int> intValues;
|
||||
intValues.reserve( values.size() );
|
||||
for( auto enumValue : values )
|
||||
intValues.push_back( static_cast<int>( enumValue ) );
|
||||
return registerEnum( enumName, allEnums, intValues );
|
||||
}
|
||||
};
|
||||
|
||||
} // Catch
|
||||
|
||||
#endif //TWOBLUECUBES_CATCH_INTERFACESENUMVALUESREGISTRY_H_INCLUDED
|
6
src/internal/catch_interfaces_exception.cpp
Normal file
6
src/internal/catch_interfaces_exception.cpp
Normal file
@@ -0,0 +1,6 @@
|
||||
#include "catch_interfaces_exception.h"
|
||||
|
||||
namespace Catch {
|
||||
IExceptionTranslator::~IExceptionTranslator() = default;
|
||||
IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
|
||||
}
|
84
src/internal/catch_interfaces_exception.h
Normal file
84
src/internal/catch_interfaces_exception.h
Normal file
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Created by Phil on 20/04/2011.
|
||||
* Copyright 2011 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACES_EXCEPTION_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED
|
||||
|
||||
#include "catch_interfaces_registry_hub.h"
|
||||
|
||||
#if defined(CATCH_CONFIG_DISABLE)
|
||||
#define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
|
||||
static std::string translatorName( signature )
|
||||
#endif
|
||||
|
||||
#include <exception>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Catch {
|
||||
using exceptionTranslateFunction = std::string(*)();
|
||||
|
||||
struct IExceptionTranslator;
|
||||
using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
|
||||
|
||||
struct IExceptionTranslator {
|
||||
virtual ~IExceptionTranslator();
|
||||
virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
|
||||
};
|
||||
|
||||
struct IExceptionTranslatorRegistry {
|
||||
virtual ~IExceptionTranslatorRegistry();
|
||||
|
||||
virtual std::string translateActiveException() const = 0;
|
||||
};
|
||||
|
||||
class ExceptionTranslatorRegistrar {
|
||||
template<typename T>
|
||||
class ExceptionTranslator : public IExceptionTranslator {
|
||||
public:
|
||||
|
||||
ExceptionTranslator( std::string(*translateFunction)( T& ) )
|
||||
: m_translateFunction( translateFunction )
|
||||
{}
|
||||
|
||||
std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
|
||||
try {
|
||||
if( it == itEnd )
|
||||
std::rethrow_exception(std::current_exception());
|
||||
else
|
||||
return (*it)->translate( it+1, itEnd );
|
||||
}
|
||||
catch( T& ex ) {
|
||||
return m_translateFunction( ex );
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
std::string(*m_translateFunction)( T& );
|
||||
};
|
||||
|
||||
public:
|
||||
template<typename T>
|
||||
ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
|
||||
getMutableRegistryHub().registerTranslator
|
||||
( new ExceptionTranslator<T>( translateFunction ) );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
|
||||
static std::string translatorName( signature ); \
|
||||
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
|
||||
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
|
||||
namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
|
||||
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
|
||||
static std::string translatorName( signature )
|
||||
|
||||
#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED
|
39
src/internal/catch_interfaces_generatortracker.h
Normal file
39
src/internal/catch_interfaces_generatortracker.h
Normal file
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Created by Phil Nash on 26/6/2018.
|
||||
*
|
||||
* 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_INTERFACES_GENERATORTRACKER_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_GENERATORTRACKER_INCLUDED
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
namespace Generators {
|
||||
class GeneratorUntypedBase {
|
||||
public:
|
||||
GeneratorUntypedBase() = default;
|
||||
virtual ~GeneratorUntypedBase();
|
||||
// Attempts to move the generator to the next element
|
||||
//
|
||||
// Returns true iff the move succeeded (and a valid element
|
||||
// can be retrieved).
|
||||
virtual bool next() = 0;
|
||||
};
|
||||
using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
|
||||
|
||||
} // namespace Generators
|
||||
|
||||
struct IGeneratorTracker {
|
||||
virtual ~IGeneratorTracker();
|
||||
virtual auto hasGenerator() const -> bool = 0;
|
||||
virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
|
||||
virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
|
||||
};
|
||||
|
||||
} // namespace Catch
|
||||
|
||||
#endif //TWOBLUECUBES_CATCH_INTERFACES_GENERATORTRACKER_INCLUDED
|
6
src/internal/catch_interfaces_registry_hub.cpp
Normal file
6
src/internal/catch_interfaces_registry_hub.cpp
Normal file
@@ -0,0 +1,6 @@
|
||||
#include "catch_interfaces_registry_hub.h"
|
||||
|
||||
namespace Catch {
|
||||
IRegistryHub::~IRegistryHub() = default;
|
||||
IMutableRegistryHub::~IMutableRegistryHub() = default;
|
||||
}
|
63
src/internal/catch_interfaces_registry_hub.h
Normal file
63
src/internal/catch_interfaces_registry_hub.h
Normal file
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Created by Phil on 5/8/2012.
|
||||
* Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACES_REGISTRY_HUB_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED
|
||||
|
||||
#include "catch_common.h"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
class TestCaseHandle;
|
||||
struct TestCaseInfo;
|
||||
struct ITestCaseRegistry;
|
||||
struct IExceptionTranslatorRegistry;
|
||||
struct IExceptionTranslator;
|
||||
struct IReporterRegistry;
|
||||
struct IReporterFactory;
|
||||
struct ITagAliasRegistry;
|
||||
struct ITestInvoker;
|
||||
struct IMutableEnumValuesRegistry;
|
||||
|
||||
class StartupExceptionRegistry;
|
||||
|
||||
using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
|
||||
|
||||
struct IRegistryHub {
|
||||
virtual ~IRegistryHub();
|
||||
|
||||
virtual IReporterRegistry const& getReporterRegistry() const = 0;
|
||||
virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
|
||||
virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
|
||||
virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
|
||||
|
||||
|
||||
virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
|
||||
};
|
||||
|
||||
struct IMutableRegistryHub {
|
||||
virtual ~IMutableRegistryHub();
|
||||
virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
|
||||
virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
|
||||
virtual void registerTest(std::unique_ptr<TestCaseInfo>&& testInfo, std::unique_ptr<ITestInvoker>&& invoker) = 0;
|
||||
virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
|
||||
virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
|
||||
virtual void registerStartupException() noexcept = 0;
|
||||
virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
|
||||
};
|
||||
|
||||
IRegistryHub const& getRegistryHub();
|
||||
IMutableRegistryHub& getMutableRegistryHub();
|
||||
void cleanUp();
|
||||
std::string translateActiveException();
|
||||
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED
|
197
src/internal/catch_interfaces_reporter.cpp
Normal file
197
src/internal/catch_interfaces_reporter.cpp
Normal file
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Created by Martin on 19/07/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_interfaces_reporter.h"
|
||||
#include "catch_console_colour.h"
|
||||
#include "../reporters/catch_reporter_listening.h"
|
||||
#include "catch_list.h"
|
||||
#include "catch_text.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <iomanip>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
|
||||
: m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
|
||||
|
||||
ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
|
||||
: m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
|
||||
|
||||
std::ostream& ReporterConfig::stream() const { return *m_stream; }
|
||||
IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
|
||||
|
||||
|
||||
TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
|
||||
|
||||
GroupInfo::GroupInfo( std::string const& _name,
|
||||
std::size_t _groupIndex,
|
||||
std::size_t _groupsCount )
|
||||
: name( _name ),
|
||||
groupIndex( _groupIndex ),
|
||||
groupsCounts( _groupsCount )
|
||||
{}
|
||||
|
||||
AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
|
||||
std::vector<MessageInfo> const& _infoMessages,
|
||||
Totals const& _totals )
|
||||
: assertionResult( _assertionResult ),
|
||||
infoMessages( _infoMessages ),
|
||||
totals( _totals )
|
||||
{
|
||||
assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
|
||||
|
||||
if( assertionResult.hasMessage() ) {
|
||||
// Copy message into messages list.
|
||||
// !TBD This should have been done earlier, somewhere
|
||||
MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
|
||||
builder << assertionResult.getMessage();
|
||||
builder.m_info.message = builder.m_stream.str();
|
||||
|
||||
infoMessages.push_back( builder.m_info );
|
||||
}
|
||||
}
|
||||
|
||||
AssertionStats::~AssertionStats() = default;
|
||||
|
||||
SectionStats::SectionStats( SectionInfo const& _sectionInfo,
|
||||
Counts const& _assertions,
|
||||
double _durationInSeconds,
|
||||
bool _missingAssertions )
|
||||
: sectionInfo( _sectionInfo ),
|
||||
assertions( _assertions ),
|
||||
durationInSeconds( _durationInSeconds ),
|
||||
missingAssertions( _missingAssertions )
|
||||
{}
|
||||
|
||||
SectionStats::~SectionStats() = default;
|
||||
|
||||
|
||||
TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
|
||||
Totals const& _totals,
|
||||
std::string const& _stdOut,
|
||||
std::string const& _stdErr,
|
||||
bool _aborting )
|
||||
: testInfo( &_testInfo ),
|
||||
totals( _totals ),
|
||||
stdOut( _stdOut ),
|
||||
stdErr( _stdErr ),
|
||||
aborting( _aborting )
|
||||
{}
|
||||
|
||||
TestCaseStats::~TestCaseStats() = default;
|
||||
|
||||
|
||||
TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
|
||||
Totals const& _totals,
|
||||
bool _aborting )
|
||||
: groupInfo( _groupInfo ),
|
||||
totals( _totals ),
|
||||
aborting( _aborting )
|
||||
{}
|
||||
|
||||
TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
|
||||
: groupInfo( _groupInfo ),
|
||||
aborting( false )
|
||||
{}
|
||||
|
||||
TestGroupStats::~TestGroupStats() = default;
|
||||
|
||||
TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
|
||||
Totals const& _totals,
|
||||
bool _aborting )
|
||||
: runInfo( _runInfo ),
|
||||
totals( _totals ),
|
||||
aborting( _aborting )
|
||||
{}
|
||||
|
||||
TestRunStats::~TestRunStats() = default;
|
||||
|
||||
void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
|
||||
bool IStreamingReporter::isMulti() const { return false; }
|
||||
|
||||
void IStreamingReporter::listReporters(std::vector<ReporterDescription> const& descriptions, Config const& config) {
|
||||
Catch::cout() << "Available reporters:\n";
|
||||
const auto maxNameLen = std::max_element(descriptions.begin(), descriptions.end(),
|
||||
[](ReporterDescription const& lhs, ReporterDescription const& rhs) { return lhs.name.size() < rhs.name.size(); })
|
||||
->name.size();
|
||||
|
||||
for (auto const& desc : descriptions) {
|
||||
if (config.verbosity() == Verbosity::Quiet) {
|
||||
Catch::cout()
|
||||
<< Column(desc.name)
|
||||
.indent(2)
|
||||
.width(5 + maxNameLen) << '\n';
|
||||
} else {
|
||||
Catch::cout()
|
||||
<< Column(desc.name + ":")
|
||||
.indent(2)
|
||||
.width(5 + maxNameLen)
|
||||
+ Column(desc.description)
|
||||
.initialIndent(0)
|
||||
.indent(2)
|
||||
.width(CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8)
|
||||
<< '\n';
|
||||
}
|
||||
}
|
||||
Catch::cout() << std::endl;
|
||||
}
|
||||
|
||||
void IStreamingReporter::listTests(std::vector<TestCaseHandle> const& tests, Config const& config) {
|
||||
if (config.hasTestFilters())
|
||||
Catch::cout() << "Matching test cases:\n";
|
||||
else {
|
||||
Catch::cout() << "All available test cases:\n";
|
||||
}
|
||||
|
||||
for (auto const& test : tests) {
|
||||
auto const& testCaseInfo = test.getTestCaseInfo();
|
||||
Colour::Code colour = testCaseInfo.isHidden()
|
||||
? Colour::SecondaryText
|
||||
: Colour::None;
|
||||
Colour colourGuard(colour);
|
||||
|
||||
Catch::cout() << Column(testCaseInfo.name).initialIndent(2).indent(4) << '\n';
|
||||
if (config.verbosity() >= Verbosity::High) {
|
||||
Catch::cout() << Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4) << std::endl;
|
||||
}
|
||||
if (!testCaseInfo.tags.empty() && config.verbosity() > Verbosity::Quiet) {
|
||||
Catch::cout() << Column(testCaseInfo.tagsAsString()).indent(6) << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
if (!config.hasTestFilters()) {
|
||||
Catch::cout() << pluralise(tests.size(), "test case") << '\n' << std::endl;
|
||||
} else {
|
||||
Catch::cout() << pluralise(tests.size(), "matching test case") << '\n' << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void IStreamingReporter::listTags(std::vector<TagInfo> const& tags, Config const& config) {
|
||||
if (config.hasTestFilters()) {
|
||||
Catch::cout() << "Tags for matching test cases:\n";
|
||||
} else {
|
||||
Catch::cout() << "All available tags:\n";
|
||||
}
|
||||
|
||||
for (auto const& tagCount : tags) {
|
||||
ReusableStringStream rss;
|
||||
rss << " " << std::setw(2) << tagCount.count << " ";
|
||||
auto str = rss.str();
|
||||
auto wrapper = Column(tagCount.all())
|
||||
.initialIndent(0)
|
||||
.indent(str.size())
|
||||
.width(CATCH_CONFIG_CONSOLE_WIDTH - 10);
|
||||
Catch::cout() << str << wrapper << '\n';
|
||||
}
|
||||
Catch::cout() << pluralise(tags.size(), "tag") << '\n' << std::endl;
|
||||
}
|
||||
|
||||
IReporterFactory::~IReporterFactory() = default;
|
||||
IReporterRegistry::~IReporterRegistry() = default;
|
||||
|
||||
} // end namespace Catch
|
278
src/internal/catch_interfaces_reporter.h
Normal file
278
src/internal/catch_interfaces_reporter.h
Normal file
@@ -0,0 +1,278 @@
|
||||
/*
|
||||
* Created by Phil on 31/12/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACES_REPORTER_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED
|
||||
|
||||
#include "catch_section_info.h"
|
||||
#include "catch_common.h"
|
||||
#include "catch_config.hpp"
|
||||
#include "catch_totals.h"
|
||||
#include "catch_test_case_info.h"
|
||||
#include "catch_assertionresult.h"
|
||||
#include "catch_message.h"
|
||||
#include "catch_option.hpp"
|
||||
#include "catch_stringref.h"
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
#include "benchmark/catch_estimate.hpp"
|
||||
#include "benchmark/catch_outlier_classification.hpp"
|
||||
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
|
||||
|
||||
|
||||
#include <string>
|
||||
#include <iosfwd>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <memory>
|
||||
#include <algorithm>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct ReporterDescription;
|
||||
struct TagInfo;
|
||||
|
||||
struct ReporterConfig {
|
||||
explicit ReporterConfig( IConfigPtr const& _fullConfig );
|
||||
|
||||
ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
|
||||
|
||||
std::ostream& stream() const;
|
||||
IConfigPtr fullConfig() const;
|
||||
|
||||
private:
|
||||
std::ostream* m_stream;
|
||||
IConfigPtr m_fullConfig;
|
||||
};
|
||||
|
||||
struct ReporterPreferences {
|
||||
bool shouldRedirectStdOut = false;
|
||||
bool shouldReportAllAssertions = false;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct LazyStat : Option<T> {
|
||||
LazyStat& operator=( T const& _value ) {
|
||||
Option<T>::operator=( _value );
|
||||
used = false;
|
||||
return *this;
|
||||
}
|
||||
void reset() {
|
||||
Option<T>::reset();
|
||||
used = false;
|
||||
}
|
||||
bool used = false;
|
||||
};
|
||||
|
||||
struct TestRunInfo {
|
||||
TestRunInfo( std::string const& _name );
|
||||
std::string name;
|
||||
};
|
||||
struct GroupInfo {
|
||||
GroupInfo( std::string const& _name,
|
||||
std::size_t _groupIndex,
|
||||
std::size_t _groupsCount );
|
||||
|
||||
std::string name;
|
||||
std::size_t groupIndex;
|
||||
std::size_t groupsCounts;
|
||||
};
|
||||
|
||||
struct AssertionStats {
|
||||
AssertionStats( AssertionResult const& _assertionResult,
|
||||
std::vector<MessageInfo> const& _infoMessages,
|
||||
Totals const& _totals );
|
||||
|
||||
AssertionStats( AssertionStats const& ) = default;
|
||||
AssertionStats( AssertionStats && ) = default;
|
||||
AssertionStats& operator = ( AssertionStats const& ) = delete;
|
||||
AssertionStats& operator = ( AssertionStats && ) = delete;
|
||||
virtual ~AssertionStats();
|
||||
|
||||
AssertionResult assertionResult;
|
||||
std::vector<MessageInfo> infoMessages;
|
||||
Totals totals;
|
||||
};
|
||||
|
||||
struct SectionStats {
|
||||
SectionStats( SectionInfo const& _sectionInfo,
|
||||
Counts const& _assertions,
|
||||
double _durationInSeconds,
|
||||
bool _missingAssertions );
|
||||
SectionStats( SectionStats const& ) = default;
|
||||
SectionStats( SectionStats && ) = default;
|
||||
SectionStats& operator = ( SectionStats const& ) = default;
|
||||
SectionStats& operator = ( SectionStats && ) = default;
|
||||
virtual ~SectionStats();
|
||||
|
||||
SectionInfo sectionInfo;
|
||||
Counts assertions;
|
||||
double durationInSeconds;
|
||||
bool missingAssertions;
|
||||
};
|
||||
|
||||
struct TestCaseStats {
|
||||
TestCaseStats( TestCaseInfo const& _testInfo,
|
||||
Totals const& _totals,
|
||||
std::string const& _stdOut,
|
||||
std::string const& _stdErr,
|
||||
bool _aborting );
|
||||
|
||||
TestCaseStats( TestCaseStats const& ) = default;
|
||||
TestCaseStats( TestCaseStats && ) = default;
|
||||
TestCaseStats& operator = ( TestCaseStats const& ) = default;
|
||||
TestCaseStats& operator = ( TestCaseStats && ) = default;
|
||||
virtual ~TestCaseStats();
|
||||
|
||||
TestCaseInfo const * testInfo;
|
||||
Totals totals;
|
||||
std::string stdOut;
|
||||
std::string stdErr;
|
||||
bool aborting;
|
||||
};
|
||||
|
||||
struct TestGroupStats {
|
||||
TestGroupStats( GroupInfo const& _groupInfo,
|
||||
Totals const& _totals,
|
||||
bool _aborting );
|
||||
TestGroupStats( GroupInfo const& _groupInfo );
|
||||
|
||||
TestGroupStats( TestGroupStats const& ) = default;
|
||||
TestGroupStats( TestGroupStats && ) = default;
|
||||
TestGroupStats& operator = ( TestGroupStats const& ) = default;
|
||||
TestGroupStats& operator = ( TestGroupStats && ) = default;
|
||||
virtual ~TestGroupStats();
|
||||
|
||||
GroupInfo groupInfo;
|
||||
Totals totals;
|
||||
bool aborting;
|
||||
};
|
||||
|
||||
struct TestRunStats {
|
||||
TestRunStats( TestRunInfo const& _runInfo,
|
||||
Totals const& _totals,
|
||||
bool _aborting );
|
||||
|
||||
TestRunStats( TestRunStats const& ) = default;
|
||||
TestRunStats( TestRunStats && ) = default;
|
||||
TestRunStats& operator = ( TestRunStats const& ) = default;
|
||||
TestRunStats& operator = ( TestRunStats && ) = default;
|
||||
virtual ~TestRunStats();
|
||||
|
||||
TestRunInfo runInfo;
|
||||
Totals totals;
|
||||
bool aborting;
|
||||
};
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
struct BenchmarkInfo {
|
||||
std::string name;
|
||||
double estimatedDuration;
|
||||
int iterations;
|
||||
int samples;
|
||||
unsigned int resamples;
|
||||
double clockResolution;
|
||||
double clockCost;
|
||||
};
|
||||
|
||||
template <class Duration>
|
||||
struct BenchmarkStats {
|
||||
BenchmarkInfo info;
|
||||
|
||||
std::vector<Duration> samples;
|
||||
Benchmark::Estimate<Duration> mean;
|
||||
Benchmark::Estimate<Duration> standardDeviation;
|
||||
Benchmark::OutlierClassification outliers;
|
||||
double outlierVariance;
|
||||
|
||||
template <typename Duration2>
|
||||
operator BenchmarkStats<Duration2>() const {
|
||||
std::vector<Duration2> samples2;
|
||||
samples2.reserve(samples.size());
|
||||
std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
|
||||
return {
|
||||
info,
|
||||
std::move(samples2),
|
||||
mean,
|
||||
standardDeviation,
|
||||
outliers,
|
||||
outlierVariance,
|
||||
};
|
||||
}
|
||||
};
|
||||
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
|
||||
|
||||
struct IStreamingReporter {
|
||||
virtual ~IStreamingReporter() = default;
|
||||
|
||||
// Implementing class must also provide the following static methods:
|
||||
// static std::string getDescription();
|
||||
|
||||
virtual ReporterPreferences getPreferences() const = 0;
|
||||
|
||||
virtual void noMatchingTestCases( std::string const& spec ) = 0;
|
||||
|
||||
virtual void reportInvalidArguments(std::string const&) {}
|
||||
|
||||
virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
|
||||
virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
|
||||
|
||||
virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
|
||||
virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
|
||||
|
||||
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
|
||||
virtual void benchmarkPreparing( std::string const& ) {}
|
||||
virtual void benchmarkStarting( BenchmarkInfo const& ) {}
|
||||
virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
|
||||
virtual void benchmarkFailed( std::string const& ) {}
|
||||
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
|
||||
|
||||
virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
|
||||
|
||||
// The return value indicates if the messages buffer should be cleared:
|
||||
virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
|
||||
|
||||
virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
|
||||
virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
|
||||
virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
|
||||
virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
|
||||
|
||||
virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
|
||||
|
||||
// Default empty implementation provided
|
||||
virtual void fatalErrorEncountered( StringRef name );
|
||||
|
||||
virtual bool isMulti() const;
|
||||
|
||||
// Listing support
|
||||
virtual void listReporters(std::vector<ReporterDescription> const& descriptions, Config const& config);
|
||||
virtual void listTests(std::vector<TestCaseHandle> const& tests, Config const& config);
|
||||
virtual void listTags(std::vector<TagInfo> const& tags, Config const& config);
|
||||
|
||||
};
|
||||
using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
|
||||
|
||||
struct IReporterFactory {
|
||||
virtual ~IReporterFactory();
|
||||
virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
|
||||
virtual std::string getDescription() const = 0;
|
||||
};
|
||||
using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
|
||||
|
||||
struct IReporterRegistry {
|
||||
using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
|
||||
using Listeners = std::vector<IReporterFactoryPtr>;
|
||||
|
||||
virtual ~IReporterRegistry();
|
||||
virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
|
||||
virtual FactoryMap const& getFactories() const = 0;
|
||||
virtual Listeners const& getListeners() const = 0;
|
||||
};
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED
|
5
src/internal/catch_interfaces_runner.cpp
Normal file
5
src/internal/catch_interfaces_runner.cpp
Normal file
@@ -0,0 +1,5 @@
|
||||
#include "catch_interfaces_runner.h"
|
||||
|
||||
namespace Catch {
|
||||
IRunner::~IRunner() = default;
|
||||
}
|
19
src/internal/catch_interfaces_runner.h
Normal file
19
src/internal/catch_interfaces_runner.h
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Created by Phil on 07/01/2011.
|
||||
* Copyright 2011 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACES_RUNNER_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct IRunner {
|
||||
virtual ~IRunner();
|
||||
virtual bool aborting() const = 0;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED
|
28
src/internal/catch_interfaces_tag_alias_registry.h
Normal file
28
src/internal/catch_interfaces_tag_alias_registry.h
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Created by Phil on 27/6/2014.
|
||||
* Copyright 2014 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct TagAlias;
|
||||
|
||||
struct ITagAliasRegistry {
|
||||
virtual ~ITagAliasRegistry();
|
||||
// Nullptr if not present
|
||||
virtual TagAlias const* find( std::string const& alias ) const = 0;
|
||||
virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
|
||||
|
||||
static ITagAliasRegistry const& get();
|
||||
};
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED
|
6
src/internal/catch_interfaces_testcase.cpp
Normal file
6
src/internal/catch_interfaces_testcase.cpp
Normal file
@@ -0,0 +1,6 @@
|
||||
#include "catch_interfaces_testcase.h"
|
||||
|
||||
namespace Catch {
|
||||
ITestInvoker::~ITestInvoker() = default;
|
||||
ITestCaseRegistry::~ITestCaseRegistry() = default;
|
||||
}
|
41
src/internal/catch_interfaces_testcase.h
Normal file
41
src/internal/catch_interfaces_testcase.h
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Created by Phil on 07/01/2011.
|
||||
* Copyright 2011 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_INTERFACES_TESTCASE_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED
|
||||
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
class TestSpec;
|
||||
struct TestCaseInfo;
|
||||
|
||||
struct ITestInvoker {
|
||||
virtual void invoke () const = 0;
|
||||
virtual ~ITestInvoker();
|
||||
};
|
||||
|
||||
class TestCaseHandle;
|
||||
struct IConfig;
|
||||
|
||||
struct ITestCaseRegistry {
|
||||
virtual ~ITestCaseRegistry();
|
||||
virtual std::vector<std::unique_ptr<TestCaseInfo>> const& getAllInfos() const = 0;
|
||||
virtual std::vector<TestCaseHandle> const& getAllTests() const = 0;
|
||||
virtual std::vector<TestCaseHandle> const& getAllTestsSorted( IConfig const& config ) const = 0;
|
||||
};
|
||||
|
||||
bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config );
|
||||
bool matchTest( TestCaseHandle const& testCase, TestSpec const& testSpec, IConfig const& config );
|
||||
std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config );
|
||||
std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config );
|
||||
|
||||
}
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED
|
37
src/internal/catch_leak_detector.cpp
Normal file
37
src/internal/catch_leak_detector.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Created by Martin on 12/07/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_leak_detector.h"
|
||||
#include "catch_interfaces_registry_hub.h"
|
||||
|
||||
|
||||
#ifdef CATCH_CONFIG_WINDOWS_CRTDBG
|
||||
#include <crtdbg.h>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
LeakDetector::LeakDetector() {
|
||||
int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
|
||||
flag |= _CRTDBG_LEAK_CHECK_DF;
|
||||
flag |= _CRTDBG_ALLOC_MEM_DF;
|
||||
_CrtSetDbgFlag(flag);
|
||||
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
|
||||
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
|
||||
// Change this to leaking allocation's number to break there
|
||||
_CrtSetBreakAlloc(-1);
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
Catch::LeakDetector::LeakDetector() {}
|
||||
|
||||
#endif
|
||||
|
||||
Catch::LeakDetector::~LeakDetector() {
|
||||
Catch::cleanUp();
|
||||
}
|
18
src/internal/catch_leak_detector.h
Normal file
18
src/internal/catch_leak_detector.h
Normal file
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Created by Martin on 12/07/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_LEAK_DETECTOR_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_LEAK_DETECTOR_H_INCLUDED
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct LeakDetector {
|
||||
LeakDetector();
|
||||
~LeakDetector();
|
||||
};
|
||||
|
||||
}
|
||||
#endif // TWOBLUECUBES_CATCH_LEAK_DETECTOR_H_INCLUDED
|
112
src/internal/catch_list.cpp
Normal file
112
src/internal/catch_list.cpp
Normal file
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Created by Phil on 5/11/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_list.h"
|
||||
|
||||
#include "catch_interfaces_registry_hub.h"
|
||||
#include "catch_interfaces_reporter.h"
|
||||
#include "catch_interfaces_testcase.h"
|
||||
|
||||
#include "catch_context.h"
|
||||
#include "catch_stream.h"
|
||||
#include "catch_text.h"
|
||||
|
||||
#include "catch_console_colour.h"
|
||||
#include "catch_test_spec_parser.h"
|
||||
#include "catch_tostring.h"
|
||||
#include "catch_string_manip.h"
|
||||
|
||||
#include <limits>
|
||||
#include <algorithm>
|
||||
#include <set>
|
||||
|
||||
namespace Catch {
|
||||
namespace {
|
||||
|
||||
void listTests(IStreamingReporter& reporter, Config const& config) {
|
||||
TestSpec testSpec = config.testSpec();
|
||||
auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
|
||||
reporter.listTests(matchedTestCases, config);
|
||||
}
|
||||
|
||||
void listTags(IStreamingReporter& reporter, Config const& config) {
|
||||
TestSpec testSpec = config.testSpec();
|
||||
std::vector<TestCaseHandle> matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
|
||||
|
||||
std::map<StringRef, TagInfo> tagCounts;
|
||||
for (auto const& testCase : matchedTestCases) {
|
||||
for (auto const& tagName : testCase.getTestCaseInfo().tags) {
|
||||
auto it = tagCounts.find(tagName.lowerCased);
|
||||
if (it == tagCounts.end())
|
||||
it = tagCounts.insert(std::make_pair(tagName.lowerCased, TagInfo())).first;
|
||||
it->second.add(tagName.original);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<TagInfo> infos; infos.reserve(tagCounts.size());
|
||||
for (auto const& tagc : tagCounts) {
|
||||
infos.push_back(std::move(tagc.second));
|
||||
}
|
||||
|
||||
reporter.listTags(infos, config);
|
||||
}
|
||||
|
||||
void listReporters(IStreamingReporter& reporter, Config const& config) {
|
||||
std::vector<ReporterDescription> descriptions;
|
||||
|
||||
IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
|
||||
descriptions.reserve(factories.size());
|
||||
for (auto const& fac : factories) {
|
||||
descriptions.push_back({ fac.first, fac.second->getDescription() });
|
||||
}
|
||||
|
||||
reporter.listReporters(descriptions, config);
|
||||
}
|
||||
|
||||
} // end anonymous namespace
|
||||
|
||||
void TagInfo::add( StringRef spelling ) {
|
||||
++count;
|
||||
spellings.insert( spelling );
|
||||
}
|
||||
|
||||
std::string TagInfo::all() const {
|
||||
// 2 per tag for brackets '[' and ']'
|
||||
size_t size = spellings.size() * 2;
|
||||
for (auto const& spelling : spellings) {
|
||||
size += spelling.size();
|
||||
}
|
||||
|
||||
std::string out; out.reserve(size);
|
||||
for (auto const& spelling : spellings) {
|
||||
out += '[';
|
||||
out += spelling;
|
||||
out += ']';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool list( IStreamingReporter& reporter, std::shared_ptr<Config> const& config ) {
|
||||
bool listed = false;
|
||||
getCurrentMutableContext().setConfig( config );
|
||||
if (config->listTests()) {
|
||||
listed = true;
|
||||
listTests(reporter, *config);
|
||||
}
|
||||
if (config->listTags()) {
|
||||
listed = true;
|
||||
listTags(reporter, *config);
|
||||
}
|
||||
if (config->listReporters()) {
|
||||
listed = true;
|
||||
listReporters(reporter, *config);
|
||||
}
|
||||
return listed;
|
||||
}
|
||||
|
||||
} // end namespace Catch
|
39
src/internal/catch_list.h
Normal file
39
src/internal/catch_list.h
Normal file
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Created by Phil on 5/11/2010.
|
||||
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_LIST_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_LIST_H_INCLUDED
|
||||
|
||||
#include "catch_config.hpp"
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
|
||||
namespace Catch {
|
||||
|
||||
struct IStreamingReporter;
|
||||
|
||||
struct ReporterDescription {
|
||||
std::string name, description;
|
||||
};
|
||||
|
||||
struct TagInfo {
|
||||
void add(StringRef spelling);
|
||||
std::string all() const;
|
||||
|
||||
std::set<StringRef> spellings;
|
||||
std::size_t count = 0;
|
||||
};
|
||||
|
||||
struct testClassInfo {};
|
||||
|
||||
bool list( IStreamingReporter& reporter, std::shared_ptr<Config> const& config );
|
||||
|
||||
} // end namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_LIST_H_INCLUDED
|
28
src/internal/catch_matchers.cpp
Normal file
28
src/internal/catch_matchers.cpp
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Created by Phil Nash on 19/07/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_matchers.h"
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
namespace Impl {
|
||||
|
||||
std::string MatcherUntypedBase::toString() const {
|
||||
if( m_cachedToString.empty() )
|
||||
m_cachedToString = describe();
|
||||
return m_cachedToString;
|
||||
}
|
||||
|
||||
MatcherUntypedBase::~MatcherUntypedBase() = default;
|
||||
|
||||
} // namespace Impl
|
||||
} // namespace Matchers
|
||||
|
||||
using namespace Matchers;
|
||||
using Matchers::Impl::MatcherBase;
|
||||
|
||||
} // namespace Catch
|
172
src/internal/catch_matchers.h
Normal file
172
src/internal/catch_matchers.h
Normal file
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Created by Phil Nash on 04/03/2012.
|
||||
* Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_MATCHERS_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED
|
||||
|
||||
#include "catch_common.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
namespace Impl {
|
||||
|
||||
template<typename ArgT> struct MatchAllOf;
|
||||
template<typename ArgT> struct MatchAnyOf;
|
||||
template<typename ArgT> struct MatchNotOf;
|
||||
|
||||
class MatcherUntypedBase {
|
||||
public:
|
||||
MatcherUntypedBase() = default;
|
||||
MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
|
||||
MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
|
||||
std::string toString() const;
|
||||
|
||||
protected:
|
||||
virtual ~MatcherUntypedBase();
|
||||
virtual std::string describe() const = 0;
|
||||
mutable std::string m_cachedToString;
|
||||
};
|
||||
|
||||
#ifdef __clang__
|
||||
# pragma clang diagnostic push
|
||||
# pragma clang diagnostic ignored "-Wnon-virtual-dtor"
|
||||
#endif
|
||||
|
||||
template<typename ObjectT>
|
||||
struct MatcherMethod {
|
||||
virtual bool match( ObjectT const& arg ) const = 0;
|
||||
};
|
||||
|
||||
#if defined(__OBJC__)
|
||||
// Hack to fix Catch GH issue #1661. Could use id for generic Object support.
|
||||
// use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
|
||||
template<>
|
||||
struct MatcherMethod<NSString*> {
|
||||
virtual bool match( NSString* arg ) const = 0;
|
||||
};
|
||||
#endif
|
||||
|
||||
#ifdef __clang__
|
||||
# pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
template<typename T>
|
||||
struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
|
||||
|
||||
|
||||
MatchAllOf<T> operator && ( MatcherBase const& other ) const;
|
||||
MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
|
||||
MatchNotOf<T> operator ! () const;
|
||||
};
|
||||
|
||||
template<typename ArgT>
|
||||
struct MatchAllOf : MatcherBase<ArgT> {
|
||||
bool match( ArgT const& arg ) const override {
|
||||
for( auto matcher : m_matchers ) {
|
||||
if (!matcher->match(arg))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::string describe() const override {
|
||||
std::string description;
|
||||
description.reserve( 4 + m_matchers.size()*32 );
|
||||
description += "( ";
|
||||
bool first = true;
|
||||
for( auto matcher : m_matchers ) {
|
||||
if( first )
|
||||
first = false;
|
||||
else
|
||||
description += " and ";
|
||||
description += matcher->toString();
|
||||
}
|
||||
description += " )";
|
||||
return description;
|
||||
}
|
||||
|
||||
MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
|
||||
m_matchers.push_back( &other );
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::vector<MatcherBase<ArgT> const*> m_matchers;
|
||||
};
|
||||
template<typename ArgT>
|
||||
struct MatchAnyOf : MatcherBase<ArgT> {
|
||||
|
||||
bool match( ArgT const& arg ) const override {
|
||||
for( auto matcher : m_matchers ) {
|
||||
if (matcher->match(arg))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
std::string describe() const override {
|
||||
std::string description;
|
||||
description.reserve( 4 + m_matchers.size()*32 );
|
||||
description += "( ";
|
||||
bool first = true;
|
||||
for( auto matcher : m_matchers ) {
|
||||
if( first )
|
||||
first = false;
|
||||
else
|
||||
description += " or ";
|
||||
description += matcher->toString();
|
||||
}
|
||||
description += " )";
|
||||
return description;
|
||||
}
|
||||
|
||||
MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
|
||||
m_matchers.push_back( &other );
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::vector<MatcherBase<ArgT> const*> m_matchers;
|
||||
};
|
||||
|
||||
template<typename ArgT>
|
||||
struct MatchNotOf : MatcherBase<ArgT> {
|
||||
|
||||
MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
|
||||
|
||||
bool match( ArgT const& arg ) const override {
|
||||
return !m_underlyingMatcher.match( arg );
|
||||
}
|
||||
|
||||
std::string describe() const override {
|
||||
return "not " + m_underlyingMatcher.toString();
|
||||
}
|
||||
MatcherBase<ArgT> const& m_underlyingMatcher;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
|
||||
return MatchAllOf<T>() && *this && other;
|
||||
}
|
||||
template<typename T>
|
||||
MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
|
||||
return MatchAnyOf<T>() || *this || other;
|
||||
}
|
||||
template<typename T>
|
||||
MatchNotOf<T> MatcherBase<T>::operator ! () const {
|
||||
return MatchNotOf<T>( *this );
|
||||
}
|
||||
|
||||
} // namespace Impl
|
||||
|
||||
} // namespace Matchers
|
||||
|
||||
using namespace Matchers;
|
||||
using Matchers::Impl::MatcherBase;
|
||||
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED
|
30
src/internal/catch_matchers_exception.cpp
Normal file
30
src/internal/catch_matchers_exception.cpp
Normal file
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Created by Martin Hořeňovský on 13/10/2019.
|
||||
*
|
||||
* 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_matchers_exception.hpp"
|
||||
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
namespace Exception {
|
||||
|
||||
bool ExceptionMessageMatcher::match(std::exception const& ex) const {
|
||||
return ex.what() == m_message;
|
||||
}
|
||||
|
||||
std::string ExceptionMessageMatcher::describe() const {
|
||||
return "exception message matches \"" + m_message + "\"";
|
||||
}
|
||||
|
||||
}
|
||||
Exception::ExceptionMessageMatcher Message(std::string const& message) {
|
||||
return Exception::ExceptionMessageMatcher(message);
|
||||
}
|
||||
|
||||
// namespace Exception
|
||||
} // namespace Matchers
|
||||
} // namespace Catch
|
36
src/internal/catch_matchers_exception.hpp
Normal file
36
src/internal/catch_matchers_exception.hpp
Normal file
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Created by Martin Hořeňovský on 13/10/2019.
|
||||
*
|
||||
* 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_MATCHERS_EXCEPTION_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_MATCHERS_EXCEPTION_HPP_INCLUDED
|
||||
|
||||
#include "catch_matchers.h"
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
namespace Exception {
|
||||
|
||||
class ExceptionMessageMatcher : public MatcherBase<std::exception> {
|
||||
std::string m_message;
|
||||
public:
|
||||
|
||||
ExceptionMessageMatcher(std::string const& message):
|
||||
m_message(message)
|
||||
{}
|
||||
|
||||
bool match(std::exception const& ex) const override;
|
||||
|
||||
std::string describe() const override;
|
||||
};
|
||||
|
||||
} // namespace Exception
|
||||
|
||||
Exception::ExceptionMessageMatcher Message(std::string const& message);
|
||||
|
||||
} // namespace Matchers
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_MATCHERS_EXCEPTION_HPP_INCLUDED
|
255
src/internal/catch_matchers_floating.cpp
Normal file
255
src/internal/catch_matchers_floating.cpp
Normal file
@@ -0,0 +1,255 @@
|
||||
/*
|
||||
* Created by Martin on 07/11/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_matchers_floating.h"
|
||||
#include "catch_enforce.h"
|
||||
#include "catch_polyfills.hpp"
|
||||
#include "catch_to_string.hpp"
|
||||
#include "catch_tostring.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <type_traits>
|
||||
#include <iomanip>
|
||||
#include <limits>
|
||||
|
||||
|
||||
namespace Catch {
|
||||
namespace {
|
||||
|
||||
int32_t convert(float f) {
|
||||
static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
|
||||
int32_t i;
|
||||
std::memcpy(&i, &f, sizeof(f));
|
||||
return i;
|
||||
}
|
||||
|
||||
int64_t convert(double d) {
|
||||
static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
|
||||
int64_t i;
|
||||
std::memcpy(&i, &d, sizeof(d));
|
||||
return i;
|
||||
}
|
||||
|
||||
template <typename FP>
|
||||
bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
|
||||
// Comparison with NaN should always be false.
|
||||
// This way we can rule it out before getting into the ugly details
|
||||
if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto lc = convert(lhs);
|
||||
auto rc = convert(rhs);
|
||||
|
||||
if ((lc < 0) != (rc < 0)) {
|
||||
// Potentially we can have +0 and -0
|
||||
return lhs == rhs;
|
||||
}
|
||||
|
||||
auto ulpDiff = std::abs(lc - rc);
|
||||
return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
|
||||
}
|
||||
|
||||
} //end anonymous namespace
|
||||
|
||||
#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic push
|
||||
// The long double overload is currently unused
|
||||
#pragma clang diagnostic ignored "-Wunused-function"
|
||||
#endif
|
||||
|
||||
float nextafter(float x, float y) {
|
||||
return ::nextafterf(x, y);
|
||||
}
|
||||
|
||||
double nextafter(double x, double y) {
|
||||
return ::nextafter(x, y);
|
||||
}
|
||||
|
||||
long double nextafter(long double x, long double y) {
|
||||
return ::nextafterl(x, y);
|
||||
}
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
#endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
|
||||
|
||||
namespace {
|
||||
|
||||
template <typename FP>
|
||||
FP step(FP start, FP direction, uint64_t steps) {
|
||||
for (uint64_t i = 0; i < steps; ++i) {
|
||||
#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
|
||||
start = Catch::nextafter(start, direction);
|
||||
#else
|
||||
start = std::nextafter(start, direction);
|
||||
#endif
|
||||
}
|
||||
return start;
|
||||
}
|
||||
|
||||
// Performs equivalent check of std::fabs(lhs - rhs) <= margin
|
||||
// But without the subtraction to allow for INFINITY in comparison
|
||||
bool marginComparison(double lhs, double rhs, double margin) {
|
||||
return (lhs + margin >= rhs) && (rhs + margin >= lhs);
|
||||
}
|
||||
|
||||
template <typename FloatingPoint>
|
||||
void write(std::ostream& out, FloatingPoint num) {
|
||||
out << std::scientific
|
||||
<< std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
|
||||
<< num;
|
||||
}
|
||||
|
||||
} // end anonymous namespace
|
||||
|
||||
namespace Matchers {
|
||||
namespace Floating {
|
||||
|
||||
enum class FloatingPointKind : uint8_t {
|
||||
Float,
|
||||
Double
|
||||
};
|
||||
|
||||
|
||||
WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
|
||||
:m_target{ target }, m_margin{ margin } {
|
||||
CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
|
||||
<< " Margin has to be non-negative.");
|
||||
}
|
||||
|
||||
// Performs equivalent check of std::fabs(lhs - rhs) <= margin
|
||||
// But without the subtraction to allow for INFINITY in comparison
|
||||
bool WithinAbsMatcher::match(double const& matchee) const {
|
||||
return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
|
||||
}
|
||||
|
||||
std::string WithinAbsMatcher::describe() const {
|
||||
return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
|
||||
}
|
||||
|
||||
|
||||
WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
|
||||
:m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
|
||||
CATCH_ENFORCE(m_type == FloatingPointKind::Double
|
||||
|| m_ulps < (std::numeric_limits<uint32_t>::max)(),
|
||||
"Provided ULP is impossibly large for a float comparison.");
|
||||
}
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic push
|
||||
// Clang <3.5 reports on the default branch in the switch below
|
||||
#pragma clang diagnostic ignored "-Wunreachable-code"
|
||||
#endif
|
||||
|
||||
bool WithinUlpsMatcher::match(double const& matchee) const {
|
||||
switch (m_type) {
|
||||
case FloatingPointKind::Float:
|
||||
return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
|
||||
case FloatingPointKind::Double:
|
||||
return almostEqualUlps<double>(matchee, m_target, m_ulps);
|
||||
default:
|
||||
CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
std::string WithinUlpsMatcher::describe() const {
|
||||
std::stringstream ret;
|
||||
|
||||
ret << "is within " << m_ulps << " ULPs of ";
|
||||
|
||||
if (m_type == FloatingPointKind::Float) {
|
||||
write(ret, static_cast<float>(m_target));
|
||||
ret << 'f';
|
||||
} else {
|
||||
write(ret, m_target);
|
||||
}
|
||||
|
||||
ret << " ([";
|
||||
if (m_type == FloatingPointKind::Double) {
|
||||
write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
|
||||
ret << ", ";
|
||||
write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
|
||||
} else {
|
||||
// We have to cast INFINITY to float because of MinGW, see #1782
|
||||
write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
|
||||
ret << ", ";
|
||||
write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
|
||||
}
|
||||
ret << "])";
|
||||
|
||||
return ret.str();
|
||||
}
|
||||
|
||||
WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
|
||||
m_target(target),
|
||||
m_epsilon(epsilon){
|
||||
CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
|
||||
CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
|
||||
}
|
||||
|
||||
bool WithinRelMatcher::match(double const& matchee) const {
|
||||
const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
|
||||
return marginComparison(matchee, m_target,
|
||||
std::isinf(relMargin)? 0 : relMargin);
|
||||
}
|
||||
|
||||
std::string WithinRelMatcher::describe() const {
|
||||
Catch::ReusableStringStream sstr;
|
||||
sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
|
||||
return sstr.str();
|
||||
}
|
||||
|
||||
}// namespace Floating
|
||||
|
||||
|
||||
|
||||
Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
|
||||
return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
|
||||
}
|
||||
|
||||
Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
|
||||
return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
|
||||
}
|
||||
|
||||
Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
|
||||
return Floating::WithinAbsMatcher(target, margin);
|
||||
}
|
||||
|
||||
Floating::WithinRelMatcher WithinRel(double target, double eps) {
|
||||
return Floating::WithinRelMatcher(target, eps);
|
||||
}
|
||||
|
||||
Floating::WithinRelMatcher WithinRel(double target) {
|
||||
return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
|
||||
}
|
||||
|
||||
Floating::WithinRelMatcher WithinRel(float target, float eps) {
|
||||
return Floating::WithinRelMatcher(target, eps);
|
||||
}
|
||||
|
||||
Floating::WithinRelMatcher WithinRel(float target) {
|
||||
return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
|
||||
}
|
||||
|
||||
|
||||
} // namespace Matchers
|
||||
} // namespace Catch
|
||||
|
70
src/internal/catch_matchers_floating.h
Normal file
70
src/internal/catch_matchers_floating.h
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Created by Martin on 07/11/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_MATCHERS_FLOATING_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_MATCHERS_FLOATING_H_INCLUDED
|
||||
|
||||
#include "catch_matchers.h"
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
|
||||
namespace Floating {
|
||||
|
||||
enum class FloatingPointKind : uint8_t;
|
||||
|
||||
struct WithinAbsMatcher : MatcherBase<double> {
|
||||
WithinAbsMatcher(double target, double margin);
|
||||
bool match(double const& matchee) const override;
|
||||
std::string describe() const override;
|
||||
private:
|
||||
double m_target;
|
||||
double m_margin;
|
||||
};
|
||||
|
||||
struct WithinUlpsMatcher : MatcherBase<double> {
|
||||
WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
|
||||
bool match(double const& matchee) const override;
|
||||
std::string describe() const override;
|
||||
private:
|
||||
double m_target;
|
||||
uint64_t m_ulps;
|
||||
FloatingPointKind m_type;
|
||||
};
|
||||
|
||||
// Given IEEE-754 format for floats and doubles, we can assume
|
||||
// that float -> double promotion is lossless. Given this, we can
|
||||
// assume that if we do the standard relative comparison of
|
||||
// |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
|
||||
// the same result if we do this for floats, as if we do this for
|
||||
// doubles that were promoted from floats.
|
||||
struct WithinRelMatcher : MatcherBase<double> {
|
||||
WithinRelMatcher(double target, double epsilon);
|
||||
bool match(double const& matchee) const override;
|
||||
std::string describe() const override;
|
||||
private:
|
||||
double m_target;
|
||||
double m_epsilon;
|
||||
};
|
||||
|
||||
} // namespace Floating
|
||||
|
||||
// The following functions create the actual matcher objects.
|
||||
// This allows the types to be inferred
|
||||
Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
|
||||
Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
|
||||
Floating::WithinAbsMatcher WithinAbs(double target, double margin);
|
||||
Floating::WithinRelMatcher WithinRel(double target, double eps);
|
||||
// defaults epsilon to 100*numeric_limits<double>::epsilon()
|
||||
Floating::WithinRelMatcher WithinRel(double target);
|
||||
Floating::WithinRelMatcher WithinRel(float target, float eps);
|
||||
// defaults epsilon to 100*numeric_limits<float>::epsilon()
|
||||
Floating::WithinRelMatcher WithinRel(float target);
|
||||
|
||||
} // namespace Matchers
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_MATCHERS_FLOATING_H_INCLUDED
|
9
src/internal/catch_matchers_generic.cpp
Normal file
9
src/internal/catch_matchers_generic.cpp
Normal file
@@ -0,0 +1,9 @@
|
||||
#include "catch_matchers_generic.hpp"
|
||||
|
||||
std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
|
||||
if (desc.empty()) {
|
||||
return "matches undescribed predicate";
|
||||
} else {
|
||||
return "matches predicate: \"" + desc + '"';
|
||||
}
|
||||
}
|
61
src/internal/catch_matchers_generic.hpp
Normal file
61
src/internal/catch_matchers_generic.hpp
Normal file
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Created by Martin Hořeňovský on 03/04/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_MATCHERS_GENERIC_HPP_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_MATCHERS_GENERIC_HPP_INCLUDED
|
||||
|
||||
#include "catch_common.h"
|
||||
#include "catch_matchers.h"
|
||||
#include "catch_meta.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
namespace Generic {
|
||||
|
||||
namespace Detail {
|
||||
std::string finalizeDescription(const std::string& desc);
|
||||
}
|
||||
|
||||
template <typename T, typename Predicate>
|
||||
class PredicateMatcher : public MatcherBase<T> {
|
||||
Predicate m_predicate;
|
||||
std::string m_description;
|
||||
public:
|
||||
|
||||
PredicateMatcher(Predicate&& elem, std::string const& descr)
|
||||
:m_predicate(std::forward<Predicate>(elem)),
|
||||
m_description(Detail::finalizeDescription(descr))
|
||||
{}
|
||||
|
||||
bool match( T const& item ) const override {
|
||||
return m_predicate(item);
|
||||
}
|
||||
|
||||
std::string describe() const override {
|
||||
return m_description;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Generic
|
||||
|
||||
// The following functions create the actual matcher objects.
|
||||
// The user has to explicitly specify type to the function, because
|
||||
// inferring std::function<bool(T const&)> is hard (but possible) and
|
||||
// requires a lot of TMP.
|
||||
template<typename T, typename Pred>
|
||||
Generic::PredicateMatcher<T, Pred> Predicate(Pred&& predicate, std::string const& description = "") {
|
||||
static_assert(is_callable<Pred(T)>::value, "Predicate not callable with argument T");
|
||||
static_assert(std::is_same<bool, FunctionReturnType<Pred, T>>::value, "Predicate does not return bool");
|
||||
return Generic::PredicateMatcher<T, Pred>(std::forward<Pred>(predicate), description);
|
||||
}
|
||||
|
||||
} // namespace Matchers
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_MATCHERS_GENERIC_HPP_INCLUDED
|
118
src/internal/catch_matchers_string.cpp
Normal file
118
src/internal/catch_matchers_string.cpp
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Created by Phil Nash on 08/02/2017.
|
||||
* Copyright (c) 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_matchers_string.h"
|
||||
#include "catch_string_manip.h"
|
||||
#include "catch_tostring.h"
|
||||
|
||||
#include <regex>
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
|
||||
namespace StdString {
|
||||
|
||||
CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
|
||||
: m_caseSensitivity( caseSensitivity ),
|
||||
m_str( adjustString( str ) )
|
||||
{}
|
||||
std::string CasedString::adjustString( std::string const& str ) const {
|
||||
return m_caseSensitivity == CaseSensitive::No
|
||||
? toLower( str )
|
||||
: str;
|
||||
}
|
||||
std::string CasedString::caseSensitivitySuffix() const {
|
||||
return m_caseSensitivity == CaseSensitive::No
|
||||
? " (case insensitive)"
|
||||
: std::string();
|
||||
}
|
||||
|
||||
|
||||
StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
|
||||
: m_comparator( comparator ),
|
||||
m_operation( operation ) {
|
||||
}
|
||||
|
||||
std::string StringMatcherBase::describe() const {
|
||||
std::string description;
|
||||
description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
|
||||
m_comparator.caseSensitivitySuffix().size());
|
||||
description += m_operation;
|
||||
description += ": \"";
|
||||
description += m_comparator.m_str;
|
||||
description += "\"";
|
||||
description += m_comparator.caseSensitivitySuffix();
|
||||
return description;
|
||||
}
|
||||
|
||||
EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
|
||||
|
||||
bool EqualsMatcher::match( std::string const& source ) const {
|
||||
return m_comparator.adjustString( source ) == m_comparator.m_str;
|
||||
}
|
||||
|
||||
|
||||
ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
|
||||
|
||||
bool ContainsMatcher::match( std::string const& source ) const {
|
||||
return contains( m_comparator.adjustString( source ), m_comparator.m_str );
|
||||
}
|
||||
|
||||
|
||||
StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
|
||||
|
||||
bool StartsWithMatcher::match( std::string const& source ) const {
|
||||
return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
|
||||
}
|
||||
|
||||
|
||||
EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
|
||||
|
||||
bool EndsWithMatcher::match( std::string const& source ) const {
|
||||
return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
|
||||
}
|
||||
|
||||
|
||||
|
||||
RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
|
||||
|
||||
bool RegexMatcher::match(std::string const& matchee) const {
|
||||
auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
|
||||
if (m_caseSensitivity == CaseSensitive::Choice::No) {
|
||||
flags |= std::regex::icase;
|
||||
}
|
||||
auto reg = std::regex(m_regex, flags);
|
||||
return std::regex_match(matchee, reg);
|
||||
}
|
||||
|
||||
std::string RegexMatcher::describe() const {
|
||||
return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
|
||||
}
|
||||
|
||||
} // namespace StdString
|
||||
|
||||
|
||||
StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
|
||||
return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
|
||||
}
|
||||
StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
|
||||
return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
|
||||
}
|
||||
StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
|
||||
return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
|
||||
}
|
||||
StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
|
||||
return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
|
||||
}
|
||||
|
||||
StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
|
||||
return StdString::RegexMatcher(regex, caseSensitivity);
|
||||
}
|
||||
|
||||
} // namespace Matchers
|
||||
} // namespace Catch
|
80
src/internal/catch_matchers_string.h
Normal file
80
src/internal/catch_matchers_string.h
Normal file
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Created by Phil Nash on 08/02/2017.
|
||||
* Copyright (c) 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_MATCHERS_STRING_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_MATCHERS_STRING_H_INCLUDED
|
||||
|
||||
#include "catch_matchers.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
|
||||
namespace StdString {
|
||||
|
||||
struct CasedString
|
||||
{
|
||||
CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
|
||||
std::string adjustString( std::string const& str ) const;
|
||||
std::string caseSensitivitySuffix() const;
|
||||
|
||||
CaseSensitive::Choice m_caseSensitivity;
|
||||
std::string m_str;
|
||||
};
|
||||
|
||||
struct StringMatcherBase : MatcherBase<std::string> {
|
||||
StringMatcherBase( std::string const& operation, CasedString const& comparator );
|
||||
std::string describe() const override;
|
||||
|
||||
CasedString m_comparator;
|
||||
std::string m_operation;
|
||||
};
|
||||
|
||||
struct EqualsMatcher : StringMatcherBase {
|
||||
EqualsMatcher( CasedString const& comparator );
|
||||
bool match( std::string const& source ) const override;
|
||||
};
|
||||
struct ContainsMatcher : StringMatcherBase {
|
||||
ContainsMatcher( CasedString const& comparator );
|
||||
bool match( std::string const& source ) const override;
|
||||
};
|
||||
struct StartsWithMatcher : StringMatcherBase {
|
||||
StartsWithMatcher( CasedString const& comparator );
|
||||
bool match( std::string const& source ) const override;
|
||||
};
|
||||
struct EndsWithMatcher : StringMatcherBase {
|
||||
EndsWithMatcher( CasedString const& comparator );
|
||||
bool match( std::string const& source ) const override;
|
||||
};
|
||||
|
||||
struct RegexMatcher : MatcherBase<std::string> {
|
||||
RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
|
||||
bool match( std::string const& matchee ) const override;
|
||||
std::string describe() const override;
|
||||
|
||||
private:
|
||||
std::string m_regex;
|
||||
CaseSensitive::Choice m_caseSensitivity;
|
||||
};
|
||||
|
||||
} // namespace StdString
|
||||
|
||||
|
||||
// The following functions create the actual matcher objects.
|
||||
// This allows the types to be inferred
|
||||
|
||||
StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
|
||||
StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
|
||||
StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
|
||||
StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
|
||||
StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
|
||||
|
||||
} // namespace Matchers
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_MATCHERS_STRING_H_INCLUDED
|
182
src/internal/catch_matchers_vector.h
Normal file
182
src/internal/catch_matchers_vector.h
Normal file
@@ -0,0 +1,182 @@
|
||||
/*
|
||||
* Created by Phil Nash on 21/02/2017.
|
||||
* Copyright (c) 2017 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_MATCHERS_VECTOR_H_INCLUDED
|
||||
#define TWOBLUECUBES_CATCH_MATCHERS_VECTOR_H_INCLUDED
|
||||
|
||||
#include "catch_matchers.h"
|
||||
#include "catch_approx.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace Catch {
|
||||
namespace Matchers {
|
||||
|
||||
namespace Vector {
|
||||
template<typename T>
|
||||
struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
|
||||
|
||||
ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
|
||||
|
||||
bool match(std::vector<T> const &v) const override {
|
||||
for (auto const& el : v) {
|
||||
if (el == m_comparator) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string describe() const override {
|
||||
return "Contains: " + ::Catch::Detail::stringify( m_comparator );
|
||||
}
|
||||
|
||||
T const& m_comparator;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct ContainsMatcher : MatcherBase<std::vector<T>> {
|
||||
|
||||
ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
|
||||
|
||||
bool match(std::vector<T> const &v) const override {
|
||||
// !TBD: see note in EqualsMatcher
|
||||
if (m_comparator.size() > v.size())
|
||||
return false;
|
||||
for (auto const& comparator : m_comparator) {
|
||||
auto present = false;
|
||||
for (const auto& el : v) {
|
||||
if (el == comparator) {
|
||||
present = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!present) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::string describe() const override {
|
||||
return "Contains: " + ::Catch::Detail::stringify( m_comparator );
|
||||
}
|
||||
|
||||
std::vector<T> const& m_comparator;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct EqualsMatcher : MatcherBase<std::vector<T>> {
|
||||
|
||||
EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
|
||||
|
||||
bool match(std::vector<T> const &v) const override {
|
||||
// !TBD: This currently works if all elements can be compared using !=
|
||||
// - a more general approach would be via a compare template that defaults
|
||||
// to using !=. but could be specialised for, e.g. std::vector<T> etc
|
||||
// - then just call that directly
|
||||
if (m_comparator.size() != v.size())
|
||||
return false;
|
||||
for (std::size_t i = 0; i < v.size(); ++i)
|
||||
if (m_comparator[i] != v[i])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
std::string describe() const override {
|
||||
return "Equals: " + ::Catch::Detail::stringify( m_comparator );
|
||||
}
|
||||
std::vector<T> const& m_comparator;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct ApproxMatcher : MatcherBase<std::vector<T>> {
|
||||
|
||||
ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
|
||||
|
||||
bool match(std::vector<T> const &v) const override {
|
||||
if (m_comparator.size() != v.size())
|
||||
return false;
|
||||
for (std::size_t i = 0; i < v.size(); ++i)
|
||||
if (m_comparator[i] != approx(v[i]))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
std::string describe() const override {
|
||||
return "is approx: " + ::Catch::Detail::stringify( m_comparator );
|
||||
}
|
||||
template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
ApproxMatcher& epsilon( T const& newEpsilon ) {
|
||||
approx.epsilon(newEpsilon);
|
||||
return *this;
|
||||
}
|
||||
template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
ApproxMatcher& margin( T const& newMargin ) {
|
||||
approx.margin(newMargin);
|
||||
return *this;
|
||||
}
|
||||
template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
|
||||
ApproxMatcher& scale( T const& newScale ) {
|
||||
approx.scale(newScale);
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::vector<T> const& m_comparator;
|
||||
mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
|
||||
UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
|
||||
bool match(std::vector<T> const& vec) const override {
|
||||
// Note: This is a reimplementation of std::is_permutation,
|
||||
// because I don't want to include <algorithm> inside the common path
|
||||
if (m_target.size() != vec.size()) {
|
||||
return false;
|
||||
}
|
||||
return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
|
||||
}
|
||||
|
||||
std::string describe() const override {
|
||||
return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
|
||||
}
|
||||
private:
|
||||
std::vector<T> const& m_target;
|
||||
};
|
||||
|
||||
} // namespace Vector
|
||||
|
||||
// The following functions create the actual matcher objects.
|
||||
// This allows the types to be inferred
|
||||
|
||||
template<typename T>
|
||||
Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
|
||||
return Vector::ContainsMatcher<T>( comparator );
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
|
||||
return Vector::ContainsElementMatcher<T>( comparator );
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
|
||||
return Vector::EqualsMatcher<T>( comparator );
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {
|
||||
return Vector::ApproxMatcher<T>( comparator );
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
|
||||
return Vector::UnorderedEqualsMatcher<T>(target);
|
||||
}
|
||||
|
||||
} // namespace Matchers
|
||||
} // namespace Catch
|
||||
|
||||
#endif // TWOBLUECUBES_CATCH_MATCHERS_VECTOR_H_INCLUDED
|
142
src/internal/catch_message.cpp
Normal file
142
src/internal/catch_message.cpp
Normal file
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* Created by Phil Nash on 1/2/2013.
|
||||
* Copyright 2013 Two Blue Cubes Ltd. All rights reserved.
|
||||
*
|
||||
* 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_message.h"
|
||||
#include "catch_interfaces_capture.h"
|
||||
#include "catch_uncaught_exceptions.h"
|
||||
#include "catch_enforce.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <stack>
|
||||
|
||||
namespace Catch {
|
||||
|
||||
MessageInfo::MessageInfo( StringRef const& _macroName,
|
||||
SourceLineInfo const& _lineInfo,
|
||||
ResultWas::OfType _type )
|
||||
: macroName( _macroName ),
|
||||
lineInfo( _lineInfo ),
|
||||
type( _type ),
|
||||
sequence( ++globalCount )
|
||||
{}
|
||||
|
||||
bool MessageInfo::operator==( MessageInfo const& other ) const {
|
||||
return sequence == other.sequence;
|
||||
}
|
||||
|
||||
bool MessageInfo::operator<( MessageInfo const& other ) const {
|
||||
return sequence < other.sequence;
|
||||
}
|
||||
|
||||
// This may need protecting if threading support is added
|
||||
unsigned int MessageInfo::globalCount = 0;
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
|
||||
SourceLineInfo const& lineInfo,
|
||||
ResultWas::OfType type )
|
||||
:m_info(macroName, lineInfo, type) {}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
ScopedMessage::ScopedMessage( MessageBuilder const& builder )
|
||||
: m_info( builder.m_info ), m_moved()
|
||||
{
|
||||
m_info.message = builder.m_stream.str();
|
||||
getResultCapture().pushScopedMessage( m_info );
|
||||
}
|
||||
|
||||
ScopedMessage::ScopedMessage( ScopedMessage&& old )
|
||||
: m_info( old.m_info ), m_moved()
|
||||
{
|
||||
old.m_moved = true;
|
||||
}
|
||||
|
||||
ScopedMessage::~ScopedMessage() {
|
||||
if ( !uncaught_exceptions() && !m_moved ){
|
||||
getResultCapture().popScopedMessage(m_info);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
|
||||
auto trimmed = [&] (size_t start, size_t end) {
|
||||
while (names[start] == ',' || isspace(names[start])) {
|
||||
++start;
|
||||
}
|
||||
while (names[end] == ',' || isspace(names[end])) {
|
||||
--end;
|
||||
}
|
||||
return names.substr(start, end - start + 1);
|
||||
};
|
||||
auto skipq = [&] (size_t start, char quote) {
|
||||
for (auto i = start + 1; i < names.size() ; ++i) {
|
||||
if (names[i] == quote)
|
||||
return i;
|
||||
if (names[i] == '\\')
|
||||
++i;
|
||||
}
|
||||
CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
|
||||
};
|
||||
|
||||
size_t start = 0;
|
||||
std::stack<char> openings;
|
||||
for (size_t pos = 0; pos < names.size(); ++pos) {
|
||||
char c = names[pos];
|
||||
switch (c) {
|
||||
case '[':
|
||||
case '{':
|
||||
case '(':
|
||||
// It is basically impossible to disambiguate between
|
||||
// comparison and start of template args in this context
|
||||
// case '<':
|
||||
openings.push(c);
|
||||
break;
|
||||
case ']':
|
||||
case '}':
|
||||
case ')':
|
||||
// case '>':
|
||||
openings.pop();
|
||||
break;
|
||||
case '"':
|
||||
case '\'':
|
||||
pos = skipq(pos, c);
|
||||
break;
|
||||
case ',':
|
||||
if (start != pos && openings.size() == 0) {
|
||||
m_messages.emplace_back(macroName, lineInfo, resultType);
|
||||
m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
|
||||
m_messages.back().message += " := ";
|
||||
start = pos;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(openings.size() == 0 && "Mismatched openings");
|
||||
m_messages.emplace_back(macroName, lineInfo, resultType);
|
||||
m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
|
||||
m_messages.back().message += " := ";
|
||||
}
|
||||
Capturer::~Capturer() {
|
||||
if ( !uncaught_exceptions() ){
|
||||
assert( m_captured == m_messages.size() );
|
||||
for( size_t i = 0; i < m_captured; ++i )
|
||||
m_resultCapture.popScopedMessage( m_messages[i] );
|
||||
}
|
||||
}
|
||||
|
||||
void Capturer::captureValue( size_t index, std::string const& value ) {
|
||||
assert( index < m_messages.size() );
|
||||
m_messages[index].message += value;
|
||||
m_resultCapture.pushScopedMessage( m_messages[index] );
|
||||
m_captured++;
|
||||
}
|
||||
|
||||
} // end namespace Catch
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user