| 1 |
|
| 2 |
// Copyright Catch2 Authors |
| 3 |
// Distributed under the Boost Software License, Version 1.0. |
| 4 |
// (See accompanying file LICENSE.txt or copy at |
| 5 |
// https://www.boost.org/LICENSE_1_0.txt) |
| 6 |
|
| 7 |
// SPDX-License-Identifier: BSL-1.0 |
| 8 |
|
| 9 |
// Catch v3.8.1 |
| 10 |
// Generated: 2025-04-08 12:33:19.863332 |
| 11 |
// ---------------------------------------------------------- |
| 12 |
// This file is an amalgamation of multiple different files. |
| 13 |
// You probably shouldn't edit it directly. |
| 14 |
// ---------------------------------------------------------- |
| 15 |
|
| 16 |
#include "catch_amalgamated.hpp" |
| 17 |
|
| 18 |
|
| 19 |
#ifndef CATCH_WINDOWS_H_PROXY_HPP_INCLUDED |
| 20 |
#define CATCH_WINDOWS_H_PROXY_HPP_INCLUDED |
| 21 |
|
| 22 |
|
| 23 |
#if defined(CATCH_PLATFORM_WINDOWS) |
| 24 |
|
| 25 |
// We might end up with the define made globally through the compiler, |
| 26 |
// and we don't want to trigger warnings for this |
| 27 |
#if !defined(NOMINMAX) |
| 28 |
# define NOMINMAX |
| 29 |
#endif |
| 30 |
#if !defined(WIN32_LEAN_AND_MEAN) |
| 31 |
# define WIN32_LEAN_AND_MEAN |
| 32 |
#endif |
| 33 |
|
| 34 |
#include <windows.h> |
| 35 |
|
| 36 |
#endif // defined(CATCH_PLATFORM_WINDOWS) |
| 37 |
|
| 38 |
#endif // CATCH_WINDOWS_H_PROXY_HPP_INCLUDED |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
namespace Catch { |
| 44 |
namespace Benchmark { |
| 45 |
namespace Detail { |
| 46 |
ChronometerConcept::~ChronometerConcept() = default; |
| 47 |
} // namespace Detail |
| 48 |
} // namespace Benchmark |
| 49 |
} // namespace Catch |
| 50 |
|
| 51 |
|
| 52 |
// Adapted from donated nonius code. |
| 53 |
|
| 54 |
|
| 55 |
#include <vector> |
| 56 |
|
| 57 |
namespace Catch { |
| 58 |
namespace Benchmark { |
| 59 |
namespace Detail { |
| 60 |
SampleAnalysis analyse(const IConfig &cfg, FDuration* first, FDuration* last) { |
| 61 |
if (!cfg.benchmarkNoAnalysis()) { |
| 62 |
std::vector<double> samples; |
| 63 |
samples.reserve(static_cast<size_t>(last - first)); |
| 64 |
for (auto current = first; current != last; ++current) { |
| 65 |
samples.push_back( current->count() ); |
| 66 |
} |
| 67 |
|
| 68 |
auto analysis = Catch::Benchmark::Detail::analyse_samples( |
| 69 |
cfg.benchmarkConfidenceInterval(), |
| 70 |
cfg.benchmarkResamples(), |
| 71 |
samples.data(), |
| 72 |
samples.data() + samples.size() ); |
| 73 |
auto outliers = Catch::Benchmark::Detail::classify_outliers( |
| 74 |
samples.data(), samples.data() + samples.size() ); |
| 75 |
|
| 76 |
auto wrap_estimate = [](Estimate<double> e) { |
| 77 |
return Estimate<FDuration> { |
| 78 |
FDuration(e.point), |
| 79 |
FDuration(e.lower_bound), |
| 80 |
FDuration(e.upper_bound), |
| 81 |
e.confidence_interval, |
| 82 |
}; |
| 83 |
}; |
| 84 |
std::vector<FDuration> samples2; |
| 85 |
samples2.reserve(samples.size()); |
| 86 |
for (auto s : samples) { |
| 87 |
samples2.push_back( FDuration( s ) ); |
| 88 |
} |
| 89 |
|
| 90 |
return { |
| 91 |
CATCH_MOVE(samples2), |
| 92 |
wrap_estimate(analysis.mean), |
| 93 |
wrap_estimate(analysis.standard_deviation), |
| 94 |
outliers, |
| 95 |
analysis.outlier_variance, |
| 96 |
}; |
| 97 |
} else { |
| 98 |
std::vector<FDuration> samples; |
| 99 |
samples.reserve(static_cast<size_t>(last - first)); |
| 100 |
|
| 101 |
FDuration mean = FDuration(0); |
| 102 |
int i = 0; |
| 103 |
for (auto it = first; it < last; ++it, ++i) { |
| 104 |
samples.push_back(*it); |
| 105 |
mean += *it; |
| 106 |
} |
| 107 |
mean /= i; |
| 108 |
|
| 109 |
return SampleAnalysis{ |
| 110 |
CATCH_MOVE(samples), |
| 111 |
Estimate<FDuration>{ mean, mean, mean, 0.0 }, |
| 112 |
Estimate<FDuration>{ FDuration( 0 ), |
| 113 |
FDuration( 0 ), |
| 114 |
FDuration( 0 ), |
| 115 |
0.0 }, |
| 116 |
OutlierClassification{}, |
| 117 |
0.0 |
| 118 |
}; |
| 119 |
} |
| 120 |
} |
| 121 |
} // namespace Detail |
| 122 |
} // namespace Benchmark |
| 123 |
} // namespace Catch |
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
namespace Catch { |
| 129 |
namespace Benchmark { |
| 130 |
namespace Detail { |
| 131 |
struct do_nothing { |
| 132 |
void operator()() const {} |
| 133 |
}; |
| 134 |
|
| 135 |
BenchmarkFunction::callable::~callable() = default; |
| 136 |
BenchmarkFunction::BenchmarkFunction(): |
| 137 |
f( new model<do_nothing>{ {} } ){} |
| 138 |
} // namespace Detail |
| 139 |
} // namespace Benchmark |
| 140 |
} // namespace Catch |
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
#include <exception> |
| 146 |
|
| 147 |
namespace Catch { |
| 148 |
namespace Benchmark { |
| 149 |
namespace Detail { |
| 150 |
struct optimized_away_error : std::exception { |
| 151 |
const char* what() const noexcept override; |
| 152 |
}; |
| 153 |
|
| 154 |
const char* optimized_away_error::what() const noexcept { |
| 155 |
return "could not measure benchmark, maybe it was optimized away"; |
| 156 |
} |
| 157 |
|
| 158 |
void throw_optimized_away_error() { |
| 159 |
Catch::throw_exception(optimized_away_error{}); |
| 160 |
} |
| 161 |
|
| 162 |
} // namespace Detail |
| 163 |
} // namespace Benchmark |
| 164 |
} // namespace Catch |
| 165 |
|
| 166 |
|
| 167 |
// Adapted from donated nonius code. |
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
#include <algorithm> |
| 172 |
#include <cassert> |
| 173 |
#include <cmath> |
| 174 |
#include <cstddef> |
| 175 |
#include <numeric> |
| 176 |
#include <random> |
| 177 |
|
| 178 |
|
| 179 |
#if defined(CATCH_CONFIG_USE_ASYNC) |
| 180 |
#include <future> |
| 181 |
#endif |
| 182 |
|
| 183 |
namespace Catch { |
| 184 |
namespace Benchmark { |
| 185 |
namespace Detail { |
| 186 |
namespace { |
| 187 |
|
| 188 |
template <typename URng, typename Estimator> |
| 189 |
static sample |
| 190 |
resample( URng& rng, |
| 191 |
unsigned int resamples, |
| 192 |
double const* first, |
| 193 |
double const* last, |
| 194 |
Estimator& estimator ) { |
| 195 |
auto n = static_cast<size_t>( last - first ); |
| 196 |
Catch::uniform_integer_distribution<size_t> dist( 0, n - 1 ); |
| 197 |
|
| 198 |
sample out; |
| 199 |
out.reserve( resamples ); |
| 200 |
std::vector<double> resampled; |
| 201 |
resampled.reserve( n ); |
| 202 |
for ( size_t i = 0; i < resamples; ++i ) { |
| 203 |
resampled.clear(); |
| 204 |
for ( size_t s = 0; s < n; ++s ) { |
| 205 |
resampled.push_back( first[dist( rng )] ); |
| 206 |
} |
| 207 |
const auto estimate = |
| 208 |
estimator( resampled.data(), resampled.data() + resampled.size() ); |
| 209 |
out.push_back( estimate ); |
| 210 |
} |
| 211 |
std::sort( out.begin(), out.end() ); |
| 212 |
return out; |
| 213 |
} |
| 214 |
|
| 215 |
static double outlier_variance( Estimate<double> mean, |
| 216 |
Estimate<double> stddev, |
| 217 |
int n ) { |
| 218 |
double sb = stddev.point; |
| 219 |
double mn = mean.point / n; |
| 220 |
double mg_min = mn / 2.; |
| 221 |
double sg = (std::min)( mg_min / 4., sb / std::sqrt( n ) ); |
| 222 |
double sg2 = sg * sg; |
| 223 |
double sb2 = sb * sb; |
| 224 |
|
| 225 |
auto c_max = [n, mn, sb2, sg2]( double x ) -> double { |
| 226 |
double k = mn - x; |
| 227 |
double d = k * k; |
| 228 |
double nd = n * d; |
| 229 |
double k0 = -n * nd; |
| 230 |
double k1 = sb2 - n * sg2 + nd; |
| 231 |
double det = k1 * k1 - 4 * sg2 * k0; |
| 232 |
return static_cast<int>( -2. * k0 / |
| 233 |
( k1 + std::sqrt( det ) ) ); |
| 234 |
}; |
| 235 |
|
| 236 |
auto var_out = [n, sb2, sg2]( double c ) { |
| 237 |
double nc = n - c; |
| 238 |
return ( nc / n ) * ( sb2 - nc * sg2 ); |
| 239 |
}; |
| 240 |
|
| 241 |
return (std::min)( var_out( 1 ), |
| 242 |
var_out( |
| 243 |
(std::min)( c_max( 0. ), |
| 244 |
c_max( mg_min ) ) ) ) / |
| 245 |
sb2; |
| 246 |
} |
| 247 |
|
| 248 |
static double erf_inv( double x ) { |
| 249 |
// Code accompanying the article "Approximating the erfinv |
| 250 |
// function" in GPU Computing Gems, Volume 2 |
| 251 |
double w, p; |
| 252 |
|
| 253 |
w = -log( ( 1.0 - x ) * ( 1.0 + x ) ); |
| 254 |
|
| 255 |
if ( w < 6.250000 ) { |
| 256 |
w = w - 3.125000; |
| 257 |
p = -3.6444120640178196996e-21; |
| 258 |
p = -1.685059138182016589e-19 + p * w; |
| 259 |
p = 1.2858480715256400167e-18 + p * w; |
| 260 |
p = 1.115787767802518096e-17 + p * w; |
| 261 |
p = -1.333171662854620906e-16 + p * w; |
| 262 |
p = 2.0972767875968561637e-17 + p * w; |
| 263 |
p = 6.6376381343583238325e-15 + p * w; |
| 264 |
p = -4.0545662729752068639e-14 + p * w; |
| 265 |
p = -8.1519341976054721522e-14 + p * w; |
| 266 |
p = 2.6335093153082322977e-12 + p * w; |
| 267 |
p = -1.2975133253453532498e-11 + p * w; |
| 268 |
p = -5.4154120542946279317e-11 + p * w; |
| 269 |
p = 1.051212273321532285e-09 + p * w; |
| 270 |
p = -4.1126339803469836976e-09 + p * w; |
| 271 |
p = -2.9070369957882005086e-08 + p * w; |
| 272 |
p = 4.2347877827932403518e-07 + p * w; |
| 273 |
p = -1.3654692000834678645e-06 + p * w; |
| 274 |
p = -1.3882523362786468719e-05 + p * w; |
| 275 |
p = 0.0001867342080340571352 + p * w; |
| 276 |
p = -0.00074070253416626697512 + p * w; |
| 277 |
p = -0.0060336708714301490533 + p * w; |
| 278 |
p = 0.24015818242558961693 + p * w; |
| 279 |
p = 1.6536545626831027356 + p * w; |
| 280 |
} else if ( w < 16.000000 ) { |
| 281 |
w = sqrt( w ) - 3.250000; |
| 282 |
p = 2.2137376921775787049e-09; |
| 283 |
p = 9.0756561938885390979e-08 + p * w; |
| 284 |
p = -2.7517406297064545428e-07 + p * w; |
| 285 |
p = 1.8239629214389227755e-08 + p * w; |
| 286 |
p = 1.5027403968909827627e-06 + p * w; |
| 287 |
p = -4.013867526981545969e-06 + p * w; |
| 288 |
p = 2.9234449089955446044e-06 + p * w; |
| 289 |
p = 1.2475304481671778723e-05 + p * w; |
| 290 |
p = -4.7318229009055733981e-05 + p * w; |
| 291 |
p = 6.8284851459573175448e-05 + p * w; |
| 292 |
p = 2.4031110387097893999e-05 + p * w; |
| 293 |
p = -0.0003550375203628474796 + p * w; |
| 294 |
p = 0.00095328937973738049703 + p * w; |
| 295 |
p = -0.0016882755560235047313 + p * w; |
| 296 |
p = 0.0024914420961078508066 + p * w; |
| 297 |
p = -0.0037512085075692412107 + p * w; |
| 298 |
p = 0.005370914553590063617 + p * w; |
| 299 |
p = 1.0052589676941592334 + p * w; |
| 300 |
p = 3.0838856104922207635 + p * w; |
| 301 |
} else { |
| 302 |
w = sqrt( w ) - 5.000000; |
| 303 |
p = -2.7109920616438573243e-11; |
| 304 |
p = -2.5556418169965252055e-10 + p * w; |
| 305 |
p = 1.5076572693500548083e-09 + p * w; |
| 306 |
p = -3.7894654401267369937e-09 + p * w; |
| 307 |
p = 7.6157012080783393804e-09 + p * w; |
| 308 |
p = -1.4960026627149240478e-08 + p * w; |
| 309 |
p = 2.9147953450901080826e-08 + p * w; |
| 310 |
p = -6.7711997758452339498e-08 + p * w; |
| 311 |
p = 2.2900482228026654717e-07 + p * w; |
| 312 |
p = -9.9298272942317002539e-07 + p * w; |
| 313 |
p = 4.5260625972231537039e-06 + p * w; |
| 314 |
p = -1.9681778105531670567e-05 + p * w; |
| 315 |
p = 7.5995277030017761139e-05 + p * w; |
| 316 |
p = -0.00021503011930044477347 + p * w; |
| 317 |
p = -0.00013871931833623122026 + p * w; |
| 318 |
p = 1.0103004648645343977 + p * w; |
| 319 |
p = 4.8499064014085844221 + p * w; |
| 320 |
} |
| 321 |
return p * x; |
| 322 |
} |
| 323 |
|
| 324 |
static double |
| 325 |
standard_deviation( double const* first, double const* last ) { |
| 326 |
auto m = Catch::Benchmark::Detail::mean( first, last ); |
| 327 |
double variance = |
| 328 |
std::accumulate( first, |
| 329 |
last, |
| 330 |
0., |
| 331 |
[m]( double a, double b ) { |
| 332 |
double diff = b - m; |
| 333 |
return a + diff * diff; |
| 334 |
} ) / |
| 335 |
static_cast<double>( last - first ); |
| 336 |
return std::sqrt( variance ); |
| 337 |
} |
| 338 |
|
| 339 |
static sample jackknife( double ( *estimator )( double const*, |
| 340 |
double const* ), |
| 341 |
double* first, |
| 342 |
double* last ) { |
| 343 |
const auto second = first + 1; |
| 344 |
sample results; |
| 345 |
results.reserve( static_cast<size_t>( last - first ) ); |
| 346 |
|
| 347 |
for ( auto it = first; it != last; ++it ) { |
| 348 |
std::iter_swap( it, first ); |
| 349 |
results.push_back( estimator( second, last ) ); |
| 350 |
} |
| 351 |
|
| 352 |
return results; |
| 353 |
} |
| 354 |
|
| 355 |
|
| 356 |
} // namespace |
| 357 |
} // namespace Detail |
| 358 |
} // namespace Benchmark |
| 359 |
} // namespace Catch |
| 360 |
|
| 361 |
namespace Catch { |
| 362 |
namespace Benchmark { |
| 363 |
namespace Detail { |
| 364 |
|
| 365 |
double weighted_average_quantile( int k, |
| 366 |
int q, |
| 367 |
double* first, |
| 368 |
double* last ) { |
| 369 |
auto count = last - first; |
| 370 |
double idx = static_cast<double>((count - 1) * k) / static_cast<double>(q); |
| 371 |
int j = static_cast<int>(idx); |
| 372 |
double g = idx - j; |
| 373 |
std::nth_element(first, first + j, last); |
| 374 |
auto xj = first[j]; |
| 375 |
if ( Catch::Detail::directCompare( g, 0 ) ) { |
| 376 |
return xj; |
| 377 |
} |
| 378 |
|
| 379 |
auto xj1 = *std::min_element(first + (j + 1), last); |
| 380 |
return xj + g * (xj1 - xj); |
| 381 |
} |
| 382 |
|
| 383 |
OutlierClassification |
| 384 |
classify_outliers( double const* first, double const* last ) { |
| 385 |
std::vector<double> copy( first, last ); |
| 386 |
|
| 387 |
auto q1 = weighted_average_quantile( 1, 4, copy.data(), copy.data() + copy.size() ); |
| 388 |
auto q3 = weighted_average_quantile( 3, 4, copy.data(), copy.data() + copy.size() ); |
| 389 |
auto iqr = q3 - q1; |
| 390 |
auto los = q1 - ( iqr * 3. ); |
| 391 |
auto lom = q1 - ( iqr * 1.5 ); |
| 392 |
auto him = q3 + ( iqr * 1.5 ); |
| 393 |
auto his = q3 + ( iqr * 3. ); |
| 394 |
|
| 395 |
OutlierClassification o; |
| 396 |
for ( ; first != last; ++first ) { |
| 397 |
const double t = *first; |
| 398 |
if ( t < los ) { |
| 399 |
++o.low_severe; |
| 400 |
} else if ( t < lom ) { |
| 401 |
++o.low_mild; |
| 402 |
} else if ( t > his ) { |
| 403 |
++o.high_severe; |
| 404 |
} else if ( t > him ) { |
| 405 |
++o.high_mild; |
| 406 |
} |
| 407 |
++o.samples_seen; |
| 408 |
} |
| 409 |
return o; |
| 410 |
} |
| 411 |
|
| 412 |
double mean( double const* first, double const* last ) { |
| 413 |
auto count = last - first; |
| 414 |
double sum = 0.; |
| 415 |
while (first != last) { |
| 416 |
sum += *first; |
| 417 |
++first; |
| 418 |
} |
| 419 |
return sum / static_cast<double>(count); |
| 420 |
} |
| 421 |
|
| 422 |
double normal_cdf( double x ) { |
| 423 |
return std::erfc( -x / std::sqrt( 2.0 ) ) / 2.0; |
| 424 |
} |
| 425 |
|
| 426 |
double erfc_inv(double x) { |
| 427 |
return erf_inv(1.0 - x); |
| 428 |
} |
| 429 |
|
| 430 |
double normal_quantile(double p) { |
| 431 |
static const double ROOT_TWO = std::sqrt(2.0); |
| 432 |
|
| 433 |
double result = 0.0; |
| 434 |
assert(p >= 0 && p <= 1); |
| 435 |
if (p < 0 || p > 1) { |
| 436 |
return result; |
| 437 |
} |
| 438 |
|
| 439 |
result = -erfc_inv(2.0 * p); |
| 440 |
// result *= normal distribution standard deviation (1.0) * sqrt(2) |
| 441 |
result *= /*sd * */ ROOT_TWO; |
| 442 |
// result += normal disttribution mean (0) |
| 443 |
return result; |
| 444 |
} |
| 445 |
|
| 446 |
Estimate<double> |
| 447 |
bootstrap( double confidence_level, |
| 448 |
double* first, |
| 449 |
double* last, |
| 450 |
sample const& resample, |
| 451 |
double ( *estimator )( double const*, double const* ) ) { |
| 452 |
auto n_samples = last - first; |
| 453 |
|
| 454 |
double point = estimator( first, last ); |
| 455 |
// Degenerate case with a single sample |
| 456 |
if ( n_samples == 1 ) |
| 457 |
return { point, point, point, confidence_level }; |
| 458 |
|
| 459 |
sample jack = jackknife( estimator, first, last ); |
| 460 |
double jack_mean = |
| 461 |
mean( jack.data(), jack.data() + jack.size() ); |
| 462 |
double sum_squares = 0, sum_cubes = 0; |
| 463 |
for ( double x : jack ) { |
| 464 |
auto difference = jack_mean - x; |
| 465 |
auto square = difference * difference; |
| 466 |
auto cube = square * difference; |
| 467 |
sum_squares += square; |
| 468 |
sum_cubes += cube; |
| 469 |
} |
| 470 |
|
| 471 |
double accel = sum_cubes / ( 6 * std::pow( sum_squares, 1.5 ) ); |
| 472 |
long n = static_cast<long>( resample.size() ); |
| 473 |
double prob_n = static_cast<double>( |
| 474 |
std::count_if( resample.begin(), |
| 475 |
resample.end(), |
| 476 |
[point]( double x ) { return x < point; } )) / |
| 477 |
static_cast<double>( n ); |
| 478 |
// degenerate case with uniform samples |
| 479 |
if ( Catch::Detail::directCompare( prob_n, 0. ) ) { |
| 480 |
return { point, point, point, confidence_level }; |
| 481 |
} |
| 482 |
|
| 483 |
double bias = normal_quantile( prob_n ); |
| 484 |
double z1 = normal_quantile( ( 1. - confidence_level ) / 2. ); |
| 485 |
|
| 486 |
auto cumn = [n]( double x ) -> long { |
| 487 |
return std::lround( normal_cdf( x ) * |
| 488 |
static_cast<double>( n ) ); |
| 489 |
}; |
| 490 |
auto a = [bias, accel]( double b ) { |
| 491 |
return bias + b / ( 1. - accel * b ); |
| 492 |
}; |
| 493 |
double b1 = bias + z1; |
| 494 |
double b2 = bias - z1; |
| 495 |
double a1 = a( b1 ); |
| 496 |
double a2 = a( b2 ); |
| 497 |
auto lo = static_cast<size_t>( (std::max)( cumn( a1 ), 0l ) ); |
| 498 |
auto hi = |
| 499 |
static_cast<size_t>( (std::min)( cumn( a2 ), n - 1 ) ); |
| 500 |
|
| 501 |
return { point, resample[lo], resample[hi], confidence_level }; |
| 502 |
} |
| 503 |
|
| 504 |
bootstrap_analysis analyse_samples(double confidence_level, |
| 505 |
unsigned int n_resamples, |
| 506 |
double* first, |
| 507 |
double* last) { |
| 508 |
auto mean = &Detail::mean; |
| 509 |
auto stddev = &standard_deviation; |
| 510 |
|
| 511 |
#if defined(CATCH_CONFIG_USE_ASYNC) |
| 512 |
auto Estimate = [=](double(*f)(double const*, double const*)) { |
| 513 |
std::random_device rd; |
| 514 |
auto seed = rd(); |
| 515 |
return std::async(std::launch::async, [=] { |
| 516 |
SimplePcg32 rng( seed ); |
| 517 |
auto resampled = resample(rng, n_resamples, first, last, f); |
| 518 |
return bootstrap(confidence_level, first, last, resampled, f); |
| 519 |
}); |
| 520 |
}; |
| 521 |
|
| 522 |
auto mean_future = Estimate(mean); |
| 523 |
auto stddev_future = Estimate(stddev); |
| 524 |
|
| 525 |
auto mean_estimate = mean_future.get(); |
| 526 |
auto stddev_estimate = stddev_future.get(); |
| 527 |
#else |
| 528 |
auto Estimate = [=](double(*f)(double const* , double const*)) { |
| 529 |
std::random_device rd; |
| 530 |
auto seed = rd(); |
| 531 |
SimplePcg32 rng( seed ); |
| 532 |
auto resampled = resample(rng, n_resamples, first, last, f); |
| 533 |
return bootstrap(confidence_level, first, last, resampled, f); |
| 534 |
}; |
| 535 |
|
| 536 |
auto mean_estimate = Estimate(mean); |
| 537 |
auto stddev_estimate = Estimate(stddev); |
| 538 |
#endif // CATCH_USE_ASYNC |
| 539 |
|
| 540 |
auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++ |
| 541 |
double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n); |
| 542 |
|
| 543 |
return { mean_estimate, stddev_estimate, outlier_variance }; |
| 544 |
} |
| 545 |
} // namespace Detail |
| 546 |
} // namespace Benchmark |
| 547 |
} // namespace Catch |
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
#include <cmath> |
| 552 |
#include <limits> |
| 553 |
|
| 554 |
namespace { |
| 555 |
|
| 556 |
// Performs equivalent check of std::fabs(lhs - rhs) <= margin |
| 557 |
// But without the subtraction to allow for INFINITY in comparison |
| 558 |
bool marginComparison(double lhs, double rhs, double margin) { |
| 559 |
return (lhs + margin >= rhs) && (rhs + margin >= lhs); |
| 560 |
} |
| 561 |
|
| 562 |
} |
| 563 |
|
| 564 |
namespace Catch { |
| 565 |
|
| 566 |
Approx::Approx ( double value ) |
| 567 |
: m_epsilon( static_cast<double>(std::numeric_limits<float>::epsilon())*100. ), |
| 568 |
m_margin( 0.0 ), |
| 569 |
m_scale( 0.0 ), |
| 570 |
m_value( value ) |
| 571 |
{} |
| 572 |
|
| 573 |
Approx Approx::custom() { |
| 574 |
return Approx( 0 ); |
| 575 |
} |
| 576 |
|
| 577 |
Approx Approx::operator-() const { |
| 578 |
auto temp(*this); |
| 579 |
temp.m_value = -temp.m_value; |
| 580 |
return temp; |
| 581 |
} |
| 582 |
|
| 583 |
|
| 584 |
std::string Approx::toString() const { |
| 585 |
ReusableStringStream rss; |
| 586 |
rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )"; |
| 587 |
return rss.str(); |
| 588 |
} |
| 589 |
|
| 590 |
bool Approx::equalityComparisonImpl(const double other) const { |
| 591 |
// First try with fixed margin, then compute margin based on epsilon, scale and Approx's value |
| 592 |
// Thanks to Richard Harris for his help refining the scaled margin value |
| 593 |
return marginComparison(m_value, other, m_margin) |
| 594 |
|| marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value))); |
| 595 |
} |
| 596 |
|
| 597 |
void Approx::setMargin(double newMargin) { |
| 598 |
CATCH_ENFORCE(newMargin >= 0, |
| 599 |
"Invalid Approx::margin: " << newMargin << '.' |
| 600 |
<< " Approx::Margin has to be non-negative."); |
| 601 |
m_margin = newMargin; |
| 602 |
} |
| 603 |
|
| 604 |
void Approx::setEpsilon(double newEpsilon) { |
| 605 |
CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0, |
| 606 |
"Invalid Approx::epsilon: " << newEpsilon << '.' |
| 607 |
<< " Approx::epsilon has to be in [0, 1]"); |
| 608 |
m_epsilon = newEpsilon; |
| 609 |
} |
| 610 |
|
| 611 |
namespace literals { |
| 612 |
Approx operator ""_a(long double val) { |
| 613 |
return Approx(val); |
| 614 |
} |
| 615 |
Approx operator ""_a(unsigned long long val) { |
| 616 |
return Approx(val); |
| 617 |
} |
| 618 |
} // end namespace literals |
| 619 |
|
| 620 |
std::string StringMaker<Catch::Approx>::convert(Catch::Approx const& value) { |
| 621 |
return value.toString(); |
| 622 |
} |
| 623 |
|
| 624 |
} // end namespace Catch |
| 625 |
|
| 626 |
|
| 627 |
|
| 628 |
namespace Catch { |
| 629 |
|
| 630 |
AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const& _lazyExpression): |
| 631 |
lazyExpression(_lazyExpression), |
| 632 |
resultType(_resultType) {} |
| 633 |
|
| 634 |
std::string AssertionResultData::reconstructExpression() const { |
| 635 |
|
| 636 |
if( reconstructedExpression.empty() ) { |
| 637 |
if( lazyExpression ) { |
| 638 |
ReusableStringStream rss; |
| 639 |
rss << lazyExpression; |
| 640 |
reconstructedExpression = rss.str(); |
| 641 |
} |
| 642 |
} |
| 643 |
return reconstructedExpression; |
| 644 |
} |
| 645 |
|
| 646 |
AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData&& data ) |
| 647 |
: m_info( info ), |
| 648 |
m_resultData( CATCH_MOVE(data) ) |
| 649 |
{} |
| 650 |
|
| 651 |
// Result was a success |
| 652 |
bool AssertionResult::succeeded() const { |
| 653 |
return Catch::isOk( m_resultData.resultType ); |
| 654 |
} |
| 655 |
|
| 656 |
// Result was a success, or failure is suppressed |
| 657 |
bool AssertionResult::isOk() const { |
| 658 |
return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); |
| 659 |
} |
| 660 |
|
| 661 |
ResultWas::OfType AssertionResult::getResultType() const { |
| 662 |
return m_resultData.resultType; |
| 663 |
} |
| 664 |
|
| 665 |
bool AssertionResult::hasExpression() const { |
| 666 |
return !m_info.capturedExpression.empty(); |
| 667 |
} |
| 668 |
|
| 669 |
bool AssertionResult::hasMessage() const { |
| 670 |
return !m_resultData.message.empty(); |
| 671 |
} |
| 672 |
|
| 673 |
std::string AssertionResult::getExpression() const { |
| 674 |
// Possibly overallocating by 3 characters should be basically free |
| 675 |
std::string expr; expr.reserve(m_info.capturedExpression.size() + 3); |
| 676 |
if (isFalseTest(m_info.resultDisposition)) { |
| 677 |
expr += "!("; |
| 678 |
} |
| 679 |
expr += m_info.capturedExpression; |
| 680 |
if (isFalseTest(m_info.resultDisposition)) { |
| 681 |
expr += ')'; |
| 682 |
} |
| 683 |
return expr; |
| 684 |
} |
| 685 |
|
| 686 |
std::string AssertionResult::getExpressionInMacro() const { |
| 687 |
if ( m_info.macroName.empty() ) { |
| 688 |
return static_cast<std::string>( m_info.capturedExpression ); |
| 689 |
} |
| 690 |
std::string expr; |
| 691 |
expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 ); |
| 692 |
expr += m_info.macroName; |
| 693 |
expr += "( "; |
| 694 |
expr += m_info.capturedExpression; |
| 695 |
expr += " )"; |
| 696 |
return expr; |
| 697 |
} |
| 698 |
|
| 699 |
bool AssertionResult::hasExpandedExpression() const { |
| 700 |
return hasExpression() && getExpandedExpression() != getExpression(); |
| 701 |
} |
| 702 |
|
| 703 |
std::string AssertionResult::getExpandedExpression() const { |
| 704 |
std::string expr = m_resultData.reconstructExpression(); |
| 705 |
return expr.empty() |
| 706 |
? getExpression() |
| 707 |
: expr; |
| 708 |
} |
| 709 |
|
| 710 |
StringRef AssertionResult::getMessage() const { |
| 711 |
return m_resultData.message; |
| 712 |
} |
| 713 |
SourceLineInfo AssertionResult::getSourceInfo() const { |
| 714 |
return m_info.lineInfo; |
| 715 |
} |
| 716 |
|
| 717 |
StringRef AssertionResult::getTestMacroName() const { |
| 718 |
return m_info.macroName; |
| 719 |
} |
| 720 |
|
| 721 |
} // end namespace Catch |
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
#include <fstream> |
| 726 |
|
| 727 |
namespace Catch { |
| 728 |
|
| 729 |
namespace { |
| 730 |
static bool enableBazelEnvSupport() { |
| 731 |
#if defined( CATCH_CONFIG_BAZEL_SUPPORT ) |
| 732 |
return true; |
| 733 |
#else |
| 734 |
return Detail::getEnv( "BAZEL_TEST" ) != nullptr; |
| 735 |
#endif |
| 736 |
} |
| 737 |
|
| 738 |
struct bazelShardingOptions { |
| 739 |
unsigned int shardIndex, shardCount; |
| 740 |
std::string shardFilePath; |
| 741 |
}; |
| 742 |
|
| 743 |
static Optional<bazelShardingOptions> readBazelShardingOptions() { |
| 744 |
const auto bazelShardIndex = Detail::getEnv( "TEST_SHARD_INDEX" ); |
| 745 |
const auto bazelShardTotal = Detail::getEnv( "TEST_TOTAL_SHARDS" ); |
| 746 |
const auto bazelShardInfoFile = Detail::getEnv( "TEST_SHARD_STATUS_FILE" ); |
| 747 |
|
| 748 |
|
| 749 |
const bool has_all = |
| 750 |
bazelShardIndex && bazelShardTotal && bazelShardInfoFile; |
| 751 |
if ( !has_all ) { |
| 752 |
// We provide nice warning message if the input is |
| 753 |
// misconfigured. |
| 754 |
auto warn = []( const char* env_var ) { |
| 755 |
Catch::cerr() |
| 756 |
<< "Warning: Bazel shard configuration is missing '" |
| 757 |
<< env_var << "'. Shard configuration is skipped.\n"; |
| 758 |
}; |
| 759 |
if ( !bazelShardIndex ) { |
| 760 |
warn( "TEST_SHARD_INDEX" ); |
| 761 |
} |
| 762 |
if ( !bazelShardTotal ) { |
| 763 |
warn( "TEST_TOTAL_SHARDS" ); |
| 764 |
} |
| 765 |
if ( !bazelShardInfoFile ) { |
| 766 |
warn( "TEST_SHARD_STATUS_FILE" ); |
| 767 |
} |
| 768 |
return {}; |
| 769 |
} |
| 770 |
|
| 771 |
auto shardIndex = parseUInt( bazelShardIndex ); |
| 772 |
if ( !shardIndex ) { |
| 773 |
Catch::cerr() |
| 774 |
<< "Warning: could not parse 'TEST_SHARD_INDEX' ('" << bazelShardIndex |
| 775 |
<< "') as unsigned int.\n"; |
| 776 |
return {}; |
| 777 |
} |
| 778 |
auto shardTotal = parseUInt( bazelShardTotal ); |
| 779 |
if ( !shardTotal ) { |
| 780 |
Catch::cerr() |
| 781 |
<< "Warning: could not parse 'TEST_TOTAL_SHARD' ('" |
| 782 |
<< bazelShardTotal << "') as unsigned int.\n"; |
| 783 |
return {}; |
| 784 |
} |
| 785 |
|
| 786 |
return bazelShardingOptions{ |
| 787 |
*shardIndex, *shardTotal, bazelShardInfoFile }; |
| 788 |
|
| 789 |
} |
| 790 |
} // end namespace |
| 791 |
|
| 792 |
|
| 793 |
bool operator==( ProcessedReporterSpec const& lhs, |
| 794 |
ProcessedReporterSpec const& rhs ) { |
| 795 |
return lhs.name == rhs.name && |
| 796 |
lhs.outputFilename == rhs.outputFilename && |
| 797 |
lhs.colourMode == rhs.colourMode && |
| 798 |
lhs.customOptions == rhs.customOptions; |
| 799 |
} |
| 800 |
|
| 801 |
Config::Config( ConfigData const& data ): |
| 802 |
m_data( data ) { |
| 803 |
// We need to trim filter specs to avoid trouble with superfluous |
| 804 |
// whitespace (esp. important for bdd macros, as those are manually |
| 805 |
// aligned with whitespace). |
| 806 |
|
| 807 |
for (auto& elem : m_data.testsOrTags) { |
| 808 |
elem = trim(elem); |
| 809 |
} |
| 810 |
for (auto& elem : m_data.sectionsToRun) { |
| 811 |
elem = trim(elem); |
| 812 |
} |
| 813 |
|
| 814 |
// Insert the default reporter if user hasn't asked for a specific one |
| 815 |
if ( m_data.reporterSpecifications.empty() ) { |
| 816 |
#if defined( CATCH_CONFIG_DEFAULT_REPORTER ) |
| 817 |
const auto default_spec = CATCH_CONFIG_DEFAULT_REPORTER; |
| 818 |
#else |
| 819 |
const auto default_spec = "console"; |
| 820 |
#endif |
| 821 |
auto parsed = parseReporterSpec(default_spec); |
| 822 |
CATCH_ENFORCE( parsed, |
| 823 |
"Cannot parse the provided default reporter spec: '" |
| 824 |
<< default_spec << '\'' ); |
| 825 |
m_data.reporterSpecifications.push_back( std::move( *parsed ) ); |
| 826 |
} |
| 827 |
|
| 828 |
if ( enableBazelEnvSupport() ) { |
| 829 |
readBazelEnvVars(); |
| 830 |
} |
| 831 |
|
| 832 |
// Bazel support can modify the test specs, so parsing has to happen |
| 833 |
// after reading Bazel env vars. |
| 834 |
TestSpecParser parser( ITagAliasRegistry::get() ); |
| 835 |
if ( !m_data.testsOrTags.empty() ) { |
| 836 |
m_hasTestFilters = true; |
| 837 |
for ( auto const& testOrTags : m_data.testsOrTags ) { |
| 838 |
parser.parse( testOrTags ); |
| 839 |
} |
| 840 |
} |
| 841 |
m_testSpec = parser.testSpec(); |
| 842 |
|
| 843 |
|
| 844 |
// We now fixup the reporter specs to handle default output spec, |
| 845 |
// default colour spec, etc |
| 846 |
bool defaultOutputUsed = false; |
| 847 |
for ( auto const& reporterSpec : m_data.reporterSpecifications ) { |
| 848 |
// We do the default-output check separately, while always |
| 849 |
// using the default output below to make the code simpler |
| 850 |
// and avoid superfluous copies. |
| 851 |
if ( reporterSpec.outputFile().none() ) { |
| 852 |
CATCH_ENFORCE( !defaultOutputUsed, |
| 853 |
"Internal error: cannot use default output for " |
| 854 |
"multiple reporters" ); |
| 855 |
defaultOutputUsed = true; |
| 856 |
} |
| 857 |
|
| 858 |
m_processedReporterSpecs.push_back( ProcessedReporterSpec{ |
| 859 |
reporterSpec.name(), |
| 860 |
reporterSpec.outputFile() ? *reporterSpec.outputFile() |
| 861 |
: data.defaultOutputFilename, |
| 862 |
reporterSpec.colourMode().valueOr( data.defaultColourMode ), |
| 863 |
reporterSpec.customOptions() } ); |
| 864 |
} |
| 865 |
} |
| 866 |
|
| 867 |
Config::~Config() = default; |
| 868 |
|
| 869 |
|
| 870 |
bool Config::listTests() const { return m_data.listTests; } |
| 871 |
bool Config::listTags() const { return m_data.listTags; } |
| 872 |
bool Config::listReporters() const { return m_data.listReporters; } |
| 873 |
bool Config::listListeners() const { return m_data.listListeners; } |
| 874 |
|
| 875 |
std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; } |
| 876 |
std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; } |
| 877 |
|
| 878 |
std::vector<ReporterSpec> const& Config::getReporterSpecs() const { |
| 879 |
return m_data.reporterSpecifications; |
| 880 |
} |
| 881 |
|
| 882 |
std::vector<ProcessedReporterSpec> const& |
| 883 |
Config::getProcessedReporterSpecs() const { |
| 884 |
return m_processedReporterSpecs; |
| 885 |
} |
| 886 |
|
| 887 |
TestSpec const& Config::testSpec() const { return m_testSpec; } |
| 888 |
bool Config::hasTestFilters() const { return m_hasTestFilters; } |
| 889 |
|
| 890 |
bool Config::showHelp() const { return m_data.showHelp; } |
| 891 |
|
| 892 |
// IConfig interface |
| 893 |
bool Config::allowThrows() const { return !m_data.noThrow; } |
| 894 |
StringRef Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } |
| 895 |
bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; } |
| 896 |
bool Config::warnAboutMissingAssertions() const { |
| 897 |
return !!( m_data.warnings & WarnAbout::NoAssertions ); |
| 898 |
} |
| 899 |
bool Config::warnAboutUnmatchedTestSpecs() const { |
| 900 |
return !!( m_data.warnings & WarnAbout::UnmatchedTestSpec ); |
| 901 |
} |
| 902 |
bool Config::zeroTestsCountAsSuccess() const { return m_data.allowZeroTests; } |
| 903 |
ShowDurations Config::showDurations() const { return m_data.showDurations; } |
| 904 |
double Config::minDuration() const { return m_data.minDuration; } |
| 905 |
TestRunOrder Config::runOrder() const { return m_data.runOrder; } |
| 906 |
uint32_t Config::rngSeed() const { return m_data.rngSeed; } |
| 907 |
unsigned int Config::shardCount() const { return m_data.shardCount; } |
| 908 |
unsigned int Config::shardIndex() const { return m_data.shardIndex; } |
| 909 |
ColourMode Config::defaultColourMode() const { return m_data.defaultColourMode; } |
| 910 |
bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; } |
| 911 |
int Config::abortAfter() const { return m_data.abortAfter; } |
| 912 |
bool Config::showInvisibles() const { return m_data.showInvisibles; } |
| 913 |
Verbosity Config::verbosity() const { return m_data.verbosity; } |
| 914 |
|
| 915 |
bool Config::skipBenchmarks() const { return m_data.skipBenchmarks; } |
| 916 |
bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; } |
| 917 |
unsigned int Config::benchmarkSamples() const { return m_data.benchmarkSamples; } |
| 918 |
double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; } |
| 919 |
unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; } |
| 920 |
std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); } |
| 921 |
|
| 922 |
void Config::readBazelEnvVars() { |
| 923 |
// Register a JUnit reporter for Bazel. Bazel sets an environment |
| 924 |
// variable with the path to XML output. If this file is written to |
| 925 |
// during test, Bazel will not generate a default XML output. |
| 926 |
// This allows the XML output file to contain higher level of detail |
| 927 |
// than what is possible otherwise. |
| 928 |
const auto bazelOutputFile = Detail::getEnv( "XML_OUTPUT_FILE" ); |
| 929 |
|
| 930 |
if ( bazelOutputFile ) { |
| 931 |
m_data.reporterSpecifications.push_back( |
| 932 |
{ "junit", std::string( bazelOutputFile ), {}, {} } ); |
| 933 |
} |
| 934 |
|
| 935 |
const auto bazelTestSpec = Detail::getEnv( "TESTBRIDGE_TEST_ONLY" ); |
| 936 |
if ( bazelTestSpec ) { |
| 937 |
// Presumably the test spec from environment should overwrite |
| 938 |
// the one we got from CLI (if we got any) |
| 939 |
m_data.testsOrTags.clear(); |
| 940 |
m_data.testsOrTags.push_back( bazelTestSpec ); |
| 941 |
} |
| 942 |
|
| 943 |
const auto bazelShardOptions = readBazelShardingOptions(); |
| 944 |
if ( bazelShardOptions ) { |
| 945 |
std::ofstream f( bazelShardOptions->shardFilePath, |
| 946 |
std::ios_base::out | std::ios_base::trunc ); |
| 947 |
if ( f.is_open() ) { |
| 948 |
f << ""; |
| 949 |
m_data.shardIndex = bazelShardOptions->shardIndex; |
| 950 |
m_data.shardCount = bazelShardOptions->shardCount; |
| 951 |
} |
| 952 |
} |
| 953 |
} |
| 954 |
|
| 955 |
} // end namespace Catch |
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
|
| 961 |
namespace Catch { |
| 962 |
std::uint32_t getSeed() { |
| 963 |
return getCurrentContext().getConfig()->rngSeed(); |
| 964 |
} |
| 965 |
} |
| 966 |
|
| 967 |
|
| 968 |
|
| 969 |
#include <cassert> |
| 970 |
#include <stack> |
| 971 |
|
| 972 |
namespace Catch { |
| 973 |
|
| 974 |
//////////////////////////////////////////////////////////////////////////// |
| 975 |
|
| 976 |
|
| 977 |
ScopedMessage::ScopedMessage( MessageBuilder&& builder ): |
| 978 |
m_info( CATCH_MOVE(builder.m_info) ) { |
| 979 |
m_info.message = builder.m_stream.str(); |
| 980 |
getResultCapture().pushScopedMessage( m_info ); |
| 981 |
} |
| 982 |
|
| 983 |
ScopedMessage::ScopedMessage( ScopedMessage&& old ) noexcept: |
| 984 |
m_info( CATCH_MOVE( old.m_info ) ) { |
| 985 |
old.m_moved = true; |
| 986 |
} |
| 987 |
|
| 988 |
ScopedMessage::~ScopedMessage() { |
| 989 |
if ( !uncaught_exceptions() && !m_moved ){ |
| 990 |
getResultCapture().popScopedMessage(m_info); |
| 991 |
} |
| 992 |
} |
| 993 |
|
| 994 |
|
| 995 |
Capturer::Capturer( StringRef macroName, |
| 996 |
SourceLineInfo const& lineInfo, |
| 997 |
ResultWas::OfType resultType, |
| 998 |
StringRef names ): |
| 999 |
m_resultCapture( getResultCapture() ) { |
| 1000 |
auto trimmed = [&] (size_t start, size_t end) { |
| 1001 |
while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) { |
| 1002 |
++start; |
| 1003 |
} |
| 1004 |
while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) { |
| 1005 |
--end; |
| 1006 |
} |
| 1007 |
return names.substr(start, end - start + 1); |
| 1008 |
}; |
| 1009 |
auto skipq = [&] (size_t start, char quote) { |
| 1010 |
for (auto i = start + 1; i < names.size() ; ++i) { |
| 1011 |
if (names[i] == quote) |
| 1012 |
return i; |
| 1013 |
if (names[i] == '\\') |
| 1014 |
++i; |
| 1015 |
} |
| 1016 |
CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote"); |
| 1017 |
}; |
| 1018 |
|
| 1019 |
size_t start = 0; |
| 1020 |
std::stack<char> openings; |
| 1021 |
for (size_t pos = 0; pos < names.size(); ++pos) { |
| 1022 |
char c = names[pos]; |
| 1023 |
switch (c) { |
| 1024 |
case '[': |
| 1025 |
case '{': |
| 1026 |
case '(': |
| 1027 |
// It is basically impossible to disambiguate between |
| 1028 |
// comparison and start of template args in this context |
| 1029 |
// case '<': |
| 1030 |
openings.push(c); |
| 1031 |
break; |
| 1032 |
case ']': |
| 1033 |
case '}': |
| 1034 |
case ')': |
| 1035 |
// case '>': |
| 1036 |
openings.pop(); |
| 1037 |
break; |
| 1038 |
case '"': |
| 1039 |
case '\'': |
| 1040 |
pos = skipq(pos, c); |
| 1041 |
break; |
| 1042 |
case ',': |
| 1043 |
if (start != pos && openings.empty()) { |
| 1044 |
m_messages.emplace_back(macroName, lineInfo, resultType); |
| 1045 |
m_messages.back().message = static_cast<std::string>(trimmed(start, pos)); |
| 1046 |
m_messages.back().message += " := "; |
| 1047 |
start = pos; |
| 1048 |
} |
| 1049 |
break; |
| 1050 |
default:; // noop |
| 1051 |
} |
| 1052 |
} |
| 1053 |
assert(openings.empty() && "Mismatched openings"); |
| 1054 |
m_messages.emplace_back(macroName, lineInfo, resultType); |
| 1055 |
m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1)); |
| 1056 |
m_messages.back().message += " := "; |
| 1057 |
} |
| 1058 |
Capturer::~Capturer() { |
| 1059 |
if ( !uncaught_exceptions() ){ |
| 1060 |
assert( m_captured == m_messages.size() ); |
| 1061 |
for( size_t i = 0; i < m_captured; ++i ) |
| 1062 |
m_resultCapture.popScopedMessage( m_messages[i] ); |
| 1063 |
} |
| 1064 |
} |
| 1065 |
|
| 1066 |
void Capturer::captureValue( size_t index, std::string const& value ) { |
| 1067 |
assert( index < m_messages.size() ); |
| 1068 |
m_messages[index].message += value; |
| 1069 |
m_resultCapture.pushScopedMessage( m_messages[index] ); |
| 1070 |
m_captured++; |
| 1071 |
} |
| 1072 |
|
| 1073 |
} // end namespace Catch |
| 1074 |
|
| 1075 |
|
| 1076 |
|
| 1077 |
|
| 1078 |
#include <exception> |
| 1079 |
|
| 1080 |
namespace Catch { |
| 1081 |
|
| 1082 |
namespace { |
| 1083 |
|
| 1084 |
class RegistryHub : public IRegistryHub, |
| 1085 |
public IMutableRegistryHub, |
| 1086 |
private Detail::NonCopyable { |
| 1087 |
|
| 1088 |
public: // IRegistryHub |
| 1089 |
RegistryHub() = default; |
| 1090 |
ReporterRegistry const& getReporterRegistry() const override { |
| 1091 |
return m_reporterRegistry; |
| 1092 |
} |
| 1093 |
ITestCaseRegistry const& getTestCaseRegistry() const override { |
| 1094 |
return m_testCaseRegistry; |
| 1095 |
} |
| 1096 |
IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override { |
| 1097 |
return m_exceptionTranslatorRegistry; |
| 1098 |
} |
| 1099 |
ITagAliasRegistry const& getTagAliasRegistry() const override { |
| 1100 |
return m_tagAliasRegistry; |
| 1101 |
} |
| 1102 |
StartupExceptionRegistry const& getStartupExceptionRegistry() const override { |
| 1103 |
return m_exceptionRegistry; |
| 1104 |
} |
| 1105 |
|
| 1106 |
public: // IMutableRegistryHub |
| 1107 |
void registerReporter( std::string const& name, IReporterFactoryPtr factory ) override { |
| 1108 |
m_reporterRegistry.registerReporter( name, CATCH_MOVE(factory) ); |
| 1109 |
} |
| 1110 |
void registerListener( Detail::unique_ptr<EventListenerFactory> factory ) override { |
| 1111 |
m_reporterRegistry.registerListener( CATCH_MOVE(factory) ); |
| 1112 |
} |
| 1113 |
void registerTest( Detail::unique_ptr<TestCaseInfo>&& testInfo, Detail::unique_ptr<ITestInvoker>&& invoker ) override { |
| 1114 |
m_testCaseRegistry.registerTest( CATCH_MOVE(testInfo), CATCH_MOVE(invoker) ); |
| 1115 |
} |
| 1116 |
void registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator ) override { |
| 1117 |
m_exceptionTranslatorRegistry.registerTranslator( CATCH_MOVE(translator) ); |
| 1118 |
} |
| 1119 |
void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override { |
| 1120 |
m_tagAliasRegistry.add( alias, tag, lineInfo ); |
| 1121 |
} |
| 1122 |
void registerStartupException() noexcept override { |
| 1123 |
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) |
| 1124 |
m_exceptionRegistry.add(std::current_exception()); |
| 1125 |
#else |
| 1126 |
CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); |
| 1127 |
#endif |
| 1128 |
} |
| 1129 |
IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override { |
| 1130 |
return m_enumValuesRegistry; |
| 1131 |
} |
| 1132 |
|
| 1133 |
private: |
| 1134 |
TestRegistry m_testCaseRegistry; |
| 1135 |
ReporterRegistry m_reporterRegistry; |
| 1136 |
ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; |
| 1137 |
TagAliasRegistry m_tagAliasRegistry; |
| 1138 |
StartupExceptionRegistry m_exceptionRegistry; |
| 1139 |
Detail::EnumValuesRegistry m_enumValuesRegistry; |
| 1140 |
}; |
| 1141 |
} |
| 1142 |
|
| 1143 |
using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>; |
| 1144 |
|
| 1145 |
IRegistryHub const& getRegistryHub() { |
| 1146 |
return RegistryHubSingleton::get(); |
| 1147 |
} |
| 1148 |
IMutableRegistryHub& getMutableRegistryHub() { |
| 1149 |
return RegistryHubSingleton::getMutable(); |
| 1150 |
} |
| 1151 |
void cleanUp() { |
| 1152 |
cleanupSingletons(); |
| 1153 |
cleanUpContext(); |
| 1154 |
} |
| 1155 |
std::string translateActiveException() { |
| 1156 |
return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); |
| 1157 |
} |
| 1158 |
|
| 1159 |
|
| 1160 |
} // end namespace Catch |
| 1161 |
|
| 1162 |
|
| 1163 |
|
| 1164 |
#include <algorithm> |
| 1165 |
#include <cassert> |
| 1166 |
#include <exception> |
| 1167 |
#include <iomanip> |
| 1168 |
#include <set> |
| 1169 |
|
| 1170 |
namespace Catch { |
| 1171 |
|
| 1172 |
namespace { |
| 1173 |
static constexpr int TestFailureExitCode = 42; |
| 1174 |
static constexpr int UnspecifiedErrorExitCode = 1; |
| 1175 |
static constexpr int AllTestsSkippedExitCode = 4; |
| 1176 |
static constexpr int NoTestsRunExitCode = 2; |
| 1177 |
static constexpr int UnmatchedTestSpecExitCode = 3; |
| 1178 |
static constexpr int InvalidTestSpecExitCode = 5; |
| 1179 |
|
| 1180 |
|
| 1181 |
IEventListenerPtr createReporter(std::string const& reporterName, ReporterConfig&& config) { |
| 1182 |
auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, CATCH_MOVE(config)); |
| 1183 |
CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << '\''); |
| 1184 |
|
| 1185 |
return reporter; |
| 1186 |
} |
| 1187 |
|
| 1188 |
IEventListenerPtr prepareReporters(Config const* config) { |
| 1189 |
if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty() |
| 1190 |
&& config->getProcessedReporterSpecs().size() == 1) { |
| 1191 |
auto const& spec = config->getProcessedReporterSpecs()[0]; |
| 1192 |
return createReporter( |
| 1193 |
spec.name, |
| 1194 |
ReporterConfig( config, |
| 1195 |
makeStream( spec.outputFilename ), |
| 1196 |
spec.colourMode, |
| 1197 |
spec.customOptions ) ); |
| 1198 |
} |
| 1199 |
|
| 1200 |
auto multi = Detail::make_unique<MultiReporter>(config); |
| 1201 |
|
| 1202 |
auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners(); |
| 1203 |
for (auto const& listener : listeners) { |
| 1204 |
multi->addListener(listener->create(config)); |
| 1205 |
} |
| 1206 |
|
| 1207 |
for ( auto const& reporterSpec : config->getProcessedReporterSpecs() ) { |
| 1208 |
multi->addReporter( createReporter( |
| 1209 |
reporterSpec.name, |
| 1210 |
ReporterConfig( config, |
| 1211 |
makeStream( reporterSpec.outputFilename ), |
| 1212 |
reporterSpec.colourMode, |
| 1213 |
reporterSpec.customOptions ) ) ); |
| 1214 |
} |
| 1215 |
|
| 1216 |
return multi; |
| 1217 |
} |
| 1218 |
|
| 1219 |
class TestGroup { |
| 1220 |
public: |
| 1221 |
explicit TestGroup(IEventListenerPtr&& reporter, Config const* config): |
| 1222 |
m_reporter(reporter.get()), |
| 1223 |
m_config{config}, |
| 1224 |
m_context{config, CATCH_MOVE(reporter)} { |
| 1225 |
|
| 1226 |
assert( m_config->testSpec().getInvalidSpecs().empty() && |
| 1227 |
"Invalid test specs should be handled before running tests" ); |
| 1228 |
|
| 1229 |
auto const& allTestCases = getAllTestCasesSorted(*m_config); |
| 1230 |
auto const& testSpec = m_config->testSpec(); |
| 1231 |
if ( !testSpec.hasFilters() ) { |
| 1232 |
for ( auto const& test : allTestCases ) { |
| 1233 |
if ( !test.getTestCaseInfo().isHidden() ) { |
| 1234 |
m_tests.emplace( &test ); |
| 1235 |
} |
| 1236 |
} |
| 1237 |
} else { |
| 1238 |
m_matches = |
| 1239 |
testSpec.matchesByFilter( allTestCases, *m_config ); |
| 1240 |
for ( auto const& match : m_matches ) { |
| 1241 |
m_tests.insert( match.tests.begin(), |
| 1242 |
match.tests.end() ); |
| 1243 |
} |
| 1244 |
} |
| 1245 |
|
| 1246 |
m_tests = createShard(m_tests, m_config->shardCount(), m_config->shardIndex()); |
| 1247 |
} |
| 1248 |
|
| 1249 |
Totals execute() { |
| 1250 |
Totals totals; |
| 1251 |
for (auto const& testCase : m_tests) { |
| 1252 |
if (!m_context.aborting()) |
| 1253 |
totals += m_context.runTest(*testCase); |
| 1254 |
else |
| 1255 |
m_reporter->skipTest(testCase->getTestCaseInfo()); |
| 1256 |
} |
| 1257 |
|
| 1258 |
for (auto const& match : m_matches) { |
| 1259 |
if (match.tests.empty()) { |
| 1260 |
m_unmatchedTestSpecs = true; |
| 1261 |
m_reporter->noMatchingTestCases( match.name ); |
| 1262 |
} |
| 1263 |
} |
| 1264 |
|
| 1265 |
return totals; |
| 1266 |
} |
| 1267 |
|
| 1268 |
bool hadUnmatchedTestSpecs() const { |
| 1269 |
return m_unmatchedTestSpecs; |
| 1270 |
} |
| 1271 |
|
| 1272 |
|
| 1273 |
private: |
| 1274 |
IEventListener* m_reporter; |
| 1275 |
Config const* m_config; |
| 1276 |
RunContext m_context; |
| 1277 |
std::set<TestCaseHandle const*> m_tests; |
| 1278 |
TestSpec::Matches m_matches; |
| 1279 |
bool m_unmatchedTestSpecs = false; |
| 1280 |
}; |
| 1281 |
|
| 1282 |
void applyFilenamesAsTags() { |
| 1283 |
for (auto const& testInfo : getRegistryHub().getTestCaseRegistry().getAllInfos()) { |
| 1284 |
testInfo->addFilenameTag(); |
| 1285 |
} |
| 1286 |
} |
| 1287 |
|
| 1288 |
} // anon namespace |
| 1289 |
|
| 1290 |
Session::Session() { |
| 1291 |
static bool alreadyInstantiated = false; |
| 1292 |
if( alreadyInstantiated ) { |
| 1293 |
CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); } |
| 1294 |
CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); } |
| 1295 |
} |
| 1296 |
|
| 1297 |
// There cannot be exceptions at startup in no-exception mode. |
| 1298 |
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) |
| 1299 |
const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions(); |
| 1300 |
if ( !exceptions.empty() ) { |
| 1301 |
config(); |
| 1302 |
getCurrentMutableContext().setConfig(m_config.get()); |
| 1303 |
|
| 1304 |
m_startupExceptions = true; |
| 1305 |
auto errStream = makeStream( "%stderr" ); |
| 1306 |
auto colourImpl = makeColourImpl( |
| 1307 |
ColourMode::PlatformDefault, errStream.get() ); |
| 1308 |
auto guard = colourImpl->guardColour( Colour::Red ); |
| 1309 |
errStream->stream() << "Errors occurred during startup!" << '\n'; |
| 1310 |
// iterate over all exceptions and notify user |
| 1311 |
for ( const auto& ex_ptr : exceptions ) { |
| 1312 |
try { |
| 1313 |
std::rethrow_exception(ex_ptr); |
| 1314 |
} catch ( std::exception const& ex ) { |
| 1315 |
errStream->stream() << TextFlow::Column( ex.what() ).indent(2) << '\n'; |
| 1316 |
} |
| 1317 |
} |
| 1318 |
} |
| 1319 |
#endif |
| 1320 |
|
| 1321 |
alreadyInstantiated = true; |
| 1322 |
m_cli = makeCommandLineParser( m_configData ); |
| 1323 |
} |
| 1324 |
Session::~Session() { |
| 1325 |
Catch::cleanUp(); |
| 1326 |
} |
| 1327 |
|
| 1328 |
void Session::showHelp() const { |
| 1329 |
Catch::cout() |
| 1330 |
<< "\nCatch2 v" << libraryVersion() << '\n' |
| 1331 |
<< m_cli << '\n' |
| 1332 |
<< "For more detailed usage please see the project docs\n\n" << std::flush; |
| 1333 |
} |
| 1334 |
void Session::libIdentify() { |
| 1335 |
Catch::cout() |
| 1336 |
<< std::left << std::setw(16) << "description: " << "A Catch2 test executable\n" |
| 1337 |
<< std::left << std::setw(16) << "category: " << "testframework\n" |
| 1338 |
<< std::left << std::setw(16) << "framework: " << "Catch2\n" |
| 1339 |
<< std::left << std::setw(16) << "version: " << libraryVersion() << '\n' << std::flush; |
| 1340 |
} |
| 1341 |
|
| 1342 |
int Session::applyCommandLine( int argc, char const * const * argv ) { |
| 1343 |
if ( m_startupExceptions ) { return UnspecifiedErrorExitCode; } |
| 1344 |
|
| 1345 |
auto result = m_cli.parse( Clara::Args( argc, argv ) ); |
| 1346 |
|
| 1347 |
if( !result ) { |
| 1348 |
config(); |
| 1349 |
getCurrentMutableContext().setConfig(m_config.get()); |
| 1350 |
auto errStream = makeStream( "%stderr" ); |
| 1351 |
auto colour = makeColourImpl( ColourMode::PlatformDefault, errStream.get() ); |
| 1352 |
|
| 1353 |
errStream->stream() |
| 1354 |
<< colour->guardColour( Colour::Red ) |
| 1355 |
<< "\nError(s) in input:\n" |
| 1356 |
<< TextFlow::Column( result.errorMessage() ).indent( 2 ) |
| 1357 |
<< "\n\n"; |
| 1358 |
errStream->stream() << "Run with -? for usage\n\n" << std::flush; |
| 1359 |
return UnspecifiedErrorExitCode; |
| 1360 |
} |
| 1361 |
|
| 1362 |
if( m_configData.showHelp ) |
| 1363 |
showHelp(); |
| 1364 |
if( m_configData.libIdentify ) |
| 1365 |
libIdentify(); |
| 1366 |
|
| 1367 |
m_config.reset(); |
| 1368 |
return 0; |
| 1369 |
} |
| 1370 |
|
| 1371 |
#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) |
| 1372 |
int Session::applyCommandLine( int argc, wchar_t const * const * argv ) { |
| 1373 |
|
| 1374 |
char **utf8Argv = new char *[ argc ]; |
| 1375 |
|
| 1376 |
for ( int i = 0; i < argc; ++i ) { |
| 1377 |
int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr ); |
| 1378 |
|
| 1379 |
utf8Argv[ i ] = new char[ bufSize ]; |
| 1380 |
|
| 1381 |
WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr ); |
| 1382 |
} |
| 1383 |
|
| 1384 |
int returnCode = applyCommandLine( argc, utf8Argv ); |
| 1385 |
|
| 1386 |
for ( int i = 0; i < argc; ++i ) |
| 1387 |
delete [] utf8Argv[ i ]; |
| 1388 |
|
| 1389 |
delete [] utf8Argv; |
| 1390 |
|
| 1391 |
return returnCode; |
| 1392 |
} |
| 1393 |
#endif |
| 1394 |
|
| 1395 |
void Session::useConfigData( ConfigData const& configData ) { |
| 1396 |
m_configData = configData; |
| 1397 |
m_config.reset(); |
| 1398 |
} |
| 1399 |
|
| 1400 |
int Session::run() { |
| 1401 |
if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) { |
| 1402 |
Catch::cout() << "...waiting for enter/ return before starting\n" << std::flush; |
| 1403 |
static_cast<void>(std::getchar()); |
| 1404 |
} |
| 1405 |
int exitCode = runInternal(); |
| 1406 |
if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) { |
| 1407 |
Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << '\n' << std::flush; |
| 1408 |
static_cast<void>(std::getchar()); |
| 1409 |
} |
| 1410 |
return exitCode; |
| 1411 |
} |
| 1412 |
|
| 1413 |
Clara::Parser const& Session::cli() const { |
| 1414 |
return m_cli; |
| 1415 |
} |
| 1416 |
void Session::cli( Clara::Parser const& newParser ) { |
| 1417 |
m_cli = newParser; |
| 1418 |
} |
| 1419 |
ConfigData& Session::configData() { |
| 1420 |
return m_configData; |
| 1421 |
} |
| 1422 |
Config& Session::config() { |
| 1423 |
if( !m_config ) |
| 1424 |
m_config = Detail::make_unique<Config>( m_configData ); |
| 1425 |
return *m_config; |
| 1426 |
} |
| 1427 |
|
| 1428 |
int Session::runInternal() { |
| 1429 |
if ( m_startupExceptions ) { return UnspecifiedErrorExitCode; } |
| 1430 |
|
| 1431 |
if (m_configData.showHelp || m_configData.libIdentify) { |
| 1432 |
return 0; |
| 1433 |
} |
| 1434 |
|
| 1435 |
if ( m_configData.shardIndex >= m_configData.shardCount ) { |
| 1436 |
Catch::cerr() << "The shard count (" << m_configData.shardCount |
| 1437 |
<< ") must be greater than the shard index (" |
| 1438 |
<< m_configData.shardIndex << ")\n" |
| 1439 |
<< std::flush; |
| 1440 |
return UnspecifiedErrorExitCode; |
| 1441 |
} |
| 1442 |
|
| 1443 |
CATCH_TRY { |
| 1444 |
config(); // Force config to be constructed |
| 1445 |
|
| 1446 |
seedRng( *m_config ); |
| 1447 |
|
| 1448 |
if (m_configData.filenamesAsTags) { |
| 1449 |
applyFilenamesAsTags(); |
| 1450 |
} |
| 1451 |
|
| 1452 |
// Set up global config instance before we start calling into other functions |
| 1453 |
getCurrentMutableContext().setConfig(m_config.get()); |
| 1454 |
|
| 1455 |
// Create reporter(s) so we can route listings through them |
| 1456 |
auto reporter = prepareReporters(m_config.get()); |
| 1457 |
|
| 1458 |
auto const& invalidSpecs = m_config->testSpec().getInvalidSpecs(); |
| 1459 |
if ( !invalidSpecs.empty() ) { |
| 1460 |
for ( auto const& spec : invalidSpecs ) { |
| 1461 |
reporter->reportInvalidTestSpec( spec ); |
| 1462 |
} |
| 1463 |
return InvalidTestSpecExitCode; |
| 1464 |
} |
| 1465 |
|
| 1466 |
|
| 1467 |
// Handle list request |
| 1468 |
if (list(*reporter, *m_config)) { |
| 1469 |
return 0; |
| 1470 |
} |
| 1471 |
|
| 1472 |
TestGroup tests { CATCH_MOVE(reporter), m_config.get() }; |
| 1473 |
auto const totals = tests.execute(); |
| 1474 |
|
| 1475 |
if ( tests.hadUnmatchedTestSpecs() |
| 1476 |
&& m_config->warnAboutUnmatchedTestSpecs() ) { |
| 1477 |
// UnmatchedTestSpecExitCode |
| 1478 |
return UnmatchedTestSpecExitCode; |
| 1479 |
} |
| 1480 |
|
| 1481 |
if ( totals.testCases.total() == 0 |
| 1482 |
&& !m_config->zeroTestsCountAsSuccess() ) { |
| 1483 |
return NoTestsRunExitCode; |
| 1484 |
} |
| 1485 |
|
| 1486 |
if ( totals.testCases.total() > 0 && |
| 1487 |
totals.testCases.total() == totals.testCases.skipped |
| 1488 |
&& !m_config->zeroTestsCountAsSuccess() ) { |
| 1489 |
return AllTestsSkippedExitCode; |
| 1490 |
} |
| 1491 |
|
| 1492 |
if ( totals.assertions.failed ) { return TestFailureExitCode; } |
| 1493 |
return 0; |
| 1494 |
|
| 1495 |
} |
| 1496 |
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) |
| 1497 |
catch( std::exception& ex ) { |
| 1498 |
Catch::cerr() << ex.what() << '\n' << std::flush; |
| 1499 |
return UnspecifiedErrorExitCode; |
| 1500 |
} |
| 1501 |
#endif |
| 1502 |
} |
| 1503 |
|
| 1504 |
} // end namespace Catch |
| 1505 |
|
| 1506 |
|
| 1507 |
|
| 1508 |
|
| 1509 |
namespace Catch { |
| 1510 |
|
| 1511 |
RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) { |
| 1512 |
CATCH_TRY { |
| 1513 |
getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo); |
| 1514 |
} CATCH_CATCH_ALL { |
| 1515 |
// Do not throw when constructing global objects, instead register the exception to be processed later |
| 1516 |
getMutableRegistryHub().registerStartupException(); |
| 1517 |
} |
| 1518 |
} |
| 1519 |
|
| 1520 |
} |
| 1521 |
|
| 1522 |
|
| 1523 |
|
| 1524 |
#include <cassert> |
| 1525 |
#include <cctype> |
| 1526 |
#include <algorithm> |
| 1527 |
|
| 1528 |
namespace Catch { |
| 1529 |
|
| 1530 |
namespace { |
| 1531 |
using TCP_underlying_type = uint8_t; |
| 1532 |
static_assert(sizeof(TestCaseProperties) == sizeof(TCP_underlying_type), |
| 1533 |
"The size of the TestCaseProperties is different from the assumed size"); |
| 1534 |
|
| 1535 |
constexpr TestCaseProperties operator|(TestCaseProperties lhs, TestCaseProperties rhs) { |
| 1536 |
return static_cast<TestCaseProperties>( |
| 1537 |
static_cast<TCP_underlying_type>(lhs) | static_cast<TCP_underlying_type>(rhs) |
| 1538 |
); |
| 1539 |
} |
| 1540 |
|
| 1541 |
constexpr TestCaseProperties& operator|=(TestCaseProperties& lhs, TestCaseProperties rhs) { |
| 1542 |
lhs = static_cast<TestCaseProperties>( |
| 1543 |
static_cast<TCP_underlying_type>(lhs) | static_cast<TCP_underlying_type>(rhs) |
| 1544 |
); |
| 1545 |
return lhs; |
| 1546 |
} |
| 1547 |
|
| 1548 |
constexpr TestCaseProperties operator&(TestCaseProperties lhs, TestCaseProperties rhs) { |
| 1549 |
return static_cast<TestCaseProperties>( |
| 1550 |
static_cast<TCP_underlying_type>(lhs) & static_cast<TCP_underlying_type>(rhs) |
| 1551 |
); |
| 1552 |
} |
| 1553 |
|
| 1554 |
constexpr bool applies(TestCaseProperties tcp) { |
| 1555 |
static_assert(static_cast<TCP_underlying_type>(TestCaseProperties::None) == 0, |
| 1556 |
"TestCaseProperties::None must be equal to 0"); |
| 1557 |
return tcp != TestCaseProperties::None; |
| 1558 |
} |
| 1559 |
|
| 1560 |
TestCaseProperties parseSpecialTag( StringRef tag ) { |
| 1561 |
if( !tag.empty() && tag[0] == '.' ) |
| 1562 |
return TestCaseProperties::IsHidden; |
| 1563 |
else if( tag == "!throws"_sr ) |
| 1564 |
return TestCaseProperties::Throws; |
| 1565 |
else if( tag == "!shouldfail"_sr ) |
| 1566 |
return TestCaseProperties::ShouldFail; |
| 1567 |
else if( tag == "!mayfail"_sr ) |
| 1568 |
return TestCaseProperties::MayFail; |
| 1569 |
else if( tag == "!nonportable"_sr ) |
| 1570 |
return TestCaseProperties::NonPortable; |
| 1571 |
else if( tag == "!benchmark"_sr ) |
| 1572 |
return TestCaseProperties::Benchmark | TestCaseProperties::IsHidden; |
| 1573 |
else |
| 1574 |
return TestCaseProperties::None; |
| 1575 |
} |
| 1576 |
bool isReservedTag( StringRef tag ) { |
| 1577 |
return parseSpecialTag( tag ) == TestCaseProperties::None |
| 1578 |
&& tag.size() > 0 |
| 1579 |
&& !std::isalnum( static_cast<unsigned char>(tag[0]) ); |
| 1580 |
} |
| 1581 |
void enforceNotReservedTag( StringRef tag, SourceLineInfo const& _lineInfo ) { |
| 1582 |
CATCH_ENFORCE( !isReservedTag(tag), |
| 1583 |
"Tag name: [" << tag << "] is not allowed.\n" |
| 1584 |
<< "Tag names starting with non alphanumeric characters are reserved\n" |
| 1585 |
<< _lineInfo ); |
| 1586 |
} |
| 1587 |
|
| 1588 |
std::string makeDefaultName() { |
| 1589 |
static size_t counter = 0; |
| 1590 |
return "Anonymous test case " + std::to_string(++counter); |
| 1591 |
} |
| 1592 |
|
| 1593 |
constexpr StringRef extractFilenamePart(StringRef filename) { |
| 1594 |
size_t lastDot = filename.size(); |
| 1595 |
while (lastDot > 0 && filename[lastDot - 1] != '.') { |
| 1596 |
--lastDot; |
| 1597 |
} |
| 1598 |
// In theory we could have filename without any extension in it |
| 1599 |
if ( lastDot == 0 ) { return StringRef(); } |
| 1600 |
|
| 1601 |
--lastDot; |
| 1602 |
size_t nameStart = lastDot; |
| 1603 |
while (nameStart > 0 && filename[nameStart - 1] != '/' && filename[nameStart - 1] != '\\') { |
| 1604 |
--nameStart; |
| 1605 |
} |
| 1606 |
|
| 1607 |
return filename.substr(nameStart, lastDot - nameStart); |
| 1608 |
} |
| 1609 |
|
| 1610 |
// Returns the upper bound on size of extra tags ([#file]+[.]) |
| 1611 |
constexpr size_t sizeOfExtraTags(StringRef filepath) { |
| 1612 |
// [.] is 3, [#] is another 3 |
| 1613 |
const size_t extras = 3 + 3; |
| 1614 |
return extractFilenamePart(filepath).size() + extras; |
| 1615 |
} |
| 1616 |
} // end unnamed namespace |
| 1617 |
|
| 1618 |
bool operator<( Tag const& lhs, Tag const& rhs ) { |
| 1619 |
Detail::CaseInsensitiveLess cmp; |
| 1620 |
return cmp( lhs.original, rhs.original ); |
| 1621 |
} |
| 1622 |
bool operator==( Tag const& lhs, Tag const& rhs ) { |
| 1623 |
Detail::CaseInsensitiveEqualTo cmp; |
| 1624 |
return cmp( lhs.original, rhs.original ); |
| 1625 |
} |
| 1626 |
|
| 1627 |
Detail::unique_ptr<TestCaseInfo> |
| 1628 |
makeTestCaseInfo(StringRef _className, |
| 1629 |
NameAndTags const& nameAndTags, |
| 1630 |
SourceLineInfo const& _lineInfo ) { |
| 1631 |
return Detail::make_unique<TestCaseInfo>(_className, nameAndTags, _lineInfo); |
| 1632 |
} |
| 1633 |
|
| 1634 |
TestCaseInfo::TestCaseInfo(StringRef _className, |
| 1635 |
NameAndTags const& _nameAndTags, |
| 1636 |
SourceLineInfo const& _lineInfo): |
| 1637 |
name( _nameAndTags.name.empty() ? makeDefaultName() : _nameAndTags.name ), |
| 1638 |
className( _className ), |
| 1639 |
lineInfo( _lineInfo ) |
| 1640 |
{ |
| 1641 |
StringRef originalTags = _nameAndTags.tags; |
| 1642 |
// We need to reserve enough space to store all of the tags |
| 1643 |
// (including optional hidden tag and filename tag) |
| 1644 |
auto requiredSize = originalTags.size() + sizeOfExtraTags(_lineInfo.file); |
| 1645 |
backingTags.reserve(requiredSize); |
| 1646 |
|
| 1647 |
// We cannot copy the tags directly, as we need to normalize |
| 1648 |
// some tags, so that [.foo] is copied as [.][foo]. |
| 1649 |
size_t tagStart = 0; |
| 1650 |
size_t tagEnd = 0; |
| 1651 |
bool inTag = false; |
| 1652 |
for (size_t idx = 0; idx < originalTags.size(); ++idx) { |
| 1653 |
auto c = originalTags[idx]; |
| 1654 |
if (c == '[') { |
| 1655 |
CATCH_ENFORCE( |
| 1656 |
!inTag, |
| 1657 |
"Found '[' inside a tag while registering test case '" |
| 1658 |
<< _nameAndTags.name << "' at " << _lineInfo ); |
| 1659 |
|
| 1660 |
inTag = true; |
| 1661 |
tagStart = idx; |
| 1662 |
} |
| 1663 |
if (c == ']') { |
| 1664 |
CATCH_ENFORCE( |
| 1665 |
inTag, |
| 1666 |
"Found unmatched ']' while registering test case '" |
| 1667 |
<< _nameAndTags.name << "' at " << _lineInfo ); |
| 1668 |
|
| 1669 |
inTag = false; |
| 1670 |
tagEnd = idx; |
| 1671 |
assert(tagStart < tagEnd); |
| 1672 |
|
| 1673 |
// We need to check the tag for special meanings, copy |
| 1674 |
// it over to backing storage and actually reference the |
| 1675 |
// backing storage in the saved tags |
| 1676 |
StringRef tagStr = originalTags.substr(tagStart+1, tagEnd - tagStart - 1); |
| 1677 |
CATCH_ENFORCE( !tagStr.empty(), |
| 1678 |
"Found an empty tag while registering test case '" |
| 1679 |
<< _nameAndTags.name << "' at " |
| 1680 |
<< _lineInfo ); |
| 1681 |
|
| 1682 |
enforceNotReservedTag(tagStr, lineInfo); |
| 1683 |
properties |= parseSpecialTag(tagStr); |
| 1684 |
// When copying a tag to the backing storage, we need to |
| 1685 |
// check if it is a merged hide tag, such as [.foo], and |
| 1686 |
// if it is, we need to handle it as if it was [foo]. |
| 1687 |
if (tagStr.size() > 1 && tagStr[0] == '.') { |
| 1688 |
tagStr = tagStr.substr(1, tagStr.size() - 1); |
| 1689 |
} |
| 1690 |
// We skip over dealing with the [.] tag, as we will add |
| 1691 |
// it later unconditionally and then sort and unique all |
| 1692 |
// the tags. |
| 1693 |
internalAppendTag(tagStr); |
| 1694 |
} |
| 1695 |
} |
| 1696 |
CATCH_ENFORCE( !inTag, |
| 1697 |
"Found an unclosed tag while registering test case '" |
| 1698 |
<< _nameAndTags.name << "' at " << _lineInfo ); |
| 1699 |
|
| 1700 |
|
| 1701 |
// Add [.] if relevant |
| 1702 |
if (isHidden()) { |
| 1703 |
internalAppendTag("."_sr); |
| 1704 |
} |
| 1705 |
|
| 1706 |
// Sort and prepare tags |
| 1707 |
std::sort(begin(tags), end(tags)); |
| 1708 |
tags.erase(std::unique(begin(tags), end(tags)), |
| 1709 |
end(tags)); |
| 1710 |
} |
| 1711 |
|
| 1712 |
bool TestCaseInfo::isHidden() const { |
| 1713 |
return applies( properties & TestCaseProperties::IsHidden ); |
| 1714 |
} |
| 1715 |
bool TestCaseInfo::throws() const { |
| 1716 |
return applies( properties & TestCaseProperties::Throws ); |
| 1717 |
} |
| 1718 |
bool TestCaseInfo::okToFail() const { |
| 1719 |
return applies( properties & (TestCaseProperties::ShouldFail | TestCaseProperties::MayFail ) ); |
| 1720 |
} |
| 1721 |
bool TestCaseInfo::expectedToFail() const { |
| 1722 |
return applies( properties & (TestCaseProperties::ShouldFail) ); |
| 1723 |
} |
| 1724 |
|
| 1725 |
void TestCaseInfo::addFilenameTag() { |
| 1726 |
std::string combined("#"); |
| 1727 |
combined += extractFilenamePart(lineInfo.file); |
| 1728 |
internalAppendTag(combined); |
| 1729 |
} |
| 1730 |
|
| 1731 |
std::string TestCaseInfo::tagsAsString() const { |
| 1732 |
std::string ret; |
| 1733 |
// '[' and ']' per tag |
| 1734 |
std::size_t full_size = 2 * tags.size(); |
| 1735 |
for (const auto& tag : tags) { |
| 1736 |
full_size += tag.original.size(); |
| 1737 |
} |
| 1738 |
ret.reserve(full_size); |
| 1739 |
for (const auto& tag : tags) { |
| 1740 |
ret.push_back('['); |
| 1741 |
ret += tag.original; |
| 1742 |
ret.push_back(']'); |
| 1743 |
} |
| 1744 |
|
| 1745 |
return ret; |
| 1746 |
} |
| 1747 |
|
| 1748 |
void TestCaseInfo::internalAppendTag(StringRef tagStr) { |
| 1749 |
backingTags += '['; |
| 1750 |
const auto backingStart = backingTags.size(); |
| 1751 |
backingTags += tagStr; |
| 1752 |
const auto backingEnd = backingTags.size(); |
| 1753 |
backingTags += ']'; |
| 1754 |
tags.emplace_back(StringRef(backingTags.c_str() + backingStart, backingEnd - backingStart)); |
| 1755 |
} |
| 1756 |
|
| 1757 |
bool operator<( TestCaseInfo const& lhs, TestCaseInfo const& rhs ) { |
| 1758 |
// We want to avoid redoing the string comparisons multiple times, |
| 1759 |
// so we store the result of a three-way comparison before using |
| 1760 |
// it in the actual comparison logic. |
| 1761 |
const auto cmpName = lhs.name.compare( rhs.name ); |
| 1762 |
if ( cmpName != 0 ) { |
| 1763 |
return cmpName < 0; |
| 1764 |
} |
| 1765 |
const auto cmpClassName = lhs.className.compare( rhs.className ); |
| 1766 |
if ( cmpClassName != 0 ) { |
| 1767 |
return cmpClassName < 0; |
| 1768 |
} |
| 1769 |
return lhs.tags < rhs.tags; |
| 1770 |
} |
| 1771 |
|
| 1772 |
} // end namespace Catch |
| 1773 |
|
| 1774 |
|
| 1775 |
|
| 1776 |
#include <algorithm> |
| 1777 |
#include <string> |
| 1778 |
#include <vector> |
| 1779 |
#include <ostream> |
| 1780 |
|
| 1781 |
namespace Catch { |
| 1782 |
|
| 1783 |
TestSpec::Pattern::Pattern( std::string const& name ) |
| 1784 |
: m_name( name ) |
| 1785 |
{} |
| 1786 |
|
| 1787 |
TestSpec::Pattern::~Pattern() = default; |
| 1788 |
|
| 1789 |
std::string const& TestSpec::Pattern::name() const { |
| 1790 |
return m_name; |
| 1791 |
} |
| 1792 |
|
| 1793 |
|
| 1794 |
TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString ) |
| 1795 |
: Pattern( filterString ) |
| 1796 |
, m_wildcardPattern( toLower( name ), CaseSensitive::No ) |
| 1797 |
{} |
| 1798 |
|
| 1799 |
bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const { |
| 1800 |
return m_wildcardPattern.matches( testCase.name ); |
| 1801 |
} |
| 1802 |
|
| 1803 |
void TestSpec::NamePattern::serializeTo( std::ostream& out ) const { |
| 1804 |
out << '"' << name() << '"'; |
| 1805 |
} |
| 1806 |
|
| 1807 |
|
| 1808 |
TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString ) |
| 1809 |
: Pattern( filterString ) |
| 1810 |
, m_tag( tag ) |
| 1811 |
{} |
| 1812 |
|
| 1813 |
bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const { |
| 1814 |
return std::find( begin( testCase.tags ), |
| 1815 |
end( testCase.tags ), |
| 1816 |
Tag( m_tag ) ) != end( testCase.tags ); |
| 1817 |
} |
| 1818 |
|
| 1819 |
void TestSpec::TagPattern::serializeTo( std::ostream& out ) const { |
| 1820 |
out << name(); |
| 1821 |
} |
| 1822 |
|
| 1823 |
bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const { |
| 1824 |
bool should_use = !testCase.isHidden(); |
| 1825 |
for (auto const& pattern : m_required) { |
| 1826 |
should_use = true; |
| 1827 |
if (!pattern->matches(testCase)) { |
| 1828 |
return false; |
| 1829 |
} |
| 1830 |
} |
| 1831 |
for (auto const& pattern : m_forbidden) { |
| 1832 |
if (pattern->matches(testCase)) { |
| 1833 |
return false; |
| 1834 |
} |
| 1835 |
} |
| 1836 |
return should_use; |
| 1837 |
} |
| 1838 |
|
| 1839 |
void TestSpec::Filter::serializeTo( std::ostream& out ) const { |
| 1840 |
bool first = true; |
| 1841 |
for ( auto const& pattern : m_required ) { |
| 1842 |
if ( !first ) { |
| 1843 |
out << ' '; |
| 1844 |
} |
| 1845 |
out << *pattern; |
| 1846 |
first = false; |
| 1847 |
} |
| 1848 |
for ( auto const& pattern : m_forbidden ) { |
| 1849 |
if ( !first ) { |
| 1850 |
out << ' '; |
| 1851 |
} |
| 1852 |
out << *pattern; |
| 1853 |
first = false; |
| 1854 |
} |
| 1855 |
} |
| 1856 |
|
| 1857 |
|
| 1858 |
std::string TestSpec::extractFilterName( Filter const& filter ) { |
| 1859 |
Catch::ReusableStringStream sstr; |
| 1860 |
sstr << filter; |
| 1861 |
return sstr.str(); |
| 1862 |
} |
| 1863 |
|
| 1864 |
bool TestSpec::hasFilters() const { |
| 1865 |
return !m_filters.empty(); |
| 1866 |
} |
| 1867 |
|
| 1868 |
bool TestSpec::matches( TestCaseInfo const& testCase ) const { |
| 1869 |
return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } ); |
| 1870 |
} |
| 1871 |
|
| 1872 |
TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCaseHandle> const& testCases, IConfig const& config ) const { |
| 1873 |
Matches matches; |
| 1874 |
matches.reserve( m_filters.size() ); |
| 1875 |
for ( auto const& filter : m_filters ) { |
| 1876 |
std::vector<TestCaseHandle const*> currentMatches; |
| 1877 |
for ( auto const& test : testCases ) |
| 1878 |
if ( isThrowSafe( test, config ) && |
| 1879 |
filter.matches( test.getTestCaseInfo() ) ) |
| 1880 |
currentMatches.emplace_back( &test ); |
| 1881 |
matches.push_back( |
| 1882 |
FilterMatch{ extractFilterName( filter ), currentMatches } ); |
| 1883 |
} |
| 1884 |
return matches; |
| 1885 |
} |
| 1886 |
|
| 1887 |
const TestSpec::vectorStrings& TestSpec::getInvalidSpecs() const { |
| 1888 |
return m_invalidSpecs; |
| 1889 |
} |
| 1890 |
|
| 1891 |
void TestSpec::serializeTo( std::ostream& out ) const { |
| 1892 |
bool first = true; |
| 1893 |
for ( auto const& filter : m_filters ) { |
| 1894 |
if ( !first ) { |
| 1895 |
out << ','; |
| 1896 |
} |
| 1897 |
out << filter; |
| 1898 |
first = false; |
| 1899 |
} |
| 1900 |
} |
| 1901 |
|
| 1902 |
} |
| 1903 |
|
| 1904 |
|
| 1905 |
|
| 1906 |
#include <chrono> |
| 1907 |
|
| 1908 |
namespace Catch { |
| 1909 |
|
| 1910 |
namespace { |
| 1911 |
static auto getCurrentNanosecondsSinceEpoch() -> uint64_t { |
| 1912 |
return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count(); |
| 1913 |
} |
| 1914 |
} // end unnamed namespace |
| 1915 |
|
| 1916 |
void Timer::start() { |
| 1917 |
m_nanoseconds = getCurrentNanosecondsSinceEpoch(); |
| 1918 |
} |
| 1919 |
auto Timer::getElapsedNanoseconds() const -> uint64_t { |
| 1920 |
return getCurrentNanosecondsSinceEpoch() - m_nanoseconds; |
| 1921 |
} |
| 1922 |
auto Timer::getElapsedMicroseconds() const -> uint64_t { |
| 1923 |
return getElapsedNanoseconds()/1000; |
| 1924 |
} |
| 1925 |
auto Timer::getElapsedMilliseconds() const -> unsigned int { |
| 1926 |
return static_cast<unsigned int>(getElapsedMicroseconds()/1000); |
| 1927 |
} |
| 1928 |
auto Timer::getElapsedSeconds() const -> double { |
| 1929 |
return static_cast<double>(getElapsedMicroseconds())/1000000.0; |
| 1930 |
} |
| 1931 |
|
| 1932 |
|
| 1933 |
} // namespace Catch |
| 1934 |
|
| 1935 |
|
| 1936 |
|
| 1937 |
|
| 1938 |
#include <cmath> |
| 1939 |
#include <iomanip> |
| 1940 |
|
| 1941 |
namespace Catch { |
| 1942 |
|
| 1943 |
namespace Detail { |
| 1944 |
|
| 1945 |
namespace { |
| 1946 |
const int hexThreshold = 255; |
| 1947 |
|
| 1948 |
struct Endianness { |
| 1949 |
enum Arch : uint8_t { |
| 1950 |
Big, |
| 1951 |
Little |
| 1952 |
}; |
| 1953 |
|
| 1954 |
static Arch which() { |
| 1955 |
int one = 1; |
| 1956 |
// If the lowest byte we read is non-zero, we can assume |
| 1957 |
// that little endian format is used. |
| 1958 |
auto value = *reinterpret_cast<char*>(&one); |
| 1959 |
return value ? Little : Big; |
| 1960 |
} |
| 1961 |
}; |
| 1962 |
|
| 1963 |
template<typename T> |
| 1964 |
std::string fpToString(T value, int precision) { |
| 1965 |
if (Catch::isnan(value)) { |
| 1966 |
return "nan"; |
| 1967 |
} |
| 1968 |
|
| 1969 |
ReusableStringStream rss; |
| 1970 |
rss << std::setprecision(precision) |
| 1971 |
<< std::fixed |
| 1972 |
<< value; |
| 1973 |
std::string d = rss.str(); |
| 1974 |
std::size_t i = d.find_last_not_of('0'); |
| 1975 |
if (i != std::string::npos && i != d.size() - 1) { |
| 1976 |
if (d[i] == '.') |
| 1977 |
i++; |
| 1978 |
d = d.substr(0, i + 1); |
| 1979 |
} |
| 1980 |
return d; |
| 1981 |
} |
| 1982 |
} // end unnamed namespace |
| 1983 |
|
| 1984 |
std::string convertIntoString(StringRef string, bool escapeInvisibles) { |
| 1985 |
std::string ret; |
| 1986 |
// This is enough for the "don't escape invisibles" case, and a good |
| 1987 |
// lower bound on the "escape invisibles" case. |
| 1988 |
ret.reserve(string.size() + 2); |
| 1989 |
|
| 1990 |
if (!escapeInvisibles) { |
| 1991 |
ret += '"'; |
| 1992 |
ret += string; |
| 1993 |
ret += '"'; |
| 1994 |
return ret; |
| 1995 |
} |
| 1996 |
|
| 1997 |
ret += '"'; |
| 1998 |
for (char c : string) { |
| 1999 |
switch (c) { |
| 2000 |
case '\r': |
| 2001 |
ret.append("\\r"); |
| 2002 |
break; |
| 2003 |
case '\n': |
| 2004 |
ret.append("\\n"); |
| 2005 |
break; |
| 2006 |
case '\t': |
| 2007 |
ret.append("\\t"); |
| 2008 |
break; |
| 2009 |
case '\f': |
| 2010 |
ret.append("\\f"); |
| 2011 |
break; |
| 2012 |
default: |
| 2013 |
ret.push_back(c); |
| 2014 |
break; |
| 2015 |
} |
| 2016 |
} |
| 2017 |
ret += '"'; |
| 2018 |
|
| 2019 |
return ret; |
| 2020 |
} |
| 2021 |
|
| 2022 |
std::string convertIntoString(StringRef string) { |
| 2023 |
return convertIntoString(string, getCurrentContext().getConfig()->showInvisibles()); |
| 2024 |
} |
| 2025 |
|
| 2026 |
std::string rawMemoryToString( const void *object, std::size_t size ) { |
| 2027 |
// Reverse order for little endian architectures |
| 2028 |
int i = 0, end = static_cast<int>( size ), inc = 1; |
| 2029 |
if( Endianness::which() == Endianness::Little ) { |
| 2030 |
i = end-1; |
| 2031 |
end = inc = -1; |
| 2032 |
} |
| 2033 |
|
| 2034 |
unsigned char const *bytes = static_cast<unsigned char const *>(object); |
| 2035 |
ReusableStringStream rss; |
| 2036 |
rss << "0x" << std::setfill('0') << std::hex; |
| 2037 |
for( ; i != end; i += inc ) |
| 2038 |
rss << std::setw(2) << static_cast<unsigned>(bytes[i]); |
| 2039 |
return rss.str(); |
| 2040 |
} |
| 2041 |
} // end Detail namespace |
| 2042 |
|
| 2043 |
|
| 2044 |
|
| 2045 |
//// ======================================================= //// |
| 2046 |
// |
| 2047 |
// Out-of-line defs for full specialization of StringMaker |
| 2048 |
// |
| 2049 |
//// ======================================================= //// |
| 2050 |
|
| 2051 |
std::string StringMaker<std::string>::convert(const std::string& str) { |
| 2052 |
return Detail::convertIntoString( str ); |
| 2053 |
} |
| 2054 |
|
| 2055 |
#ifdef CATCH_CONFIG_CPP17_STRING_VIEW |
| 2056 |
std::string StringMaker<std::string_view>::convert(std::string_view str) { |
| 2057 |
return Detail::convertIntoString( StringRef( str.data(), str.size() ) ); |
| 2058 |
} |
| 2059 |
#endif |
| 2060 |
|
| 2061 |
std::string StringMaker<char const*>::convert(char const* str) { |
| 2062 |
if (str) { |
| 2063 |
return Detail::convertIntoString( str ); |
| 2064 |
} else { |
| 2065 |
return{ "{null string}" }; |
| 2066 |
} |
| 2067 |
} |
| 2068 |
std::string StringMaker<char*>::convert(char* str) { // NOLINT(readability-non-const-parameter) |
| 2069 |
if (str) { |
| 2070 |
return Detail::convertIntoString( str ); |
| 2071 |
} else { |
| 2072 |
return{ "{null string}" }; |
| 2073 |
} |
| 2074 |
} |
| 2075 |
|
| 2076 |
#ifdef CATCH_CONFIG_WCHAR |
| 2077 |
std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) { |
| 2078 |
std::string s; |
| 2079 |
s.reserve(wstr.size()); |
| 2080 |
for (auto c : wstr) { |
| 2081 |
s += (c <= 0xff) ? static_cast<char>(c) : '?'; |
| 2082 |
} |
| 2083 |
return ::Catch::Detail::stringify(s); |
| 2084 |
} |
| 2085 |
|
| 2086 |
# ifdef CATCH_CONFIG_CPP17_STRING_VIEW |
| 2087 |
std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) { |
| 2088 |
return StringMaker<std::wstring>::convert(std::wstring(str)); |
| 2089 |
} |
| 2090 |
# endif |
| 2091 |
|
| 2092 |
std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) { |
| 2093 |
if (str) { |
| 2094 |
return ::Catch::Detail::stringify(std::wstring{ str }); |
| 2095 |
} else { |
| 2096 |
return{ "{null string}" }; |
| 2097 |
} |
| 2098 |
} |
| 2099 |
std::string StringMaker<wchar_t *>::convert(wchar_t * str) { |
| 2100 |
if (str) { |
| 2101 |
return ::Catch::Detail::stringify(std::wstring{ str }); |
| 2102 |
} else { |
| 2103 |
return{ "{null string}" }; |
| 2104 |
} |
| 2105 |
} |
| 2106 |
#endif |
| 2107 |
|
| 2108 |
#if defined(CATCH_CONFIG_CPP17_BYTE) |
| 2109 |
#include <cstddef> |
| 2110 |
std::string StringMaker<std::byte>::convert(std::byte value) { |
| 2111 |
return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value)); |
| 2112 |
} |
| 2113 |
#endif // defined(CATCH_CONFIG_CPP17_BYTE) |
| 2114 |
|
| 2115 |
std::string StringMaker<int>::convert(int value) { |
| 2116 |
return ::Catch::Detail::stringify(static_cast<long long>(value)); |
| 2117 |
} |
| 2118 |
std::string StringMaker<long>::convert(long value) { |
| 2119 |
return ::Catch::Detail::stringify(static_cast<long long>(value)); |
| 2120 |
} |
| 2121 |
std::string StringMaker<long long>::convert(long long value) { |
| 2122 |
ReusableStringStream rss; |
| 2123 |
rss << value; |
| 2124 |
if (value > Detail::hexThreshold) { |
| 2125 |
rss << " (0x" << std::hex << value << ')'; |
| 2126 |
} |
| 2127 |
return rss.str(); |
| 2128 |
} |
| 2129 |
|
| 2130 |
std::string StringMaker<unsigned int>::convert(unsigned int value) { |
| 2131 |
return ::Catch::Detail::stringify(static_cast<unsigned long long>(value)); |
| 2132 |
} |
| 2133 |
std::string StringMaker<unsigned long>::convert(unsigned long value) { |
| 2134 |
return ::Catch::Detail::stringify(static_cast<unsigned long long>(value)); |
| 2135 |
} |
| 2136 |
std::string StringMaker<unsigned long long>::convert(unsigned long long value) { |
| 2137 |
ReusableStringStream rss; |
| 2138 |
rss << value; |
| 2139 |
if (value > Detail::hexThreshold) { |
| 2140 |
rss << " (0x" << std::hex << value << ')'; |
| 2141 |
} |
| 2142 |
return rss.str(); |
| 2143 |
} |
| 2144 |
|
| 2145 |
std::string StringMaker<signed char>::convert(signed char value) { |
| 2146 |
if (value == '\r') { |
| 2147 |
return "'\\r'"; |
| 2148 |
} else if (value == '\f') { |
| 2149 |
return "'\\f'"; |
| 2150 |
} else if (value == '\n') { |
| 2151 |
return "'\\n'"; |
| 2152 |
} else if (value == '\t') { |
| 2153 |
return "'\\t'"; |
| 2154 |
} else if ('\0' <= value && value < ' ') { |
| 2155 |
return ::Catch::Detail::stringify(static_cast<unsigned int>(value)); |
| 2156 |
} else { |
| 2157 |
char chstr[] = "' '"; |
| 2158 |
chstr[1] = value; |
| 2159 |
return chstr; |
| 2160 |
} |
| 2161 |
} |
| 2162 |
std::string StringMaker<char>::convert(char c) { |
| 2163 |
return ::Catch::Detail::stringify(static_cast<signed char>(c)); |
| 2164 |
} |
| 2165 |
std::string StringMaker<unsigned char>::convert(unsigned char value) { |
| 2166 |
return ::Catch::Detail::stringify(static_cast<char>(value)); |
| 2167 |
} |
| 2168 |
|
| 2169 |
int StringMaker<float>::precision = std::numeric_limits<float>::max_digits10; |
| 2170 |
|
| 2171 |
std::string StringMaker<float>::convert(float value) { |
| 2172 |
return Detail::fpToString(value, precision) + 'f'; |
| 2173 |
} |
| 2174 |
|
| 2175 |
int StringMaker<double>::precision = std::numeric_limits<double>::max_digits10; |
| 2176 |
|
| 2177 |
std::string StringMaker<double>::convert(double value) { |
| 2178 |
return Detail::fpToString(value, precision); |
| 2179 |
} |
| 2180 |
|
| 2181 |
} // end namespace Catch |
| 2182 |
|
| 2183 |
|
| 2184 |
|
| 2185 |
namespace Catch { |
| 2186 |
|
| 2187 |
Counts Counts::operator - ( Counts const& other ) const { |
| 2188 |
Counts diff; |
| 2189 |
diff.passed = passed - other.passed; |
| 2190 |
diff.failed = failed - other.failed; |
| 2191 |
diff.failedButOk = failedButOk - other.failedButOk; |
| 2192 |
diff.skipped = skipped - other.skipped; |
| 2193 |
return diff; |
| 2194 |
} |
| 2195 |
|
| 2196 |
Counts& Counts::operator += ( Counts const& other ) { |
| 2197 |
passed += other.passed; |
| 2198 |
failed += other.failed; |
| 2199 |
failedButOk += other.failedButOk; |
| 2200 |
skipped += other.skipped; |
| 2201 |
return *this; |
| 2202 |
} |
| 2203 |
|
| 2204 |
std::uint64_t Counts::total() const { |
| 2205 |
return passed + failed + failedButOk + skipped; |
| 2206 |
} |
| 2207 |
bool Counts::allPassed() const { |
| 2208 |
return failed == 0 && failedButOk == 0 && skipped == 0; |
| 2209 |
} |
| 2210 |
bool Counts::allOk() const { |
| 2211 |
return failed == 0; |
| 2212 |
} |
| 2213 |
|
| 2214 |
Totals Totals::operator - ( Totals const& other ) const { |
| 2215 |
Totals diff; |
| 2216 |
diff.assertions = assertions - other.assertions; |
| 2217 |
diff.testCases = testCases - other.testCases; |
| 2218 |
return diff; |
| 2219 |
} |
| 2220 |
|
| 2221 |
Totals& Totals::operator += ( Totals const& other ) { |
| 2222 |
assertions += other.assertions; |
| 2223 |
testCases += other.testCases; |
| 2224 |
return *this; |
| 2225 |
} |
| 2226 |
|
| 2227 |
Totals Totals::delta( Totals const& prevTotals ) const { |
| 2228 |
Totals diff = *this - prevTotals; |
| 2229 |
if( diff.assertions.failed > 0 ) |
| 2230 |
++diff.testCases.failed; |
| 2231 |
else if( diff.assertions.failedButOk > 0 ) |
| 2232 |
++diff.testCases.failedButOk; |
| 2233 |
else if ( diff.assertions.skipped > 0 ) |
| 2234 |
++ diff.testCases.skipped; |
| 2235 |
else |
| 2236 |
++diff.testCases.passed; |
| 2237 |
return diff; |
| 2238 |
} |
| 2239 |
|
| 2240 |
} |
| 2241 |
|
| 2242 |
|
| 2243 |
|
| 2244 |
|
| 2245 |
namespace Catch { |
| 2246 |
namespace Detail { |
| 2247 |
void registerTranslatorImpl( |
| 2248 |
Detail::unique_ptr<IExceptionTranslator>&& translator ) { |
| 2249 |
getMutableRegistryHub().registerTranslator( |
| 2250 |
CATCH_MOVE( translator ) ); |
| 2251 |
} |
| 2252 |
} // namespace Detail |
| 2253 |
} // namespace Catch |
| 2254 |
|
| 2255 |
|
| 2256 |
#include <ostream> |
| 2257 |
|
| 2258 |
namespace Catch { |
| 2259 |
|
| 2260 |
Version::Version |
| 2261 |
( unsigned int _majorVersion, |
| 2262 |
unsigned int _minorVersion, |
| 2263 |
unsigned int _patchNumber, |
| 2264 |
char const * const _branchName, |
| 2265 |
unsigned int _buildNumber ) |
| 2266 |
: majorVersion( _majorVersion ), |
| 2267 |
minorVersion( _minorVersion ), |
| 2268 |
patchNumber( _patchNumber ), |
| 2269 |
branchName( _branchName ), |
| 2270 |
buildNumber( _buildNumber ) |
| 2271 |
{} |
| 2272 |
|
| 2273 |
std::ostream& operator << ( std::ostream& os, Version const& version ) { |
| 2274 |
os << version.majorVersion << '.' |
| 2275 |
<< version.minorVersion << '.' |
| 2276 |
<< version.patchNumber; |
| 2277 |
// branchName is never null -> 0th char is \0 if it is empty |
| 2278 |
if (version.branchName[0]) { |
| 2279 |
os << '-' << version.branchName |
| 2280 |
<< '.' << version.buildNumber; |
| 2281 |
} |
| 2282 |
return os; |
| 2283 |
} |
| 2284 |
|
| 2285 |
Version const& libraryVersion() { |
| 2286 |
static Version version( 3, 8, 1, "", 0 ); |
| 2287 |
return version; |
| 2288 |
} |
| 2289 |
|
| 2290 |
} |
| 2291 |
|
| 2292 |
|
| 2293 |
|
| 2294 |
|
| 2295 |
namespace Catch { |
| 2296 |
|
| 2297 |
const char* GeneratorException::what() const noexcept { |
| 2298 |
return m_msg; |
| 2299 |
} |
| 2300 |
|
| 2301 |
} // end namespace Catch |
| 2302 |
|
| 2303 |
|
| 2304 |
|
| 2305 |
|
| 2306 |
namespace Catch { |
| 2307 |
|
| 2308 |
IGeneratorTracker::~IGeneratorTracker() = default; |
| 2309 |
|
| 2310 |
namespace Generators { |
| 2311 |
|
| 2312 |
namespace Detail { |
| 2313 |
|
| 2314 |
[[noreturn]] |
| 2315 |
void throw_generator_exception(char const* msg) { |
| 2316 |
Catch::throw_exception(GeneratorException{ msg }); |
| 2317 |
} |
| 2318 |
} // end namespace Detail |
| 2319 |
|
| 2320 |
GeneratorUntypedBase::~GeneratorUntypedBase() = default; |
| 2321 |
|
| 2322 |
IGeneratorTracker* acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo ) { |
| 2323 |
return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo ); |
| 2324 |
} |
| 2325 |
|
| 2326 |
IGeneratorTracker* createGeneratorTracker( StringRef generatorName, |
| 2327 |
SourceLineInfo lineInfo, |
| 2328 |
GeneratorBasePtr&& generator ) { |
| 2329 |
return getResultCapture().createGeneratorTracker( |
| 2330 |
generatorName, lineInfo, CATCH_MOVE( generator ) ); |
| 2331 |
} |
| 2332 |
|
| 2333 |
} // namespace Generators |
| 2334 |
} // namespace Catch |
| 2335 |
|
| 2336 |
|
| 2337 |
|
| 2338 |
|
| 2339 |
#include <random> |
| 2340 |
|
| 2341 |
namespace Catch { |
| 2342 |
namespace Generators { |
| 2343 |
namespace Detail { |
| 2344 |
std::uint32_t getSeed() { return sharedRng()(); } |
| 2345 |
} // namespace Detail |
| 2346 |
|
| 2347 |
struct RandomFloatingGenerator<long double>::PImpl { |
| 2348 |
PImpl( long double a, long double b, uint32_t seed ): |
| 2349 |
rng( seed ), dist( a, b ) {} |
| 2350 |
|
| 2351 |
Catch::SimplePcg32 rng; |
| 2352 |
std::uniform_real_distribution<long double> dist; |
| 2353 |
}; |
| 2354 |
|
| 2355 |
RandomFloatingGenerator<long double>::RandomFloatingGenerator( |
| 2356 |
long double a, long double b, std::uint32_t seed) : |
| 2357 |
m_pimpl(Catch::Detail::make_unique<PImpl>(a, b, seed)) { |
| 2358 |
static_cast<void>( next() ); |
| 2359 |
} |
| 2360 |
|
| 2361 |
RandomFloatingGenerator<long double>::~RandomFloatingGenerator() = |
| 2362 |
default; |
| 2363 |
bool RandomFloatingGenerator<long double>::next() { |
| 2364 |
m_current_number = m_pimpl->dist( m_pimpl->rng ); |
| 2365 |
return true; |
| 2366 |
} |
| 2367 |
} // namespace Generators |
| 2368 |
} // namespace Catch |
| 2369 |
|
| 2370 |
|
| 2371 |
|
| 2372 |
|
| 2373 |
namespace Catch { |
| 2374 |
IResultCapture::~IResultCapture() = default; |
| 2375 |
} |
| 2376 |
|
| 2377 |
|
| 2378 |
|
| 2379 |
|
| 2380 |
namespace Catch { |
| 2381 |
IConfig::~IConfig() = default; |
| 2382 |
} |
| 2383 |
|
| 2384 |
|
| 2385 |
|
| 2386 |
|
| 2387 |
namespace Catch { |
| 2388 |
IExceptionTranslator::~IExceptionTranslator() = default; |
| 2389 |
IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default; |
| 2390 |
} |
| 2391 |
|
| 2392 |
|
| 2393 |
|
| 2394 |
#include <string> |
| 2395 |
|
| 2396 |
namespace Catch { |
| 2397 |
namespace Generators { |
| 2398 |
|
| 2399 |
bool GeneratorUntypedBase::countedNext() { |
| 2400 |
auto ret = next(); |
| 2401 |
if ( ret ) { |
| 2402 |
m_stringReprCache.clear(); |
| 2403 |
++m_currentElementIndex; |
| 2404 |
} |
| 2405 |
return ret; |
| 2406 |
} |
| 2407 |
|
| 2408 |
StringRef GeneratorUntypedBase::currentElementAsString() const { |
| 2409 |
if ( m_stringReprCache.empty() ) { |
| 2410 |
m_stringReprCache = stringifyImpl(); |
| 2411 |
} |
| 2412 |
return m_stringReprCache; |
| 2413 |
} |
| 2414 |
|
| 2415 |
} // namespace Generators |
| 2416 |
} // namespace Catch |
| 2417 |
|
| 2418 |
|
| 2419 |
|
| 2420 |
|
| 2421 |
namespace Catch { |
| 2422 |
IRegistryHub::~IRegistryHub() = default; |
| 2423 |
IMutableRegistryHub::~IMutableRegistryHub() = default; |
| 2424 |
} |
| 2425 |
|
| 2426 |
|
| 2427 |
|
| 2428 |
#include <cassert> |
| 2429 |
|
| 2430 |
namespace Catch { |
| 2431 |
|
| 2432 |
ReporterConfig::ReporterConfig( |
| 2433 |
IConfig const* _fullConfig, |
| 2434 |
Detail::unique_ptr<IStream> _stream, |
| 2435 |
ColourMode colourMode, |
| 2436 |
std::map<std::string, std::string> customOptions ): |
| 2437 |
m_stream( CATCH_MOVE(_stream) ), |
| 2438 |
m_fullConfig( _fullConfig ), |
| 2439 |
m_colourMode( colourMode ), |
| 2440 |
m_customOptions( CATCH_MOVE( customOptions ) ) {} |
| 2441 |
|
| 2442 |
Detail::unique_ptr<IStream> ReporterConfig::takeStream() && { |
| 2443 |
assert( m_stream ); |
| 2444 |
return CATCH_MOVE( m_stream ); |
| 2445 |
} |
| 2446 |
IConfig const * ReporterConfig::fullConfig() const { return m_fullConfig; } |
| 2447 |
ColourMode ReporterConfig::colourMode() const { return m_colourMode; } |
| 2448 |
|
| 2449 |
std::map<std::string, std::string> const& |
| 2450 |
ReporterConfig::customOptions() const { |
| 2451 |
return m_customOptions; |
| 2452 |
} |
| 2453 |
|
| 2454 |
ReporterConfig::~ReporterConfig() = default; |
| 2455 |
|
| 2456 |
AssertionStats::AssertionStats( AssertionResult const& _assertionResult, |
| 2457 |
std::vector<MessageInfo> const& _infoMessages, |
| 2458 |
Totals const& _totals ) |
| 2459 |
: assertionResult( _assertionResult ), |
| 2460 |
infoMessages( _infoMessages ), |
| 2461 |
totals( _totals ) |
| 2462 |
{ |
| 2463 |
if( assertionResult.hasMessage() ) { |
| 2464 |
// Copy message into messages list. |
| 2465 |
// !TBD This should have been done earlier, somewhere |
| 2466 |
MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); |
| 2467 |
builder.m_info.message = static_cast<std::string>(assertionResult.getMessage()); |
| 2468 |
|
| 2469 |
infoMessages.push_back( CATCH_MOVE(builder.m_info) ); |
| 2470 |
} |
| 2471 |
} |
| 2472 |
|
| 2473 |
SectionStats::SectionStats( SectionInfo&& _sectionInfo, |
| 2474 |
Counts const& _assertions, |
| 2475 |
double _durationInSeconds, |
| 2476 |
bool _missingAssertions ) |
| 2477 |
: sectionInfo( CATCH_MOVE(_sectionInfo) ), |
| 2478 |
assertions( _assertions ), |
| 2479 |
durationInSeconds( _durationInSeconds ), |
| 2480 |
missingAssertions( _missingAssertions ) |
| 2481 |
{} |
| 2482 |
|
| 2483 |
|
| 2484 |
TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo, |
| 2485 |
Totals const& _totals, |
| 2486 |
std::string&& _stdOut, |
| 2487 |
std::string&& _stdErr, |
| 2488 |
bool _aborting ) |
| 2489 |
: testInfo( &_testInfo ), |
| 2490 |
totals( _totals ), |
| 2491 |
stdOut( CATCH_MOVE(_stdOut) ), |
| 2492 |
stdErr( CATCH_MOVE(_stdErr) ), |
| 2493 |
aborting( _aborting ) |
| 2494 |
{} |
| 2495 |
|
| 2496 |
|
| 2497 |
TestRunStats::TestRunStats( TestRunInfo const& _runInfo, |
| 2498 |
Totals const& _totals, |
| 2499 |
bool _aborting ) |
| 2500 |
: runInfo( _runInfo ), |
| 2501 |
totals( _totals ), |
| 2502 |
aborting( _aborting ) |
| 2503 |
{} |
| 2504 |
|
| 2505 |
IEventListener::~IEventListener() = default; |
| 2506 |
|
| 2507 |
} // end namespace Catch |
| 2508 |
|
| 2509 |
|
| 2510 |
|
| 2511 |
|
| 2512 |
namespace Catch { |
| 2513 |
IReporterFactory::~IReporterFactory() = default; |
| 2514 |
EventListenerFactory::~EventListenerFactory() = default; |
| 2515 |
} |
| 2516 |
|
| 2517 |
|
| 2518 |
|
| 2519 |
|
| 2520 |
namespace Catch { |
| 2521 |
ITestCaseRegistry::~ITestCaseRegistry() = default; |
| 2522 |
} |
| 2523 |
|
| 2524 |
|
| 2525 |
|
| 2526 |
namespace Catch { |
| 2527 |
|
| 2528 |
AssertionHandler::AssertionHandler |
| 2529 |
( StringRef macroName, |
| 2530 |
SourceLineInfo const& lineInfo, |
| 2531 |
StringRef capturedExpression, |
| 2532 |
ResultDisposition::Flags resultDisposition ) |
| 2533 |
: m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition }, |
| 2534 |
m_resultCapture( getResultCapture() ) |
| 2535 |
{ |
| 2536 |
m_resultCapture.notifyAssertionStarted( m_assertionInfo ); |
| 2537 |
} |
| 2538 |
|
| 2539 |
void AssertionHandler::handleExpr( ITransientExpression const& expr ) { |
| 2540 |
m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction ); |
| 2541 |
} |
| 2542 |
void AssertionHandler::handleMessage(ResultWas::OfType resultType, std::string&& message) { |
| 2543 |
m_resultCapture.handleMessage( m_assertionInfo, resultType, CATCH_MOVE(message), m_reaction ); |
| 2544 |
} |
| 2545 |
|
| 2546 |
auto AssertionHandler::allowThrows() const -> bool { |
| 2547 |
return getCurrentContext().getConfig()->allowThrows(); |
| 2548 |
} |
| 2549 |
|
| 2550 |
void AssertionHandler::complete() { |
| 2551 |
m_completed = true; |
| 2552 |
if( m_reaction.shouldDebugBreak ) { |
| 2553 |
|
| 2554 |
// If you find your debugger stopping you here then go one level up on the |
| 2555 |
// call-stack for the code that caused it (typically a failed assertion) |
| 2556 |
|
| 2557 |
// (To go back to the test and change execution, jump over the throw, next) |
| 2558 |
CATCH_BREAK_INTO_DEBUGGER(); |
| 2559 |
} |
| 2560 |
if (m_reaction.shouldThrow) { |
| 2561 |
throw_test_failure_exception(); |
| 2562 |
} |
| 2563 |
if ( m_reaction.shouldSkip ) { |
| 2564 |
throw_test_skip_exception(); |
| 2565 |
} |
| 2566 |
} |
| 2567 |
|
| 2568 |
void AssertionHandler::handleUnexpectedInflightException() { |
| 2569 |
m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction ); |
| 2570 |
} |
| 2571 |
|
| 2572 |
void AssertionHandler::handleExceptionThrownAsExpected() { |
| 2573 |
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); |
| 2574 |
} |
| 2575 |
void AssertionHandler::handleExceptionNotThrownAsExpected() { |
| 2576 |
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); |
| 2577 |
} |
| 2578 |
|
| 2579 |
void AssertionHandler::handleUnexpectedExceptionNotThrown() { |
| 2580 |
m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction ); |
| 2581 |
} |
| 2582 |
|
| 2583 |
void AssertionHandler::handleThrowingCallSkipped() { |
| 2584 |
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); |
| 2585 |
} |
| 2586 |
|
| 2587 |
// This is the overload that takes a string and infers the Equals matcher from it |
| 2588 |
// The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp |
| 2589 |
void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str ) { |
| 2590 |
handleExceptionMatchExpr( handler, Matchers::Equals( str ) ); |
| 2591 |
} |
| 2592 |
|
| 2593 |
} // namespace Catch |
| 2594 |
|
| 2595 |
|
| 2596 |
|
| 2597 |
|
| 2598 |
#include <algorithm> |
| 2599 |
|
| 2600 |
namespace Catch { |
| 2601 |
namespace Detail { |
| 2602 |
|
| 2603 |
bool CaseInsensitiveLess::operator()( StringRef lhs, |
| 2604 |
StringRef rhs ) const { |
| 2605 |
return std::lexicographical_compare( |
| 2606 |
lhs.begin(), lhs.end(), |
| 2607 |
rhs.begin(), rhs.end(), |
| 2608 |
[]( char l, char r ) { return toLower( l ) < toLower( r ); } ); |
| 2609 |
} |
| 2610 |
|
| 2611 |
bool |
| 2612 |
CaseInsensitiveEqualTo::operator()( StringRef lhs, |
| 2613 |
StringRef rhs ) const { |
| 2614 |
return std::equal( |
| 2615 |
lhs.begin(), lhs.end(), |
| 2616 |
rhs.begin(), rhs.end(), |
| 2617 |
[]( char l, char r ) { return toLower( l ) == toLower( r ); } ); |
| 2618 |
} |
| 2619 |
|
| 2620 |
} // namespace Detail |
| 2621 |
} // namespace Catch |
| 2622 |
|
| 2623 |
|
| 2624 |
|
| 2625 |
|
| 2626 |
#include <algorithm> |
| 2627 |
#include <ostream> |
| 2628 |
|
| 2629 |
namespace { |
| 2630 |
bool isOptPrefix( char c ) { |
| 2631 |
return c == '-' |
| 2632 |
#ifdef CATCH_PLATFORM_WINDOWS |
| 2633 |
|| c == '/' |
| 2634 |
#endif |
| 2635 |
; |
| 2636 |
} |
| 2637 |
|
| 2638 |
Catch::StringRef normaliseOpt( Catch::StringRef optName ) { |
| 2639 |
if ( optName[0] == '-' |
| 2640 |
#if defined(CATCH_PLATFORM_WINDOWS) |
| 2641 |
|| optName[0] == '/' |
| 2642 |
#endif |
| 2643 |
) { |
| 2644 |
return optName.substr( 1, optName.size() ); |
| 2645 |
} |
| 2646 |
|
| 2647 |
return optName; |
| 2648 |
} |
| 2649 |
|
| 2650 |
static size_t find_first_separator(Catch::StringRef sr) { |
| 2651 |
auto is_separator = []( char c ) { |
| 2652 |
return c == ' ' || c == ':' || c == '='; |
| 2653 |
}; |
| 2654 |
size_t pos = 0; |
| 2655 |
while (pos < sr.size()) { |
| 2656 |
if (is_separator(sr[pos])) { return pos; } |
| 2657 |
++pos; |
| 2658 |
} |
| 2659 |
|
| 2660 |
return Catch::StringRef::npos; |
| 2661 |
} |
| 2662 |
|
| 2663 |
} // namespace |
| 2664 |
|
| 2665 |
namespace Catch { |
| 2666 |
namespace Clara { |
| 2667 |
namespace Detail { |
| 2668 |
|
| 2669 |
void TokenStream::loadBuffer() { |
| 2670 |
m_tokenBuffer.clear(); |
| 2671 |
|
| 2672 |
// Skip any empty strings |
| 2673 |
while ( it != itEnd && it->empty() ) { |
| 2674 |
++it; |
| 2675 |
} |
| 2676 |
|
| 2677 |
if ( it != itEnd ) { |
| 2678 |
StringRef next = *it; |
| 2679 |
if ( isOptPrefix( next[0] ) ) { |
| 2680 |
auto delimiterPos = find_first_separator(next); |
| 2681 |
if ( delimiterPos != StringRef::npos ) { |
| 2682 |
m_tokenBuffer.push_back( |
| 2683 |
{ TokenType::Option, |
| 2684 |
next.substr( 0, delimiterPos ) } ); |
| 2685 |
m_tokenBuffer.push_back( |
| 2686 |
{ TokenType::Argument, |
| 2687 |
next.substr( delimiterPos + 1, next.size() ) } ); |
| 2688 |
} else { |
| 2689 |
if ( next.size() > 1 && next[1] != '-' && next.size() > 2 ) { |
| 2690 |
// Combined short args, e.g. "-ab" for "-a -b" |
| 2691 |
for ( size_t i = 1; i < next.size(); ++i ) { |
| 2692 |
m_tokenBuffer.push_back( |
| 2693 |
{ TokenType::Option, |
| 2694 |
next.substr( i, 1 ) } ); |
| 2695 |
} |
| 2696 |
} else { |
| 2697 |
m_tokenBuffer.push_back( |
| 2698 |
{ TokenType::Option, next } ); |
| 2699 |
} |
| 2700 |
} |
| 2701 |
} else { |
| 2702 |
m_tokenBuffer.push_back( |
| 2703 |
{ TokenType::Argument, next } ); |
| 2704 |
} |
| 2705 |
} |
| 2706 |
} |
| 2707 |
|
| 2708 |
TokenStream::TokenStream( Args const& args ): |
| 2709 |
TokenStream( args.m_args.begin(), args.m_args.end() ) {} |
| 2710 |
|
| 2711 |
TokenStream::TokenStream( Iterator it_, Iterator itEnd_ ): |
| 2712 |
it( it_ ), itEnd( itEnd_ ) { |
| 2713 |
loadBuffer(); |
| 2714 |
} |
| 2715 |
|
| 2716 |
TokenStream& TokenStream::operator++() { |
| 2717 |
if ( m_tokenBuffer.size() >= 2 ) { |
| 2718 |
m_tokenBuffer.erase( m_tokenBuffer.begin() ); |
| 2719 |
} else { |
| 2720 |
if ( it != itEnd ) |
| 2721 |
++it; |
| 2722 |
loadBuffer(); |
| 2723 |
} |
| 2724 |
return *this; |
| 2725 |
} |
| 2726 |
|
| 2727 |
ParserResult convertInto( std::string const& source, |
| 2728 |
std::string& target ) { |
| 2729 |
target = source; |
| 2730 |
return ParserResult::ok( ParseResultType::Matched ); |
| 2731 |
} |
| 2732 |
|
| 2733 |
ParserResult convertInto( std::string const& source, |
| 2734 |
bool& target ) { |
| 2735 |
std::string srcLC = toLower( source ); |
| 2736 |
|
| 2737 |
if ( srcLC == "y" || srcLC == "1" || srcLC == "true" || |
| 2738 |
srcLC == "yes" || srcLC == "on" ) { |
| 2739 |
target = true; |
| 2740 |
} else if ( srcLC == "n" || srcLC == "0" || srcLC == "false" || |
| 2741 |
srcLC == "no" || srcLC == "off" ) { |
| 2742 |
target = false; |
| 2743 |
} else { |
| 2744 |
return ParserResult::runtimeError( |
| 2745 |
"Expected a boolean value but did not recognise: '" + |
| 2746 |
source + '\'' ); |
| 2747 |
} |
| 2748 |
return ParserResult::ok( ParseResultType::Matched ); |
| 2749 |
} |
| 2750 |
|
| 2751 |
size_t ParserBase::cardinality() const { return 1; } |
| 2752 |
|
| 2753 |
InternalParseResult ParserBase::parse( Args const& args ) const { |
| 2754 |
return parse( static_cast<std::string>(args.exeName()), TokenStream( args ) ); |
| 2755 |
} |
| 2756 |
|
| 2757 |
ParseState::ParseState( ParseResultType type, |
| 2758 |
TokenStream remainingTokens ): |
| 2759 |
m_type( type ), m_remainingTokens( CATCH_MOVE(remainingTokens) ) {} |
| 2760 |
|
| 2761 |
ParserResult BoundFlagRef::setFlag( bool flag ) { |
| 2762 |
m_ref = flag; |
| 2763 |
return ParserResult::ok( ParseResultType::Matched ); |
| 2764 |
} |
| 2765 |
|
| 2766 |
ResultBase::~ResultBase() = default; |
| 2767 |
|
| 2768 |
bool BoundRef::isContainer() const { return false; } |
| 2769 |
|
| 2770 |
bool BoundRef::isFlag() const { return false; } |
| 2771 |
|
| 2772 |
bool BoundFlagRefBase::isFlag() const { return true; } |
| 2773 |
|
| 2774 |
} // namespace Detail |
| 2775 |
|
| 2776 |
Detail::InternalParseResult Arg::parse(std::string const&, |
| 2777 |
Detail::TokenStream tokens) const { |
| 2778 |
auto validationResult = validate(); |
| 2779 |
if (!validationResult) |
| 2780 |
return Detail::InternalParseResult(validationResult); |
| 2781 |
|
| 2782 |
auto token = *tokens; |
| 2783 |
if (token.type != Detail::TokenType::Argument) |
| 2784 |
return Detail::InternalParseResult::ok(Detail::ParseState( |
| 2785 |
ParseResultType::NoMatch, CATCH_MOVE(tokens))); |
| 2786 |
|
| 2787 |
assert(!m_ref->isFlag()); |
| 2788 |
auto valueRef = |
| 2789 |
static_cast<Detail::BoundValueRefBase*>(m_ref.get()); |
| 2790 |
|
| 2791 |
auto result = valueRef->setValue(static_cast<std::string>(token.token)); |
| 2792 |
if ( !result ) |
| 2793 |
return Detail::InternalParseResult( result ); |
| 2794 |
else |
| 2795 |
return Detail::InternalParseResult::ok( |
| 2796 |
Detail::ParseState( ParseResultType::Matched, |
| 2797 |
CATCH_MOVE( ++tokens ) ) ); |
| 2798 |
} |
| 2799 |
|
| 2800 |
Opt::Opt(bool& ref) : |
| 2801 |
ParserRefImpl(std::make_shared<Detail::BoundFlagRef>(ref)) {} |
| 2802 |
|
| 2803 |
Detail::HelpColumns Opt::getHelpColumns() const { |
| 2804 |
ReusableStringStream oss; |
| 2805 |
bool first = true; |
| 2806 |
for (auto const& opt : m_optNames) { |
| 2807 |
if (first) |
| 2808 |
first = false; |
| 2809 |
else |
| 2810 |
oss << ", "; |
| 2811 |
oss << opt; |
| 2812 |
} |
| 2813 |
if (!m_hint.empty()) |
| 2814 |
oss << " <" << m_hint << '>'; |
| 2815 |
return { oss.str(), m_description }; |
| 2816 |
} |
| 2817 |
|
| 2818 |
bool Opt::isMatch(StringRef optToken) const { |
| 2819 |
auto normalisedToken = normaliseOpt(optToken); |
| 2820 |
for (auto const& name : m_optNames) { |
| 2821 |
if (normaliseOpt(name) == normalisedToken) |
| 2822 |
return true; |
| 2823 |
} |
| 2824 |
return false; |
| 2825 |
} |
| 2826 |
|
| 2827 |
Detail::InternalParseResult Opt::parse(std::string const&, |
| 2828 |
Detail::TokenStream tokens) const { |
| 2829 |
auto validationResult = validate(); |
| 2830 |
if (!validationResult) |
| 2831 |
return Detail::InternalParseResult(validationResult); |
| 2832 |
|
| 2833 |
if (tokens && |
| 2834 |
tokens->type == Detail::TokenType::Option) { |
| 2835 |
auto const& token = *tokens; |
| 2836 |
if (isMatch(token.token)) { |
| 2837 |
if (m_ref->isFlag()) { |
| 2838 |
auto flagRef = |
| 2839 |
static_cast<Detail::BoundFlagRefBase*>( |
| 2840 |
m_ref.get()); |
| 2841 |
auto result = flagRef->setFlag(true); |
| 2842 |
if (!result) |
| 2843 |
return Detail::InternalParseResult(result); |
| 2844 |
if (result.value() == |
| 2845 |
ParseResultType::ShortCircuitAll) |
| 2846 |
return Detail::InternalParseResult::ok(Detail::ParseState( |
| 2847 |
result.value(), CATCH_MOVE(tokens))); |
| 2848 |
} else { |
| 2849 |
auto valueRef = |
| 2850 |
static_cast<Detail::BoundValueRefBase*>( |
| 2851 |
m_ref.get()); |
| 2852 |
++tokens; |
| 2853 |
if (!tokens) |
| 2854 |
return Detail::InternalParseResult::runtimeError( |
| 2855 |
"Expected argument following " + |
| 2856 |
token.token); |
| 2857 |
auto const& argToken = *tokens; |
| 2858 |
if (argToken.type != Detail::TokenType::Argument) |
| 2859 |
return Detail::InternalParseResult::runtimeError( |
| 2860 |
"Expected argument following " + |
| 2861 |
token.token); |
| 2862 |
const auto result = valueRef->setValue(static_cast<std::string>(argToken.token)); |
| 2863 |
if (!result) |
| 2864 |
return Detail::InternalParseResult(result); |
| 2865 |
if (result.value() == |
| 2866 |
ParseResultType::ShortCircuitAll) |
| 2867 |
return Detail::InternalParseResult::ok(Detail::ParseState( |
| 2868 |
result.value(), CATCH_MOVE(tokens))); |
| 2869 |
} |
| 2870 |
return Detail::InternalParseResult::ok(Detail::ParseState( |
| 2871 |
ParseResultType::Matched, CATCH_MOVE(++tokens))); |
| 2872 |
} |
| 2873 |
} |
| 2874 |
return Detail::InternalParseResult::ok( |
| 2875 |
Detail::ParseState(ParseResultType::NoMatch, CATCH_MOVE(tokens))); |
| 2876 |
} |
| 2877 |
|
| 2878 |
Detail::Result Opt::validate() const { |
| 2879 |
if (m_optNames.empty()) |
| 2880 |
return Detail::Result::logicError("No options supplied to Opt"); |
| 2881 |
for (auto const& name : m_optNames) { |
| 2882 |
if (name.empty()) |
| 2883 |
return Detail::Result::logicError( |
| 2884 |
"Option name cannot be empty"); |
| 2885 |
#ifdef CATCH_PLATFORM_WINDOWS |
| 2886 |
if (name[0] != '-' && name[0] != '/') |
| 2887 |
return Detail::Result::logicError( |
| 2888 |
"Option name must begin with '-' or '/'"); |
| 2889 |
#else |
| 2890 |
if (name[0] != '-') |
| 2891 |
return Detail::Result::logicError( |
| 2892 |
"Option name must begin with '-'"); |
| 2893 |
#endif |
| 2894 |
} |
| 2895 |
return ParserRefImpl::validate(); |
| 2896 |
} |
| 2897 |
|
| 2898 |
ExeName::ExeName() : |
| 2899 |
m_name(std::make_shared<std::string>("<executable>")) {} |
| 2900 |
|
| 2901 |
ExeName::ExeName(std::string& ref) : ExeName() { |
| 2902 |
m_ref = std::make_shared<Detail::BoundValueRef<std::string>>(ref); |
| 2903 |
} |
| 2904 |
|
| 2905 |
Detail::InternalParseResult |
| 2906 |
ExeName::parse(std::string const&, |
| 2907 |
Detail::TokenStream tokens) const { |
| 2908 |
return Detail::InternalParseResult::ok( |
| 2909 |
Detail::ParseState(ParseResultType::NoMatch, CATCH_MOVE(tokens))); |
| 2910 |
} |
| 2911 |
|
| 2912 |
ParserResult ExeName::set(std::string const& newName) { |
| 2913 |
auto lastSlash = newName.find_last_of("\\/"); |
| 2914 |
auto filename = (lastSlash == std::string::npos) |
| 2915 |
? newName |
| 2916 |
: newName.substr(lastSlash + 1); |
| 2917 |
|
| 2918 |
*m_name = filename; |
| 2919 |
if (m_ref) |
| 2920 |
return m_ref->setValue(filename); |
| 2921 |
else |
| 2922 |
return ParserResult::ok(ParseResultType::Matched); |
| 2923 |
} |
| 2924 |
|
| 2925 |
|
| 2926 |
|
| 2927 |
|
| 2928 |
Parser& Parser::operator|=( Parser const& other ) { |
| 2929 |
m_options.insert( m_options.end(), |
| 2930 |
other.m_options.begin(), |
| 2931 |
other.m_options.end() ); |
| 2932 |
m_args.insert( |
| 2933 |
m_args.end(), other.m_args.begin(), other.m_args.end() ); |
| 2934 |
return *this; |
| 2935 |
} |
| 2936 |
|
| 2937 |
std::vector<Detail::HelpColumns> Parser::getHelpColumns() const { |
| 2938 |
std::vector<Detail::HelpColumns> cols; |
| 2939 |
cols.reserve( m_options.size() ); |
| 2940 |
for ( auto const& o : m_options ) { |
| 2941 |
cols.push_back(o.getHelpColumns()); |
| 2942 |
} |
| 2943 |
return cols; |
| 2944 |
} |
| 2945 |
|
| 2946 |
void Parser::writeToStream( std::ostream& os ) const { |
| 2947 |
if ( !m_exeName.name().empty() ) { |
| 2948 |
os << "usage:\n" |
| 2949 |
<< " " << m_exeName.name() << ' '; |
| 2950 |
bool required = true, first = true; |
| 2951 |
for ( auto const& arg : m_args ) { |
| 2952 |
if ( first ) |
| 2953 |
first = false; |
| 2954 |
else |
| 2955 |
os << ' '; |
| 2956 |
if ( arg.isOptional() && required ) { |
| 2957 |
os << '['; |
| 2958 |
required = false; |
| 2959 |
} |
| 2960 |
os << '<' << arg.hint() << '>'; |
| 2961 |
if ( arg.cardinality() == 0 ) |
| 2962 |
os << " ... "; |
| 2963 |
} |
| 2964 |
if ( !required ) |
| 2965 |
os << ']'; |
| 2966 |
if ( !m_options.empty() ) |
| 2967 |
os << " options"; |
| 2968 |
os << "\n\nwhere options are:\n"; |
| 2969 |
} |
| 2970 |
|
| 2971 |
auto rows = getHelpColumns(); |
| 2972 |
size_t consoleWidth = CATCH_CONFIG_CONSOLE_WIDTH; |
| 2973 |
size_t optWidth = 0; |
| 2974 |
for ( auto const& cols : rows ) |
| 2975 |
optWidth = ( std::max )( optWidth, cols.left.size() + 2 ); |
| 2976 |
|
| 2977 |
optWidth = ( std::min )( optWidth, consoleWidth / 2 ); |
| 2978 |
|
| 2979 |
for ( auto& cols : rows ) { |
| 2980 |
auto row = TextFlow::Column( CATCH_MOVE(cols.left) ) |
| 2981 |
.width( optWidth ) |
| 2982 |
.indent( 2 ) + |
| 2983 |
TextFlow::Spacer( 4 ) + |
| 2984 |
TextFlow::Column( static_cast<std::string>(cols.descriptions) ) |
| 2985 |
.width( consoleWidth - 7 - optWidth ); |
| 2986 |
os << row << '\n'; |
| 2987 |
} |
| 2988 |
} |
| 2989 |
|
| 2990 |
Detail::Result Parser::validate() const { |
| 2991 |
for ( auto const& opt : m_options ) { |
| 2992 |
auto result = opt.validate(); |
| 2993 |
if ( !result ) |
| 2994 |
return result; |
| 2995 |
} |
| 2996 |
for ( auto const& arg : m_args ) { |
| 2997 |
auto result = arg.validate(); |
| 2998 |
if ( !result ) |
| 2999 |
return result; |
| 3000 |
} |
| 3001 |
return Detail::Result::ok(); |
| 3002 |
} |
| 3003 |
|
| 3004 |
Detail::InternalParseResult |
| 3005 |
Parser::parse( std::string const& exeName, |
| 3006 |
Detail::TokenStream tokens ) const { |
| 3007 |
|
| 3008 |
struct ParserInfo { |
| 3009 |
ParserBase const* parser = nullptr; |
| 3010 |
size_t count = 0; |
| 3011 |
}; |
| 3012 |
std::vector<ParserInfo> parseInfos; |
| 3013 |
parseInfos.reserve( m_options.size() + m_args.size() ); |
| 3014 |
for ( auto const& opt : m_options ) { |
| 3015 |
parseInfos.push_back( { &opt, 0 } ); |
| 3016 |
} |
| 3017 |
for ( auto const& arg : m_args ) { |
| 3018 |
parseInfos.push_back( { &arg, 0 } ); |
| 3019 |
} |
| 3020 |
|
| 3021 |
m_exeName.set( exeName ); |
| 3022 |
|
| 3023 |
auto result = Detail::InternalParseResult::ok( |
| 3024 |
Detail::ParseState( ParseResultType::NoMatch, CATCH_MOVE(tokens) ) ); |
| 3025 |
while ( result.value().remainingTokens() ) { |
| 3026 |
bool tokenParsed = false; |
| 3027 |
|
| 3028 |
for ( auto& parseInfo : parseInfos ) { |
| 3029 |
if ( parseInfo.parser->cardinality() == 0 || |
| 3030 |
parseInfo.count < parseInfo.parser->cardinality() ) { |
| 3031 |
result = parseInfo.parser->parse( |
| 3032 |
exeName, CATCH_MOVE(result).value().remainingTokens() ); |
| 3033 |
if ( !result ) |
| 3034 |
return result; |
| 3035 |
if ( result.value().type() != |
| 3036 |
ParseResultType::NoMatch ) { |
| 3037 |
tokenParsed = true; |
| 3038 |
++parseInfo.count; |
| 3039 |
break; |
| 3040 |
} |
| 3041 |
} |
| 3042 |
} |
| 3043 |
|
| 3044 |
if ( result.value().type() == ParseResultType::ShortCircuitAll ) |
| 3045 |
return result; |
| 3046 |
if ( !tokenParsed ) |
| 3047 |
return Detail::InternalParseResult::runtimeError( |
| 3048 |
"Unrecognised token: " + |
| 3049 |
result.value().remainingTokens()->token ); |
| 3050 |
} |
| 3051 |
// !TBD Check missing required options |
| 3052 |
return result; |
| 3053 |
} |
| 3054 |
|
| 3055 |
Args::Args(int argc, char const* const* argv) : |
| 3056 |
m_exeName(argv[0]), m_args(argv + 1, argv + argc) {} |
| 3057 |
|
| 3058 |
Args::Args(std::initializer_list<StringRef> args) : |
| 3059 |
m_exeName(*args.begin()), |
| 3060 |
m_args(args.begin() + 1, args.end()) {} |
| 3061 |
|
| 3062 |
|
| 3063 |
Help::Help( bool& showHelpFlag ): |
| 3064 |
Opt( [&]( bool flag ) { |
| 3065 |
showHelpFlag = flag; |
| 3066 |
return ParserResult::ok( ParseResultType::ShortCircuitAll ); |
| 3067 |
} ) { |
| 3068 |
static_cast<Opt&> ( *this )( |
| 3069 |
"display usage information" )["-?"]["-h"]["--help"] |
| 3070 |
.optional(); |
| 3071 |
} |
| 3072 |
|
| 3073 |
} // namespace Clara |
| 3074 |
} // namespace Catch |
| 3075 |
|
| 3076 |
|
| 3077 |
|
| 3078 |
|
| 3079 |
#include <fstream> |
| 3080 |
#include <string> |
| 3081 |
|
| 3082 |
namespace Catch { |
| 3083 |
|
| 3084 |
Clara::Parser makeCommandLineParser( ConfigData& config ) { |
| 3085 |
|
| 3086 |
using namespace Clara; |
| 3087 |
|
| 3088 |
auto const setWarning = [&]( std::string const& warning ) { |
| 3089 |
if ( warning == "NoAssertions" ) { |
| 3090 |
config.warnings = static_cast<WarnAbout::What>(config.warnings | WarnAbout::NoAssertions); |
| 3091 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3092 |
} else if ( warning == "UnmatchedTestSpec" ) { |
| 3093 |
config.warnings = static_cast<WarnAbout::What>(config.warnings | WarnAbout::UnmatchedTestSpec); |
| 3094 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3095 |
} |
| 3096 |
|
| 3097 |
return ParserResult ::runtimeError( |
| 3098 |
"Unrecognised warning option: '" + warning + '\'' ); |
| 3099 |
}; |
| 3100 |
auto const loadTestNamesFromFile = [&]( std::string const& filename ) { |
| 3101 |
std::ifstream f( filename.c_str() ); |
| 3102 |
if( !f.is_open() ) |
| 3103 |
return ParserResult::runtimeError( "Unable to load input file: '" + filename + '\'' ); |
| 3104 |
|
| 3105 |
std::string line; |
| 3106 |
while( std::getline( f, line ) ) { |
| 3107 |
line = trim(line); |
| 3108 |
if( !line.empty() && !startsWith( line, '#' ) ) { |
| 3109 |
if( !startsWith( line, '"' ) ) |
| 3110 |
line = '"' + CATCH_MOVE(line) + '"'; |
| 3111 |
config.testsOrTags.push_back( line ); |
| 3112 |
config.testsOrTags.emplace_back( "," ); |
| 3113 |
} |
| 3114 |
} |
| 3115 |
//Remove comma in the end |
| 3116 |
if(!config.testsOrTags.empty()) |
| 3117 |
config.testsOrTags.erase( config.testsOrTags.end()-1 ); |
| 3118 |
|
| 3119 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3120 |
}; |
| 3121 |
auto const setTestOrder = [&]( std::string const& order ) { |
| 3122 |
if( startsWith( "declared", order ) ) |
| 3123 |
config.runOrder = TestRunOrder::Declared; |
| 3124 |
else if( startsWith( "lexical", order ) ) |
| 3125 |
config.runOrder = TestRunOrder::LexicographicallySorted; |
| 3126 |
else if( startsWith( "random", order ) ) |
| 3127 |
config.runOrder = TestRunOrder::Randomized; |
| 3128 |
else |
| 3129 |
return ParserResult::runtimeError( "Unrecognised ordering: '" + order + '\'' ); |
| 3130 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3131 |
}; |
| 3132 |
auto const setRngSeed = [&]( std::string const& seed ) { |
| 3133 |
if( seed == "time" ) { |
| 3134 |
config.rngSeed = generateRandomSeed(GenerateFrom::Time); |
| 3135 |
return ParserResult::ok(ParseResultType::Matched); |
| 3136 |
} else if (seed == "random-device") { |
| 3137 |
config.rngSeed = generateRandomSeed(GenerateFrom::RandomDevice); |
| 3138 |
return ParserResult::ok(ParseResultType::Matched); |
| 3139 |
} |
| 3140 |
|
| 3141 |
// TODO: ideally we should be parsing uint32_t directly |
| 3142 |
// fix this later when we add new parse overload |
| 3143 |
auto parsedSeed = parseUInt( seed, 0 ); |
| 3144 |
if ( !parsedSeed ) { |
| 3145 |
return ParserResult::runtimeError( "Could not parse '" + seed + "' as seed" ); |
| 3146 |
} |
| 3147 |
config.rngSeed = *parsedSeed; |
| 3148 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3149 |
}; |
| 3150 |
auto const setDefaultColourMode = [&]( std::string const& colourMode ) { |
| 3151 |
Optional<ColourMode> maybeMode = Catch::Detail::stringToColourMode(toLower( colourMode )); |
| 3152 |
if ( !maybeMode ) { |
| 3153 |
return ParserResult::runtimeError( |
| 3154 |
"colour mode must be one of: default, ansi, win32, " |
| 3155 |
"or none. '" + |
| 3156 |
colourMode + "' is not recognised" ); |
| 3157 |
} |
| 3158 |
auto mode = *maybeMode; |
| 3159 |
if ( !isColourImplAvailable( mode ) ) { |
| 3160 |
return ParserResult::runtimeError( |
| 3161 |
"colour mode '" + colourMode + |
| 3162 |
"' is not supported in this binary" ); |
| 3163 |
} |
| 3164 |
config.defaultColourMode = mode; |
| 3165 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3166 |
}; |
| 3167 |
auto const setWaitForKeypress = [&]( std::string const& keypress ) { |
| 3168 |
auto keypressLc = toLower( keypress ); |
| 3169 |
if (keypressLc == "never") |
| 3170 |
config.waitForKeypress = WaitForKeypress::Never; |
| 3171 |
else if( keypressLc == "start" ) |
| 3172 |
config.waitForKeypress = WaitForKeypress::BeforeStart; |
| 3173 |
else if( keypressLc == "exit" ) |
| 3174 |
config.waitForKeypress = WaitForKeypress::BeforeExit; |
| 3175 |
else if( keypressLc == "both" ) |
| 3176 |
config.waitForKeypress = WaitForKeypress::BeforeStartAndExit; |
| 3177 |
else |
| 3178 |
return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" ); |
| 3179 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3180 |
}; |
| 3181 |
auto const setVerbosity = [&]( std::string const& verbosity ) { |
| 3182 |
auto lcVerbosity = toLower( verbosity ); |
| 3183 |
if( lcVerbosity == "quiet" ) |
| 3184 |
config.verbosity = Verbosity::Quiet; |
| 3185 |
else if( lcVerbosity == "normal" ) |
| 3186 |
config.verbosity = Verbosity::Normal; |
| 3187 |
else if( lcVerbosity == "high" ) |
| 3188 |
config.verbosity = Verbosity::High; |
| 3189 |
else |
| 3190 |
return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + '\'' ); |
| 3191 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3192 |
}; |
| 3193 |
auto const setReporter = [&]( std::string const& userReporterSpec ) { |
| 3194 |
if ( userReporterSpec.empty() ) { |
| 3195 |
return ParserResult::runtimeError( "Received empty reporter spec." ); |
| 3196 |
} |
| 3197 |
|
| 3198 |
Optional<ReporterSpec> parsed = |
| 3199 |
parseReporterSpec( userReporterSpec ); |
| 3200 |
if ( !parsed ) { |
| 3201 |
return ParserResult::runtimeError( |
| 3202 |
"Could not parse reporter spec '" + userReporterSpec + |
| 3203 |
"'" ); |
| 3204 |
} |
| 3205 |
|
| 3206 |
auto const& reporterSpec = *parsed; |
| 3207 |
|
| 3208 |
auto const& factories = |
| 3209 |
getRegistryHub().getReporterRegistry().getFactories(); |
| 3210 |
auto result = factories.find( reporterSpec.name() ); |
| 3211 |
|
| 3212 |
if ( result == factories.end() ) { |
| 3213 |
return ParserResult::runtimeError( |
| 3214 |
"Unrecognized reporter, '" + reporterSpec.name() + |
| 3215 |
"'. Check available with --list-reporters" ); |
| 3216 |
} |
| 3217 |
|
| 3218 |
|
| 3219 |
const bool hadOutputFile = reporterSpec.outputFile().some(); |
| 3220 |
config.reporterSpecifications.push_back( CATCH_MOVE( *parsed ) ); |
| 3221 |
// It would be enough to check this only once at the very end, but |
| 3222 |
// there is not a place where we could call this check, so do it |
| 3223 |
// every time it could fail. For valid inputs, this is still called |
| 3224 |
// at most once. |
| 3225 |
if (!hadOutputFile) { |
| 3226 |
int n_reporters_without_file = 0; |
| 3227 |
for (auto const& spec : config.reporterSpecifications) { |
| 3228 |
if (spec.outputFile().none()) { |
| 3229 |
n_reporters_without_file++; |
| 3230 |
} |
| 3231 |
} |
| 3232 |
if (n_reporters_without_file > 1) { |
| 3233 |
return ParserResult::runtimeError( "Only one reporter may have unspecified output file." ); |
| 3234 |
} |
| 3235 |
} |
| 3236 |
|
| 3237 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3238 |
}; |
| 3239 |
auto const setShardCount = [&]( std::string const& shardCount ) { |
| 3240 |
auto parsedCount = parseUInt( shardCount ); |
| 3241 |
if ( !parsedCount ) { |
| 3242 |
return ParserResult::runtimeError( |
| 3243 |
"Could not parse '" + shardCount + "' as shard count" ); |
| 3244 |
} |
| 3245 |
if ( *parsedCount == 0 ) { |
| 3246 |
return ParserResult::runtimeError( |
| 3247 |
"Shard count must be positive" ); |
| 3248 |
} |
| 3249 |
config.shardCount = *parsedCount; |
| 3250 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3251 |
}; |
| 3252 |
|
| 3253 |
auto const setShardIndex = [&](std::string const& shardIndex) { |
| 3254 |
auto parsedIndex = parseUInt( shardIndex ); |
| 3255 |
if ( !parsedIndex ) { |
| 3256 |
return ParserResult::runtimeError( |
| 3257 |
"Could not parse '" + shardIndex + "' as shard index" ); |
| 3258 |
} |
| 3259 |
config.shardIndex = *parsedIndex; |
| 3260 |
return ParserResult::ok( ParseResultType::Matched ); |
| 3261 |
}; |
| 3262 |
|
| 3263 |
auto cli |
| 3264 |
= ExeName( config.processName ) |
| 3265 |
| Help( config.showHelp ) |
| 3266 |
| Opt( config.showSuccessfulTests ) |
| 3267 |
["-s"]["--success"] |
| 3268 |
( "include successful tests in output" ) |
| 3269 |
| Opt( config.shouldDebugBreak ) |
| 3270 |
["-b"]["--break"] |
| 3271 |
( "break into debugger on failure" ) |
| 3272 |
| Opt( config.noThrow ) |
| 3273 |
["-e"]["--nothrow"] |
| 3274 |
( "skip exception tests" ) |
| 3275 |
| Opt( config.showInvisibles ) |
| 3276 |
["-i"]["--invisibles"] |
| 3277 |
( "show invisibles (tabs, newlines)" ) |
| 3278 |
| Opt( config.defaultOutputFilename, "filename" ) |
| 3279 |
["-o"]["--out"] |
| 3280 |
( "default output filename" ) |
| 3281 |
| Opt( accept_many, setReporter, "name[::key=value]*" ) |
| 3282 |
["-r"]["--reporter"] |
| 3283 |
( "reporter to use (defaults to console)" ) |
| 3284 |
| Opt( config.name, "name" ) |
| 3285 |
["-n"]["--name"] |
| 3286 |
( "suite name" ) |
| 3287 |
| Opt( [&]( bool ){ config.abortAfter = 1; } ) |
| 3288 |
["-a"]["--abort"] |
| 3289 |
( "abort at first failure" ) |
| 3290 |
| Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" ) |
| 3291 |
["-x"]["--abortx"] |
| 3292 |
( "abort after x failures" ) |
| 3293 |
| Opt( accept_many, setWarning, "warning name" ) |
| 3294 |
["-w"]["--warn"] |
| 3295 |
( "enable warnings" ) |
| 3296 |
| Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" ) |
| 3297 |
["-d"]["--durations"] |
| 3298 |
( "show test durations" ) |
| 3299 |
| Opt( config.minDuration, "seconds" ) |
| 3300 |
["-D"]["--min-duration"] |
| 3301 |
( "show test durations for tests taking at least the given number of seconds" ) |
| 3302 |
| Opt( loadTestNamesFromFile, "filename" ) |
| 3303 |
["-f"]["--input-file"] |
| 3304 |
( "load test names to run from a file" ) |
| 3305 |
| Opt( config.filenamesAsTags ) |
| 3306 |
["-#"]["--filenames-as-tags"] |
| 3307 |
( "adds a tag for the filename" ) |
| 3308 |
| Opt( config.sectionsToRun, "section name" ) |
| 3309 |
["-c"]["--section"] |
| 3310 |
( "specify section to run" ) |
| 3311 |
| Opt( setVerbosity, "quiet|normal|high" ) |
| 3312 |
["-v"]["--verbosity"] |
| 3313 |
( "set output verbosity" ) |
| 3314 |
| Opt( config.listTests ) |
| 3315 |
["--list-tests"] |
| 3316 |
( "list all/matching test cases" ) |
| 3317 |
| Opt( config.listTags ) |
| 3318 |
["--list-tags"] |
| 3319 |
( "list all/matching tags" ) |
| 3320 |
| Opt( config.listReporters ) |
| 3321 |
["--list-reporters"] |
| 3322 |
( "list all available reporters" ) |
| 3323 |
| Opt( config.listListeners ) |
| 3324 |
["--list-listeners"] |
| 3325 |
( "list all listeners" ) |
| 3326 |
| Opt( setTestOrder, "decl|lex|rand" ) |
| 3327 |
["--order"] |
| 3328 |
( "test case order (defaults to decl)" ) |
| 3329 |
| Opt( setRngSeed, "'time'|'random-device'|number" ) |
| 3330 |
["--rng-seed"] |
| 3331 |
( "set a specific seed for random numbers" ) |
| 3332 |
| Opt( setDefaultColourMode, "ansi|win32|none|default" ) |
| 3333 |
["--colour-mode"] |
| 3334 |
( "what color mode should be used as default" ) |
| 3335 |
| Opt( config.libIdentify ) |
| 3336 |
["--libidentify"] |
| 3337 |
( "report name and version according to libidentify standard" ) |
| 3338 |
| Opt( setWaitForKeypress, "never|start|exit|both" ) |
| 3339 |
["--wait-for-keypress"] |
| 3340 |
( "waits for a keypress before exiting" ) |
| 3341 |
| Opt( config.skipBenchmarks) |
| 3342 |
["--skip-benchmarks"] |
| 3343 |
( "disable running benchmarks") |
| 3344 |
| Opt( config.benchmarkSamples, "samples" ) |
| 3345 |
["--benchmark-samples"] |
| 3346 |
( "number of samples to collect (default: 100)" ) |
| 3347 |
| Opt( config.benchmarkResamples, "resamples" ) |
| 3348 |
["--benchmark-resamples"] |
| 3349 |
( "number of resamples for the bootstrap (default: 100000)" ) |
| 3350 |
| Opt( config.benchmarkConfidenceInterval, "confidence interval" ) |
| 3351 |
["--benchmark-confidence-interval"] |
| 3352 |
( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" ) |
| 3353 |
| Opt( config.benchmarkNoAnalysis ) |
| 3354 |
["--benchmark-no-analysis"] |
| 3355 |
( "perform only measurements; do not perform any analysis" ) |
| 3356 |
| Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" ) |
| 3357 |
["--benchmark-warmup-time"] |
| 3358 |
( "amount of time in milliseconds spent on warming up each test (default: 100)" ) |
| 3359 |
| Opt( setShardCount, "shard count" ) |
| 3360 |
["--shard-count"] |
| 3361 |
( "split the tests to execute into this many groups" ) |
| 3362 |
| Opt( setShardIndex, "shard index" ) |
| 3363 |
["--shard-index"] |
| 3364 |
( "index of the group of tests to execute (see --shard-count)" ) |
| 3365 |
| Opt( config.allowZeroTests ) |
| 3366 |
["--allow-running-no-tests"] |
| 3367 |
( "Treat 'No tests run' as a success" ) |
| 3368 |
| Arg( config.testsOrTags, "test name|pattern|tags" ) |
| 3369 |
( "which test or tests to use" ); |
| 3370 |
|
| 3371 |
return cli; |
| 3372 |
} |
| 3373 |
|
| 3374 |
} // end namespace Catch |
| 3375 |
|
| 3376 |
|
| 3377 |
#if defined(__clang__) |
| 3378 |
# pragma clang diagnostic push |
| 3379 |
# pragma clang diagnostic ignored "-Wexit-time-destructors" |
| 3380 |
#endif |
| 3381 |
|
| 3382 |
|
| 3383 |
|
| 3384 |
#include <cassert> |
| 3385 |
#include <ostream> |
| 3386 |
#include <utility> |
| 3387 |
|
| 3388 |
namespace Catch { |
| 3389 |
|
| 3390 |
ColourImpl::~ColourImpl() = default; |
| 3391 |
|
| 3392 |
ColourImpl::ColourGuard ColourImpl::guardColour( Colour::Code colourCode ) { |
| 3393 |
return ColourGuard(colourCode, this ); |
| 3394 |
} |
| 3395 |
|
| 3396 |
void ColourImpl::ColourGuard::engageImpl( std::ostream& stream ) { |
| 3397 |
assert( &stream == &m_colourImpl->m_stream->stream() && |
| 3398 |
"Engaging colour guard for different stream than used by the " |
| 3399 |
"parent colour implementation" ); |
| 3400 |
static_cast<void>( stream ); |
| 3401 |
|
| 3402 |
m_engaged = true; |
| 3403 |
m_colourImpl->use( m_code ); |
| 3404 |
} |
| 3405 |
|
| 3406 |
ColourImpl::ColourGuard::ColourGuard( Colour::Code code, |
| 3407 |
ColourImpl const* colour ): |
| 3408 |
m_colourImpl( colour ), m_code( code ) { |
| 3409 |
} |
| 3410 |
ColourImpl::ColourGuard::ColourGuard( ColourGuard&& rhs ) noexcept: |
| 3411 |
m_colourImpl( rhs.m_colourImpl ), |
| 3412 |
m_code( rhs.m_code ), |
| 3413 |
m_engaged( rhs.m_engaged ) { |
| 3414 |
rhs.m_engaged = false; |
| 3415 |
} |
| 3416 |
ColourImpl::ColourGuard& |
| 3417 |
ColourImpl::ColourGuard::operator=( ColourGuard&& rhs ) noexcept { |
| 3418 |
using std::swap; |
| 3419 |
swap( m_colourImpl, rhs.m_colourImpl ); |
| 3420 |
swap( m_code, rhs.m_code ); |
| 3421 |
swap( m_engaged, rhs.m_engaged ); |
| 3422 |
|
| 3423 |
return *this; |
| 3424 |
} |
| 3425 |
ColourImpl::ColourGuard::~ColourGuard() { |
| 3426 |
if ( m_engaged ) { |
| 3427 |
m_colourImpl->use( Colour::None ); |
| 3428 |
} |
| 3429 |
} |
| 3430 |
|
| 3431 |
ColourImpl::ColourGuard& |
| 3432 |
ColourImpl::ColourGuard::engage( std::ostream& stream ) & { |
| 3433 |
engageImpl( stream ); |
| 3434 |
return *this; |
| 3435 |
} |
| 3436 |
|
| 3437 |
ColourImpl::ColourGuard&& |
| 3438 |
ColourImpl::ColourGuard::engage( std::ostream& stream ) && { |
| 3439 |
engageImpl( stream ); |
| 3440 |
return CATCH_MOVE(*this); |
| 3441 |
} |
| 3442 |
|
| 3443 |
namespace { |
| 3444 |
//! A do-nothing implementation of colour, used as fallback for unknown |
| 3445 |
//! platforms, and when the user asks to deactivate all colours. |
| 3446 |
class NoColourImpl final : public ColourImpl { |
| 3447 |
public: |
| 3448 |
NoColourImpl( IStream* stream ): ColourImpl( stream ) {} |
| 3449 |
|
| 3450 |
private: |
| 3451 |
void use( Colour::Code ) const override {} |
| 3452 |
}; |
| 3453 |
} // namespace |
| 3454 |
|
| 3455 |
|
| 3456 |
} // namespace Catch |
| 3457 |
|
| 3458 |
|
| 3459 |
#if defined ( CATCH_CONFIG_COLOUR_WIN32 ) ///////////////////////////////////////// |
| 3460 |
|
| 3461 |
namespace Catch { |
| 3462 |
namespace { |
| 3463 |
|
| 3464 |
class Win32ColourImpl final : public ColourImpl { |
| 3465 |
public: |
| 3466 |
Win32ColourImpl(IStream* stream): |
| 3467 |
ColourImpl(stream) { |
| 3468 |
CONSOLE_SCREEN_BUFFER_INFO csbiInfo; |
| 3469 |
GetConsoleScreenBufferInfo( GetStdHandle( STD_OUTPUT_HANDLE ), |
| 3470 |
&csbiInfo ); |
| 3471 |
originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); |
| 3472 |
originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); |
| 3473 |
} |
| 3474 |
|
| 3475 |
static bool useImplementationForStream(IStream const& stream) { |
| 3476 |
// Win32 text colour APIs can only be used on console streams |
| 3477 |
// We cannot check that the output hasn't been redirected, |
| 3478 |
// so we just check that the original stream is console stream. |
| 3479 |
return stream.isConsole(); |
| 3480 |
} |
| 3481 |
|
| 3482 |
private: |
| 3483 |
void use( Colour::Code _colourCode ) const override { |
| 3484 |
switch( _colourCode ) { |
| 3485 |
case Colour::None: return setTextAttribute( originalForegroundAttributes ); |
| 3486 |
case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); |
| 3487 |
case Colour::Red: return setTextAttribute( FOREGROUND_RED ); |
| 3488 |
case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); |
| 3489 |
case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); |
| 3490 |
case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); |
| 3491 |
case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); |
| 3492 |
case Colour::Grey: return setTextAttribute( 0 ); |
| 3493 |
|
| 3494 |
case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); |
| 3495 |
case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); |
| 3496 |
case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); |
| 3497 |
case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); |
| 3498 |
case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN ); |
| 3499 |
|
| 3500 |
case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); |
| 3501 |
|
| 3502 |
default: |
| 3503 |
CATCH_ERROR( "Unknown colour requested" ); |
| 3504 |
} |
| 3505 |
} |
| 3506 |
|
| 3507 |
void setTextAttribute( WORD _textAttribute ) const { |
| 3508 |
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), |
| 3509 |
_textAttribute | |
| 3510 |
originalBackgroundAttributes ); |
| 3511 |
} |
| 3512 |
WORD originalForegroundAttributes; |
| 3513 |
WORD originalBackgroundAttributes; |
| 3514 |
}; |
| 3515 |
|
| 3516 |
} // end anon namespace |
| 3517 |
} // end namespace Catch |
| 3518 |
|
| 3519 |
#endif // Windows/ ANSI/ None |
| 3520 |
|
| 3521 |
|
| 3522 |
#if defined( CATCH_PLATFORM_LINUX ) || defined( CATCH_PLATFORM_MAC ) || defined( __GLIBC__ ) |
| 3523 |
# define CATCH_INTERNAL_HAS_ISATTY |
| 3524 |
# include <unistd.h> |
| 3525 |
#endif |
| 3526 |
|
| 3527 |
namespace Catch { |
| 3528 |
namespace { |
| 3529 |
|
| 3530 |
class ANSIColourImpl final : public ColourImpl { |
| 3531 |
public: |
| 3532 |
ANSIColourImpl( IStream* stream ): ColourImpl( stream ) {} |
| 3533 |
|
| 3534 |
static bool useImplementationForStream(IStream const& stream) { |
| 3535 |
// This is kinda messy due to trying to support a bunch of |
| 3536 |
// different platforms at once. |
| 3537 |
// The basic idea is that if we are asked to do autodetection (as |
| 3538 |
// opposed to being told to use posixy colours outright), then we |
| 3539 |
// only want to use the colours if we are writing to console. |
| 3540 |
// However, console might be redirected, so we make an attempt at |
| 3541 |
// checking for that on platforms where we know how to do that. |
| 3542 |
bool useColour = stream.isConsole(); |
| 3543 |
#if defined( CATCH_INTERNAL_HAS_ISATTY ) && \ |
| 3544 |
!( defined( __DJGPP__ ) && defined( __STRICT_ANSI__ ) ) |
| 3545 |
ErrnoGuard _; // for isatty |
| 3546 |
useColour = useColour && isatty( STDOUT_FILENO ); |
| 3547 |
# endif |
| 3548 |
# if defined( CATCH_PLATFORM_MAC ) || defined( CATCH_PLATFORM_IPHONE ) |
| 3549 |
useColour = useColour && !isDebuggerActive(); |
| 3550 |
# endif |
| 3551 |
|
| 3552 |
return useColour; |
| 3553 |
} |
| 3554 |
|
| 3555 |
private: |
| 3556 |
void use( Colour::Code _colourCode ) const override { |
| 3557 |
auto setColour = [&out = |
| 3558 |
m_stream->stream()]( char const* escapeCode ) { |
| 3559 |
// The escape sequence must be flushed to console, otherwise |
| 3560 |
// if stdin and stderr are intermixed, we'd get accidentally |
| 3561 |
// coloured output. |
| 3562 |
out << '\033' << escapeCode << std::flush; |
| 3563 |
}; |
| 3564 |
switch( _colourCode ) { |
| 3565 |
case Colour::None: |
| 3566 |
case Colour::White: return setColour( "[0m" ); |
| 3567 |
case Colour::Red: return setColour( "[0;31m" ); |
| 3568 |
case Colour::Green: return setColour( "[0;32m" ); |
| 3569 |
case Colour::Blue: return setColour( "[0;34m" ); |
| 3570 |
case Colour::Cyan: return setColour( "[0;36m" ); |
| 3571 |
case Colour::Yellow: return setColour( "[0;33m" ); |
| 3572 |
case Colour::Grey: return setColour( "[1;30m" ); |
| 3573 |
|
| 3574 |
case Colour::LightGrey: return setColour( "[0;37m" ); |
| 3575 |
case Colour::BrightRed: return setColour( "[1;31m" ); |
| 3576 |
case Colour::BrightGreen: return setColour( "[1;32m" ); |
| 3577 |
case Colour::BrightWhite: return setColour( "[1;37m" ); |
| 3578 |
case Colour::BrightYellow: return setColour( "[1;33m" ); |
| 3579 |
|
| 3580 |
case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); |
| 3581 |
default: CATCH_INTERNAL_ERROR( "Unknown colour requested" ); |
| 3582 |
} |
| 3583 |
} |
| 3584 |
}; |
| 3585 |
|
| 3586 |
} // end anon namespace |
| 3587 |
} // end namespace Catch |
| 3588 |
|
| 3589 |
namespace Catch { |
| 3590 |
|
| 3591 |
Detail::unique_ptr<ColourImpl> makeColourImpl( ColourMode colourSelection, |
| 3592 |
IStream* stream ) { |
| 3593 |
#if defined( CATCH_CONFIG_COLOUR_WIN32 ) |
| 3594 |
if ( colourSelection == ColourMode::Win32 ) { |
| 3595 |
return Detail::make_unique<Win32ColourImpl>( stream ); |
| 3596 |
} |
| 3597 |
#endif |
| 3598 |
if ( colourSelection == ColourMode::ANSI ) { |
| 3599 |
return Detail::make_unique<ANSIColourImpl>( stream ); |
| 3600 |
} |
| 3601 |
if ( colourSelection == ColourMode::None ) { |
| 3602 |
return Detail::make_unique<NoColourImpl>( stream ); |
| 3603 |
} |
| 3604 |
|
| 3605 |
if ( colourSelection == ColourMode::PlatformDefault) { |
| 3606 |
#if defined( CATCH_CONFIG_COLOUR_WIN32 ) |
| 3607 |
if ( Win32ColourImpl::useImplementationForStream( *stream ) ) { |
| 3608 |
return Detail::make_unique<Win32ColourImpl>( stream ); |
| 3609 |
} |
| 3610 |
#endif |
| 3611 |
if ( ANSIColourImpl::useImplementationForStream( *stream ) ) { |
| 3612 |
return Detail::make_unique<ANSIColourImpl>( stream ); |
| 3613 |
} |
| 3614 |
return Detail::make_unique<NoColourImpl>( stream ); |
| 3615 |
} |
| 3616 |
|
| 3617 |
CATCH_ERROR( "Could not create colour impl for selection " << static_cast<int>(colourSelection) ); |
| 3618 |
} |
| 3619 |
|
| 3620 |
bool isColourImplAvailable( ColourMode colourSelection ) { |
| 3621 |
switch ( colourSelection ) { |
| 3622 |
#if defined( CATCH_CONFIG_COLOUR_WIN32 ) |
| 3623 |
case ColourMode::Win32: |
| 3624 |
#endif |
| 3625 |
case ColourMode::ANSI: |
| 3626 |
case ColourMode::None: |
| 3627 |
case ColourMode::PlatformDefault: |
| 3628 |
return true; |
| 3629 |
default: |
| 3630 |
return false; |
| 3631 |
} |
| 3632 |
} |
| 3633 |
|
| 3634 |
|
| 3635 |
} // end namespace Catch |
| 3636 |
|
| 3637 |
#if defined(__clang__) |
| 3638 |
# pragma clang diagnostic pop |
| 3639 |
#endif |
| 3640 |
|
| 3641 |
|
| 3642 |
|
| 3643 |
|
| 3644 |
namespace Catch { |
| 3645 |
|
| 3646 |
Context* Context::currentContext = nullptr; |
| 3647 |
|
| 3648 |
void cleanUpContext() { |
| 3649 |
delete Context::currentContext; |
| 3650 |
Context::currentContext = nullptr; |
| 3651 |
} |
| 3652 |
void Context::createContext() { |
| 3653 |
currentContext = new Context(); |
| 3654 |
} |
| 3655 |
|
| 3656 |
Context& getCurrentMutableContext() { |
| 3657 |
if ( !Context::currentContext ) { Context::createContext(); } |
| 3658 |
// NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn) |
| 3659 |
return *Context::currentContext; |
| 3660 |
} |
| 3661 |
|
| 3662 |
SimplePcg32& sharedRng() { |
| 3663 |
static SimplePcg32 s_rng; |
| 3664 |
return s_rng; |
| 3665 |
} |
| 3666 |
|
| 3667 |
} |
| 3668 |
|
| 3669 |
|
| 3670 |
|
| 3671 |
|
| 3672 |
|
| 3673 |
#include <ostream> |
| 3674 |
|
| 3675 |
#if defined(CATCH_CONFIG_ANDROID_LOGWRITE) |
| 3676 |
#include <android/log.h> |
| 3677 |
|
| 3678 |
namespace Catch { |
| 3679 |
void writeToDebugConsole( std::string const& text ) { |
| 3680 |
__android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() ); |
| 3681 |
} |
| 3682 |
} |
| 3683 |
|
| 3684 |
#elif defined(CATCH_PLATFORM_WINDOWS) |
| 3685 |
|
| 3686 |
namespace Catch { |
| 3687 |
void writeToDebugConsole( std::string const& text ) { |
| 3688 |
::OutputDebugStringA( text.c_str() ); |
| 3689 |
} |
| 3690 |
} |
| 3691 |
|
| 3692 |
#else |
| 3693 |
|
| 3694 |
namespace Catch { |
| 3695 |
void writeToDebugConsole( std::string const& text ) { |
| 3696 |
// !TBD: Need a version for Mac/ XCode and other IDEs |
| 3697 |
Catch::cout() << text; |
| 3698 |
} |
| 3699 |
} |
| 3700 |
|
| 3701 |
#endif // Platform |
| 3702 |
|
| 3703 |
|
| 3704 |
|
| 3705 |
#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) |
| 3706 |
|
| 3707 |
# include <cassert> |
| 3708 |
# include <sys/types.h> |
| 3709 |
# include <unistd.h> |
| 3710 |
# include <cstddef> |
| 3711 |
# include <ostream> |
| 3712 |
|
| 3713 |
#ifdef __apple_build_version__ |
| 3714 |
// These headers will only compile with AppleClang (XCode) |
| 3715 |
// For other compilers (Clang, GCC, ... ) we need to exclude them |
| 3716 |
# include <sys/sysctl.h> |
| 3717 |
#endif |
| 3718 |
|
| 3719 |
namespace Catch { |
| 3720 |
#ifdef __apple_build_version__ |
| 3721 |
// The following function is taken directly from the following technical note: |
| 3722 |
// https://developer.apple.com/library/archive/qa/qa1361/_index.html |
| 3723 |
|
| 3724 |
// Returns true if the current process is being debugged (either |
| 3725 |
// running under the debugger or has a debugger attached post facto). |
| 3726 |
bool isDebuggerActive(){ |
| 3727 |
int mib[4]; |
| 3728 |
struct kinfo_proc info; |
| 3729 |
std::size_t size; |
| 3730 |
|
| 3731 |
// Initialize the flags so that, if sysctl fails for some bizarre |
| 3732 |
// reason, we get a predictable result. |
| 3733 |
|
| 3734 |
info.kp_proc.p_flag = 0; |
| 3735 |
|
| 3736 |
// Initialize mib, which tells sysctl the info we want, in this case |
| 3737 |
// we're looking for information about a specific process ID. |
| 3738 |
|
| 3739 |
mib[0] = CTL_KERN; |
| 3740 |
mib[1] = KERN_PROC; |
| 3741 |
mib[2] = KERN_PROC_PID; |
| 3742 |
mib[3] = getpid(); |
| 3743 |
|
| 3744 |
// Call sysctl. |
| 3745 |
|
| 3746 |
size = sizeof(info); |
| 3747 |
if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) { |
| 3748 |
Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n\n" << std::flush; |
| 3749 |
return false; |
| 3750 |
} |
| 3751 |
|
| 3752 |
// We're being debugged if the P_TRACED flag is set. |
| 3753 |
|
| 3754 |
return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); |
| 3755 |
} |
| 3756 |
#else |
| 3757 |
bool isDebuggerActive() { |
| 3758 |
// We need to find another way to determine this for non-appleclang compilers on macOS |
| 3759 |
return false; |
| 3760 |
} |
| 3761 |
#endif |
| 3762 |
} // namespace Catch |
| 3763 |
|
| 3764 |
#elif defined(CATCH_PLATFORM_LINUX) |
| 3765 |
#include <fstream> |
| 3766 |
#include <string> |
| 3767 |
|
| 3768 |
namespace Catch{ |
| 3769 |
// The standard POSIX way of detecting a debugger is to attempt to |
| 3770 |
// ptrace() the process, but this needs to be done from a child and not |
| 3771 |
// this process itself to still allow attaching to this process later |
| 3772 |
// if wanted, so is rather heavy. Under Linux we have the PID of the |
| 3773 |
// "debugger" (which doesn't need to be gdb, of course, it could also |
| 3774 |
// be strace, for example) in /proc/$PID/status, so just get it from |
| 3775 |
// there instead. |
| 3776 |
bool isDebuggerActive(){ |
| 3777 |
// Libstdc++ has a bug, where std::ifstream sets errno to 0 |
| 3778 |
// This way our users can properly assert over errno values |
| 3779 |
ErrnoGuard guard; |
| 3780 |
std::ifstream in("/proc/self/status"); |
| 3781 |
for( std::string line; std::getline(in, line); ) { |
| 3782 |
static const int PREFIX_LEN = 11; |
| 3783 |
if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) { |
| 3784 |
// We're traced if the PID is not 0 and no other PID starts |
| 3785 |
// with 0 digit, so it's enough to check for just a single |
| 3786 |
// character. |
| 3787 |
return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; |
| 3788 |
} |
| 3789 |
} |
| 3790 |
|
| 3791 |
return false; |
| 3792 |
} |
| 3793 |
} // namespace Catch |
| 3794 |
#elif defined(_MSC_VER) |
| 3795 |
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); |
| 3796 |
namespace Catch { |
| 3797 |
bool isDebuggerActive() { |
| 3798 |
return IsDebuggerPresent() != 0; |
| 3799 |
} |
| 3800 |
} |
| 3801 |
#elif defined(__MINGW32__) |
| 3802 |
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); |
| 3803 |
namespace Catch { |
| 3804 |
bool isDebuggerActive() { |
| 3805 |
return IsDebuggerPresent() != 0; |
| 3806 |
} |
| 3807 |
} |
| 3808 |
#else |
| 3809 |
namespace Catch { |
| 3810 |
bool isDebuggerActive() { return false; } |
| 3811 |
} |
| 3812 |
#endif // Platform |
| 3813 |
|
| 3814 |
|
| 3815 |
|
| 3816 |
|
| 3817 |
namespace Catch { |
| 3818 |
|
| 3819 |
void ITransientExpression::streamReconstructedExpression( |
| 3820 |
std::ostream& os ) const { |
| 3821 |
// We can't make this function pure virtual to keep ITransientExpression |
| 3822 |
// constexpr, so we write error message instead |
| 3823 |
os << "Some class derived from ITransientExpression without overriding streamReconstructedExpression"; |
| 3824 |
} |
| 3825 |
|
| 3826 |
void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) { |
| 3827 |
if( lhs.size() + rhs.size() < 40 && |
| 3828 |
lhs.find('\n') == std::string::npos && |
| 3829 |
rhs.find('\n') == std::string::npos ) |
| 3830 |
os << lhs << ' ' << op << ' ' << rhs; |
| 3831 |
else |
| 3832 |
os << lhs << '\n' << op << '\n' << rhs; |
| 3833 |
} |
| 3834 |
} |
| 3835 |
|
| 3836 |
|
| 3837 |
|
| 3838 |
#include <stdexcept> |
| 3839 |
|
| 3840 |
|
| 3841 |
namespace Catch { |
| 3842 |
#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) |
| 3843 |
[[noreturn]] |
| 3844 |
void throw_exception(std::exception const& e) { |
| 3845 |
Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n" |
| 3846 |
<< "The message was: " << e.what() << '\n'; |
| 3847 |
std::terminate(); |
| 3848 |
} |
| 3849 |
#endif |
| 3850 |
|
| 3851 |
[[noreturn]] |
| 3852 |
void throw_logic_error(std::string const& msg) { |
| 3853 |
throw_exception(std::logic_error(msg)); |
| 3854 |
} |
| 3855 |
|
| 3856 |
[[noreturn]] |
| 3857 |
void throw_domain_error(std::string const& msg) { |
| 3858 |
throw_exception(std::domain_error(msg)); |
| 3859 |
} |
| 3860 |
|
| 3861 |
[[noreturn]] |
| 3862 |
void throw_runtime_error(std::string const& msg) { |
| 3863 |
throw_exception(std::runtime_error(msg)); |
| 3864 |
} |
| 3865 |
|
| 3866 |
|
| 3867 |
|
| 3868 |
} // namespace Catch; |
| 3869 |
|
| 3870 |
|
| 3871 |
|
| 3872 |
#include <cassert> |
| 3873 |
|
| 3874 |
namespace Catch { |
| 3875 |
|
| 3876 |
IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() = default; |
| 3877 |
|
| 3878 |
namespace Detail { |
| 3879 |
|
| 3880 |
namespace { |
| 3881 |
// Extracts the actual name part of an enum instance |
| 3882 |
// In other words, it returns the Blue part of Bikeshed::Colour::Blue |
| 3883 |
StringRef extractInstanceName(StringRef enumInstance) { |
| 3884 |
// Find last occurrence of ":" |
| 3885 |
size_t name_start = enumInstance.size(); |
| 3886 |
while (name_start > 0 && enumInstance[name_start - 1] != ':') { |
| 3887 |
--name_start; |
| 3888 |
} |
| 3889 |
return enumInstance.substr(name_start, enumInstance.size() - name_start); |
| 3890 |
} |
| 3891 |
} |
| 3892 |
|
| 3893 |
std::vector<StringRef> parseEnums( StringRef enums ) { |
| 3894 |
auto enumValues = splitStringRef( enums, ',' ); |
| 3895 |
std::vector<StringRef> parsed; |
| 3896 |
parsed.reserve( enumValues.size() ); |
| 3897 |
for( auto const& enumValue : enumValues ) { |
| 3898 |
parsed.push_back(trim(extractInstanceName(enumValue))); |
| 3899 |
} |
| 3900 |
return parsed; |
| 3901 |
} |
| 3902 |
|
| 3903 |
EnumInfo::~EnumInfo() = default; |
| 3904 |
|
| 3905 |
StringRef EnumInfo::lookup( int value ) const { |
| 3906 |
for( auto const& valueToName : m_values ) { |
| 3907 |
if( valueToName.first == value ) |
| 3908 |
return valueToName.second; |
| 3909 |
} |
| 3910 |
return "{** unexpected enum value **}"_sr; |
| 3911 |
} |
| 3912 |
|
| 3913 |
Catch::Detail::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) { |
| 3914 |
auto enumInfo = Catch::Detail::make_unique<EnumInfo>(); |
| 3915 |
enumInfo->m_name = enumName; |
| 3916 |
enumInfo->m_values.reserve( values.size() ); |
| 3917 |
|
| 3918 |
const auto valueNames = Catch::Detail::parseEnums( allValueNames ); |
| 3919 |
assert( valueNames.size() == values.size() ); |
| 3920 |
std::size_t i = 0; |
| 3921 |
for( auto value : values ) |
| 3922 |
enumInfo->m_values.emplace_back(value, valueNames[i++]); |
| 3923 |
|
| 3924 |
return enumInfo; |
| 3925 |
} |
| 3926 |
|
| 3927 |
EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) { |
| 3928 |
m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values)); |
| 3929 |
return *m_enumInfos.back(); |
| 3930 |
} |
| 3931 |
|
| 3932 |
} // Detail |
| 3933 |
} // Catch |
| 3934 |
|
| 3935 |
|
| 3936 |
|
| 3937 |
|
| 3938 |
|
| 3939 |
#include <cerrno> |
| 3940 |
|
| 3941 |
namespace Catch { |
| 3942 |
ErrnoGuard::ErrnoGuard():m_oldErrno(errno){} |
| 3943 |
ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; } |
| 3944 |
} |
| 3945 |
|
| 3946 |
|
| 3947 |
|
| 3948 |
#include <exception> |
| 3949 |
|
| 3950 |
namespace Catch { |
| 3951 |
|
| 3952 |
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) |
| 3953 |
namespace { |
| 3954 |
static std::string tryTranslators( |
| 3955 |
std::vector< |
| 3956 |
Detail::unique_ptr<IExceptionTranslator const>> const& translators ) { |
| 3957 |
if ( translators.empty() ) { |
| 3958 |
std::rethrow_exception( std::current_exception() ); |
| 3959 |
} else { |
| 3960 |
return translators[0]->translate( translators.begin() + 1, |
| 3961 |
translators.end() ); |
| 3962 |
} |
| 3963 |
} |
| 3964 |
|
| 3965 |
} |
| 3966 |
#endif //!defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) |
| 3967 |
|
| 3968 |
ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() = default; |
| 3969 |
|
| 3970 |
void ExceptionTranslatorRegistry::registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator ) { |
| 3971 |
m_translators.push_back( CATCH_MOVE( translator ) ); |
| 3972 |
} |
| 3973 |
|
| 3974 |
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) |
| 3975 |
std::string ExceptionTranslatorRegistry::translateActiveException() const { |
| 3976 |
// Compiling a mixed mode project with MSVC means that CLR |
| 3977 |
// exceptions will be caught in (...) as well. However, these do |
| 3978 |
// do not fill-in std::current_exception and thus lead to crash |
| 3979 |
// when attempting rethrow. |
| 3980 |
// /EHa switch also causes structured exceptions to be caught |
| 3981 |
// here, but they fill-in current_exception properly, so |
| 3982 |
// at worst the output should be a little weird, instead of |
| 3983 |
// causing a crash. |
| 3984 |
if ( std::current_exception() == nullptr ) { |
| 3985 |
return "Non C++ exception. Possibly a CLR exception."; |
| 3986 |
} |
| 3987 |
|
| 3988 |
// First we try user-registered translators. If none of them can |
| 3989 |
// handle the exception, it will be rethrown handled by our defaults. |
| 3990 |
try { |
| 3991 |
return tryTranslators(m_translators); |
| 3992 |
} |
| 3993 |
// To avoid having to handle TFE explicitly everywhere, we just |
| 3994 |
// rethrow it so that it goes back up the caller. |
| 3995 |
catch( TestFailureException& ) { |
| 3996 |
std::rethrow_exception(std::current_exception()); |
| 3997 |
} |
| 3998 |
catch( TestSkipException& ) { |
| 3999 |
std::rethrow_exception(std::current_exception()); |
| 4000 |
} |
| 4001 |
catch( std::exception const& ex ) { |
| 4002 |
return ex.what(); |
| 4003 |
} |
| 4004 |
catch( std::string const& msg ) { |
| 4005 |
return msg; |
| 4006 |
} |
| 4007 |
catch( const char* msg ) { |
| 4008 |
return msg; |
| 4009 |
} |
| 4010 |
catch(...) { |
| 4011 |
return "Unknown exception"; |
| 4012 |
} |
| 4013 |
} |
| 4014 |
|
| 4015 |
#else // ^^ Exceptions are enabled // Exceptions are disabled vv |
| 4016 |
std::string ExceptionTranslatorRegistry::translateActiveException() const { |
| 4017 |
CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); |
| 4018 |
} |
| 4019 |
#endif |
| 4020 |
|
| 4021 |
} |
| 4022 |
|
| 4023 |
|
| 4024 |
|
| 4025 |
/** \file |
| 4026 |
* This file provides platform specific implementations of FatalConditionHandler |
| 4027 |
* |
| 4028 |
* This means that there is a lot of conditional compilation, and platform |
| 4029 |
* specific code. Currently, Catch2 supports a dummy handler (if no |
| 4030 |
* handler is desired), and 2 platform specific handlers: |
| 4031 |
* * Windows' SEH |
| 4032 |
* * POSIX signals |
| 4033 |
* |
| 4034 |
* Consequently, various pieces of code below are compiled if either of |
| 4035 |
* the platform specific handlers is enabled, or if none of them are |
| 4036 |
* enabled. It is assumed that both cannot be enabled at the same time, |
| 4037 |
* and doing so should cause a compilation error. |
| 4038 |
* |
| 4039 |
* If another platform specific handler is added, the compile guards |
| 4040 |
* below will need to be updated taking these assumptions into account. |
| 4041 |
*/ |
| 4042 |
|
| 4043 |
|
| 4044 |
|
| 4045 |
#include <algorithm> |
| 4046 |
|
| 4047 |
#if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS ) |
| 4048 |
|
| 4049 |
namespace Catch { |
| 4050 |
|
| 4051 |
// If neither SEH nor signal handling is required, the handler impls |
| 4052 |
// do not have to do anything, and can be empty. |
| 4053 |
void FatalConditionHandler::engage_platform() {} |
| 4054 |
void FatalConditionHandler::disengage_platform() noexcept {} |
| 4055 |
FatalConditionHandler::FatalConditionHandler() = default; |
| 4056 |
FatalConditionHandler::~FatalConditionHandler() = default; |
| 4057 |
|
| 4058 |
} // end namespace Catch |
| 4059 |
|
| 4060 |
#endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS |
| 4061 |
|
| 4062 |
#if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS ) |
| 4063 |
#error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time" |
| 4064 |
#endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS |
| 4065 |
|
| 4066 |
#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) |
| 4067 |
|
| 4068 |
namespace { |
| 4069 |
//! Signals fatal error message to the run context |
| 4070 |
void reportFatal( char const * const message ) { |
| 4071 |
Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message ); |
| 4072 |
} |
| 4073 |
|
| 4074 |
//! Minimal size Catch2 needs for its own fatal error handling. |
| 4075 |
//! Picked empirically, so it might not be sufficient on all |
| 4076 |
//! platforms, and for all configurations. |
| 4077 |
constexpr std::size_t minStackSizeForErrors = 32 * 1024; |
| 4078 |
} // end unnamed namespace |
| 4079 |
|
| 4080 |
#endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS |
| 4081 |
|
| 4082 |
#if defined( CATCH_CONFIG_WINDOWS_SEH ) |
| 4083 |
|
| 4084 |
namespace Catch { |
| 4085 |
|
| 4086 |
struct SignalDefs { DWORD id; const char* name; }; |
| 4087 |
|
| 4088 |
// There is no 1-1 mapping between signals and windows exceptions. |
| 4089 |
// Windows can easily distinguish between SO and SigSegV, |
| 4090 |
// but SigInt, SigTerm, etc are handled differently. |
| 4091 |
static SignalDefs signalDefs[] = { |
| 4092 |
{ EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" }, |
| 4093 |
{ EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" }, |
| 4094 |
{ EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" }, |
| 4095 |
{ EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" }, |
| 4096 |
}; |
| 4097 |
|
| 4098 |
static LONG CALLBACK topLevelExceptionFilter(PEXCEPTION_POINTERS ExceptionInfo) { |
| 4099 |
for (auto const& def : signalDefs) { |
| 4100 |
if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) { |
| 4101 |
reportFatal(def.name); |
| 4102 |
} |
| 4103 |
} |
| 4104 |
// If its not an exception we care about, pass it along. |
| 4105 |
// This stops us from eating debugger breaks etc. |
| 4106 |
return EXCEPTION_CONTINUE_SEARCH; |
| 4107 |
} |
| 4108 |
|
| 4109 |
// Since we do not support multiple instantiations, we put these |
| 4110 |
// into global variables and rely on cleaning them up in outlined |
| 4111 |
// constructors/destructors |
| 4112 |
static LPTOP_LEVEL_EXCEPTION_FILTER previousTopLevelExceptionFilter = nullptr; |
| 4113 |
|
| 4114 |
|
| 4115 |
// For MSVC, we reserve part of the stack memory for handling |
| 4116 |
// memory overflow structured exception. |
| 4117 |
FatalConditionHandler::FatalConditionHandler() { |
| 4118 |
ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors); |
| 4119 |
if (!SetThreadStackGuarantee(&guaranteeSize)) { |
| 4120 |
// We do not want to fully error out, because needing |
| 4121 |
// the stack reserve should be rare enough anyway. |
| 4122 |
Catch::cerr() |
| 4123 |
<< "Failed to reserve piece of stack." |
| 4124 |
<< " Stack overflows will not be reported successfully."; |
| 4125 |
} |
| 4126 |
} |
| 4127 |
|
| 4128 |
// We do not attempt to unset the stack guarantee, because |
| 4129 |
// Windows does not support lowering the stack size guarantee. |
| 4130 |
FatalConditionHandler::~FatalConditionHandler() = default; |
| 4131 |
|
| 4132 |
|
| 4133 |
void FatalConditionHandler::engage_platform() { |
| 4134 |
// Register as a the top level exception filter. |
| 4135 |
previousTopLevelExceptionFilter = SetUnhandledExceptionFilter(topLevelExceptionFilter); |
| 4136 |
} |
| 4137 |
|
| 4138 |
void FatalConditionHandler::disengage_platform() noexcept { |
| 4139 |
if (SetUnhandledExceptionFilter(previousTopLevelExceptionFilter) != topLevelExceptionFilter) { |
| 4140 |
Catch::cerr() |
| 4141 |
<< "Unexpected SEH unhandled exception filter on disengage." |
| 4142 |
<< " The filter was restored, but might be rolled back unexpectedly."; |
| 4143 |
} |
| 4144 |
previousTopLevelExceptionFilter = nullptr; |
| 4145 |
} |
| 4146 |
|
| 4147 |
} // end namespace Catch |
| 4148 |
|
| 4149 |
#endif // CATCH_CONFIG_WINDOWS_SEH |
| 4150 |
|
| 4151 |
#if defined( CATCH_CONFIG_POSIX_SIGNALS ) |
| 4152 |
|
| 4153 |
#include <signal.h> |
| 4154 |
|
| 4155 |
namespace Catch { |
| 4156 |
|
| 4157 |
struct SignalDefs { |
| 4158 |
int id; |
| 4159 |
const char* name; |
| 4160 |
}; |
| 4161 |
|
| 4162 |
static SignalDefs signalDefs[] = { |
| 4163 |
{ SIGINT, "SIGINT - Terminal interrupt signal" }, |
| 4164 |
{ SIGILL, "SIGILL - Illegal instruction signal" }, |
| 4165 |
{ SIGFPE, "SIGFPE - Floating point error signal" }, |
| 4166 |
{ SIGSEGV, "SIGSEGV - Segmentation violation signal" }, |
| 4167 |
{ SIGTERM, "SIGTERM - Termination request signal" }, |
| 4168 |
{ SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } |
| 4169 |
}; |
| 4170 |
|
| 4171 |
// Older GCCs trigger -Wmissing-field-initializers for T foo = {} |
| 4172 |
// which is zero initialization, but not explicit. We want to avoid |
| 4173 |
// that. |
| 4174 |
#if defined(__GNUC__) |
| 4175 |
# pragma GCC diagnostic push |
| 4176 |
# pragma GCC diagnostic ignored "-Wmissing-field-initializers" |
| 4177 |
#endif |
| 4178 |
|
| 4179 |
static char* altStackMem = nullptr; |
| 4180 |
static std::size_t altStackSize = 0; |
| 4181 |
static stack_t oldSigStack{}; |
| 4182 |
static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{}; |
| 4183 |
|
| 4184 |
static void restorePreviousSignalHandlers() noexcept { |
| 4185 |
// We set signal handlers back to the previous ones. Hopefully |
| 4186 |
// nobody overwrote them in the meantime, and doesn't expect |
| 4187 |
// their signal handlers to live past ours given that they |
| 4188 |
// installed them after ours.. |
| 4189 |
for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { |
| 4190 |
sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); |
| 4191 |
} |
| 4192 |
// Return the old stack |
| 4193 |
sigaltstack(&oldSigStack, nullptr); |
| 4194 |
} |
| 4195 |
|
| 4196 |
static void handleSignal( int sig ) { |
| 4197 |
char const * name = "<unknown signal>"; |
| 4198 |
for (auto const& def : signalDefs) { |
| 4199 |
if (sig == def.id) { |
| 4200 |
name = def.name; |
| 4201 |
break; |
| 4202 |
} |
| 4203 |
} |
| 4204 |
// We need to restore previous signal handlers and let them do |
| 4205 |
// their thing, so that the users can have the debugger break |
| 4206 |
// when a signal is raised, and so on. |
| 4207 |
restorePreviousSignalHandlers(); |
| 4208 |
reportFatal( name ); |
| 4209 |
raise( sig ); |
| 4210 |
} |
| 4211 |
|
| 4212 |
FatalConditionHandler::FatalConditionHandler() { |
| 4213 |
assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists"); |
| 4214 |
if (altStackSize == 0) { |
| 4215 |
altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors); |
| 4216 |
} |
| 4217 |
altStackMem = new char[altStackSize](); |
| 4218 |
} |
| 4219 |
|
| 4220 |
FatalConditionHandler::~FatalConditionHandler() { |
| 4221 |
delete[] altStackMem; |
| 4222 |
// We signal that another instance can be constructed by zeroing |
| 4223 |
// out the pointer. |
| 4224 |
altStackMem = nullptr; |
| 4225 |
} |
| 4226 |
|
| 4227 |
void FatalConditionHandler::engage_platform() { |
| 4228 |
stack_t sigStack; |
| 4229 |
sigStack.ss_sp = altStackMem; |
| 4230 |
sigStack.ss_size = altStackSize; |
| 4231 |
sigStack.ss_flags = 0; |
| 4232 |
sigaltstack(&sigStack, &oldSigStack); |
| 4233 |
struct sigaction sa = { }; |
| 4234 |
|
| 4235 |
sa.sa_handler = handleSignal; |
| 4236 |
sa.sa_flags = SA_ONSTACK; |
| 4237 |
for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) { |
| 4238 |
sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); |
| 4239 |
} |
| 4240 |
} |
| 4241 |
|
| 4242 |
#if defined(__GNUC__) |
| 4243 |
# pragma GCC diagnostic pop |
| 4244 |
#endif |
| 4245 |
|
| 4246 |
|
| 4247 |
void FatalConditionHandler::disengage_platform() noexcept { |
| 4248 |
restorePreviousSignalHandlers(); |
| 4249 |
} |
| 4250 |
|
| 4251 |
} // end namespace Catch |
| 4252 |
|
| 4253 |
#endif // CATCH_CONFIG_POSIX_SIGNALS |
| 4254 |
|
| 4255 |
|
| 4256 |
|
| 4257 |
|
| 4258 |
#include <cstring> |
| 4259 |
|
| 4260 |
namespace Catch { |
| 4261 |
namespace Detail { |
| 4262 |
|
| 4263 |
uint32_t convertToBits(float f) { |
| 4264 |
static_assert(sizeof(float) == sizeof(uint32_t), "Important ULP matcher assumption violated"); |
| 4265 |
uint32_t i; |
| 4266 |
std::memcpy(&i, &f, sizeof(f)); |
| 4267 |
return i; |
| 4268 |
} |
| 4269 |
|
| 4270 |
uint64_t convertToBits(double d) { |
| 4271 |
static_assert(sizeof(double) == sizeof(uint64_t), "Important ULP matcher assumption violated"); |
| 4272 |
uint64_t i; |
| 4273 |
std::memcpy(&i, &d, sizeof(d)); |
| 4274 |
return i; |
| 4275 |
} |
| 4276 |
|
| 4277 |
#if defined( __GNUC__ ) || defined( __clang__ ) |
| 4278 |
# pragma GCC diagnostic push |
| 4279 |
# pragma GCC diagnostic ignored "-Wfloat-equal" |
| 4280 |
#endif |
| 4281 |
bool directCompare( float lhs, float rhs ) { return lhs == rhs; } |
| 4282 |
bool directCompare( double lhs, double rhs ) { return lhs == rhs; } |
| 4283 |
#if defined( __GNUC__ ) || defined( __clang__ ) |
| 4284 |
# pragma GCC diagnostic pop |
| 4285 |
#endif |
| 4286 |
|
| 4287 |
|
| 4288 |
} // end namespace Detail |
| 4289 |
} // end namespace Catch |
| 4290 |
|
| 4291 |
|
| 4292 |
|
| 4293 |
|
| 4294 |
|
| 4295 |
|
| 4296 |
#include <cstdlib> |
| 4297 |
|
| 4298 |
namespace Catch { |
| 4299 |
namespace Detail { |
| 4300 |
|
| 4301 |
#if !defined (CATCH_CONFIG_GETENV) |
| 4302 |
char const* getEnv( char const* ) { return nullptr; } |
| 4303 |
#else |
| 4304 |
|
| 4305 |
char const* getEnv( char const* varName ) { |
| 4306 |
# if defined( _MSC_VER ) |
| 4307 |
# pragma warning( push ) |
| 4308 |
# pragma warning( disable : 4996 ) // use getenv_s instead of getenv |
| 4309 |
# endif |
| 4310 |
|
| 4311 |
return std::getenv( varName ); |
| 4312 |
|
| 4313 |
# if defined( _MSC_VER ) |
| 4314 |
# pragma warning( pop ) |
| 4315 |
# endif |
| 4316 |
} |
| 4317 |
#endif |
| 4318 |
} // namespace Detail |
| 4319 |
} // namespace Catch |
| 4320 |
|
| 4321 |
|
| 4322 |
|
| 4323 |
|
| 4324 |
#include <cstdio> |
| 4325 |
#include <fstream> |
| 4326 |
#include <sstream> |
| 4327 |
#include <vector> |
| 4328 |
|
| 4329 |
namespace Catch { |
| 4330 |
|
| 4331 |
Catch::IStream::~IStream() = default; |
| 4332 |
|
| 4333 |
namespace Detail { |
| 4334 |
namespace { |
| 4335 |
template<typename WriterF, std::size_t bufferSize=256> |
| 4336 |
class StreamBufImpl final : public std::streambuf { |
| 4337 |
char data[bufferSize]; |
| 4338 |
WriterF m_writer; |
| 4339 |
|
| 4340 |
public: |
| 4341 |
StreamBufImpl() { |
| 4342 |
setp( data, data + sizeof(data) ); |
| 4343 |
} |
| 4344 |
|
| 4345 |
~StreamBufImpl() noexcept override { |
| 4346 |
StreamBufImpl::sync(); |
| 4347 |
} |
| 4348 |
|
| 4349 |
private: |
| 4350 |
int overflow( int c ) override { |
| 4351 |
sync(); |
| 4352 |
|
| 4353 |
if( c != EOF ) { |
| 4354 |
if( pbase() == epptr() ) |
| 4355 |
m_writer( std::string( 1, static_cast<char>( c ) ) ); |
| 4356 |
else |
| 4357 |
sputc( static_cast<char>( c ) ); |
| 4358 |
} |
| 4359 |
return 0; |
| 4360 |
} |
| 4361 |
|
| 4362 |
int sync() override { |
| 4363 |
if( pbase() != pptr() ) { |
| 4364 |
m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) ); |
| 4365 |
setp( pbase(), epptr() ); |
| 4366 |
} |
| 4367 |
return 0; |
| 4368 |
} |
| 4369 |
}; |
| 4370 |
|
| 4371 |
/////////////////////////////////////////////////////////////////////////// |
| 4372 |
|
| 4373 |
struct OutputDebugWriter { |
| 4374 |
|
| 4375 |
void operator()( std::string const& str ) { |
| 4376 |
if ( !str.empty() ) { |
| 4377 |
writeToDebugConsole( str ); |
| 4378 |
} |
| 4379 |
} |
| 4380 |
}; |
| 4381 |
|
| 4382 |
/////////////////////////////////////////////////////////////////////////// |
| 4383 |
|
| 4384 |
class FileStream final : public IStream { |
| 4385 |
std::ofstream m_ofs; |
| 4386 |
public: |
| 4387 |
FileStream( std::string const& filename ) { |
| 4388 |
m_ofs.open( filename.c_str() ); |
| 4389 |
CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << '\'' ); |
| 4390 |
m_ofs << std::unitbuf; |
| 4391 |
} |
| 4392 |
public: // IStream |
| 4393 |
std::ostream& stream() override { |
| 4394 |
return m_ofs; |
| 4395 |
} |
| 4396 |
}; |
| 4397 |
|
| 4398 |
/////////////////////////////////////////////////////////////////////////// |
| 4399 |
|
| 4400 |
class CoutStream final : public IStream { |
| 4401 |
std::ostream m_os; |
| 4402 |
public: |
| 4403 |
// Store the streambuf from cout up-front because |
| 4404 |
// cout may get redirected when running tests |
| 4405 |
CoutStream() : m_os( Catch::cout().rdbuf() ) {} |
| 4406 |
|
| 4407 |
public: // IStream |
| 4408 |
std::ostream& stream() override { return m_os; } |
| 4409 |
bool isConsole() const override { return true; } |
| 4410 |
}; |
| 4411 |
|
| 4412 |
class CerrStream : public IStream { |
| 4413 |
std::ostream m_os; |
| 4414 |
|
| 4415 |
public: |
| 4416 |
// Store the streambuf from cerr up-front because |
| 4417 |
// cout may get redirected when running tests |
| 4418 |
CerrStream(): m_os( Catch::cerr().rdbuf() ) {} |
| 4419 |
|
| 4420 |
public: // IStream |
| 4421 |
std::ostream& stream() override { return m_os; } |
| 4422 |
bool isConsole() const override { return true; } |
| 4423 |
}; |
| 4424 |
|
| 4425 |
/////////////////////////////////////////////////////////////////////////// |
| 4426 |
|
| 4427 |
class DebugOutStream final : public IStream { |
| 4428 |
Detail::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf; |
| 4429 |
std::ostream m_os; |
| 4430 |
public: |
| 4431 |
DebugOutStream() |
| 4432 |
: m_streamBuf( Detail::make_unique<StreamBufImpl<OutputDebugWriter>>() ), |
| 4433 |
m_os( m_streamBuf.get() ) |
| 4434 |
{} |
| 4435 |
|
| 4436 |
public: // IStream |
| 4437 |
std::ostream& stream() override { return m_os; } |
| 4438 |
}; |
| 4439 |
|
| 4440 |
} // unnamed namespace |
| 4441 |
} // namespace Detail |
| 4442 |
|
| 4443 |
/////////////////////////////////////////////////////////////////////////// |
| 4444 |
|
| 4445 |
auto makeStream( std::string const& filename ) -> Detail::unique_ptr<IStream> { |
| 4446 |
if ( filename.empty() || filename == "-" ) { |
| 4447 |
return Detail::make_unique<Detail::CoutStream>(); |
| 4448 |
} |
| 4449 |
if( filename[0] == '%' ) { |
| 4450 |
if ( filename == "%debug" ) { |
| 4451 |
return Detail::make_unique<Detail::DebugOutStream>(); |
| 4452 |
} else if ( filename == "%stderr" ) { |
| 4453 |
return Detail::make_unique<Detail::CerrStream>(); |
| 4454 |
} else if ( filename == "%stdout" ) { |
| 4455 |
return Detail::make_unique<Detail::CoutStream>(); |
| 4456 |
} else { |
| 4457 |
CATCH_ERROR( "Unrecognised stream: '" << filename << '\'' ); |
| 4458 |
} |
| 4459 |
} |
| 4460 |
return Detail::make_unique<Detail::FileStream>( filename ); |
| 4461 |
} |
| 4462 |
|
| 4463 |
} |
| 4464 |
|
| 4465 |
|
| 4466 |
|
| 4467 |
namespace Catch { |
| 4468 |
void JsonUtils::indent( std::ostream& os, std::uint64_t level ) { |
| 4469 |
for ( std::uint64_t i = 0; i < level; ++i ) { |
| 4470 |
os << " "; |
| 4471 |
} |
| 4472 |
} |
| 4473 |
void JsonUtils::appendCommaNewline( std::ostream& os, |
| 4474 |
bool& should_comma, |
| 4475 |
std::uint64_t level ) { |
| 4476 |
if ( should_comma ) { os << ','; } |
| 4477 |
should_comma = true; |
| 4478 |
os << '\n'; |
| 4479 |
indent( os, level ); |
| 4480 |
} |
| 4481 |
|
| 4482 |
JsonObjectWriter::JsonObjectWriter( std::ostream& os ): |
| 4483 |
JsonObjectWriter{ os, 0 } {} |
| 4484 |
|
| 4485 |
JsonObjectWriter::JsonObjectWriter( std::ostream& os, |
| 4486 |
std::uint64_t indent_level ): |
| 4487 |
m_os{ os }, m_indent_level{ indent_level } { |
| 4488 |
m_os << '{'; |
| 4489 |
} |
| 4490 |
JsonObjectWriter::JsonObjectWriter( JsonObjectWriter&& source ) noexcept: |
| 4491 |
m_os{ source.m_os }, |
| 4492 |
m_indent_level{ source.m_indent_level }, |
| 4493 |
m_should_comma{ source.m_should_comma }, |
| 4494 |
m_active{ source.m_active } { |
| 4495 |
source.m_active = false; |
| 4496 |
} |
| 4497 |
|
| 4498 |
JsonObjectWriter::~JsonObjectWriter() { |
| 4499 |
if ( !m_active ) { return; } |
| 4500 |
|
| 4501 |
m_os << '\n'; |
| 4502 |
JsonUtils::indent( m_os, m_indent_level ); |
| 4503 |
m_os << '}'; |
| 4504 |
} |
| 4505 |
|
| 4506 |
JsonValueWriter JsonObjectWriter::write( StringRef key ) { |
| 4507 |
JsonUtils::appendCommaNewline( |
| 4508 |
m_os, m_should_comma, m_indent_level + 1 ); |
| 4509 |
|
| 4510 |
m_os << '"' << key << "\": "; |
| 4511 |
return JsonValueWriter{ m_os, m_indent_level + 1 }; |
| 4512 |
} |
| 4513 |
|
| 4514 |
JsonArrayWriter::JsonArrayWriter( std::ostream& os ): |
| 4515 |
JsonArrayWriter{ os, 0 } {} |
| 4516 |
JsonArrayWriter::JsonArrayWriter( std::ostream& os, |
| 4517 |
std::uint64_t indent_level ): |
| 4518 |
m_os{ os }, m_indent_level{ indent_level } { |
| 4519 |
m_os << '['; |
| 4520 |
} |
| 4521 |
JsonArrayWriter::JsonArrayWriter( JsonArrayWriter&& source ) noexcept: |
| 4522 |
m_os{ source.m_os }, |
| 4523 |
m_indent_level{ source.m_indent_level }, |
| 4524 |
m_should_comma{ source.m_should_comma }, |
| 4525 |
m_active{ source.m_active } { |
| 4526 |
source.m_active = false; |
| 4527 |
} |
| 4528 |
JsonArrayWriter::~JsonArrayWriter() { |
| 4529 |
if ( !m_active ) { return; } |
| 4530 |
|
| 4531 |
m_os << '\n'; |
| 4532 |
JsonUtils::indent( m_os, m_indent_level ); |
| 4533 |
m_os << ']'; |
| 4534 |
} |
| 4535 |
|
| 4536 |
JsonObjectWriter JsonArrayWriter::writeObject() { |
| 4537 |
JsonUtils::appendCommaNewline( |
| 4538 |
m_os, m_should_comma, m_indent_level + 1 ); |
| 4539 |
return JsonObjectWriter{ m_os, m_indent_level + 1 }; |
| 4540 |
} |
| 4541 |
|
| 4542 |
JsonArrayWriter JsonArrayWriter::writeArray() { |
| 4543 |
JsonUtils::appendCommaNewline( |
| 4544 |
m_os, m_should_comma, m_indent_level + 1 ); |
| 4545 |
return JsonArrayWriter{ m_os, m_indent_level + 1 }; |
| 4546 |
} |
| 4547 |
|
| 4548 |
JsonArrayWriter& JsonArrayWriter::write( bool value ) { |
| 4549 |
return writeImpl( value ); |
| 4550 |
} |
| 4551 |
|
| 4552 |
JsonValueWriter::JsonValueWriter( std::ostream& os ): |
| 4553 |
JsonValueWriter{ os, 0 } {} |
| 4554 |
|
| 4555 |
JsonValueWriter::JsonValueWriter( std::ostream& os, |
| 4556 |
std::uint64_t indent_level ): |
| 4557 |
m_os{ os }, m_indent_level{ indent_level } {} |
| 4558 |
|
| 4559 |
JsonObjectWriter JsonValueWriter::writeObject() && { |
| 4560 |
return JsonObjectWriter{ m_os, m_indent_level }; |
| 4561 |
} |
| 4562 |
|
| 4563 |
JsonArrayWriter JsonValueWriter::writeArray() && { |
| 4564 |
return JsonArrayWriter{ m_os, m_indent_level }; |
| 4565 |
} |
| 4566 |
|
| 4567 |
void JsonValueWriter::write( Catch::StringRef value ) && { |
| 4568 |
writeImpl( value, true ); |
| 4569 |
} |
| 4570 |
|
| 4571 |
void JsonValueWriter::write( bool value ) && { |
| 4572 |
writeImpl( value ? "true"_sr : "false"_sr, false ); |
| 4573 |
} |
| 4574 |
|
| 4575 |
void JsonValueWriter::writeImpl( Catch::StringRef value, bool quote ) { |
| 4576 |
if ( quote ) { m_os << '"'; } |
| 4577 |
for (char c : value) { |
| 4578 |
// Escape list taken from https://www.json.org/json-en.html, |
| 4579 |
// string definition. |
| 4580 |
// Note that while forward slash _can_ be escaped, it does |
| 4581 |
// not have to be, if JSON is not further embedded somewhere |
| 4582 |
// where forward slash is meaningful. |
| 4583 |
if ( c == '"' ) { |
| 4584 |
m_os << "\\\""; |
| 4585 |
} else if ( c == '\\' ) { |
| 4586 |
m_os << "\\\\"; |
| 4587 |
} else if ( c == '\b' ) { |
| 4588 |
m_os << "\\b"; |
| 4589 |
} else if ( c == '\f' ) { |
| 4590 |
m_os << "\\f"; |
| 4591 |
} else if ( c == '\n' ) { |
| 4592 |
m_os << "\\n"; |
| 4593 |
} else if ( c == '\r' ) { |
| 4594 |
m_os << "\\r"; |
| 4595 |
} else if ( c == '\t' ) { |
| 4596 |
m_os << "\\t"; |
| 4597 |
} else { |
| 4598 |
m_os << c; |
| 4599 |
} |
| 4600 |
} |
| 4601 |
if ( quote ) { m_os << '"'; } |
| 4602 |
} |
| 4603 |
|
| 4604 |
} // namespace Catch |
| 4605 |
|
| 4606 |
|
| 4607 |
|
| 4608 |
|
| 4609 |
namespace Catch { |
| 4610 |
|
| 4611 |
auto operator << (std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream& { |
| 4612 |
if (lazyExpr.m_isNegated) |
| 4613 |
os << '!'; |
| 4614 |
|
| 4615 |
if (lazyExpr) { |
| 4616 |
if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression()) |
| 4617 |
os << '(' << *lazyExpr.m_transientExpression << ')'; |
| 4618 |
else |
| 4619 |
os << *lazyExpr.m_transientExpression; |
| 4620 |
} else { |
| 4621 |
os << "{** error - unchecked empty expression requested **}"; |
| 4622 |
} |
| 4623 |
return os; |
| 4624 |
} |
| 4625 |
|
| 4626 |
} // namespace Catch |
| 4627 |
|
| 4628 |
|
| 4629 |
|
| 4630 |
|
| 4631 |
#ifdef CATCH_CONFIG_WINDOWS_CRTDBG |
| 4632 |
#include <crtdbg.h> |
| 4633 |
|
| 4634 |
namespace Catch { |
| 4635 |
|
| 4636 |
LeakDetector::LeakDetector() { |
| 4637 |
int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); |
| 4638 |
flag |= _CRTDBG_LEAK_CHECK_DF; |
| 4639 |
flag |= _CRTDBG_ALLOC_MEM_DF; |
| 4640 |
_CrtSetDbgFlag(flag); |
| 4641 |
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); |
| 4642 |
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); |
| 4643 |
// Change this to leaking allocation's number to break there |
| 4644 |
_CrtSetBreakAlloc(-1); |
| 4645 |
} |
| 4646 |
} |
| 4647 |
|
| 4648 |
#else // ^^ Windows crt debug heap enabled // Windows crt debug heap disabled vv |
| 4649 |
|
| 4650 |
Catch::LeakDetector::LeakDetector() = default; |
| 4651 |
|
| 4652 |
#endif // CATCH_CONFIG_WINDOWS_CRTDBG |
| 4653 |
|
| 4654 |
Catch::LeakDetector::~LeakDetector() { |
| 4655 |
Catch::cleanUp(); |
| 4656 |
} |
| 4657 |
|
| 4658 |
|
| 4659 |
|
| 4660 |
|
| 4661 |
namespace Catch { |
| 4662 |
namespace { |
| 4663 |
|
| 4664 |
void listTests(IEventListener& reporter, IConfig const& config) { |
| 4665 |
auto const& testSpec = config.testSpec(); |
| 4666 |
auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config); |
| 4667 |
reporter.listTests(matchedTestCases); |
| 4668 |
} |
| 4669 |
|
| 4670 |
void listTags(IEventListener& reporter, IConfig const& config) { |
| 4671 |
auto const& testSpec = config.testSpec(); |
| 4672 |
std::vector<TestCaseHandle> matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config); |
| 4673 |
|
| 4674 |
std::map<StringRef, TagInfo, Detail::CaseInsensitiveLess> tagCounts; |
| 4675 |
for (auto const& testCase : matchedTestCases) { |
| 4676 |
for (auto const& tagName : testCase.getTestCaseInfo().tags) { |
| 4677 |
auto it = tagCounts.find(tagName.original); |
| 4678 |
if (it == tagCounts.end()) |
| 4679 |
it = tagCounts.insert(std::make_pair(tagName.original, TagInfo())).first; |
| 4680 |
it->second.add(tagName.original); |
| 4681 |
} |
| 4682 |
} |
| 4683 |
|
| 4684 |
std::vector<TagInfo> infos; infos.reserve(tagCounts.size()); |
| 4685 |
for (auto& tagc : tagCounts) { |
| 4686 |
infos.push_back(CATCH_MOVE(tagc.second)); |
| 4687 |
} |
| 4688 |
|
| 4689 |
reporter.listTags(infos); |
| 4690 |
} |
| 4691 |
|
| 4692 |
void listReporters(IEventListener& reporter) { |
| 4693 |
std::vector<ReporterDescription> descriptions; |
| 4694 |
|
| 4695 |
auto const& factories = getRegistryHub().getReporterRegistry().getFactories(); |
| 4696 |
descriptions.reserve(factories.size()); |
| 4697 |
for (auto const& fac : factories) { |
| 4698 |
descriptions.push_back({ fac.first, fac.second->getDescription() }); |
| 4699 |
} |
| 4700 |
|
| 4701 |
reporter.listReporters(descriptions); |
| 4702 |
} |
| 4703 |
|
| 4704 |
void listListeners(IEventListener& reporter) { |
| 4705 |
std::vector<ListenerDescription> descriptions; |
| 4706 |
|
| 4707 |
auto const& factories = |
| 4708 |
getRegistryHub().getReporterRegistry().getListeners(); |
| 4709 |
descriptions.reserve( factories.size() ); |
| 4710 |
for ( auto const& fac : factories ) { |
| 4711 |
descriptions.push_back( { fac->getName(), fac->getDescription() } ); |
| 4712 |
} |
| 4713 |
|
| 4714 |
reporter.listListeners( descriptions ); |
| 4715 |
} |
| 4716 |
|
| 4717 |
} // end anonymous namespace |
| 4718 |
|
| 4719 |
void TagInfo::add( StringRef spelling ) { |
| 4720 |
++count; |
| 4721 |
spellings.insert( spelling ); |
| 4722 |
} |
| 4723 |
|
| 4724 |
std::string TagInfo::all() const { |
| 4725 |
// 2 per tag for brackets '[' and ']' |
| 4726 |
size_t size = spellings.size() * 2; |
| 4727 |
for (auto const& spelling : spellings) { |
| 4728 |
size += spelling.size(); |
| 4729 |
} |
| 4730 |
|
| 4731 |
std::string out; out.reserve(size); |
| 4732 |
for (auto const& spelling : spellings) { |
| 4733 |
out += '['; |
| 4734 |
out += spelling; |
| 4735 |
out += ']'; |
| 4736 |
} |
| 4737 |
return out; |
| 4738 |
} |
| 4739 |
|
| 4740 |
bool list( IEventListener& reporter, Config const& config ) { |
| 4741 |
bool listed = false; |
| 4742 |
if (config.listTests()) { |
| 4743 |
listed = true; |
| 4744 |
listTests(reporter, config); |
| 4745 |
} |
| 4746 |
if (config.listTags()) { |
| 4747 |
listed = true; |
| 4748 |
listTags(reporter, config); |
| 4749 |
} |
| 4750 |
if (config.listReporters()) { |
| 4751 |
listed = true; |
| 4752 |
listReporters(reporter); |
| 4753 |
} |
| 4754 |
if ( config.listListeners() ) { |
| 4755 |
listed = true; |
| 4756 |
listListeners( reporter ); |
| 4757 |
} |
| 4758 |
return listed; |
| 4759 |
} |
| 4760 |
|
| 4761 |
} // end namespace Catch |
| 4762 |
|
| 4763 |
|
| 4764 |
|
| 4765 |
namespace Catch { |
| 4766 |
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION |
| 4767 |
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS |
| 4768 |
static LeakDetector leakDetector; |
| 4769 |
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION |
| 4770 |
} |
| 4771 |
|
| 4772 |
// Allow users of amalgamated .cpp file to remove our main and provide their own. |
| 4773 |
#if !defined(CATCH_AMALGAMATED_CUSTOM_MAIN) |
| 4774 |
|
| 4775 |
#if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) |
| 4776 |
// Standard C/C++ Win32 Unicode wmain entry point |
| 4777 |
extern "C" int __cdecl wmain (int argc, wchar_t * argv[], wchar_t * []) { |
| 4778 |
#else |
| 4779 |
// Standard C/C++ main entry point |
| 4780 |
int main (int argc, char * argv[]) { |
| 4781 |
#endif |
| 4782 |
|
| 4783 |
// We want to force the linker not to discard the global variable |
| 4784 |
// and its constructor, as it (optionally) registers leak detector |
| 4785 |
(void)&Catch::leakDetector; |
| 4786 |
|
| 4787 |
return Catch::Session().run( argc, argv ); |
| 4788 |
} |
| 4789 |
|
| 4790 |
#endif // !defined(CATCH_AMALGAMATED_CUSTOM_MAIN |
| 4791 |
|
| 4792 |
|
| 4793 |
|
| 4794 |
|
| 4795 |
namespace Catch { |
| 4796 |
|
| 4797 |
MessageInfo::MessageInfo( StringRef _macroName, |
| 4798 |
SourceLineInfo const& _lineInfo, |
| 4799 |
ResultWas::OfType _type ) |
| 4800 |
: macroName( _macroName ), |
| 4801 |
lineInfo( _lineInfo ), |
| 4802 |
type( _type ), |
| 4803 |
sequence( ++globalCount ) |
| 4804 |
{} |
| 4805 |
|
| 4806 |
// This may need protecting if threading support is added |
| 4807 |
unsigned int MessageInfo::globalCount = 0; |
| 4808 |
|
| 4809 |
} // end namespace Catch |
| 4810 |
|
| 4811 |
|
| 4812 |
|
| 4813 |
#include <cstdio> |
| 4814 |
#include <cstring> |
| 4815 |
#include <iosfwd> |
| 4816 |
#include <sstream> |
| 4817 |
|
| 4818 |
#if defined( CATCH_CONFIG_NEW_CAPTURE ) |
| 4819 |
# if defined( _MSC_VER ) |
| 4820 |
# include <io.h> //_dup and _dup2 |
| 4821 |
# define dup _dup |
| 4822 |
# define dup2 _dup2 |
| 4823 |
# define fileno _fileno |
| 4824 |
# else |
| 4825 |
# include <unistd.h> // dup and dup2 |
| 4826 |
# endif |
| 4827 |
#endif |
| 4828 |
|
| 4829 |
namespace Catch { |
| 4830 |
|
| 4831 |
namespace { |
| 4832 |
//! A no-op implementation, used if no reporter wants output |
| 4833 |
//! redirection. |
| 4834 |
class NoopRedirect : public OutputRedirect { |
| 4835 |
void activateImpl() override {} |
| 4836 |
void deactivateImpl() override {} |
| 4837 |
std::string getStdout() override { return {}; } |
| 4838 |
std::string getStderr() override { return {}; } |
| 4839 |
void clearBuffers() override {} |
| 4840 |
}; |
| 4841 |
|
| 4842 |
/** |
| 4843 |
* Redirects specific stream's rdbuf with another's. |
| 4844 |
* |
| 4845 |
* Redirection can be stopped and started on-demand, assumes |
| 4846 |
* that the underlying stream's rdbuf aren't changed by other |
| 4847 |
* users. |
| 4848 |
*/ |
| 4849 |
class RedirectedStreamNew { |
| 4850 |
std::ostream& m_originalStream; |
| 4851 |
std::ostream& m_redirectionStream; |
| 4852 |
std::streambuf* m_prevBuf; |
| 4853 |
|
| 4854 |
public: |
| 4855 |
RedirectedStreamNew( std::ostream& originalStream, |
| 4856 |
std::ostream& redirectionStream ): |
| 4857 |
m_originalStream( originalStream ), |
| 4858 |
m_redirectionStream( redirectionStream ), |
| 4859 |
m_prevBuf( m_originalStream.rdbuf() ) {} |
| 4860 |
|
| 4861 |
void startRedirect() { |
| 4862 |
m_originalStream.rdbuf( m_redirectionStream.rdbuf() ); |
| 4863 |
} |
| 4864 |
void stopRedirect() { m_originalStream.rdbuf( m_prevBuf ); } |
| 4865 |
}; |
| 4866 |
|
| 4867 |
/** |
| 4868 |
* Redirects the `std::cout`, `std::cerr`, `std::clog` streams, |
| 4869 |
* but does not touch the actual `stdout`/`stderr` file descriptors. |
| 4870 |
*/ |
| 4871 |
class StreamRedirect : public OutputRedirect { |
| 4872 |
ReusableStringStream m_redirectedOut, m_redirectedErr; |
| 4873 |
RedirectedStreamNew m_cout, m_cerr, m_clog; |
| 4874 |
|
| 4875 |
public: |
| 4876 |
StreamRedirect(): |
| 4877 |
m_cout( Catch::cout(), m_redirectedOut.get() ), |
| 4878 |
m_cerr( Catch::cerr(), m_redirectedErr.get() ), |
| 4879 |
m_clog( Catch::clog(), m_redirectedErr.get() ) {} |
| 4880 |
|
| 4881 |
void activateImpl() override { |
| 4882 |
m_cout.startRedirect(); |
| 4883 |
m_cerr.startRedirect(); |
| 4884 |
m_clog.startRedirect(); |
| 4885 |
} |
| 4886 |
void deactivateImpl() override { |
| 4887 |
m_cout.stopRedirect(); |
| 4888 |
m_cerr.stopRedirect(); |
| 4889 |
m_clog.stopRedirect(); |
| 4890 |
} |
| 4891 |
std::string getStdout() override { return m_redirectedOut.str(); } |
| 4892 |
std::string getStderr() override { return m_redirectedErr.str(); } |
| 4893 |
void clearBuffers() override { |
| 4894 |
m_redirectedOut.str( "" ); |
| 4895 |
m_redirectedErr.str( "" ); |
| 4896 |
} |
| 4897 |
}; |
| 4898 |
|
| 4899 |
#if defined( CATCH_CONFIG_NEW_CAPTURE ) |
| 4900 |
|
| 4901 |
// Windows's implementation of std::tmpfile is terrible (it tries |
| 4902 |
// to create a file inside system folder, thus requiring elevated |
| 4903 |
// privileges for the binary), so we have to use tmpnam(_s) and |
| 4904 |
// create the file ourselves there. |
| 4905 |
class TempFile { |
| 4906 |
public: |
| 4907 |
TempFile( TempFile const& ) = delete; |
| 4908 |
TempFile& operator=( TempFile const& ) = delete; |
| 4909 |
TempFile( TempFile&& ) = delete; |
| 4910 |
TempFile& operator=( TempFile&& ) = delete; |
| 4911 |
|
| 4912 |
# if defined( _MSC_VER ) |
| 4913 |
TempFile() { |
| 4914 |
if ( tmpnam_s( m_buffer ) ) { |
| 4915 |
CATCH_RUNTIME_ERROR( "Could not get a temp filename" ); |
| 4916 |
} |
| 4917 |
if ( fopen_s( &m_file, m_buffer, "wb+" ) ) { |
| 4918 |
char buffer[100]; |
| 4919 |
if ( strerror_s( buffer, errno ) ) { |
| 4920 |
CATCH_RUNTIME_ERROR( |
| 4921 |
"Could not translate errno to a string" ); |
| 4922 |
} |
| 4923 |
CATCH_RUNTIME_ERROR( "Could not open the temp file: '" |
| 4924 |
<< m_buffer |
| 4925 |
<< "' because: " << buffer ); |
| 4926 |
} |
| 4927 |
} |
| 4928 |
# else |
| 4929 |
TempFile() { |
| 4930 |
m_file = std::tmpfile(); |
| 4931 |
if ( !m_file ) { |
| 4932 |
CATCH_RUNTIME_ERROR( "Could not create a temp file." ); |
| 4933 |
} |
| 4934 |
} |
| 4935 |
# endif |
| 4936 |
|
| 4937 |
~TempFile() { |
| 4938 |
// TBD: What to do about errors here? |
| 4939 |
std::fclose( m_file ); |
| 4940 |
// We manually create the file on Windows only, on Linux |
| 4941 |
// it will be autodeleted |
| 4942 |
# if defined( _MSC_VER ) |
| 4943 |
std::remove( m_buffer ); |
| 4944 |
# endif |
| 4945 |
} |
| 4946 |
|
| 4947 |
std::FILE* getFile() { return m_file; } |
| 4948 |
std::string getContents() { |
| 4949 |
ReusableStringStream sstr; |
| 4950 |
constexpr long buffer_size = 100; |
| 4951 |
char buffer[buffer_size + 1] = {}; |
| 4952 |
long current_pos = ftell( m_file ); |
| 4953 |
CATCH_ENFORCE( current_pos >= 0, |
| 4954 |
"ftell failed, errno: " << errno ); |
| 4955 |
std::rewind( m_file ); |
| 4956 |
while ( current_pos > 0 ) { |
| 4957 |
auto read_characters = |
| 4958 |
std::fread( buffer, |
| 4959 |
1, |
| 4960 |
std::min( buffer_size, current_pos ), |
| 4961 |
m_file ); |
| 4962 |
buffer[read_characters] = '\0'; |
| 4963 |
sstr << buffer; |
| 4964 |
current_pos -= static_cast<long>( read_characters ); |
| 4965 |
} |
| 4966 |
return sstr.str(); |
| 4967 |
} |
| 4968 |
|
| 4969 |
void clear() { std::rewind( m_file ); } |
| 4970 |
|
| 4971 |
private: |
| 4972 |
std::FILE* m_file = nullptr; |
| 4973 |
char m_buffer[L_tmpnam] = { 0 }; |
| 4974 |
}; |
| 4975 |
|
| 4976 |
/** |
| 4977 |
* Redirects the actual `stdout`/`stderr` file descriptors. |
| 4978 |
* |
| 4979 |
* Works by replacing the file descriptors numbered 1 and 2 |
| 4980 |
* with an open temporary file. |
| 4981 |
*/ |
| 4982 |
class FileRedirect : public OutputRedirect { |
| 4983 |
TempFile m_outFile, m_errFile; |
| 4984 |
int m_originalOut = -1; |
| 4985 |
int m_originalErr = -1; |
| 4986 |
|
| 4987 |
// Flushes cout/cerr/clog streams and stdout/stderr FDs |
| 4988 |
void flushEverything() { |
| 4989 |
Catch::cout() << std::flush; |
| 4990 |
fflush( stdout ); |
| 4991 |
// Since we support overriding these streams, we flush cerr |
| 4992 |
// even though std::cerr is unbuffered |
| 4993 |
Catch::cerr() << std::flush; |
| 4994 |
Catch::clog() << std::flush; |
| 4995 |
fflush( stderr ); |
| 4996 |
} |
| 4997 |
|
| 4998 |
public: |
| 4999 |
FileRedirect(): |
| 5000 |
m_originalOut( dup( fileno( stdout ) ) ), |
| 5001 |
m_originalErr( dup( fileno( stderr ) ) ) { |
| 5002 |
CATCH_ENFORCE( m_originalOut >= 0, "Could not dup stdout" ); |
| 5003 |
CATCH_ENFORCE( m_originalErr >= 0, "Could not dup stderr" ); |
| 5004 |
} |
| 5005 |
|
| 5006 |
std::string getStdout() override { return m_outFile.getContents(); } |
| 5007 |
std::string getStderr() override { return m_errFile.getContents(); } |
| 5008 |
void clearBuffers() override { |
| 5009 |
m_outFile.clear(); |
| 5010 |
m_errFile.clear(); |
| 5011 |
} |
| 5012 |
|
| 5013 |
void activateImpl() override { |
| 5014 |
// We flush before starting redirect, to ensure that we do |
| 5015 |
// not capture the end of message sent before activation. |
| 5016 |
flushEverything(); |
| 5017 |
|
| 5018 |
int ret; |
| 5019 |
ret = dup2( fileno( m_outFile.getFile() ), fileno( stdout ) ); |
| 5020 |
CATCH_ENFORCE( ret >= 0, |
| 5021 |
"dup2 to stdout has failed, errno: " << errno ); |
| 5022 |
ret = dup2( fileno( m_errFile.getFile() ), fileno( stderr ) ); |
| 5023 |
CATCH_ENFORCE( ret >= 0, |
| 5024 |
"dup2 to stderr has failed, errno: " << errno ); |
| 5025 |
} |
| 5026 |
void deactivateImpl() override { |
| 5027 |
// We flush before ending redirect, to ensure that we |
| 5028 |
// capture all messages sent while the redirect was active. |
| 5029 |
flushEverything(); |
| 5030 |
|
| 5031 |
int ret; |
| 5032 |
ret = dup2( m_originalOut, fileno( stdout ) ); |
| 5033 |
CATCH_ENFORCE( |
| 5034 |
ret >= 0, |
| 5035 |
"dup2 of original stdout has failed, errno: " << errno ); |
| 5036 |
ret = dup2( m_originalErr, fileno( stderr ) ); |
| 5037 |
CATCH_ENFORCE( |
| 5038 |
ret >= 0, |
| 5039 |
"dup2 of original stderr has failed, errno: " << errno ); |
| 5040 |
} |
| 5041 |
}; |
| 5042 |
|
| 5043 |
#endif // CATCH_CONFIG_NEW_CAPTURE |
| 5044 |
|
| 5045 |
} // end namespace |
| 5046 |
|
| 5047 |
bool isRedirectAvailable( OutputRedirect::Kind kind ) { |
| 5048 |
switch ( kind ) { |
| 5049 |
// These two are always available |
| 5050 |
case OutputRedirect::None: |
| 5051 |
case OutputRedirect::Streams: |
| 5052 |
return true; |
| 5053 |
#if defined( CATCH_CONFIG_NEW_CAPTURE ) |
| 5054 |
case OutputRedirect::FileDescriptors: |
| 5055 |
return true; |
| 5056 |
#endif |
| 5057 |
default: |
| 5058 |
return false; |
| 5059 |
} |
| 5060 |
} |
| 5061 |
|
| 5062 |
Detail::unique_ptr<OutputRedirect> makeOutputRedirect( bool actual ) { |
| 5063 |
if ( actual ) { |
| 5064 |
// TODO: Clean this up later |
| 5065 |
#if defined( CATCH_CONFIG_NEW_CAPTURE ) |
| 5066 |
return Detail::make_unique<FileRedirect>(); |
| 5067 |
#else |
| 5068 |
return Detail::make_unique<StreamRedirect>(); |
| 5069 |
#endif |
| 5070 |
} else { |
| 5071 |
return Detail::make_unique<NoopRedirect>(); |
| 5072 |
} |
| 5073 |
} |
| 5074 |
|
| 5075 |
RedirectGuard scopedActivate( OutputRedirect& redirectImpl ) { |
| 5076 |
return RedirectGuard( true, redirectImpl ); |
| 5077 |
} |
| 5078 |
|
| 5079 |
RedirectGuard scopedDeactivate( OutputRedirect& redirectImpl ) { |
| 5080 |
return RedirectGuard( false, redirectImpl ); |
| 5081 |
} |
| 5082 |
|
| 5083 |
OutputRedirect::~OutputRedirect() = default; |
| 5084 |
|
| 5085 |
RedirectGuard::RedirectGuard( bool activate, OutputRedirect& redirectImpl ): |
| 5086 |
m_redirect( &redirectImpl ), |
| 5087 |
m_activate( activate ), |
| 5088 |
m_previouslyActive( redirectImpl.isActive() ) { |
| 5089 |
|
| 5090 |
// Skip cases where there is no actual state change. |
| 5091 |
if ( m_activate == m_previouslyActive ) { return; } |
| 5092 |
|
| 5093 |
if ( m_activate ) { |
| 5094 |
m_redirect->activate(); |
| 5095 |
} else { |
| 5096 |
m_redirect->deactivate(); |
| 5097 |
} |
| 5098 |
} |
| 5099 |
|
| 5100 |
RedirectGuard::~RedirectGuard() noexcept( false ) { |
| 5101 |
if ( m_moved ) { return; } |
| 5102 |
// Skip cases where there is no actual state change. |
| 5103 |
if ( m_activate == m_previouslyActive ) { return; } |
| 5104 |
|
| 5105 |
if ( m_activate ) { |
| 5106 |
m_redirect->deactivate(); |
| 5107 |
} else { |
| 5108 |
m_redirect->activate(); |
| 5109 |
} |
| 5110 |
} |
| 5111 |
|
| 5112 |
RedirectGuard::RedirectGuard( RedirectGuard&& rhs ) noexcept: |
| 5113 |
m_redirect( rhs.m_redirect ), |
| 5114 |
m_activate( rhs.m_activate ), |
| 5115 |
m_previouslyActive( rhs.m_previouslyActive ), |
| 5116 |
m_moved( false ) { |
| 5117 |
rhs.m_moved = true; |
| 5118 |
} |
| 5119 |
|
| 5120 |
RedirectGuard& RedirectGuard::operator=( RedirectGuard&& rhs ) noexcept { |
| 5121 |
m_redirect = rhs.m_redirect; |
| 5122 |
m_activate = rhs.m_activate; |
| 5123 |
m_previouslyActive = rhs.m_previouslyActive; |
| 5124 |
m_moved = false; |
| 5125 |
rhs.m_moved = true; |
| 5126 |
return *this; |
| 5127 |
} |
| 5128 |
|
| 5129 |
} // namespace Catch |
| 5130 |
|
| 5131 |
#if defined( CATCH_CONFIG_NEW_CAPTURE ) |
| 5132 |
# if defined( _MSC_VER ) |
| 5133 |
# undef dup |
| 5134 |
# undef dup2 |
| 5135 |
# undef fileno |
| 5136 |
# endif |
| 5137 |
#endif |
| 5138 |
|
| 5139 |
|
| 5140 |
|
| 5141 |
|
| 5142 |
#include <limits> |
| 5143 |
#include <stdexcept> |
| 5144 |
|
| 5145 |
namespace Catch { |
| 5146 |
|
| 5147 |
Optional<unsigned int> parseUInt(std::string const& input, int base) { |
| 5148 |
auto trimmed = trim( input ); |
| 5149 |
// std::stoull is annoying and accepts numbers starting with '-', |
| 5150 |
// it just negates them into unsigned int |
| 5151 |
if ( trimmed.empty() || trimmed[0] == '-' ) { |
| 5152 |
return {}; |
| 5153 |
} |
| 5154 |
|
| 5155 |
CATCH_TRY { |
| 5156 |
size_t pos = 0; |
| 5157 |
const auto ret = std::stoull( trimmed, &pos, base ); |
| 5158 |
|
| 5159 |
// We did not consume the whole input, so there is an issue |
| 5160 |
// This can be bunch of different stuff, like multiple numbers |
| 5161 |
// in the input, or invalid digits/characters and so on. Either |
| 5162 |
// way, we do not want to return the partially parsed result. |
| 5163 |
if ( pos != trimmed.size() ) { |
| 5164 |
return {}; |
| 5165 |
} |
| 5166 |
// Too large |
| 5167 |
if ( ret > std::numeric_limits<unsigned int>::max() ) { |
| 5168 |
return {}; |
| 5169 |
} |
| 5170 |
return static_cast<unsigned int>(ret); |
| 5171 |
} |
| 5172 |
CATCH_CATCH_ANON( std::invalid_argument const& ) { |
| 5173 |
// no conversion could be performed |
| 5174 |
} |
| 5175 |
CATCH_CATCH_ANON( std::out_of_range const& ) { |
| 5176 |
// the input does not fit into an unsigned long long |
| 5177 |
} |
| 5178 |
return {}; |
| 5179 |
} |
| 5180 |
|
| 5181 |
} // namespace Catch |
| 5182 |
|
| 5183 |
|
| 5184 |
|
| 5185 |
|
| 5186 |
#include <cmath> |
| 5187 |
|
| 5188 |
namespace Catch { |
| 5189 |
|
| 5190 |
#if !defined(CATCH_CONFIG_POLYFILL_ISNAN) |
| 5191 |
bool isnan(float f) { |
| 5192 |
return std::isnan(f); |
| 5193 |
} |
| 5194 |
bool isnan(double d) { |
| 5195 |
return std::isnan(d); |
| 5196 |
} |
| 5197 |
#else |
| 5198 |
// For now we only use this for embarcadero |
| 5199 |
bool isnan(float f) { |
| 5200 |
return std::_isnan(f); |
| 5201 |
} |
| 5202 |
bool isnan(double d) { |
| 5203 |
return std::_isnan(d); |
| 5204 |
} |
| 5205 |
#endif |
| 5206 |
|
| 5207 |
#if !defined( CATCH_CONFIG_GLOBAL_NEXTAFTER ) |
| 5208 |
float nextafter( float x, float y ) { return std::nextafter( x, y ); } |
| 5209 |
double nextafter( double x, double y ) { return std::nextafter( x, y ); } |
| 5210 |
#else |
| 5211 |
float nextafter( float x, float y ) { return ::nextafterf( x, y ); } |
| 5212 |
double nextafter( double x, double y ) { return ::nextafter( x, y ); } |
| 5213 |
#endif |
| 5214 |
|
| 5215 |
} // end namespace Catch |
| 5216 |
|
| 5217 |
|
| 5218 |
|
| 5219 |
namespace Catch { |
| 5220 |
|
| 5221 |
namespace { |
| 5222 |
|
| 5223 |
#if defined(_MSC_VER) |
| 5224 |
#pragma warning(push) |
| 5225 |
#pragma warning(disable:4146) // we negate uint32 during the rotate |
| 5226 |
#endif |
| 5227 |
// Safe rotr implementation thanks to John Regehr |
| 5228 |
uint32_t rotate_right(uint32_t val, uint32_t count) { |
| 5229 |
const uint32_t mask = 31; |
| 5230 |
count &= mask; |
| 5231 |
return (val >> count) | (val << (-count & mask)); |
| 5232 |
} |
| 5233 |
|
| 5234 |
#if defined(_MSC_VER) |
| 5235 |
#pragma warning(pop) |
| 5236 |
#endif |
| 5237 |
|
| 5238 |
} |
| 5239 |
|
| 5240 |
|
| 5241 |
SimplePcg32::SimplePcg32(result_type seed_) { |
| 5242 |
seed(seed_); |
| 5243 |
} |
| 5244 |
|
| 5245 |
|
| 5246 |
void SimplePcg32::seed(result_type seed_) { |
| 5247 |
m_state = 0; |
| 5248 |
(*this)(); |
| 5249 |
m_state += seed_; |
| 5250 |
(*this)(); |
| 5251 |
} |
| 5252 |
|
| 5253 |
void SimplePcg32::discard(uint64_t skip) { |
| 5254 |
// We could implement this to run in O(log n) steps, but this |
| 5255 |
// should suffice for our use case. |
| 5256 |
for (uint64_t s = 0; s < skip; ++s) { |
| 5257 |
static_cast<void>((*this)()); |
| 5258 |
} |
| 5259 |
} |
| 5260 |
|
| 5261 |
SimplePcg32::result_type SimplePcg32::operator()() { |
| 5262 |
// prepare the output value |
| 5263 |
const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u); |
| 5264 |
const auto output = rotate_right(xorshifted, static_cast<uint32_t>(m_state >> 59u)); |
| 5265 |
|
| 5266 |
// advance state |
| 5267 |
m_state = m_state * 6364136223846793005ULL + s_inc; |
| 5268 |
|
| 5269 |
return output; |
| 5270 |
} |
| 5271 |
|
| 5272 |
bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) { |
| 5273 |
return lhs.m_state == rhs.m_state; |
| 5274 |
} |
| 5275 |
|
| 5276 |
bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) { |
| 5277 |
return lhs.m_state != rhs.m_state; |
| 5278 |
} |
| 5279 |
} |
| 5280 |
|
| 5281 |
|
| 5282 |
|
| 5283 |
|
| 5284 |
|
| 5285 |
#include <ctime> |
| 5286 |
#include <random> |
| 5287 |
|
| 5288 |
namespace Catch { |
| 5289 |
|
| 5290 |
std::uint32_t generateRandomSeed( GenerateFrom from ) { |
| 5291 |
switch ( from ) { |
| 5292 |
case GenerateFrom::Time: |
| 5293 |
return static_cast<std::uint32_t>( std::time( nullptr ) ); |
| 5294 |
|
| 5295 |
case GenerateFrom::Default: |
| 5296 |
case GenerateFrom::RandomDevice: { |
| 5297 |
std::random_device rd; |
| 5298 |
return Detail::fillBitsFrom<std::uint32_t>( rd ); |
| 5299 |
} |
| 5300 |
|
| 5301 |
default: |
| 5302 |
CATCH_ERROR("Unknown generation method"); |
| 5303 |
} |
| 5304 |
} |
| 5305 |
|
| 5306 |
} // end namespace Catch |
| 5307 |
|
| 5308 |
|
| 5309 |
|
| 5310 |
|
| 5311 |
namespace Catch { |
| 5312 |
struct ReporterRegistry::ReporterRegistryImpl { |
| 5313 |
std::vector<Detail::unique_ptr<EventListenerFactory>> listeners; |
| 5314 |
std::map<std::string, IReporterFactoryPtr, Detail::CaseInsensitiveLess> |
| 5315 |
factories; |
| 5316 |
}; |
| 5317 |
|
| 5318 |
ReporterRegistry::ReporterRegistry(): |
| 5319 |
m_impl( Detail::make_unique<ReporterRegistryImpl>() ) { |
| 5320 |
// Because it is impossible to move out of initializer list, |
| 5321 |
// we have to add the elements manually |
| 5322 |
m_impl->factories["Automake"] = |
| 5323 |
Detail::make_unique<ReporterFactory<AutomakeReporter>>(); |
| 5324 |
m_impl->factories["compact"] = |
| 5325 |
Detail::make_unique<ReporterFactory<CompactReporter>>(); |
| 5326 |
m_impl->factories["console"] = |
| 5327 |
Detail::make_unique<ReporterFactory<ConsoleReporter>>(); |
| 5328 |
m_impl->factories["JUnit"] = |
| 5329 |
Detail::make_unique<ReporterFactory<JunitReporter>>(); |
| 5330 |
m_impl->factories["SonarQube"] = |
| 5331 |
Detail::make_unique<ReporterFactory<SonarQubeReporter>>(); |
| 5332 |
m_impl->factories["TAP"] = |
| 5333 |
Detail::make_unique<ReporterFactory<TAPReporter>>(); |
| 5334 |
m_impl->factories["TeamCity"] = |
| 5335 |
Detail::make_unique<ReporterFactory<TeamCityReporter>>(); |
| 5336 |
m_impl->factories["XML"] = |
| 5337 |
Detail::make_unique<ReporterFactory<XmlReporter>>(); |
| 5338 |
m_impl->factories["JSON"] = |
| 5339 |
Detail::make_unique<ReporterFactory<JsonReporter>>(); |
| 5340 |
} |
| 5341 |
|
| 5342 |
ReporterRegistry::~ReporterRegistry() = default; |
| 5343 |
|
| 5344 |
IEventListenerPtr |
| 5345 |
ReporterRegistry::create( std::string const& name, |
| 5346 |
ReporterConfig&& config ) const { |
| 5347 |
auto it = m_impl->factories.find( name ); |
| 5348 |
if ( it == m_impl->factories.end() ) return nullptr; |
| 5349 |
return it->second->create( CATCH_MOVE( config ) ); |
| 5350 |
} |
| 5351 |
|
| 5352 |
void ReporterRegistry::registerReporter( std::string const& name, |
| 5353 |
IReporterFactoryPtr factory ) { |
| 5354 |
CATCH_ENFORCE( name.find( "::" ) == name.npos, |
| 5355 |
"'::' is not allowed in reporter name: '" + name + |
| 5356 |
'\'' ); |
| 5357 |
auto ret = m_impl->factories.emplace( name, CATCH_MOVE( factory ) ); |
| 5358 |
CATCH_ENFORCE( ret.second, |
| 5359 |
"reporter using '" + name + |
| 5360 |
"' as name was already registered" ); |
| 5361 |
} |
| 5362 |
void ReporterRegistry::registerListener( |
| 5363 |
Detail::unique_ptr<EventListenerFactory> factory ) { |
| 5364 |
m_impl->listeners.push_back( CATCH_MOVE( factory ) ); |
| 5365 |
} |
| 5366 |
|
| 5367 |
std::map<std::string, |
| 5368 |
IReporterFactoryPtr, |
| 5369 |
Detail::CaseInsensitiveLess> const& |
| 5370 |
ReporterRegistry::getFactories() const { |
| 5371 |
return m_impl->factories; |
| 5372 |
} |
| 5373 |
|
| 5374 |
std::vector<Detail::unique_ptr<EventListenerFactory>> const& |
| 5375 |
ReporterRegistry::getListeners() const { |
| 5376 |
return m_impl->listeners; |
| 5377 |
} |
| 5378 |
} // namespace Catch |
| 5379 |
|
| 5380 |
|
| 5381 |
|
| 5382 |
|
| 5383 |
|
| 5384 |
#include <algorithm> |
| 5385 |
|
| 5386 |
namespace Catch { |
| 5387 |
|
| 5388 |
namespace { |
| 5389 |
struct kvPair { |
| 5390 |
StringRef key, value; |
| 5391 |
}; |
| 5392 |
|
| 5393 |
kvPair splitKVPair(StringRef kvString) { |
| 5394 |
auto splitPos = static_cast<size_t>( |
| 5395 |
std::find( kvString.begin(), kvString.end(), '=' ) - |
| 5396 |
kvString.begin() ); |
| 5397 |
|
| 5398 |
return { kvString.substr( 0, splitPos ), |
| 5399 |
kvString.substr( splitPos + 1, kvString.size() ) }; |
| 5400 |
} |
| 5401 |
} |
| 5402 |
|
| 5403 |
namespace Detail { |
| 5404 |
std::vector<std::string> splitReporterSpec( StringRef reporterSpec ) { |
| 5405 |
static constexpr auto separator = "::"; |
| 5406 |
static constexpr size_t separatorSize = 2; |
| 5407 |
|
| 5408 |
size_t separatorPos = 0; |
| 5409 |
auto findNextSeparator = [&reporterSpec]( size_t startPos ) { |
| 5410 |
static_assert( |
| 5411 |
separatorSize == 2, |
| 5412 |
"The code below currently assumes 2 char separator" ); |
| 5413 |
|
| 5414 |
auto currentPos = startPos; |
| 5415 |
do { |
| 5416 |
while ( currentPos < reporterSpec.size() && |
| 5417 |
reporterSpec[currentPos] != separator[0] ) { |
| 5418 |
++currentPos; |
| 5419 |
} |
| 5420 |
if ( currentPos + 1 < reporterSpec.size() && |
| 5421 |
reporterSpec[currentPos + 1] == separator[1] ) { |
| 5422 |
return currentPos; |
| 5423 |
} |
| 5424 |
++currentPos; |
| 5425 |
} while ( currentPos < reporterSpec.size() ); |
| 5426 |
|
| 5427 |
return static_cast<size_t>( -1 ); |
| 5428 |
}; |
| 5429 |
|
| 5430 |
std::vector<std::string> parts; |
| 5431 |
|
| 5432 |
while ( separatorPos < reporterSpec.size() ) { |
| 5433 |
const auto nextSeparator = findNextSeparator( separatorPos ); |
| 5434 |
parts.push_back( static_cast<std::string>( reporterSpec.substr( |
| 5435 |
separatorPos, nextSeparator - separatorPos ) ) ); |
| 5436 |
|
| 5437 |
if ( nextSeparator == static_cast<size_t>( -1 ) ) { |
| 5438 |
break; |
| 5439 |
} |
| 5440 |
separatorPos = nextSeparator + separatorSize; |
| 5441 |
} |
| 5442 |
|
| 5443 |
// Handle a separator at the end. |
| 5444 |
// This is not a valid spec, but we want to do validation in a |
| 5445 |
// centralized place |
| 5446 |
if ( separatorPos == reporterSpec.size() ) { |
| 5447 |
parts.emplace_back(); |
| 5448 |
} |
| 5449 |
|
| 5450 |
return parts; |
| 5451 |
} |
| 5452 |
|
| 5453 |
Optional<ColourMode> stringToColourMode( StringRef colourMode ) { |
| 5454 |
if ( colourMode == "default" ) { |
| 5455 |
return ColourMode::PlatformDefault; |
| 5456 |
} else if ( colourMode == "ansi" ) { |
| 5457 |
return ColourMode::ANSI; |
| 5458 |
} else if ( colourMode == "win32" ) { |
| 5459 |
return ColourMode::Win32; |
| 5460 |
} else if ( colourMode == "none" ) { |
| 5461 |
return ColourMode::None; |
| 5462 |
} else { |
| 5463 |
return {}; |
| 5464 |
} |
| 5465 |
} |
| 5466 |
} // namespace Detail |
| 5467 |
|
| 5468 |
|
| 5469 |
bool operator==( ReporterSpec const& lhs, ReporterSpec const& rhs ) { |
| 5470 |
return lhs.m_name == rhs.m_name && |
| 5471 |
lhs.m_outputFileName == rhs.m_outputFileName && |
| 5472 |
lhs.m_colourMode == rhs.m_colourMode && |
| 5473 |
lhs.m_customOptions == rhs.m_customOptions; |
| 5474 |
} |
| 5475 |
|
| 5476 |
Optional<ReporterSpec> parseReporterSpec( StringRef reporterSpec ) { |
| 5477 |
auto parts = Detail::splitReporterSpec( reporterSpec ); |
| 5478 |
|
| 5479 |
assert( parts.size() > 0 && "Split should never return empty vector" ); |
| 5480 |
|
| 5481 |
std::map<std::string, std::string> kvPairs; |
| 5482 |
Optional<std::string> outputFileName; |
| 5483 |
Optional<ColourMode> colourMode; |
| 5484 |
|
| 5485 |
// First part is always reporter name, so we skip it |
| 5486 |
for ( size_t i = 1; i < parts.size(); ++i ) { |
| 5487 |
auto kv = splitKVPair( parts[i] ); |
| 5488 |
auto key = kv.key, value = kv.value; |
| 5489 |
|
| 5490 |
if ( key.empty() || value.empty() ) { // NOLINT(bugprone-branch-clone) |
| 5491 |
return {}; |
| 5492 |
} else if ( key[0] == 'X' ) { |
| 5493 |
// This is a reporter-specific option, we don't check these |
| 5494 |
// apart from basic sanity checks |
| 5495 |
if ( key.size() == 1 ) { |
| 5496 |
return {}; |
| 5497 |
} |
| 5498 |
|
| 5499 |
auto ret = kvPairs.emplace( std::string(kv.key), std::string(kv.value) ); |
| 5500 |
if ( !ret.second ) { |
| 5501 |
// Duplicated key. We might want to handle this differently, |
| 5502 |
// e.g. by overwriting the existing value? |
| 5503 |
return {}; |
| 5504 |
} |
| 5505 |
} else if ( key == "out" ) { |
| 5506 |
// Duplicated key |
| 5507 |
if ( outputFileName ) { |
| 5508 |
return {}; |
| 5509 |
} |
| 5510 |
outputFileName = static_cast<std::string>( value ); |
| 5511 |
} else if ( key == "colour-mode" ) { |
| 5512 |
// Duplicated key |
| 5513 |
if ( colourMode ) { |
| 5514 |
return {}; |
| 5515 |
} |
| 5516 |
colourMode = Detail::stringToColourMode( value ); |
| 5517 |
// Parsing failed |
| 5518 |
if ( !colourMode ) { |
| 5519 |
return {}; |
| 5520 |
} |
| 5521 |
} else { |
| 5522 |
// Unrecognized option |
| 5523 |
return {}; |
| 5524 |
} |
| 5525 |
} |
| 5526 |
|
| 5527 |
return ReporterSpec{ CATCH_MOVE( parts[0] ), |
| 5528 |
CATCH_MOVE( outputFileName ), |
| 5529 |
CATCH_MOVE( colourMode ), |
| 5530 |
CATCH_MOVE( kvPairs ) }; |
| 5531 |
} |
| 5532 |
|
| 5533 |
ReporterSpec::ReporterSpec( |
| 5534 |
std::string name, |
| 5535 |
Optional<std::string> outputFileName, |
| 5536 |
Optional<ColourMode> colourMode, |
| 5537 |
std::map<std::string, std::string> customOptions ): |
| 5538 |
m_name( CATCH_MOVE( name ) ), |
| 5539 |
m_outputFileName( CATCH_MOVE( outputFileName ) ), |
| 5540 |
m_colourMode( CATCH_MOVE( colourMode ) ), |
| 5541 |
m_customOptions( CATCH_MOVE( customOptions ) ) {} |
| 5542 |
|
| 5543 |
} // namespace Catch |
| 5544 |
|
| 5545 |
|
| 5546 |
|
| 5547 |
#include <cstdio> |
| 5548 |
#include <sstream> |
| 5549 |
#include <vector> |
| 5550 |
|
| 5551 |
namespace Catch { |
| 5552 |
|
| 5553 |
// This class encapsulates the idea of a pool of ostringstreams that can be reused. |
| 5554 |
struct StringStreams { |
| 5555 |
std::vector<Detail::unique_ptr<std::ostringstream>> m_streams; |
| 5556 |
std::vector<std::size_t> m_unused; |
| 5557 |
std::ostringstream m_referenceStream; // Used for copy state/ flags from |
| 5558 |
|
| 5559 |
auto add() -> std::size_t { |
| 5560 |
if( m_unused.empty() ) { |
| 5561 |
m_streams.push_back( Detail::make_unique<std::ostringstream>() ); |
| 5562 |
return m_streams.size()-1; |
| 5563 |
} |
| 5564 |
else { |
| 5565 |
auto index = m_unused.back(); |
| 5566 |
m_unused.pop_back(); |
| 5567 |
return index; |
| 5568 |
} |
| 5569 |
} |
| 5570 |
|
| 5571 |
void release( std::size_t index ) { |
| 5572 |
m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state |
| 5573 |
m_unused.push_back(index); |
| 5574 |
} |
| 5575 |
}; |
| 5576 |
|
| 5577 |
ReusableStringStream::ReusableStringStream() |
| 5578 |
: m_index( Singleton<StringStreams>::getMutable().add() ), |
| 5579 |
m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() ) |
| 5580 |
{} |
| 5581 |
|
| 5582 |
ReusableStringStream::~ReusableStringStream() { |
| 5583 |
static_cast<std::ostringstream*>( m_oss )->str(""); |
| 5584 |
m_oss->clear(); |
| 5585 |
Singleton<StringStreams>::getMutable().release( m_index ); |
| 5586 |
} |
| 5587 |
|
| 5588 |
std::string ReusableStringStream::str() const { |
| 5589 |
return static_cast<std::ostringstream*>( m_oss )->str(); |
| 5590 |
} |
| 5591 |
|
| 5592 |
void ReusableStringStream::str( std::string const& str ) { |
| 5593 |
static_cast<std::ostringstream*>( m_oss )->str( str ); |
| 5594 |
} |
| 5595 |
|
| 5596 |
|
| 5597 |
} |
| 5598 |
|
| 5599 |
|
| 5600 |
|
| 5601 |
|
| 5602 |
#include <cassert> |
| 5603 |
#include <algorithm> |
| 5604 |
|
| 5605 |
namespace Catch { |
| 5606 |
|
| 5607 |
namespace Generators { |
| 5608 |
namespace { |
| 5609 |
struct GeneratorTracker final : TestCaseTracking::TrackerBase, |
| 5610 |
IGeneratorTracker { |
| 5611 |
GeneratorBasePtr m_generator; |
| 5612 |
|
| 5613 |
GeneratorTracker( |
| 5614 |
TestCaseTracking::NameAndLocation&& nameAndLocation, |
| 5615 |
TrackerContext& ctx, |
| 5616 |
ITracker* parent ): |
| 5617 |
TrackerBase( CATCH_MOVE( nameAndLocation ), ctx, parent ) {} |
| 5618 |
|
| 5619 |
static GeneratorTracker* |
| 5620 |
acquire( TrackerContext& ctx, |
| 5621 |
TestCaseTracking::NameAndLocationRef const& |
| 5622 |
nameAndLocation ) { |
| 5623 |
GeneratorTracker* tracker; |
| 5624 |
|
| 5625 |
ITracker& currentTracker = ctx.currentTracker(); |
| 5626 |
// Under specific circumstances, the generator we want |
| 5627 |
// to acquire is also the current tracker. If this is |
| 5628 |
// the case, we have to avoid looking through current |
| 5629 |
// tracker's children, and instead return the current |
| 5630 |
// tracker. |
| 5631 |
// A case where this check is important is e.g. |
| 5632 |
// for (int i = 0; i < 5; ++i) { |
| 5633 |
// int n = GENERATE(1, 2); |
| 5634 |
// } |
| 5635 |
// |
| 5636 |
// without it, the code above creates 5 nested generators. |
| 5637 |
if ( currentTracker.nameAndLocation() == nameAndLocation ) { |
| 5638 |
auto thisTracker = currentTracker.parent()->findChild( |
| 5639 |
nameAndLocation ); |
| 5640 |
assert( thisTracker ); |
| 5641 |
assert( thisTracker->isGeneratorTracker() ); |
| 5642 |
tracker = static_cast<GeneratorTracker*>( thisTracker ); |
| 5643 |
} else if ( ITracker* childTracker = |
| 5644 |
currentTracker.findChild( |
| 5645 |
nameAndLocation ) ) { |
| 5646 |
assert( childTracker ); |
| 5647 |
assert( childTracker->isGeneratorTracker() ); |
| 5648 |
tracker = |
| 5649 |
static_cast<GeneratorTracker*>( childTracker ); |
| 5650 |
} else { |
| 5651 |
return nullptr; |
| 5652 |
} |
| 5653 |
|
| 5654 |
if ( !tracker->isComplete() ) { tracker->open(); } |
| 5655 |
|
| 5656 |
return tracker; |
| 5657 |
} |
| 5658 |
|
| 5659 |
// TrackerBase interface |
| 5660 |
bool isGeneratorTracker() const override { return true; } |
| 5661 |
auto hasGenerator() const -> bool override { |
| 5662 |
return !!m_generator; |
| 5663 |
} |
| 5664 |
void close() override { |
| 5665 |
TrackerBase::close(); |
| 5666 |
// If a generator has a child (it is followed by a section) |
| 5667 |
// and none of its children have started, then we must wait |
| 5668 |
// until later to start consuming its values. |
| 5669 |
// This catches cases where `GENERATE` is placed between two |
| 5670 |
// `SECTION`s. |
| 5671 |
// **The check for m_children.empty cannot be removed**. |
| 5672 |
// doing so would break `GENERATE` _not_ followed by |
| 5673 |
// `SECTION`s. |
| 5674 |
const bool should_wait_for_child = [&]() { |
| 5675 |
// No children -> nobody to wait for |
| 5676 |
if ( m_children.empty() ) { return false; } |
| 5677 |
// If at least one child started executing, don't wait |
| 5678 |
if ( std::find_if( |
| 5679 |
m_children.begin(), |
| 5680 |
m_children.end(), |
| 5681 |
[]( TestCaseTracking::ITrackerPtr const& |
| 5682 |
tracker ) { |
| 5683 |
return tracker->hasStarted(); |
| 5684 |
} ) != m_children.end() ) { |
| 5685 |
return false; |
| 5686 |
} |
| 5687 |
|
| 5688 |
// No children have started. We need to check if they |
| 5689 |
// _can_ start, and thus we should wait for them, or |
| 5690 |
// they cannot start (due to filters), and we shouldn't |
| 5691 |
// wait for them |
| 5692 |
ITracker* parent = m_parent; |
| 5693 |
// This is safe: there is always at least one section |
| 5694 |
// tracker in a test case tracking tree |
| 5695 |
while ( !parent->isSectionTracker() ) { |
| 5696 |
parent = parent->parent(); |
| 5697 |
} |
| 5698 |
assert( parent && |
| 5699 |
"Missing root (test case) level section" ); |
| 5700 |
|
| 5701 |
auto const& parentSection = |
| 5702 |
static_cast<SectionTracker const&>( *parent ); |
| 5703 |
auto const& filters = parentSection.getFilters(); |
| 5704 |
// No filters -> no restrictions on running sections |
| 5705 |
if ( filters.empty() ) { return true; } |
| 5706 |
|
| 5707 |
for ( auto const& child : m_children ) { |
| 5708 |
if ( child->isSectionTracker() && |
| 5709 |
std::find( filters.begin(), |
| 5710 |
filters.end(), |
| 5711 |
static_cast<SectionTracker const&>( |
| 5712 |
*child ) |
| 5713 |
.trimmedName() ) != |
| 5714 |
filters.end() ) { |
| 5715 |
return true; |
| 5716 |
} |
| 5717 |
} |
| 5718 |
return false; |
| 5719 |
}(); |
| 5720 |
|
| 5721 |
// This check is a bit tricky, because m_generator->next() |
| 5722 |
// has a side-effect, where it consumes generator's current |
| 5723 |
// value, but we do not want to invoke the side-effect if |
| 5724 |
// this generator is still waiting for any child to start. |
| 5725 |
assert( m_generator && "Tracker without generator" ); |
| 5726 |
if ( should_wait_for_child || |
| 5727 |
( m_runState == CompletedSuccessfully && |
| 5728 |
m_generator->countedNext() ) ) { |
| 5729 |
m_children.clear(); |
| 5730 |
m_runState = Executing; |
| 5731 |
} |
| 5732 |
} |
| 5733 |
|
| 5734 |
// IGeneratorTracker interface |
| 5735 |
auto getGenerator() const -> GeneratorBasePtr const& override { |
| 5736 |
return m_generator; |
| 5737 |
} |
| 5738 |
void setGenerator( GeneratorBasePtr&& generator ) override { |
| 5739 |
m_generator = CATCH_MOVE( generator ); |
| 5740 |
} |
| 5741 |
}; |
| 5742 |
} // namespace |
| 5743 |
} |
| 5744 |
|
| 5745 |
RunContext::RunContext(IConfig const* _config, IEventListenerPtr&& reporter) |
| 5746 |
: m_runInfo(_config->name()), |
| 5747 |
m_config(_config), |
| 5748 |
m_reporter(CATCH_MOVE(reporter)), |
| 5749 |
m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal }, |
| 5750 |
m_outputRedirect( makeOutputRedirect( m_reporter->getPreferences().shouldRedirectStdOut ) ), |
| 5751 |
m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions ) |
| 5752 |
{ |
| 5753 |
getCurrentMutableContext().setResultCapture( this ); |
| 5754 |
m_reporter->testRunStarting(m_runInfo); |
| 5755 |
} |
| 5756 |
|
| 5757 |
RunContext::~RunContext() { |
| 5758 |
m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting())); |
| 5759 |
} |
| 5760 |
|
| 5761 |
Totals RunContext::runTest(TestCaseHandle const& testCase) { |
| 5762 |
const Totals prevTotals = m_totals; |
| 5763 |
|
| 5764 |
auto const& testInfo = testCase.getTestCaseInfo(); |
| 5765 |
m_reporter->testCaseStarting(testInfo); |
| 5766 |
testCase.prepareTestCase(); |
| 5767 |
m_activeTestCase = &testCase; |
| 5768 |
|
| 5769 |
|
| 5770 |
ITracker& rootTracker = m_trackerContext.startRun(); |
| 5771 |
assert(rootTracker.isSectionTracker()); |
| 5772 |
static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun()); |
| 5773 |
|
| 5774 |
// We intentionally only seed the internal RNG once per test case, |
| 5775 |
// before it is first invoked. The reason for that is a complex |
| 5776 |
// interplay of generator/section implementation details and the |
| 5777 |
// Random*Generator types. |
| 5778 |
// |
| 5779 |
// The issue boils down to us needing to seed the Random*Generators |
| 5780 |
// with different seed each, so that they return different sequences |
| 5781 |
// of random numbers. We do this by giving them a number from the |
| 5782 |
// shared RNG instance as their seed. |
| 5783 |
// |
| 5784 |
// However, this runs into an issue if the reseeding happens each |
| 5785 |
// time the test case is entered (as opposed to first time only), |
| 5786 |
// because multiple generators could get the same seed, e.g. in |
| 5787 |
// ```cpp |
| 5788 |
// TEST_CASE() { |
| 5789 |
// auto i = GENERATE(take(10, random(0, 100)); |
| 5790 |
// SECTION("A") { |
| 5791 |
// auto j = GENERATE(take(10, random(0, 100)); |
| 5792 |
// } |
| 5793 |
// SECTION("B") { |
| 5794 |
// auto k = GENERATE(take(10, random(0, 100)); |
| 5795 |
// } |
| 5796 |
// } |
| 5797 |
// ``` |
| 5798 |
// `i` and `j` would properly return values from different sequences, |
| 5799 |
// but `i` and `k` would return the same sequence, because their seed |
| 5800 |
// would be the same. |
| 5801 |
// (The reason their seeds would be the same is that the generator |
| 5802 |
// for k would be initialized when the test case is entered the second |
| 5803 |
// time, after the shared RNG instance was reset to the same value |
| 5804 |
// it had when the generator for i was initialized.) |
| 5805 |
seedRng( *m_config ); |
| 5806 |
|
| 5807 |
uint64_t testRuns = 0; |
| 5808 |
std::string redirectedCout; |
| 5809 |
std::string redirectedCerr; |
| 5810 |
do { |
| 5811 |
m_trackerContext.startCycle(); |
| 5812 |
m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocationRef(testInfo.name, testInfo.lineInfo)); |
| 5813 |
|
| 5814 |
m_reporter->testCasePartialStarting(testInfo, testRuns); |
| 5815 |
|
| 5816 |
const auto beforeRunTotals = m_totals; |
| 5817 |
runCurrentTest(); |
| 5818 |
std::string oneRunCout = m_outputRedirect->getStdout(); |
| 5819 |
std::string oneRunCerr = m_outputRedirect->getStderr(); |
| 5820 |
m_outputRedirect->clearBuffers(); |
| 5821 |
redirectedCout += oneRunCout; |
| 5822 |
redirectedCerr += oneRunCerr; |
| 5823 |
|
| 5824 |
const auto singleRunTotals = m_totals.delta(beforeRunTotals); |
| 5825 |
auto statsForOneRun = TestCaseStats(testInfo, singleRunTotals, CATCH_MOVE(oneRunCout), CATCH_MOVE(oneRunCerr), aborting()); |
| 5826 |
m_reporter->testCasePartialEnded(statsForOneRun, testRuns); |
| 5827 |
|
| 5828 |
++testRuns; |
| 5829 |
} while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting()); |
| 5830 |
|
| 5831 |
Totals deltaTotals = m_totals.delta(prevTotals); |
| 5832 |
if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) { |
| 5833 |
deltaTotals.assertions.failed++; |
| 5834 |
deltaTotals.testCases.passed--; |
| 5835 |
deltaTotals.testCases.failed++; |
| 5836 |
} |
| 5837 |
m_totals.testCases += deltaTotals.testCases; |
| 5838 |
testCase.tearDownTestCase(); |
| 5839 |
m_reporter->testCaseEnded(TestCaseStats(testInfo, |
| 5840 |
deltaTotals, |
| 5841 |
CATCH_MOVE(redirectedCout), |
| 5842 |
CATCH_MOVE(redirectedCerr), |
| 5843 |
aborting())); |
| 5844 |
|
| 5845 |
m_activeTestCase = nullptr; |
| 5846 |
m_testCaseTracker = nullptr; |
| 5847 |
|
| 5848 |
return deltaTotals; |
| 5849 |
} |
| 5850 |
|
| 5851 |
|
| 5852 |
void RunContext::assertionEnded(AssertionResult&& result) { |
| 5853 |
if (result.getResultType() == ResultWas::Ok) { |
| 5854 |
m_totals.assertions.passed++; |
| 5855 |
m_lastAssertionPassed = true; |
| 5856 |
} else if (result.getResultType() == ResultWas::ExplicitSkip) { |
| 5857 |
m_totals.assertions.skipped++; |
| 5858 |
m_lastAssertionPassed = true; |
| 5859 |
} else if (!result.succeeded()) { |
| 5860 |
m_lastAssertionPassed = false; |
| 5861 |
if (result.isOk()) { |
| 5862 |
} |
| 5863 |
else if( m_activeTestCase->getTestCaseInfo().okToFail() ) |
| 5864 |
m_totals.assertions.failedButOk++; |
| 5865 |
else |
| 5866 |
m_totals.assertions.failed++; |
| 5867 |
} |
| 5868 |
else { |
| 5869 |
m_lastAssertionPassed = true; |
| 5870 |
} |
| 5871 |
|
| 5872 |
{ |
| 5873 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 5874 |
m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ); |
| 5875 |
} |
| 5876 |
|
| 5877 |
if ( result.getResultType() != ResultWas::Warning ) { |
| 5878 |
m_messageScopes.clear(); |
| 5879 |
} |
| 5880 |
|
| 5881 |
// Reset working state. assertion info will be reset after |
| 5882 |
// populateReaction is run if it is needed |
| 5883 |
m_lastResult = CATCH_MOVE( result ); |
| 5884 |
} |
| 5885 |
void RunContext::resetAssertionInfo() { |
| 5886 |
m_lastAssertionInfo.macroName = StringRef(); |
| 5887 |
m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr; |
| 5888 |
m_lastAssertionInfo.resultDisposition = ResultDisposition::Normal; |
| 5889 |
} |
| 5890 |
|
| 5891 |
void RunContext::notifyAssertionStarted( AssertionInfo const& info ) { |
| 5892 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 5893 |
m_reporter->assertionStarting( info ); |
| 5894 |
} |
| 5895 |
|
| 5896 |
bool RunContext::sectionStarted( StringRef sectionName, |
| 5897 |
SourceLineInfo const& sectionLineInfo, |
| 5898 |
Counts& assertions ) { |
| 5899 |
ITracker& sectionTracker = |
| 5900 |
SectionTracker::acquire( m_trackerContext, |
| 5901 |
TestCaseTracking::NameAndLocationRef( |
| 5902 |
sectionName, sectionLineInfo ) ); |
| 5903 |
|
| 5904 |
if (!sectionTracker.isOpen()) |
| 5905 |
return false; |
| 5906 |
m_activeSections.push_back(§ionTracker); |
| 5907 |
|
| 5908 |
SectionInfo sectionInfo( sectionLineInfo, static_cast<std::string>(sectionName) ); |
| 5909 |
m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; |
| 5910 |
|
| 5911 |
{ |
| 5912 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 5913 |
m_reporter->sectionStarting( sectionInfo ); |
| 5914 |
} |
| 5915 |
|
| 5916 |
assertions = m_totals.assertions; |
| 5917 |
|
| 5918 |
return true; |
| 5919 |
} |
| 5920 |
IGeneratorTracker* |
| 5921 |
RunContext::acquireGeneratorTracker( StringRef generatorName, |
| 5922 |
SourceLineInfo const& lineInfo ) { |
| 5923 |
using namespace Generators; |
| 5924 |
GeneratorTracker* tracker = GeneratorTracker::acquire( |
| 5925 |
m_trackerContext, |
| 5926 |
TestCaseTracking::NameAndLocationRef( |
| 5927 |
generatorName, lineInfo ) ); |
| 5928 |
m_lastAssertionInfo.lineInfo = lineInfo; |
| 5929 |
return tracker; |
| 5930 |
} |
| 5931 |
|
| 5932 |
IGeneratorTracker* RunContext::createGeneratorTracker( |
| 5933 |
StringRef generatorName, |
| 5934 |
SourceLineInfo lineInfo, |
| 5935 |
Generators::GeneratorBasePtr&& generator ) { |
| 5936 |
|
| 5937 |
auto nameAndLoc = TestCaseTracking::NameAndLocation( static_cast<std::string>( generatorName ), lineInfo ); |
| 5938 |
auto& currentTracker = m_trackerContext.currentTracker(); |
| 5939 |
assert( |
| 5940 |
currentTracker.nameAndLocation() != nameAndLoc && |
| 5941 |
"Trying to create tracker for a genreator that already has one" ); |
| 5942 |
|
| 5943 |
auto newTracker = Catch::Detail::make_unique<Generators::GeneratorTracker>( |
| 5944 |
CATCH_MOVE(nameAndLoc), m_trackerContext, ¤tTracker ); |
| 5945 |
auto ret = newTracker.get(); |
| 5946 |
currentTracker.addChild( CATCH_MOVE( newTracker ) ); |
| 5947 |
|
| 5948 |
ret->setGenerator( CATCH_MOVE( generator ) ); |
| 5949 |
ret->open(); |
| 5950 |
return ret; |
| 5951 |
} |
| 5952 |
|
| 5953 |
bool RunContext::testForMissingAssertions(Counts& assertions) { |
| 5954 |
if (assertions.total() != 0) |
| 5955 |
return false; |
| 5956 |
if (!m_config->warnAboutMissingAssertions()) |
| 5957 |
return false; |
| 5958 |
if (m_trackerContext.currentTracker().hasChildren()) |
| 5959 |
return false; |
| 5960 |
m_totals.assertions.failed++; |
| 5961 |
assertions.failed++; |
| 5962 |
return true; |
| 5963 |
} |
| 5964 |
|
| 5965 |
void RunContext::sectionEnded(SectionEndInfo&& endInfo) { |
| 5966 |
Counts assertions = m_totals.assertions - endInfo.prevAssertions; |
| 5967 |
bool missingAssertions = testForMissingAssertions(assertions); |
| 5968 |
|
| 5969 |
if (!m_activeSections.empty()) { |
| 5970 |
m_activeSections.back()->close(); |
| 5971 |
m_activeSections.pop_back(); |
| 5972 |
} |
| 5973 |
|
| 5974 |
{ |
| 5975 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 5976 |
m_reporter->sectionEnded( |
| 5977 |
SectionStats( CATCH_MOVE( endInfo.sectionInfo ), |
| 5978 |
assertions, |
| 5979 |
endInfo.durationInSeconds, |
| 5980 |
missingAssertions ) ); |
| 5981 |
} |
| 5982 |
|
| 5983 |
m_messages.clear(); |
| 5984 |
m_messageScopes.clear(); |
| 5985 |
} |
| 5986 |
|
| 5987 |
void RunContext::sectionEndedEarly(SectionEndInfo&& endInfo) { |
| 5988 |
if ( m_unfinishedSections.empty() ) { |
| 5989 |
m_activeSections.back()->fail(); |
| 5990 |
} else { |
| 5991 |
m_activeSections.back()->close(); |
| 5992 |
} |
| 5993 |
m_activeSections.pop_back(); |
| 5994 |
|
| 5995 |
m_unfinishedSections.push_back(CATCH_MOVE(endInfo)); |
| 5996 |
} |
| 5997 |
|
| 5998 |
void RunContext::benchmarkPreparing( StringRef name ) { |
| 5999 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 6000 |
m_reporter->benchmarkPreparing( name ); |
| 6001 |
} |
| 6002 |
void RunContext::benchmarkStarting( BenchmarkInfo const& info ) { |
| 6003 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 6004 |
m_reporter->benchmarkStarting( info ); |
| 6005 |
} |
| 6006 |
void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) { |
| 6007 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 6008 |
m_reporter->benchmarkEnded( stats ); |
| 6009 |
} |
| 6010 |
void RunContext::benchmarkFailed( StringRef error ) { |
| 6011 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 6012 |
m_reporter->benchmarkFailed( error ); |
| 6013 |
} |
| 6014 |
|
| 6015 |
void RunContext::pushScopedMessage(MessageInfo const & message) { |
| 6016 |
m_messages.push_back(message); |
| 6017 |
} |
| 6018 |
|
| 6019 |
void RunContext::popScopedMessage(MessageInfo const & message) { |
| 6020 |
m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end()); |
| 6021 |
} |
| 6022 |
|
| 6023 |
void RunContext::emplaceUnscopedMessage( MessageBuilder&& builder ) { |
| 6024 |
m_messageScopes.emplace_back( CATCH_MOVE(builder) ); |
| 6025 |
} |
| 6026 |
|
| 6027 |
std::string RunContext::getCurrentTestName() const { |
| 6028 |
return m_activeTestCase |
| 6029 |
? m_activeTestCase->getTestCaseInfo().name |
| 6030 |
: std::string(); |
| 6031 |
} |
| 6032 |
|
| 6033 |
const AssertionResult * RunContext::getLastResult() const { |
| 6034 |
return &(*m_lastResult); |
| 6035 |
} |
| 6036 |
|
| 6037 |
void RunContext::exceptionEarlyReported() { |
| 6038 |
m_shouldReportUnexpected = false; |
| 6039 |
} |
| 6040 |
|
| 6041 |
void RunContext::handleFatalErrorCondition( StringRef message ) { |
| 6042 |
// TODO: scoped deactivate here? Just give up and do best effort? |
| 6043 |
// the deactivation can break things further, OTOH so can the |
| 6044 |
// capture |
| 6045 |
auto _ = scopedDeactivate( *m_outputRedirect ); |
| 6046 |
|
| 6047 |
// First notify reporter that bad things happened |
| 6048 |
m_reporter->fatalErrorEncountered( message ); |
| 6049 |
|
| 6050 |
// Don't rebuild the result -- the stringification itself can cause more fatal errors |
| 6051 |
// Instead, fake a result data. |
| 6052 |
AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } ); |
| 6053 |
tempResult.message = static_cast<std::string>(message); |
| 6054 |
AssertionResult result(m_lastAssertionInfo, CATCH_MOVE(tempResult)); |
| 6055 |
|
| 6056 |
assertionEnded(CATCH_MOVE(result) ); |
| 6057 |
resetAssertionInfo(); |
| 6058 |
|
| 6059 |
// Best effort cleanup for sections that have not been destructed yet |
| 6060 |
// Since this is a fatal error, we have not had and won't have the opportunity to destruct them properly |
| 6061 |
while (!m_activeSections.empty()) { |
| 6062 |
auto nl = m_activeSections.back()->nameAndLocation(); |
| 6063 |
SectionEndInfo endInfo{ SectionInfo(CATCH_MOVE(nl.location), CATCH_MOVE(nl.name)), {}, 0.0 }; |
| 6064 |
sectionEndedEarly(CATCH_MOVE(endInfo)); |
| 6065 |
} |
| 6066 |
handleUnfinishedSections(); |
| 6067 |
|
| 6068 |
// Recreate section for test case (as we will lose the one that was in scope) |
| 6069 |
auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); |
| 6070 |
SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); |
| 6071 |
|
| 6072 |
Counts assertions; |
| 6073 |
assertions.failed = 1; |
| 6074 |
SectionStats testCaseSectionStats(CATCH_MOVE(testCaseSection), assertions, 0, false); |
| 6075 |
m_reporter->sectionEnded( testCaseSectionStats ); |
| 6076 |
|
| 6077 |
auto const& testInfo = m_activeTestCase->getTestCaseInfo(); |
| 6078 |
|
| 6079 |
Totals deltaTotals; |
| 6080 |
deltaTotals.testCases.failed = 1; |
| 6081 |
deltaTotals.assertions.failed = 1; |
| 6082 |
m_reporter->testCaseEnded(TestCaseStats(testInfo, |
| 6083 |
deltaTotals, |
| 6084 |
std::string(), |
| 6085 |
std::string(), |
| 6086 |
false)); |
| 6087 |
m_totals.testCases.failed++; |
| 6088 |
m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false)); |
| 6089 |
} |
| 6090 |
|
| 6091 |
bool RunContext::lastAssertionPassed() { |
| 6092 |
return m_lastAssertionPassed; |
| 6093 |
} |
| 6094 |
|
| 6095 |
void RunContext::assertionPassed() { |
| 6096 |
m_lastAssertionPassed = true; |
| 6097 |
++m_totals.assertions.passed; |
| 6098 |
resetAssertionInfo(); |
| 6099 |
m_messageScopes.clear(); |
| 6100 |
} |
| 6101 |
|
| 6102 |
bool RunContext::aborting() const { |
| 6103 |
return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter()); |
| 6104 |
} |
| 6105 |
|
| 6106 |
void RunContext::runCurrentTest() { |
| 6107 |
auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); |
| 6108 |
SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); |
| 6109 |
m_reporter->sectionStarting(testCaseSection); |
| 6110 |
Counts prevAssertions = m_totals.assertions; |
| 6111 |
double duration = 0; |
| 6112 |
m_shouldReportUnexpected = true; |
| 6113 |
m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal }; |
| 6114 |
|
| 6115 |
Timer timer; |
| 6116 |
CATCH_TRY { |
| 6117 |
{ |
| 6118 |
auto _ = scopedActivate( *m_outputRedirect ); |
| 6119 |
timer.start(); |
| 6120 |
invokeActiveTestCase(); |
| 6121 |
} |
| 6122 |
duration = timer.getElapsedSeconds(); |
| 6123 |
} CATCH_CATCH_ANON (TestFailureException&) { |
| 6124 |
// This just means the test was aborted due to failure |
| 6125 |
} CATCH_CATCH_ANON (TestSkipException&) { |
| 6126 |
// This just means the test was explicitly skipped |
| 6127 |
} CATCH_CATCH_ALL { |
| 6128 |
// Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions |
| 6129 |
// are reported without translation at the point of origin. |
| 6130 |
if( m_shouldReportUnexpected ) { |
| 6131 |
AssertionReaction dummyReaction; |
| 6132 |
handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction ); |
| 6133 |
} |
| 6134 |
} |
| 6135 |
Counts assertions = m_totals.assertions - prevAssertions; |
| 6136 |
bool missingAssertions = testForMissingAssertions(assertions); |
| 6137 |
|
| 6138 |
m_testCaseTracker->close(); |
| 6139 |
handleUnfinishedSections(); |
| 6140 |
m_messages.clear(); |
| 6141 |
m_messageScopes.clear(); |
| 6142 |
|
| 6143 |
SectionStats testCaseSectionStats(CATCH_MOVE(testCaseSection), assertions, duration, missingAssertions); |
| 6144 |
m_reporter->sectionEnded(testCaseSectionStats); |
| 6145 |
} |
| 6146 |
|
| 6147 |
void RunContext::invokeActiveTestCase() { |
| 6148 |
// We need to engage a handler for signals/structured exceptions |
| 6149 |
// before running the tests themselves, or the binary can crash |
| 6150 |
// without failed test being reported. |
| 6151 |
FatalConditionHandlerGuard _(&m_fatalConditionhandler); |
| 6152 |
// We keep having issue where some compilers warn about an unused |
| 6153 |
// variable, even though the type has non-trivial constructor and |
| 6154 |
// destructor. This is annoying and ugly, but it makes them stfu. |
| 6155 |
(void)_; |
| 6156 |
|
| 6157 |
m_activeTestCase->invoke(); |
| 6158 |
} |
| 6159 |
|
| 6160 |
void RunContext::handleUnfinishedSections() { |
| 6161 |
// If sections ended prematurely due to an exception we stored their |
| 6162 |
// infos here so we can tear them down outside the unwind process. |
| 6163 |
for ( auto it = m_unfinishedSections.rbegin(), |
| 6164 |
itEnd = m_unfinishedSections.rend(); |
| 6165 |
it != itEnd; |
| 6166 |
++it ) { |
| 6167 |
sectionEnded( CATCH_MOVE( *it ) ); |
| 6168 |
} |
| 6169 |
m_unfinishedSections.clear(); |
| 6170 |
} |
| 6171 |
|
| 6172 |
void RunContext::handleExpr( |
| 6173 |
AssertionInfo const& info, |
| 6174 |
ITransientExpression const& expr, |
| 6175 |
AssertionReaction& reaction |
| 6176 |
) { |
| 6177 |
bool negated = isFalseTest( info.resultDisposition ); |
| 6178 |
bool result = expr.getResult() != negated; |
| 6179 |
|
| 6180 |
if( result ) { |
| 6181 |
if (!m_includeSuccessfulResults) { |
| 6182 |
assertionPassed(); |
| 6183 |
} |
| 6184 |
else { |
| 6185 |
reportExpr(info, ResultWas::Ok, &expr, negated); |
| 6186 |
} |
| 6187 |
} |
| 6188 |
else { |
| 6189 |
reportExpr(info, ResultWas::ExpressionFailed, &expr, negated ); |
| 6190 |
populateReaction( reaction ); |
| 6191 |
} |
| 6192 |
resetAssertionInfo(); |
| 6193 |
} |
| 6194 |
void RunContext::reportExpr( |
| 6195 |
AssertionInfo const &info, |
| 6196 |
ResultWas::OfType resultType, |
| 6197 |
ITransientExpression const *expr, |
| 6198 |
bool negated ) { |
| 6199 |
|
| 6200 |
m_lastAssertionInfo = info; |
| 6201 |
AssertionResultData data( resultType, LazyExpression( negated ) ); |
| 6202 |
|
| 6203 |
AssertionResult assertionResult{ info, CATCH_MOVE( data ) }; |
| 6204 |
assertionResult.m_resultData.lazyExpression.m_transientExpression = expr; |
| 6205 |
|
| 6206 |
assertionEnded( CATCH_MOVE(assertionResult) ); |
| 6207 |
} |
| 6208 |
|
| 6209 |
void RunContext::handleMessage( |
| 6210 |
AssertionInfo const& info, |
| 6211 |
ResultWas::OfType resultType, |
| 6212 |
std::string&& message, |
| 6213 |
AssertionReaction& reaction |
| 6214 |
) { |
| 6215 |
m_lastAssertionInfo = info; |
| 6216 |
|
| 6217 |
AssertionResultData data( resultType, LazyExpression( false ) ); |
| 6218 |
data.message = CATCH_MOVE( message ); |
| 6219 |
AssertionResult assertionResult{ m_lastAssertionInfo, |
| 6220 |
CATCH_MOVE( data ) }; |
| 6221 |
|
| 6222 |
const auto isOk = assertionResult.isOk(); |
| 6223 |
assertionEnded( CATCH_MOVE(assertionResult) ); |
| 6224 |
if ( !isOk ) { |
| 6225 |
populateReaction( reaction ); |
| 6226 |
} else if ( resultType == ResultWas::ExplicitSkip ) { |
| 6227 |
// TODO: Need to handle this explicitly, as ExplicitSkip is |
| 6228 |
// considered "OK" |
| 6229 |
reaction.shouldSkip = true; |
| 6230 |
} |
| 6231 |
resetAssertionInfo(); |
| 6232 |
} |
| 6233 |
void RunContext::handleUnexpectedExceptionNotThrown( |
| 6234 |
AssertionInfo const& info, |
| 6235 |
AssertionReaction& reaction |
| 6236 |
) { |
| 6237 |
handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction); |
| 6238 |
} |
| 6239 |
|
| 6240 |
void RunContext::handleUnexpectedInflightException( |
| 6241 |
AssertionInfo const& info, |
| 6242 |
std::string&& message, |
| 6243 |
AssertionReaction& reaction |
| 6244 |
) { |
| 6245 |
m_lastAssertionInfo = info; |
| 6246 |
|
| 6247 |
AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); |
| 6248 |
data.message = CATCH_MOVE(message); |
| 6249 |
AssertionResult assertionResult{ info, CATCH_MOVE(data) }; |
| 6250 |
assertionEnded( CATCH_MOVE(assertionResult) ); |
| 6251 |
populateReaction( reaction ); |
| 6252 |
resetAssertionInfo(); |
| 6253 |
} |
| 6254 |
|
| 6255 |
void RunContext::populateReaction( AssertionReaction& reaction ) { |
| 6256 |
reaction.shouldDebugBreak = m_config->shouldDebugBreak(); |
| 6257 |
reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal); |
| 6258 |
} |
| 6259 |
|
| 6260 |
void RunContext::handleIncomplete( |
| 6261 |
AssertionInfo const& info |
| 6262 |
) { |
| 6263 |
using namespace std::string_literals; |
| 6264 |
m_lastAssertionInfo = info; |
| 6265 |
|
| 6266 |
AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); |
| 6267 |
data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"s; |
| 6268 |
AssertionResult assertionResult{ info, CATCH_MOVE( data ) }; |
| 6269 |
assertionEnded( CATCH_MOVE(assertionResult) ); |
| 6270 |
resetAssertionInfo(); |
| 6271 |
} |
| 6272 |
void RunContext::handleNonExpr( |
| 6273 |
AssertionInfo const &info, |
| 6274 |
ResultWas::OfType resultType, |
| 6275 |
AssertionReaction &reaction |
| 6276 |
) { |
| 6277 |
m_lastAssertionInfo = info; |
| 6278 |
|
| 6279 |
AssertionResultData data( resultType, LazyExpression( false ) ); |
| 6280 |
AssertionResult assertionResult{ info, CATCH_MOVE( data ) }; |
| 6281 |
|
| 6282 |
const auto isOk = assertionResult.isOk(); |
| 6283 |
assertionEnded( CATCH_MOVE(assertionResult) ); |
| 6284 |
if ( !isOk ) { populateReaction( reaction ); } |
| 6285 |
resetAssertionInfo(); |
| 6286 |
} |
| 6287 |
|
| 6288 |
|
| 6289 |
IResultCapture& getResultCapture() { |
| 6290 |
if (auto* capture = getCurrentContext().getResultCapture()) |
| 6291 |
return *capture; |
| 6292 |
else |
| 6293 |
CATCH_INTERNAL_ERROR("No result capture instance"); |
| 6294 |
} |
| 6295 |
|
| 6296 |
void seedRng(IConfig const& config) { |
| 6297 |
sharedRng().seed(config.rngSeed()); |
| 6298 |
} |
| 6299 |
|
| 6300 |
unsigned int rngSeed() { |
| 6301 |
return getCurrentContext().getConfig()->rngSeed(); |
| 6302 |
} |
| 6303 |
|
| 6304 |
} |
| 6305 |
|
| 6306 |
|
| 6307 |
|
| 6308 |
namespace Catch { |
| 6309 |
|
| 6310 |
Section::Section( SectionInfo&& info ): |
| 6311 |
m_info( CATCH_MOVE( info ) ), |
| 6312 |
m_sectionIncluded( |
| 6313 |
getResultCapture().sectionStarted( m_info.name, m_info.lineInfo, m_assertions ) ) { |
| 6314 |
// Non-"included" sections will not use the timing information |
| 6315 |
// anyway, so don't bother with the potential syscall. |
| 6316 |
if (m_sectionIncluded) { |
| 6317 |
m_timer.start(); |
| 6318 |
} |
| 6319 |
} |
| 6320 |
|
| 6321 |
Section::Section( SourceLineInfo const& _lineInfo, |
| 6322 |
StringRef _name, |
| 6323 |
const char* const ): |
| 6324 |
m_info( { "invalid", static_cast<std::size_t>( -1 ) }, std::string{} ), |
| 6325 |
m_sectionIncluded( |
| 6326 |
getResultCapture().sectionStarted( _name, _lineInfo, m_assertions ) ) { |
| 6327 |
// We delay initialization the SectionInfo member until we know |
| 6328 |
// this section needs it, so we avoid allocating std::string for name. |
| 6329 |
// We also delay timer start to avoid the potential syscall unless we |
| 6330 |
// will actually use the result. |
| 6331 |
if ( m_sectionIncluded ) { |
| 6332 |
m_info.name = static_cast<std::string>( _name ); |
| 6333 |
m_info.lineInfo = _lineInfo; |
| 6334 |
m_timer.start(); |
| 6335 |
} |
| 6336 |
} |
| 6337 |
|
| 6338 |
Section::~Section() { |
| 6339 |
if( m_sectionIncluded ) { |
| 6340 |
SectionEndInfo endInfo{ CATCH_MOVE(m_info), m_assertions, m_timer.getElapsedSeconds() }; |
| 6341 |
if ( uncaught_exceptions() ) { |
| 6342 |
getResultCapture().sectionEndedEarly( CATCH_MOVE(endInfo) ); |
| 6343 |
} else { |
| 6344 |
getResultCapture().sectionEnded( CATCH_MOVE( endInfo ) ); |
| 6345 |
} |
| 6346 |
} |
| 6347 |
} |
| 6348 |
|
| 6349 |
// This indicates whether the section should be executed or not |
| 6350 |
Section::operator bool() const { |
| 6351 |
return m_sectionIncluded; |
| 6352 |
} |
| 6353 |
|
| 6354 |
|
| 6355 |
} // end namespace Catch |
| 6356 |
|
| 6357 |
|
| 6358 |
|
| 6359 |
#include <vector> |
| 6360 |
|
| 6361 |
namespace Catch { |
| 6362 |
|
| 6363 |
namespace { |
| 6364 |
static auto getSingletons() -> std::vector<ISingleton*>*& { |
| 6365 |
static std::vector<ISingleton*>* g_singletons = nullptr; |
| 6366 |
if( !g_singletons ) |
| 6367 |
g_singletons = new std::vector<ISingleton*>(); |
| 6368 |
return g_singletons; |
| 6369 |
} |
| 6370 |
} |
| 6371 |
|
| 6372 |
ISingleton::~ISingleton() = default; |
| 6373 |
|
| 6374 |
void addSingleton(ISingleton* singleton ) { |
| 6375 |
getSingletons()->push_back( singleton ); |
| 6376 |
} |
| 6377 |
void cleanupSingletons() { |
| 6378 |
auto& singletons = getSingletons(); |
| 6379 |
for( auto singleton : *singletons ) |
| 6380 |
delete singleton; |
| 6381 |
delete singletons; |
| 6382 |
singletons = nullptr; |
| 6383 |
} |
| 6384 |
|
| 6385 |
} // namespace Catch |
| 6386 |
|
| 6387 |
|
| 6388 |
|
| 6389 |
#include <cstring> |
| 6390 |
#include <ostream> |
| 6391 |
|
| 6392 |
namespace Catch { |
| 6393 |
|
| 6394 |
bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept { |
| 6395 |
return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0); |
| 6396 |
} |
| 6397 |
bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept { |
| 6398 |
// We can assume that the same file will usually have the same pointer. |
| 6399 |
// Thus, if the pointers are the same, there is no point in calling the strcmp |
| 6400 |
return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0)); |
| 6401 |
} |
| 6402 |
|
| 6403 |
std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { |
| 6404 |
#ifndef __GNUG__ |
| 6405 |
os << info.file << '(' << info.line << ')'; |
| 6406 |
#else |
| 6407 |
os << info.file << ':' << info.line; |
| 6408 |
#endif |
| 6409 |
return os; |
| 6410 |
} |
| 6411 |
|
| 6412 |
} // end namespace Catch |
| 6413 |
|
| 6414 |
|
| 6415 |
|
| 6416 |
|
| 6417 |
namespace Catch { |
| 6418 |
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) |
| 6419 |
void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept { |
| 6420 |
CATCH_TRY { |
| 6421 |
m_exceptions.push_back(exception); |
| 6422 |
} CATCH_CATCH_ALL { |
| 6423 |
// If we run out of memory during start-up there's really not a lot more we can do about it |
| 6424 |
std::terminate(); |
| 6425 |
} |
| 6426 |
} |
| 6427 |
|
| 6428 |
std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept { |
| 6429 |
return m_exceptions; |
| 6430 |
} |
| 6431 |
#endif |
| 6432 |
|
| 6433 |
} // end namespace Catch |
| 6434 |
|
| 6435 |
|
| 6436 |
|
| 6437 |
|
| 6438 |
|
| 6439 |
#include <iostream> |
| 6440 |
|
| 6441 |
namespace Catch { |
| 6442 |
|
| 6443 |
// If you #define this you must implement these functions |
| 6444 |
#if !defined( CATCH_CONFIG_NOSTDOUT ) |
| 6445 |
std::ostream& cout() { return std::cout; } |
| 6446 |
std::ostream& cerr() { return std::cerr; } |
| 6447 |
std::ostream& clog() { return std::clog; } |
| 6448 |
#endif |
| 6449 |
|
| 6450 |
} // namespace Catch |
| 6451 |
|
| 6452 |
|
| 6453 |
|
| 6454 |
#include <ostream> |
| 6455 |
#include <cstring> |
| 6456 |
#include <cctype> |
| 6457 |
#include <vector> |
| 6458 |
|
| 6459 |
namespace Catch { |
| 6460 |
|
| 6461 |
bool startsWith( std::string const& s, std::string const& prefix ) { |
| 6462 |
return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin()); |
| 6463 |
} |
| 6464 |
bool startsWith( StringRef s, char prefix ) { |
| 6465 |
return !s.empty() && s[0] == prefix; |
| 6466 |
} |
| 6467 |
bool endsWith( std::string const& s, std::string const& suffix ) { |
| 6468 |
return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); |
| 6469 |
} |
| 6470 |
bool endsWith( std::string const& s, char suffix ) { |
| 6471 |
return !s.empty() && s[s.size()-1] == suffix; |
| 6472 |
} |
| 6473 |
bool contains( std::string const& s, std::string const& infix ) { |
| 6474 |
return s.find( infix ) != std::string::npos; |
| 6475 |
} |
| 6476 |
void toLowerInPlace( std::string& s ) { |
| 6477 |
for ( char& c : s ) { |
| 6478 |
c = toLower( c ); |
| 6479 |
} |
| 6480 |
} |
| 6481 |
std::string toLower( std::string const& s ) { |
| 6482 |
std::string lc = s; |
| 6483 |
toLowerInPlace( lc ); |
| 6484 |
return lc; |
| 6485 |
} |
| 6486 |
char toLower(char c) { |
| 6487 |
return static_cast<char>(std::tolower(static_cast<unsigned char>(c))); |
| 6488 |
} |
| 6489 |
|
| 6490 |
std::string trim( std::string const& str ) { |
| 6491 |
static char const* whitespaceChars = "\n\r\t "; |
| 6492 |
std::string::size_type start = str.find_first_not_of( whitespaceChars ); |
| 6493 |
std::string::size_type end = str.find_last_not_of( whitespaceChars ); |
| 6494 |
|
| 6495 |
return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string(); |
| 6496 |
} |
| 6497 |
|
| 6498 |
StringRef trim(StringRef ref) { |
| 6499 |
const auto is_ws = [](char c) { |
| 6500 |
return c == ' ' || c == '\t' || c == '\n' || c == '\r'; |
| 6501 |
}; |
| 6502 |
size_t real_begin = 0; |
| 6503 |
while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; } |
| 6504 |
size_t real_end = ref.size(); |
| 6505 |
while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; } |
| 6506 |
|
| 6507 |
return ref.substr(real_begin, real_end - real_begin); |
| 6508 |
} |
| 6509 |
|
| 6510 |
bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { |
| 6511 |
std::size_t i = str.find( replaceThis ); |
| 6512 |
if (i == std::string::npos) { |
| 6513 |
return false; |
| 6514 |
} |
| 6515 |
std::size_t copyBegin = 0; |
| 6516 |
std::string origStr = CATCH_MOVE(str); |
| 6517 |
str.clear(); |
| 6518 |
// There is at least one replacement, so reserve with the best guess |
| 6519 |
// we can make without actually counting the number of occurences. |
| 6520 |
str.reserve(origStr.size() - replaceThis.size() + withThis.size()); |
| 6521 |
do { |
| 6522 |
str.append(origStr, copyBegin, i-copyBegin ); |
| 6523 |
str += withThis; |
| 6524 |
copyBegin = i + replaceThis.size(); |
| 6525 |
if( copyBegin < origStr.size() ) |
| 6526 |
i = origStr.find( replaceThis, copyBegin ); |
| 6527 |
else |
| 6528 |
i = std::string::npos; |
| 6529 |
} while( i != std::string::npos ); |
| 6530 |
if ( copyBegin < origStr.size() ) { |
| 6531 |
str.append(origStr, copyBegin, origStr.size() ); |
| 6532 |
} |
| 6533 |
return true; |
| 6534 |
} |
| 6535 |
|
| 6536 |
std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) { |
| 6537 |
std::vector<StringRef> subStrings; |
| 6538 |
std::size_t start = 0; |
| 6539 |
for(std::size_t pos = 0; pos < str.size(); ++pos ) { |
| 6540 |
if( str[pos] == delimiter ) { |
| 6541 |
if( pos - start > 1 ) |
| 6542 |
subStrings.push_back( str.substr( start, pos-start ) ); |
| 6543 |
start = pos+1; |
| 6544 |
} |
| 6545 |
} |
| 6546 |
if( start < str.size() ) |
| 6547 |
subStrings.push_back( str.substr( start, str.size()-start ) ); |
| 6548 |
return subStrings; |
| 6549 |
} |
| 6550 |
|
| 6551 |
std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { |
| 6552 |
os << pluraliser.m_count << ' ' << pluraliser.m_label; |
| 6553 |
if( pluraliser.m_count != 1 ) |
| 6554 |
os << 's'; |
| 6555 |
return os; |
| 6556 |
} |
| 6557 |
|
| 6558 |
} |
| 6559 |
|
| 6560 |
|
| 6561 |
|
| 6562 |
#include <algorithm> |
| 6563 |
#include <ostream> |
| 6564 |
#include <cstring> |
| 6565 |
#include <cstdint> |
| 6566 |
|
| 6567 |
namespace Catch { |
| 6568 |
StringRef::StringRef( char const* rawChars ) noexcept |
| 6569 |
: StringRef( rawChars, std::strlen(rawChars) ) |
| 6570 |
{} |
| 6571 |
|
| 6572 |
|
| 6573 |
bool StringRef::operator<(StringRef rhs) const noexcept { |
| 6574 |
if (m_size < rhs.m_size) { |
| 6575 |
return strncmp(m_start, rhs.m_start, m_size) <= 0; |
| 6576 |
} |
| 6577 |
return strncmp(m_start, rhs.m_start, rhs.m_size) < 0; |
| 6578 |
} |
| 6579 |
|
| 6580 |
int StringRef::compare( StringRef rhs ) const { |
| 6581 |
auto cmpResult = |
| 6582 |
strncmp( m_start, rhs.m_start, std::min( m_size, rhs.m_size ) ); |
| 6583 |
|
| 6584 |
// This means that strncmp found a difference before the strings |
| 6585 |
// ended, and we can return it directly |
| 6586 |
if ( cmpResult != 0 ) { |
| 6587 |
return cmpResult; |
| 6588 |
} |
| 6589 |
|
| 6590 |
// If strings are equal up to length, then their comparison results on |
| 6591 |
// their size |
| 6592 |
if ( m_size < rhs.m_size ) { |
| 6593 |
return -1; |
| 6594 |
} else if ( m_size > rhs.m_size ) { |
| 6595 |
return 1; |
| 6596 |
} else { |
| 6597 |
return 0; |
| 6598 |
} |
| 6599 |
} |
| 6600 |
|
| 6601 |
auto operator << ( std::ostream& os, StringRef str ) -> std::ostream& { |
| 6602 |
return os.write(str.data(), static_cast<std::streamsize>(str.size())); |
| 6603 |
} |
| 6604 |
|
| 6605 |
std::string operator+(StringRef lhs, StringRef rhs) { |
| 6606 |
std::string ret; |
| 6607 |
ret.reserve(lhs.size() + rhs.size()); |
| 6608 |
ret += lhs; |
| 6609 |
ret += rhs; |
| 6610 |
return ret; |
| 6611 |
} |
| 6612 |
|
| 6613 |
auto operator+=( std::string& lhs, StringRef rhs ) -> std::string& { |
| 6614 |
lhs.append(rhs.data(), rhs.size()); |
| 6615 |
return lhs; |
| 6616 |
} |
| 6617 |
|
| 6618 |
} // namespace Catch |
| 6619 |
|
| 6620 |
|
| 6621 |
|
| 6622 |
namespace Catch { |
| 6623 |
|
| 6624 |
TagAliasRegistry::~TagAliasRegistry() = default; |
| 6625 |
|
| 6626 |
TagAlias const* TagAliasRegistry::find( std::string const& alias ) const { |
| 6627 |
auto it = m_registry.find( alias ); |
| 6628 |
if( it != m_registry.end() ) |
| 6629 |
return &(it->second); |
| 6630 |
else |
| 6631 |
return nullptr; |
| 6632 |
} |
| 6633 |
|
| 6634 |
std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { |
| 6635 |
std::string expandedTestSpec = unexpandedTestSpec; |
| 6636 |
for( auto const& registryKvp : m_registry ) { |
| 6637 |
std::size_t pos = expandedTestSpec.find( registryKvp.first ); |
| 6638 |
if( pos != std::string::npos ) { |
| 6639 |
expandedTestSpec = expandedTestSpec.substr( 0, pos ) + |
| 6640 |
registryKvp.second.tag + |
| 6641 |
expandedTestSpec.substr( pos + registryKvp.first.size() ); |
| 6642 |
} |
| 6643 |
} |
| 6644 |
return expandedTestSpec; |
| 6645 |
} |
| 6646 |
|
| 6647 |
void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { |
| 6648 |
CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'), |
| 6649 |
"error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo ); |
| 6650 |
|
| 6651 |
CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second, |
| 6652 |
"error: tag alias, '" << alias << "' already registered.\n" |
| 6653 |
<< "\tFirst seen at: " << find(alias)->lineInfo << "\n" |
| 6654 |
<< "\tRedefined at: " << lineInfo ); |
| 6655 |
} |
| 6656 |
|
| 6657 |
ITagAliasRegistry::~ITagAliasRegistry() = default; |
| 6658 |
|
| 6659 |
ITagAliasRegistry const& ITagAliasRegistry::get() { |
| 6660 |
return getRegistryHub().getTagAliasRegistry(); |
| 6661 |
} |
| 6662 |
|
| 6663 |
} // end namespace Catch |
| 6664 |
|
| 6665 |
|
| 6666 |
|
| 6667 |
|
| 6668 |
namespace Catch { |
| 6669 |
TestCaseInfoHasher::TestCaseInfoHasher( hash_t seed ): m_seed( seed ) {} |
| 6670 |
|
| 6671 |
uint32_t TestCaseInfoHasher::operator()( TestCaseInfo const& t ) const { |
| 6672 |
// FNV-1a hash algorithm that is designed for uniqueness: |
| 6673 |
const hash_t prime = 1099511628211u; |
| 6674 |
hash_t hash = 14695981039346656037u; |
| 6675 |
for ( const char c : t.name ) { |
| 6676 |
hash ^= c; |
| 6677 |
hash *= prime; |
| 6678 |
} |
| 6679 |
for ( const char c : t.className ) { |
| 6680 |
hash ^= c; |
| 6681 |
hash *= prime; |
| 6682 |
} |
| 6683 |
for ( const Tag& tag : t.tags ) { |
| 6684 |
for ( const char c : tag.original ) { |
| 6685 |
hash ^= c; |
| 6686 |
hash *= prime; |
| 6687 |
} |
| 6688 |
} |
| 6689 |
hash ^= m_seed; |
| 6690 |
hash *= prime; |
| 6691 |
const uint32_t low{ static_cast<uint32_t>( hash ) }; |
| 6692 |
const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) }; |
| 6693 |
return low * high; |
| 6694 |
} |
| 6695 |
} // namespace Catch |
| 6696 |
|
| 6697 |
|
| 6698 |
|
| 6699 |
|
| 6700 |
#include <algorithm> |
| 6701 |
#include <set> |
| 6702 |
|
| 6703 |
namespace Catch { |
| 6704 |
|
| 6705 |
namespace { |
| 6706 |
static void enforceNoDuplicateTestCases( |
| 6707 |
std::vector<TestCaseHandle> const& tests ) { |
| 6708 |
auto testInfoCmp = []( TestCaseInfo const* lhs, |
| 6709 |
TestCaseInfo const* rhs ) { |
| 6710 |
return *lhs < *rhs; |
| 6711 |
}; |
| 6712 |
std::set<TestCaseInfo const*, decltype( testInfoCmp )&> seenTests( |
| 6713 |
testInfoCmp ); |
| 6714 |
for ( auto const& test : tests ) { |
| 6715 |
const auto infoPtr = &test.getTestCaseInfo(); |
| 6716 |
const auto prev = seenTests.insert( infoPtr ); |
| 6717 |
CATCH_ENFORCE( prev.second, |
| 6718 |
"error: test case \"" |
| 6719 |
<< infoPtr->name << "\", with tags \"" |
| 6720 |
<< infoPtr->tagsAsString() |
| 6721 |
<< "\" already defined.\n" |
| 6722 |
<< "\tFirst seen at " |
| 6723 |
<< ( *prev.first )->lineInfo << "\n" |
| 6724 |
<< "\tRedefined at " << infoPtr->lineInfo ); |
| 6725 |
} |
| 6726 |
} |
| 6727 |
|
| 6728 |
static bool matchTest( TestCaseHandle const& testCase, |
| 6729 |
TestSpec const& testSpec, |
| 6730 |
IConfig const& config ) { |
| 6731 |
return testSpec.matches( testCase.getTestCaseInfo() ) && |
| 6732 |
isThrowSafe( testCase, config ); |
| 6733 |
} |
| 6734 |
|
| 6735 |
} // end unnamed namespace |
| 6736 |
|
| 6737 |
std::vector<TestCaseHandle> sortTests( IConfig const& config, std::vector<TestCaseHandle> const& unsortedTestCases ) { |
| 6738 |
switch (config.runOrder()) { |
| 6739 |
case TestRunOrder::Declared: |
| 6740 |
return unsortedTestCases; |
| 6741 |
|
| 6742 |
case TestRunOrder::LexicographicallySorted: { |
| 6743 |
std::vector<TestCaseHandle> sorted = unsortedTestCases; |
| 6744 |
std::sort( |
| 6745 |
sorted.begin(), |
| 6746 |
sorted.end(), |
| 6747 |
[]( TestCaseHandle const& lhs, TestCaseHandle const& rhs ) { |
| 6748 |
return lhs.getTestCaseInfo() < rhs.getTestCaseInfo(); |
| 6749 |
} |
| 6750 |
); |
| 6751 |
return sorted; |
| 6752 |
} |
| 6753 |
case TestRunOrder::Randomized: { |
| 6754 |
using TestWithHash = std::pair<TestCaseInfoHasher::hash_t, TestCaseHandle>; |
| 6755 |
|
| 6756 |
TestCaseInfoHasher h{ config.rngSeed() }; |
| 6757 |
std::vector<TestWithHash> indexed_tests; |
| 6758 |
indexed_tests.reserve(unsortedTestCases.size()); |
| 6759 |
|
| 6760 |
for (auto const& handle : unsortedTestCases) { |
| 6761 |
indexed_tests.emplace_back(h(handle.getTestCaseInfo()), handle); |
| 6762 |
} |
| 6763 |
|
| 6764 |
std::sort( indexed_tests.begin(), |
| 6765 |
indexed_tests.end(), |
| 6766 |
[]( TestWithHash const& lhs, TestWithHash const& rhs ) { |
| 6767 |
if ( lhs.first == rhs.first ) { |
| 6768 |
return lhs.second.getTestCaseInfo() < |
| 6769 |
rhs.second.getTestCaseInfo(); |
| 6770 |
} |
| 6771 |
return lhs.first < rhs.first; |
| 6772 |
} ); |
| 6773 |
|
| 6774 |
std::vector<TestCaseHandle> randomized; |
| 6775 |
randomized.reserve(indexed_tests.size()); |
| 6776 |
|
| 6777 |
for (auto const& indexed : indexed_tests) { |
| 6778 |
randomized.push_back(indexed.second); |
| 6779 |
} |
| 6780 |
|
| 6781 |
return randomized; |
| 6782 |
} |
| 6783 |
} |
| 6784 |
|
| 6785 |
CATCH_INTERNAL_ERROR("Unknown test order value!"); |
| 6786 |
} |
| 6787 |
|
| 6788 |
bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config ) { |
| 6789 |
return !testCase.getTestCaseInfo().throws() || config.allowThrows(); |
| 6790 |
} |
| 6791 |
|
| 6792 |
std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config ) { |
| 6793 |
std::vector<TestCaseHandle> filtered; |
| 6794 |
filtered.reserve( testCases.size() ); |
| 6795 |
for (auto const& testCase : testCases) { |
| 6796 |
if ((!testSpec.hasFilters() && !testCase.getTestCaseInfo().isHidden()) || |
| 6797 |
(testSpec.hasFilters() && matchTest(testCase, testSpec, config))) { |
| 6798 |
filtered.push_back(testCase); |
| 6799 |
} |
| 6800 |
} |
| 6801 |
return createShard(filtered, config.shardCount(), config.shardIndex()); |
| 6802 |
} |
| 6803 |
std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config ) { |
| 6804 |
return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); |
| 6805 |
} |
| 6806 |
|
| 6807 |
TestRegistry::~TestRegistry() = default; |
| 6808 |
|
| 6809 |
void TestRegistry::registerTest(Detail::unique_ptr<TestCaseInfo> testInfo, Detail::unique_ptr<ITestInvoker> testInvoker) { |
| 6810 |
m_handles.emplace_back(testInfo.get(), testInvoker.get()); |
| 6811 |
m_viewed_test_infos.push_back(testInfo.get()); |
| 6812 |
m_owned_test_infos.push_back(CATCH_MOVE(testInfo)); |
| 6813 |
m_invokers.push_back(CATCH_MOVE(testInvoker)); |
| 6814 |
} |
| 6815 |
|
| 6816 |
std::vector<TestCaseInfo*> const& TestRegistry::getAllInfos() const { |
| 6817 |
return m_viewed_test_infos; |
| 6818 |
} |
| 6819 |
|
| 6820 |
std::vector<TestCaseHandle> const& TestRegistry::getAllTests() const { |
| 6821 |
return m_handles; |
| 6822 |
} |
| 6823 |
std::vector<TestCaseHandle> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const { |
| 6824 |
if( m_sortedFunctions.empty() ) |
| 6825 |
enforceNoDuplicateTestCases( m_handles ); |
| 6826 |
|
| 6827 |
if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { |
| 6828 |
m_sortedFunctions = sortTests( config, m_handles ); |
| 6829 |
m_currentSortOrder = config.runOrder(); |
| 6830 |
} |
| 6831 |
return m_sortedFunctions; |
| 6832 |
} |
| 6833 |
|
| 6834 |
} // end namespace Catch |
| 6835 |
|
| 6836 |
|
| 6837 |
|
| 6838 |
|
| 6839 |
#include <algorithm> |
| 6840 |
#include <cassert> |
| 6841 |
|
| 6842 |
#if defined(__clang__) |
| 6843 |
# pragma clang diagnostic push |
| 6844 |
# pragma clang diagnostic ignored "-Wexit-time-destructors" |
| 6845 |
#endif |
| 6846 |
|
| 6847 |
namespace Catch { |
| 6848 |
namespace TestCaseTracking { |
| 6849 |
|
| 6850 |
NameAndLocation::NameAndLocation( std::string&& _name, SourceLineInfo const& _location ) |
| 6851 |
: name( CATCH_MOVE(_name) ), |
| 6852 |
location( _location ) |
| 6853 |
{} |
| 6854 |
|
| 6855 |
|
| 6856 |
ITracker::~ITracker() = default; |
| 6857 |
|
| 6858 |
void ITracker::markAsNeedingAnotherRun() { |
| 6859 |
m_runState = NeedsAnotherRun; |
| 6860 |
} |
| 6861 |
|
| 6862 |
void ITracker::addChild( ITrackerPtr&& child ) { |
| 6863 |
m_children.push_back( CATCH_MOVE(child) ); |
| 6864 |
} |
| 6865 |
|
| 6866 |
ITracker* ITracker::findChild( NameAndLocationRef const& nameAndLocation ) { |
| 6867 |
auto it = std::find_if( |
| 6868 |
m_children.begin(), |
| 6869 |
m_children.end(), |
| 6870 |
[&nameAndLocation]( ITrackerPtr const& tracker ) { |
| 6871 |
auto const& tnameAndLoc = tracker->nameAndLocation(); |
| 6872 |
if ( tnameAndLoc.location.line != |
| 6873 |
nameAndLocation.location.line ) { |
| 6874 |
return false; |
| 6875 |
} |
| 6876 |
return tnameAndLoc == nameAndLocation; |
| 6877 |
} ); |
| 6878 |
return ( it != m_children.end() ) ? it->get() : nullptr; |
| 6879 |
} |
| 6880 |
|
| 6881 |
bool ITracker::isSectionTracker() const { return false; } |
| 6882 |
bool ITracker::isGeneratorTracker() const { return false; } |
| 6883 |
|
| 6884 |
bool ITracker::isOpen() const { |
| 6885 |
return m_runState != NotStarted && !isComplete(); |
| 6886 |
} |
| 6887 |
|
| 6888 |
bool ITracker::hasStarted() const { return m_runState != NotStarted; } |
| 6889 |
|
| 6890 |
void ITracker::openChild() { |
| 6891 |
if (m_runState != ExecutingChildren) { |
| 6892 |
m_runState = ExecutingChildren; |
| 6893 |
if (m_parent) { |
| 6894 |
m_parent->openChild(); |
| 6895 |
} |
| 6896 |
} |
| 6897 |
} |
| 6898 |
|
| 6899 |
ITracker& TrackerContext::startRun() { |
| 6900 |
using namespace std::string_literals; |
| 6901 |
m_rootTracker = Catch::Detail::make_unique<SectionTracker>( |
| 6902 |
NameAndLocation( "{root}"s, CATCH_INTERNAL_LINEINFO ), |
| 6903 |
*this, |
| 6904 |
nullptr ); |
| 6905 |
m_currentTracker = nullptr; |
| 6906 |
m_runState = Executing; |
| 6907 |
return *m_rootTracker; |
| 6908 |
} |
| 6909 |
|
| 6910 |
void TrackerContext::completeCycle() { |
| 6911 |
m_runState = CompletedCycle; |
| 6912 |
} |
| 6913 |
|
| 6914 |
bool TrackerContext::completedCycle() const { |
| 6915 |
return m_runState == CompletedCycle; |
| 6916 |
} |
| 6917 |
void TrackerContext::setCurrentTracker( ITracker* tracker ) { |
| 6918 |
m_currentTracker = tracker; |
| 6919 |
} |
| 6920 |
|
| 6921 |
|
| 6922 |
TrackerBase::TrackerBase( NameAndLocation&& nameAndLocation, TrackerContext& ctx, ITracker* parent ): |
| 6923 |
ITracker(CATCH_MOVE(nameAndLocation), parent), |
| 6924 |
m_ctx( ctx ) |
| 6925 |
{} |
| 6926 |
|
| 6927 |
bool TrackerBase::isComplete() const { |
| 6928 |
return m_runState == CompletedSuccessfully || m_runState == Failed; |
| 6929 |
} |
| 6930 |
|
| 6931 |
void TrackerBase::open() { |
| 6932 |
m_runState = Executing; |
| 6933 |
moveToThis(); |
| 6934 |
if( m_parent ) |
| 6935 |
m_parent->openChild(); |
| 6936 |
} |
| 6937 |
|
| 6938 |
void TrackerBase::close() { |
| 6939 |
|
| 6940 |
// Close any still open children (e.g. generators) |
| 6941 |
while( &m_ctx.currentTracker() != this ) |
| 6942 |
m_ctx.currentTracker().close(); |
| 6943 |
|
| 6944 |
switch( m_runState ) { |
| 6945 |
case NeedsAnotherRun: |
| 6946 |
break; |
| 6947 |
|
| 6948 |
case Executing: |
| 6949 |
m_runState = CompletedSuccessfully; |
| 6950 |
break; |
| 6951 |
case ExecutingChildren: |
| 6952 |
if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) ) |
| 6953 |
m_runState = CompletedSuccessfully; |
| 6954 |
break; |
| 6955 |
|
| 6956 |
case NotStarted: |
| 6957 |
case CompletedSuccessfully: |
| 6958 |
case Failed: |
| 6959 |
CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState ); |
| 6960 |
|
| 6961 |
default: |
| 6962 |
CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState ); |
| 6963 |
} |
| 6964 |
moveToParent(); |
| 6965 |
m_ctx.completeCycle(); |
| 6966 |
} |
| 6967 |
void TrackerBase::fail() { |
| 6968 |
m_runState = Failed; |
| 6969 |
if( m_parent ) |
| 6970 |
m_parent->markAsNeedingAnotherRun(); |
| 6971 |
moveToParent(); |
| 6972 |
m_ctx.completeCycle(); |
| 6973 |
} |
| 6974 |
|
| 6975 |
void TrackerBase::moveToParent() { |
| 6976 |
assert( m_parent ); |
| 6977 |
m_ctx.setCurrentTracker( m_parent ); |
| 6978 |
} |
| 6979 |
void TrackerBase::moveToThis() { |
| 6980 |
m_ctx.setCurrentTracker( this ); |
| 6981 |
} |
| 6982 |
|
| 6983 |
SectionTracker::SectionTracker( NameAndLocation&& nameAndLocation, TrackerContext& ctx, ITracker* parent ) |
| 6984 |
: TrackerBase( CATCH_MOVE(nameAndLocation), ctx, parent ), |
| 6985 |
m_trimmed_name(trim(StringRef(ITracker::nameAndLocation().name))) |
| 6986 |
{ |
| 6987 |
if( parent ) { |
| 6988 |
while ( !parent->isSectionTracker() ) { |
| 6989 |
parent = parent->parent(); |
| 6990 |
} |
| 6991 |
|
| 6992 |
SectionTracker& parentSection = static_cast<SectionTracker&>( *parent ); |
| 6993 |
addNextFilters( parentSection.m_filters ); |
| 6994 |
} |
| 6995 |
} |
| 6996 |
|
| 6997 |
bool SectionTracker::isComplete() const { |
| 6998 |
bool complete = true; |
| 6999 |
|
| 7000 |
if (m_filters.empty() |
| 7001 |
|| m_filters[0].empty() |
| 7002 |
|| std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) { |
| 7003 |
complete = TrackerBase::isComplete(); |
| 7004 |
} |
| 7005 |
return complete; |
| 7006 |
} |
| 7007 |
|
| 7008 |
bool SectionTracker::isSectionTracker() const { return true; } |
| 7009 |
|
| 7010 |
SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocationRef const& nameAndLocation ) { |
| 7011 |
SectionTracker* tracker; |
| 7012 |
|
| 7013 |
ITracker& currentTracker = ctx.currentTracker(); |
| 7014 |
if ( ITracker* childTracker = |
| 7015 |
currentTracker.findChild( nameAndLocation ) ) { |
| 7016 |
assert( childTracker ); |
| 7017 |
assert( childTracker->isSectionTracker() ); |
| 7018 |
tracker = static_cast<SectionTracker*>( childTracker ); |
| 7019 |
} else { |
| 7020 |
auto newTracker = Catch::Detail::make_unique<SectionTracker>( |
| 7021 |
NameAndLocation{ static_cast<std::string>(nameAndLocation.name), |
| 7022 |
nameAndLocation.location }, |
| 7023 |
ctx, |
| 7024 |
¤tTracker ); |
| 7025 |
tracker = newTracker.get(); |
| 7026 |
currentTracker.addChild( CATCH_MOVE( newTracker ) ); |
| 7027 |
} |
| 7028 |
|
| 7029 |
if ( !ctx.completedCycle() ) { |
| 7030 |
tracker->tryOpen(); |
| 7031 |
} |
| 7032 |
|
| 7033 |
return *tracker; |
| 7034 |
} |
| 7035 |
|
| 7036 |
void SectionTracker::tryOpen() { |
| 7037 |
if( !isComplete() ) |
| 7038 |
open(); |
| 7039 |
} |
| 7040 |
|
| 7041 |
void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) { |
| 7042 |
if( !filters.empty() ) { |
| 7043 |
m_filters.reserve( m_filters.size() + filters.size() + 2 ); |
| 7044 |
m_filters.emplace_back(StringRef{}); // Root - should never be consulted |
| 7045 |
m_filters.emplace_back(StringRef{}); // Test Case - not a section filter |
| 7046 |
m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); |
| 7047 |
} |
| 7048 |
} |
| 7049 |
void SectionTracker::addNextFilters( std::vector<StringRef> const& filters ) { |
| 7050 |
if( filters.size() > 1 ) |
| 7051 |
m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() ); |
| 7052 |
} |
| 7053 |
|
| 7054 |
StringRef SectionTracker::trimmedName() const { |
| 7055 |
return m_trimmed_name; |
| 7056 |
} |
| 7057 |
|
| 7058 |
} // namespace TestCaseTracking |
| 7059 |
|
| 7060 |
} // namespace Catch |
| 7061 |
|
| 7062 |
#if defined(__clang__) |
| 7063 |
# pragma clang diagnostic pop |
| 7064 |
#endif |
| 7065 |
|
| 7066 |
|
| 7067 |
|
| 7068 |
|
| 7069 |
namespace Catch { |
| 7070 |
|
| 7071 |
void throw_test_failure_exception() { |
| 7072 |
#if !defined( CATCH_CONFIG_DISABLE_EXCEPTIONS ) |
| 7073 |
throw TestFailureException{}; |
| 7074 |
#else |
| 7075 |
CATCH_ERROR( "Test failure requires aborting test!" ); |
| 7076 |
#endif |
| 7077 |
} |
| 7078 |
|
| 7079 |
void throw_test_skip_exception() { |
| 7080 |
#if !defined( CATCH_CONFIG_DISABLE_EXCEPTIONS ) |
| 7081 |
throw Catch::TestSkipException(); |
| 7082 |
#else |
| 7083 |
CATCH_ERROR( "Explicitly skipping tests during runtime requires exceptions" ); |
| 7084 |
#endif |
| 7085 |
} |
| 7086 |
|
| 7087 |
} // namespace Catch |
| 7088 |
|
| 7089 |
|
| 7090 |
|
| 7091 |
#include <algorithm> |
| 7092 |
#include <iterator> |
| 7093 |
|
| 7094 |
namespace Catch { |
| 7095 |
void ITestInvoker::prepareTestCase() {} |
| 7096 |
void ITestInvoker::tearDownTestCase() {} |
| 7097 |
ITestInvoker::~ITestInvoker() = default; |
| 7098 |
|
| 7099 |
namespace { |
| 7100 |
static StringRef extractClassName( StringRef classOrMethodName ) { |
| 7101 |
if ( !startsWith( classOrMethodName, '&' ) ) { |
| 7102 |
return classOrMethodName; |
| 7103 |
} |
| 7104 |
|
| 7105 |
// Remove the leading '&' to avoid having to special case it later |
| 7106 |
const auto methodName = |
| 7107 |
classOrMethodName.substr( 1, classOrMethodName.size() ); |
| 7108 |
|
| 7109 |
auto reverseStart = std::make_reverse_iterator( methodName.end() ); |
| 7110 |
auto reverseEnd = std::make_reverse_iterator( methodName.begin() ); |
| 7111 |
|
| 7112 |
// We make a simplifying assumption that ":" is only present |
| 7113 |
// in the input as part of "::" from C++ typenames (this is |
| 7114 |
// relatively safe assumption because the input is generated |
| 7115 |
// as stringification of type through preprocessor). |
| 7116 |
auto lastColons = std::find( reverseStart, reverseEnd, ':' ) + 1; |
| 7117 |
auto secondLastColons = |
| 7118 |
std::find( lastColons + 1, reverseEnd, ':' ); |
| 7119 |
|
| 7120 |
auto const startIdx = reverseEnd - secondLastColons; |
| 7121 |
auto const classNameSize = secondLastColons - lastColons - 1; |
| 7122 |
|
| 7123 |
return methodName.substr( |
| 7124 |
static_cast<std::size_t>( startIdx ), |
| 7125 |
static_cast<std::size_t>( classNameSize ) ); |
| 7126 |
} |
| 7127 |
|
| 7128 |
class TestInvokerAsFunction final : public ITestInvoker { |
| 7129 |
using TestType = void ( * )(); |
| 7130 |
TestType m_testAsFunction; |
| 7131 |
|
| 7132 |
public: |
| 7133 |
constexpr TestInvokerAsFunction( TestType testAsFunction ) noexcept: |
| 7134 |
m_testAsFunction( testAsFunction ) {} |
| 7135 |
|
| 7136 |
void invoke() const override { m_testAsFunction(); } |
| 7137 |
}; |
| 7138 |
|
| 7139 |
} // namespace |
| 7140 |
|
| 7141 |
Detail::unique_ptr<ITestInvoker> makeTestInvoker( void(*testAsFunction)() ) { |
| 7142 |
return Detail::make_unique<TestInvokerAsFunction>( testAsFunction ); |
| 7143 |
} |
| 7144 |
|
| 7145 |
AutoReg::AutoReg( Detail::unique_ptr<ITestInvoker> invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept { |
| 7146 |
CATCH_TRY { |
| 7147 |
getMutableRegistryHub() |
| 7148 |
.registerTest( |
| 7149 |
makeTestCaseInfo( |
| 7150 |
extractClassName( classOrMethod ), |
| 7151 |
nameAndTags, |
| 7152 |
lineInfo), |
| 7153 |
CATCH_MOVE(invoker) |
| 7154 |
); |
| 7155 |
} CATCH_CATCH_ALL { |
| 7156 |
// Do not throw when constructing global objects, instead register the exception to be processed later |
| 7157 |
getMutableRegistryHub().registerStartupException(); |
| 7158 |
} |
| 7159 |
} |
| 7160 |
} |
| 7161 |
|
| 7162 |
|
| 7163 |
|
| 7164 |
|
| 7165 |
|
| 7166 |
namespace Catch { |
| 7167 |
|
| 7168 |
TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} |
| 7169 |
|
| 7170 |
TestSpecParser& TestSpecParser::parse( std::string const& arg ) { |
| 7171 |
m_mode = None; |
| 7172 |
m_exclusion = false; |
| 7173 |
m_arg = m_tagAliases->expandAliases( arg ); |
| 7174 |
m_escapeChars.clear(); |
| 7175 |
m_substring.reserve(m_arg.size()); |
| 7176 |
m_patternName.reserve(m_arg.size()); |
| 7177 |
m_realPatternPos = 0; |
| 7178 |
|
| 7179 |
for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) |
| 7180 |
//if visitChar fails |
| 7181 |
if( !visitChar( m_arg[m_pos] ) ){ |
| 7182 |
m_testSpec.m_invalidSpecs.push_back(arg); |
| 7183 |
break; |
| 7184 |
} |
| 7185 |
endMode(); |
| 7186 |
return *this; |
| 7187 |
} |
| 7188 |
TestSpec TestSpecParser::testSpec() { |
| 7189 |
addFilter(); |
| 7190 |
return CATCH_MOVE(m_testSpec); |
| 7191 |
} |
| 7192 |
bool TestSpecParser::visitChar( char c ) { |
| 7193 |
if( (m_mode != EscapedName) && (c == '\\') ) { |
| 7194 |
escape(); |
| 7195 |
addCharToPattern(c); |
| 7196 |
return true; |
| 7197 |
}else if((m_mode != EscapedName) && (c == ',') ) { |
| 7198 |
return separate(); |
| 7199 |
} |
| 7200 |
|
| 7201 |
switch( m_mode ) { |
| 7202 |
case None: |
| 7203 |
if( processNoneChar( c ) ) |
| 7204 |
return true; |
| 7205 |
break; |
| 7206 |
case Name: |
| 7207 |
processNameChar( c ); |
| 7208 |
break; |
| 7209 |
case EscapedName: |
| 7210 |
endMode(); |
| 7211 |
addCharToPattern(c); |
| 7212 |
return true; |
| 7213 |
default: |
| 7214 |
case Tag: |
| 7215 |
case QuotedName: |
| 7216 |
if( processOtherChar( c ) ) |
| 7217 |
return true; |
| 7218 |
break; |
| 7219 |
} |
| 7220 |
|
| 7221 |
m_substring += c; |
| 7222 |
if( !isControlChar( c ) ) { |
| 7223 |
m_patternName += c; |
| 7224 |
m_realPatternPos++; |
| 7225 |
} |
| 7226 |
return true; |
| 7227 |
} |
| 7228 |
// Two of the processing methods return true to signal the caller to return |
| 7229 |
// without adding the given character to the current pattern strings |
| 7230 |
bool TestSpecParser::processNoneChar( char c ) { |
| 7231 |
switch( c ) { |
| 7232 |
case ' ': |
| 7233 |
return true; |
| 7234 |
case '~': |
| 7235 |
m_exclusion = true; |
| 7236 |
return false; |
| 7237 |
case '[': |
| 7238 |
startNewMode( Tag ); |
| 7239 |
return false; |
| 7240 |
case '"': |
| 7241 |
startNewMode( QuotedName ); |
| 7242 |
return false; |
| 7243 |
default: |
| 7244 |
startNewMode( Name ); |
| 7245 |
return false; |
| 7246 |
} |
| 7247 |
} |
| 7248 |
void TestSpecParser::processNameChar( char c ) { |
| 7249 |
if( c == '[' ) { |
| 7250 |
if( m_substring == "exclude:" ) |
| 7251 |
m_exclusion = true; |
| 7252 |
else |
| 7253 |
endMode(); |
| 7254 |
startNewMode( Tag ); |
| 7255 |
} |
| 7256 |
} |
| 7257 |
bool TestSpecParser::processOtherChar( char c ) { |
| 7258 |
if( !isControlChar( c ) ) |
| 7259 |
return false; |
| 7260 |
m_substring += c; |
| 7261 |
endMode(); |
| 7262 |
return true; |
| 7263 |
} |
| 7264 |
void TestSpecParser::startNewMode( Mode mode ) { |
| 7265 |
m_mode = mode; |
| 7266 |
} |
| 7267 |
void TestSpecParser::endMode() { |
| 7268 |
switch( m_mode ) { |
| 7269 |
case Name: |
| 7270 |
case QuotedName: |
| 7271 |
return addNamePattern(); |
| 7272 |
case Tag: |
| 7273 |
return addTagPattern(); |
| 7274 |
case EscapedName: |
| 7275 |
revertBackToLastMode(); |
| 7276 |
return; |
| 7277 |
case None: |
| 7278 |
default: |
| 7279 |
return startNewMode( None ); |
| 7280 |
} |
| 7281 |
} |
| 7282 |
void TestSpecParser::escape() { |
| 7283 |
saveLastMode(); |
| 7284 |
m_mode = EscapedName; |
| 7285 |
m_escapeChars.push_back(m_realPatternPos); |
| 7286 |
} |
| 7287 |
bool TestSpecParser::isControlChar( char c ) const { |
| 7288 |
switch( m_mode ) { |
| 7289 |
default: |
| 7290 |
return false; |
| 7291 |
case None: |
| 7292 |
return c == '~'; |
| 7293 |
case Name: |
| 7294 |
return c == '['; |
| 7295 |
case EscapedName: |
| 7296 |
return true; |
| 7297 |
case QuotedName: |
| 7298 |
return c == '"'; |
| 7299 |
case Tag: |
| 7300 |
return c == '[' || c == ']'; |
| 7301 |
} |
| 7302 |
} |
| 7303 |
|
| 7304 |
void TestSpecParser::addFilter() { |
| 7305 |
if( !m_currentFilter.m_required.empty() || !m_currentFilter.m_forbidden.empty() ) { |
| 7306 |
m_testSpec.m_filters.push_back( CATCH_MOVE(m_currentFilter) ); |
| 7307 |
m_currentFilter = TestSpec::Filter(); |
| 7308 |
} |
| 7309 |
} |
| 7310 |
|
| 7311 |
void TestSpecParser::saveLastMode() { |
| 7312 |
lastMode = m_mode; |
| 7313 |
} |
| 7314 |
|
| 7315 |
void TestSpecParser::revertBackToLastMode() { |
| 7316 |
m_mode = lastMode; |
| 7317 |
} |
| 7318 |
|
| 7319 |
bool TestSpecParser::separate() { |
| 7320 |
if( (m_mode==QuotedName) || (m_mode==Tag) ){ |
| 7321 |
//invalid argument, signal failure to previous scope. |
| 7322 |
m_mode = None; |
| 7323 |
m_pos = m_arg.size(); |
| 7324 |
m_substring.clear(); |
| 7325 |
m_patternName.clear(); |
| 7326 |
m_realPatternPos = 0; |
| 7327 |
return false; |
| 7328 |
} |
| 7329 |
endMode(); |
| 7330 |
addFilter(); |
| 7331 |
return true; //success |
| 7332 |
} |
| 7333 |
|
| 7334 |
std::string TestSpecParser::preprocessPattern() { |
| 7335 |
std::string token = m_patternName; |
| 7336 |
for (std::size_t i = 0; i < m_escapeChars.size(); ++i) |
| 7337 |
token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1); |
| 7338 |
m_escapeChars.clear(); |
| 7339 |
if (startsWith(token, "exclude:")) { |
| 7340 |
m_exclusion = true; |
| 7341 |
token = token.substr(8); |
| 7342 |
} |
| 7343 |
|
| 7344 |
m_patternName.clear(); |
| 7345 |
m_realPatternPos = 0; |
| 7346 |
|
| 7347 |
return token; |
| 7348 |
} |
| 7349 |
|
| 7350 |
void TestSpecParser::addNamePattern() { |
| 7351 |
auto token = preprocessPattern(); |
| 7352 |
|
| 7353 |
if (!token.empty()) { |
| 7354 |
if (m_exclusion) { |
| 7355 |
m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::NamePattern>(token, m_substring)); |
| 7356 |
} else { |
| 7357 |
m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::NamePattern>(token, m_substring)); |
| 7358 |
} |
| 7359 |
} |
| 7360 |
m_substring.clear(); |
| 7361 |
m_exclusion = false; |
| 7362 |
m_mode = None; |
| 7363 |
} |
| 7364 |
|
| 7365 |
void TestSpecParser::addTagPattern() { |
| 7366 |
auto token = preprocessPattern(); |
| 7367 |
|
| 7368 |
if (!token.empty()) { |
| 7369 |
// If the tag pattern is the "hide and tag" shorthand (e.g. [.foo]) |
| 7370 |
// we have to create a separate hide tag and shorten the real one |
| 7371 |
if (token.size() > 1 && token[0] == '.') { |
| 7372 |
token.erase(token.begin()); |
| 7373 |
if (m_exclusion) { |
| 7374 |
m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(".", m_substring)); |
| 7375 |
} else { |
| 7376 |
m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(".", m_substring)); |
| 7377 |
} |
| 7378 |
} |
| 7379 |
if (m_exclusion) { |
| 7380 |
m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring)); |
| 7381 |
} else { |
| 7382 |
m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring)); |
| 7383 |
} |
| 7384 |
} |
| 7385 |
m_substring.clear(); |
| 7386 |
m_exclusion = false; |
| 7387 |
m_mode = None; |
| 7388 |
} |
| 7389 |
|
| 7390 |
} // namespace Catch |
| 7391 |
|
| 7392 |
|
| 7393 |
|
| 7394 |
#include <algorithm> |
| 7395 |
#include <cstring> |
| 7396 |
#include <ostream> |
| 7397 |
|
| 7398 |
namespace { |
| 7399 |
bool isWhitespace( char c ) { |
| 7400 |
return c == ' ' || c == '\t' || c == '\n' || c == '\r'; |
| 7401 |
} |
| 7402 |
|
| 7403 |
bool isBreakableBefore( char c ) { |
| 7404 |
static const char chars[] = "[({<|"; |
| 7405 |
return std::memchr( chars, c, sizeof( chars ) - 1 ) != nullptr; |
| 7406 |
} |
| 7407 |
|
| 7408 |
bool isBreakableAfter( char c ) { |
| 7409 |
static const char chars[] = "])}>.,:;*+-=&/\\"; |
| 7410 |
return std::memchr( chars, c, sizeof( chars ) - 1 ) != nullptr; |
| 7411 |
} |
| 7412 |
|
| 7413 |
} // namespace |
| 7414 |
|
| 7415 |
namespace Catch { |
| 7416 |
namespace TextFlow { |
| 7417 |
void AnsiSkippingString::preprocessString() { |
| 7418 |
for ( auto it = m_string.begin(); it != m_string.end(); ) { |
| 7419 |
// try to read through an ansi sequence |
| 7420 |
while ( it != m_string.end() && *it == '\033' && |
| 7421 |
it + 1 != m_string.end() && *( it + 1 ) == '[' ) { |
| 7422 |
auto cursor = it + 2; |
| 7423 |
while ( cursor != m_string.end() && |
| 7424 |
( isdigit( *cursor ) || *cursor == ';' ) ) { |
| 7425 |
++cursor; |
| 7426 |
} |
| 7427 |
if ( cursor == m_string.end() || *cursor != 'm' ) { |
| 7428 |
break; |
| 7429 |
} |
| 7430 |
// 'm' -> 0xff |
| 7431 |
*cursor = AnsiSkippingString::sentinel; |
| 7432 |
// if we've read an ansi sequence, set the iterator and |
| 7433 |
// return to the top of the loop |
| 7434 |
it = cursor + 1; |
| 7435 |
} |
| 7436 |
if ( it != m_string.end() ) { |
| 7437 |
++m_size; |
| 7438 |
++it; |
| 7439 |
} |
| 7440 |
} |
| 7441 |
} |
| 7442 |
|
| 7443 |
AnsiSkippingString::AnsiSkippingString( std::string const& text ): |
| 7444 |
m_string( text ) { |
| 7445 |
preprocessString(); |
| 7446 |
} |
| 7447 |
|
| 7448 |
AnsiSkippingString::AnsiSkippingString( std::string&& text ): |
| 7449 |
m_string( CATCH_MOVE( text ) ) { |
| 7450 |
preprocessString(); |
| 7451 |
} |
| 7452 |
|
| 7453 |
AnsiSkippingString::const_iterator AnsiSkippingString::begin() const { |
| 7454 |
return const_iterator( m_string ); |
| 7455 |
} |
| 7456 |
|
| 7457 |
AnsiSkippingString::const_iterator AnsiSkippingString::end() const { |
| 7458 |
return const_iterator( m_string, const_iterator::EndTag{} ); |
| 7459 |
} |
| 7460 |
|
| 7461 |
std::string AnsiSkippingString::substring( const_iterator begin, |
| 7462 |
const_iterator end ) const { |
| 7463 |
// There's one caveat here to an otherwise simple substring: when |
| 7464 |
// making a begin iterator we might have skipped ansi sequences at |
| 7465 |
// the start. If `begin` here is a begin iterator, skipped over |
| 7466 |
// initial ansi sequences, we'll use the true beginning of the |
| 7467 |
// string. Lastly: We need to transform any chars we replaced with |
| 7468 |
// 0xff back to 'm' |
| 7469 |
auto str = std::string( begin == this->begin() ? m_string.begin() |
| 7470 |
: begin.m_it, |
| 7471 |
end.m_it ); |
| 7472 |
std::transform( str.begin(), str.end(), str.begin(), []( char c ) { |
| 7473 |
return c == AnsiSkippingString::sentinel ? 'm' : c; |
| 7474 |
} ); |
| 7475 |
return str; |
| 7476 |
} |
| 7477 |
|
| 7478 |
void AnsiSkippingString::const_iterator::tryParseAnsiEscapes() { |
| 7479 |
// check if we've landed on an ansi sequence, and if so read through |
| 7480 |
// it |
| 7481 |
while ( m_it != m_string->end() && *m_it == '\033' && |
| 7482 |
m_it + 1 != m_string->end() && *( m_it + 1 ) == '[' ) { |
| 7483 |
auto cursor = m_it + 2; |
| 7484 |
while ( cursor != m_string->end() && |
| 7485 |
( isdigit( *cursor ) || *cursor == ';' ) ) { |
| 7486 |
++cursor; |
| 7487 |
} |
| 7488 |
if ( cursor == m_string->end() || |
| 7489 |
*cursor != AnsiSkippingString::sentinel ) { |
| 7490 |
break; |
| 7491 |
} |
| 7492 |
// if we've read an ansi sequence, set the iterator and |
| 7493 |
// return to the top of the loop |
| 7494 |
m_it = cursor + 1; |
| 7495 |
} |
| 7496 |
} |
| 7497 |
|
| 7498 |
void AnsiSkippingString::const_iterator::advance() { |
| 7499 |
assert( m_it != m_string->end() ); |
| 7500 |
m_it++; |
| 7501 |
tryParseAnsiEscapes(); |
| 7502 |
} |
| 7503 |
|
| 7504 |
void AnsiSkippingString::const_iterator::unadvance() { |
| 7505 |
assert( m_it != m_string->begin() ); |
| 7506 |
m_it--; |
| 7507 |
// if *m_it is 0xff, scan back to the \033 and then m_it-- once more |
| 7508 |
// (and repeat check) |
| 7509 |
while ( *m_it == AnsiSkippingString::sentinel ) { |
| 7510 |
while ( *m_it != '\033' ) { |
| 7511 |
assert( m_it != m_string->begin() ); |
| 7512 |
m_it--; |
| 7513 |
} |
| 7514 |
// if this happens, we must have been a begin iterator that had |
| 7515 |
// skipped over ansi sequences at the start of a string |
| 7516 |
assert( m_it != m_string->begin() ); |
| 7517 |
assert( *m_it == '\033' ); |
| 7518 |
m_it--; |
| 7519 |
} |
| 7520 |
} |
| 7521 |
|
| 7522 |
static bool isBoundary( AnsiSkippingString const& line, |
| 7523 |
AnsiSkippingString::const_iterator it ) { |
| 7524 |
return it == line.end() || |
| 7525 |
( isWhitespace( *it ) && |
| 7526 |
!isWhitespace( *it.oneBefore() ) ) || |
| 7527 |
isBreakableBefore( *it ) || |
| 7528 |
isBreakableAfter( *it.oneBefore() ); |
| 7529 |
} |
| 7530 |
|
| 7531 |
void Column::const_iterator::calcLength() { |
| 7532 |
m_addHyphen = false; |
| 7533 |
m_parsedTo = m_lineStart; |
| 7534 |
AnsiSkippingString const& current_line = m_column.m_string; |
| 7535 |
|
| 7536 |
if ( m_parsedTo == current_line.end() ) { |
| 7537 |
m_lineEnd = m_parsedTo; |
| 7538 |
return; |
| 7539 |
} |
| 7540 |
|
| 7541 |
assert( m_lineStart != current_line.end() ); |
| 7542 |
if ( *m_lineStart == '\n' ) { ++m_parsedTo; } |
| 7543 |
|
| 7544 |
const auto maxLineLength = m_column.m_width - indentSize(); |
| 7545 |
std::size_t lineLength = 0; |
| 7546 |
while ( m_parsedTo != current_line.end() && |
| 7547 |
lineLength < maxLineLength && *m_parsedTo != '\n' ) { |
| 7548 |
++m_parsedTo; |
| 7549 |
++lineLength; |
| 7550 |
} |
| 7551 |
|
| 7552 |
// If we encountered a newline before the column is filled, |
| 7553 |
// then we linebreak at the newline and consider this line |
| 7554 |
// finished. |
| 7555 |
if ( lineLength < maxLineLength ) { |
| 7556 |
m_lineEnd = m_parsedTo; |
| 7557 |
} else { |
| 7558 |
// Look for a natural linebreak boundary in the column |
| 7559 |
// (We look from the end, so that the first found boundary is |
| 7560 |
// the right one) |
| 7561 |
m_lineEnd = m_parsedTo; |
| 7562 |
while ( lineLength > 0 && |
| 7563 |
!isBoundary( current_line, m_lineEnd ) ) { |
| 7564 |
--lineLength; |
| 7565 |
--m_lineEnd; |
| 7566 |
} |
| 7567 |
while ( lineLength > 0 && |
| 7568 |
isWhitespace( *m_lineEnd.oneBefore() ) ) { |
| 7569 |
--lineLength; |
| 7570 |
--m_lineEnd; |
| 7571 |
} |
| 7572 |
|
| 7573 |
// If we found one, then that is where we linebreak, otherwise |
| 7574 |
// we have to split text with a hyphen |
| 7575 |
if ( lineLength == 0 ) { |
| 7576 |
m_addHyphen = true; |
| 7577 |
m_lineEnd = m_parsedTo.oneBefore(); |
| 7578 |
} |
| 7579 |
} |
| 7580 |
} |
| 7581 |
|
| 7582 |
size_t Column::const_iterator::indentSize() const { |
| 7583 |
auto initial = m_lineStart == m_column.m_string.begin() |
| 7584 |
? m_column.m_initialIndent |
| 7585 |
: std::string::npos; |
| 7586 |
return initial == std::string::npos ? m_column.m_indent : initial; |
| 7587 |
} |
| 7588 |
|
| 7589 |
std::string Column::const_iterator::addIndentAndSuffix( |
| 7590 |
AnsiSkippingString::const_iterator start, |
| 7591 |
AnsiSkippingString::const_iterator end ) const { |
| 7592 |
std::string ret; |
| 7593 |
const auto desired_indent = indentSize(); |
| 7594 |
// ret.reserve( desired_indent + (end - start) + m_addHyphen ); |
| 7595 |
ret.append( desired_indent, ' ' ); |
| 7596 |
// ret.append( start, end ); |
| 7597 |
ret += m_column.m_string.substring( start, end ); |
| 7598 |
if ( m_addHyphen ) { ret.push_back( '-' ); } |
| 7599 |
|
| 7600 |
return ret; |
| 7601 |
} |
| 7602 |
|
| 7603 |
Column::const_iterator::const_iterator( Column const& column ): |
| 7604 |
m_column( column ), |
| 7605 |
m_lineStart( column.m_string.begin() ), |
| 7606 |
m_lineEnd( column.m_string.begin() ), |
| 7607 |
m_parsedTo( column.m_string.begin() ) { |
| 7608 |
assert( m_column.m_width > m_column.m_indent ); |
| 7609 |
assert( m_column.m_initialIndent == std::string::npos || |
| 7610 |
m_column.m_width > m_column.m_initialIndent ); |
| 7611 |
calcLength(); |
| 7612 |
if ( m_lineStart == m_lineEnd ) { |
| 7613 |
m_lineStart = m_column.m_string.end(); |
| 7614 |
} |
| 7615 |
} |
| 7616 |
|
| 7617 |
std::string Column::const_iterator::operator*() const { |
| 7618 |
assert( m_lineStart <= m_parsedTo ); |
| 7619 |
return addIndentAndSuffix( m_lineStart, m_lineEnd ); |
| 7620 |
} |
| 7621 |
|
| 7622 |
Column::const_iterator& Column::const_iterator::operator++() { |
| 7623 |
m_lineStart = m_lineEnd; |
| 7624 |
AnsiSkippingString const& current_line = m_column.m_string; |
| 7625 |
if ( m_lineStart != current_line.end() && *m_lineStart == '\n' ) { |
| 7626 |
m_lineStart++; |
| 7627 |
} else { |
| 7628 |
while ( m_lineStart != current_line.end() && |
| 7629 |
isWhitespace( *m_lineStart ) ) { |
| 7630 |
++m_lineStart; |
| 7631 |
} |
| 7632 |
} |
| 7633 |
|
| 7634 |
if ( m_lineStart != current_line.end() ) { calcLength(); } |
| 7635 |
return *this; |
| 7636 |
} |
| 7637 |
|
| 7638 |
Column::const_iterator Column::const_iterator::operator++( int ) { |
| 7639 |
const_iterator prev( *this ); |
| 7640 |
operator++(); |
| 7641 |
return prev; |
| 7642 |
} |
| 7643 |
|
| 7644 |
std::ostream& operator<<( std::ostream& os, Column const& col ) { |
| 7645 |
bool first = true; |
| 7646 |
for ( auto line : col ) { |
| 7647 |
if ( first ) { |
| 7648 |
first = false; |
| 7649 |
} else { |
| 7650 |
os << '\n'; |
| 7651 |
} |
| 7652 |
os << line; |
| 7653 |
} |
| 7654 |
return os; |
| 7655 |
} |
| 7656 |
|
| 7657 |
Column Spacer( size_t spaceWidth ) { |
| 7658 |
Column ret{ "" }; |
| 7659 |
ret.width( spaceWidth ); |
| 7660 |
return ret; |
| 7661 |
} |
| 7662 |
|
| 7663 |
Columns::iterator::iterator( Columns const& columns, EndTag ): |
| 7664 |
m_columns( columns.m_columns ), m_activeIterators( 0 ) { |
| 7665 |
|
| 7666 |
m_iterators.reserve( m_columns.size() ); |
| 7667 |
for ( auto const& col : m_columns ) { |
| 7668 |
m_iterators.push_back( col.end() ); |
| 7669 |
} |
| 7670 |
} |
| 7671 |
|
| 7672 |
Columns::iterator::iterator( Columns const& columns ): |
| 7673 |
m_columns( columns.m_columns ), |
| 7674 |
m_activeIterators( m_columns.size() ) { |
| 7675 |
|
| 7676 |
m_iterators.reserve( m_columns.size() ); |
| 7677 |
for ( auto const& col : m_columns ) { |
| 7678 |
m_iterators.push_back( col.begin() ); |
| 7679 |
} |
| 7680 |
} |
| 7681 |
|
| 7682 |
std::string Columns::iterator::operator*() const { |
| 7683 |
std::string row, padding; |
| 7684 |
|
| 7685 |
for ( size_t i = 0; i < m_columns.size(); ++i ) { |
| 7686 |
const auto width = m_columns[i].width(); |
| 7687 |
if ( m_iterators[i] != m_columns[i].end() ) { |
| 7688 |
std::string col = *m_iterators[i]; |
| 7689 |
row += padding; |
| 7690 |
row += col; |
| 7691 |
|
| 7692 |
padding.clear(); |
| 7693 |
if ( col.size() < width ) { |
| 7694 |
padding.append( width - col.size(), ' ' ); |
| 7695 |
} |
| 7696 |
} else { |
| 7697 |
padding.append( width, ' ' ); |
| 7698 |
} |
| 7699 |
} |
| 7700 |
return row; |
| 7701 |
} |
| 7702 |
|
| 7703 |
Columns::iterator& Columns::iterator::operator++() { |
| 7704 |
for ( size_t i = 0; i < m_columns.size(); ++i ) { |
| 7705 |
if ( m_iterators[i] != m_columns[i].end() ) { |
| 7706 |
++m_iterators[i]; |
| 7707 |
} |
| 7708 |
} |
| 7709 |
return *this; |
| 7710 |
} |
| 7711 |
|
| 7712 |
Columns::iterator Columns::iterator::operator++( int ) { |
| 7713 |
iterator prev( *this ); |
| 7714 |
operator++(); |
| 7715 |
return prev; |
| 7716 |
} |
| 7717 |
|
| 7718 |
std::ostream& operator<<( std::ostream& os, Columns const& cols ) { |
| 7719 |
bool first = true; |
| 7720 |
for ( auto line : cols ) { |
| 7721 |
if ( first ) { |
| 7722 |
first = false; |
| 7723 |
} else { |
| 7724 |
os << '\n'; |
| 7725 |
} |
| 7726 |
os << line; |
| 7727 |
} |
| 7728 |
return os; |
| 7729 |
} |
| 7730 |
|
| 7731 |
Columns operator+( Column const& lhs, Column const& rhs ) { |
| 7732 |
Columns cols; |
| 7733 |
cols += lhs; |
| 7734 |
cols += rhs; |
| 7735 |
return cols; |
| 7736 |
} |
| 7737 |
Columns operator+( Column&& lhs, Column&& rhs ) { |
| 7738 |
Columns cols; |
| 7739 |
cols += CATCH_MOVE( lhs ); |
| 7740 |
cols += CATCH_MOVE( rhs ); |
| 7741 |
return cols; |
| 7742 |
} |
| 7743 |
|
| 7744 |
Columns& operator+=( Columns& lhs, Column const& rhs ) { |
| 7745 |
lhs.m_columns.push_back( rhs ); |
| 7746 |
return lhs; |
| 7747 |
} |
| 7748 |
Columns& operator+=( Columns& lhs, Column&& rhs ) { |
| 7749 |
lhs.m_columns.push_back( CATCH_MOVE( rhs ) ); |
| 7750 |
return lhs; |
| 7751 |
} |
| 7752 |
Columns operator+( Columns const& lhs, Column const& rhs ) { |
| 7753 |
auto combined( lhs ); |
| 7754 |
combined += rhs; |
| 7755 |
return combined; |
| 7756 |
} |
| 7757 |
Columns operator+( Columns&& lhs, Column&& rhs ) { |
| 7758 |
lhs += CATCH_MOVE( rhs ); |
| 7759 |
return CATCH_MOVE( lhs ); |
| 7760 |
} |
| 7761 |
|
| 7762 |
} // namespace TextFlow |
| 7763 |
} // namespace Catch |
| 7764 |
|
| 7765 |
|
| 7766 |
|
| 7767 |
|
| 7768 |
#include <exception> |
| 7769 |
|
| 7770 |
namespace Catch { |
| 7771 |
bool uncaught_exceptions() { |
| 7772 |
#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) |
| 7773 |
return false; |
| 7774 |
#elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) |
| 7775 |
return std::uncaught_exceptions() > 0; |
| 7776 |
#else |
| 7777 |
return std::uncaught_exception(); |
| 7778 |
#endif |
| 7779 |
} |
| 7780 |
} // end namespace Catch |
| 7781 |
|
| 7782 |
|
| 7783 |
|
| 7784 |
namespace Catch { |
| 7785 |
|
| 7786 |
WildcardPattern::WildcardPattern( std::string const& pattern, |
| 7787 |
CaseSensitive caseSensitivity ) |
| 7788 |
: m_caseSensitivity( caseSensitivity ), |
| 7789 |
m_pattern( normaliseString( pattern ) ) |
| 7790 |
{ |
| 7791 |
if( startsWith( m_pattern, '*' ) ) { |
| 7792 |
m_pattern = m_pattern.substr( 1 ); |
| 7793 |
m_wildcard = WildcardAtStart; |
| 7794 |
} |
| 7795 |
if( endsWith( m_pattern, '*' ) ) { |
| 7796 |
m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); |
| 7797 |
m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd ); |
| 7798 |
} |
| 7799 |
} |
| 7800 |
|
| 7801 |
bool WildcardPattern::matches( std::string const& str ) const { |
| 7802 |
switch( m_wildcard ) { |
| 7803 |
case NoWildcard: |
| 7804 |
return m_pattern == normaliseString( str ); |
| 7805 |
case WildcardAtStart: |
| 7806 |
return endsWith( normaliseString( str ), m_pattern ); |
| 7807 |
case WildcardAtEnd: |
| 7808 |
return startsWith( normaliseString( str ), m_pattern ); |
| 7809 |
case WildcardAtBothEnds: |
| 7810 |
return contains( normaliseString( str ), m_pattern ); |
| 7811 |
default: |
| 7812 |
CATCH_INTERNAL_ERROR( "Unknown enum" ); |
| 7813 |
} |
| 7814 |
} |
| 7815 |
|
| 7816 |
std::string WildcardPattern::normaliseString( std::string const& str ) const { |
| 7817 |
return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str ); |
| 7818 |
} |
| 7819 |
} |
| 7820 |
|
| 7821 |
|
| 7822 |
// Note: swapping these two includes around causes MSVC to error out |
| 7823 |
// while in /permissive- mode. No, I don't know why. |
| 7824 |
// Tested on VS 2019, 18.{3, 4}.x |
| 7825 |
|
| 7826 |
#include <cstdint> |
| 7827 |
#include <iomanip> |
| 7828 |
#include <type_traits> |
| 7829 |
|
| 7830 |
namespace Catch { |
| 7831 |
|
| 7832 |
namespace { |
| 7833 |
|
| 7834 |
size_t trailingBytes(unsigned char c) { |
| 7835 |
if ((c & 0xE0) == 0xC0) { |
| 7836 |
return 2; |
| 7837 |
} |
| 7838 |
if ((c & 0xF0) == 0xE0) { |
| 7839 |
return 3; |
| 7840 |
} |
| 7841 |
if ((c & 0xF8) == 0xF0) { |
| 7842 |
return 4; |
| 7843 |
} |
| 7844 |
CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); |
| 7845 |
} |
| 7846 |
|
| 7847 |
uint32_t headerValue(unsigned char c) { |
| 7848 |
if ((c & 0xE0) == 0xC0) { |
| 7849 |
return c & 0x1F; |
| 7850 |
} |
| 7851 |
if ((c & 0xF0) == 0xE0) { |
| 7852 |
return c & 0x0F; |
| 7853 |
} |
| 7854 |
if ((c & 0xF8) == 0xF0) { |
| 7855 |
return c & 0x07; |
| 7856 |
} |
| 7857 |
CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); |
| 7858 |
} |
| 7859 |
|
| 7860 |
void hexEscapeChar(std::ostream& os, unsigned char c) { |
| 7861 |
std::ios_base::fmtflags f(os.flags()); |
| 7862 |
os << "\\x" |
| 7863 |
<< std::uppercase << std::hex << std::setfill('0') << std::setw(2) |
| 7864 |
<< static_cast<int>(c); |
| 7865 |
os.flags(f); |
| 7866 |
} |
| 7867 |
|
| 7868 |
constexpr bool shouldNewline(XmlFormatting fmt) { |
| 7869 |
return !!(static_cast<std::underlying_type_t<XmlFormatting>>(fmt & XmlFormatting::Newline)); |
| 7870 |
} |
| 7871 |
|
| 7872 |
constexpr bool shouldIndent(XmlFormatting fmt) { |
| 7873 |
return !!(static_cast<std::underlying_type_t<XmlFormatting>>(fmt & XmlFormatting::Indent)); |
| 7874 |
} |
| 7875 |
|
| 7876 |
} // anonymous namespace |
| 7877 |
|
| 7878 |
void XmlEncode::encodeTo( std::ostream& os ) const { |
| 7879 |
// Apostrophe escaping not necessary if we always use " to write attributes |
| 7880 |
// (see: http://www.w3.org/TR/xml/#syntax) |
| 7881 |
|
| 7882 |
for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { |
| 7883 |
unsigned char c = static_cast<unsigned char>(m_str[idx]); |
| 7884 |
switch (c) { |
| 7885 |
case '<': os << "<"; break; |
| 7886 |
case '&': os << "&"; break; |
| 7887 |
|
| 7888 |
case '>': |
| 7889 |
// See: http://www.w3.org/TR/xml/#syntax |
| 7890 |
if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') |
| 7891 |
os << ">"; |
| 7892 |
else |
| 7893 |
os << c; |
| 7894 |
break; |
| 7895 |
|
| 7896 |
case '\"': |
| 7897 |
if (m_forWhat == ForAttributes) |
| 7898 |
os << """; |
| 7899 |
else |
| 7900 |
os << c; |
| 7901 |
break; |
| 7902 |
|
| 7903 |
default: |
| 7904 |
// Check for control characters and invalid utf-8 |
| 7905 |
|
| 7906 |
// Escape control characters in standard ascii |
| 7907 |
// see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 7908 |
if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { |
| 7909 |
hexEscapeChar(os, c); |
| 7910 |
break; |
| 7911 |
} |
| 7912 |
|
| 7913 |
// Plain ASCII: Write it to stream |
| 7914 |
if (c < 0x7F) { |
| 7915 |
os << c; |
| 7916 |
break; |
| 7917 |
} |
| 7918 |
|
| 7919 |
// UTF-8 territory |
| 7920 |
// Check if the encoding is valid and if it is not, hex escape bytes. |
| 7921 |
// Important: We do not check the exact decoded values for validity, only the encoding format |
| 7922 |
// First check that this bytes is a valid lead byte: |
| 7923 |
// This means that it is not encoded as 1111 1XXX |
| 7924 |
// Or as 10XX XXXX |
| 7925 |
if (c < 0xC0 || |
| 7926 |
c >= 0xF8) { |
| 7927 |
hexEscapeChar(os, c); |
| 7928 |
break; |
| 7929 |
} |
| 7930 |
|
| 7931 |
auto encBytes = trailingBytes(c); |
| 7932 |
// Are there enough bytes left to avoid accessing out-of-bounds memory? |
| 7933 |
if (idx + encBytes - 1 >= m_str.size()) { |
| 7934 |
hexEscapeChar(os, c); |
| 7935 |
break; |
| 7936 |
} |
| 7937 |
// The header is valid, check data |
| 7938 |
// The next encBytes bytes must together be a valid utf-8 |
| 7939 |
// This means: bitpattern 10XX XXXX and the extracted value is sane (ish) |
| 7940 |
bool valid = true; |
| 7941 |
uint32_t value = headerValue(c); |
| 7942 |
for (std::size_t n = 1; n < encBytes; ++n) { |
| 7943 |
unsigned char nc = static_cast<unsigned char>(m_str[idx + n]); |
| 7944 |
valid &= ((nc & 0xC0) == 0x80); |
| 7945 |
value = (value << 6) | (nc & 0x3F); |
| 7946 |
} |
| 7947 |
|
| 7948 |
if ( |
| 7949 |
// Wrong bit pattern of following bytes |
| 7950 |
(!valid) || |
| 7951 |
// Overlong encodings |
| 7952 |
(value < 0x80) || |
| 7953 |
(0x80 <= value && value < 0x800 && encBytes > 2) || |
| 7954 |
(0x800 < value && value < 0x10000 && encBytes > 3) || |
| 7955 |
// Encoded value out of range |
| 7956 |
(value >= 0x110000) |
| 7957 |
) { |
| 7958 |
hexEscapeChar(os, c); |
| 7959 |
break; |
| 7960 |
} |
| 7961 |
|
| 7962 |
// If we got here, this is in fact a valid(ish) utf-8 sequence |
| 7963 |
for (std::size_t n = 0; n < encBytes; ++n) { |
| 7964 |
os << m_str[idx + n]; |
| 7965 |
} |
| 7966 |
idx += encBytes - 1; |
| 7967 |
break; |
| 7968 |
} |
| 7969 |
} |
| 7970 |
} |
| 7971 |
|
| 7972 |
std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { |
| 7973 |
xmlEncode.encodeTo( os ); |
| 7974 |
return os; |
| 7975 |
} |
| 7976 |
|
| 7977 |
XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt ) |
| 7978 |
: m_writer( writer ), |
| 7979 |
m_fmt(fmt) |
| 7980 |
{} |
| 7981 |
|
| 7982 |
XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept |
| 7983 |
: m_writer( other.m_writer ), |
| 7984 |
m_fmt(other.m_fmt) |
| 7985 |
{ |
| 7986 |
other.m_writer = nullptr; |
| 7987 |
other.m_fmt = XmlFormatting::None; |
| 7988 |
} |
| 7989 |
XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept { |
| 7990 |
if ( m_writer ) { |
| 7991 |
m_writer->endElement(); |
| 7992 |
} |
| 7993 |
m_writer = other.m_writer; |
| 7994 |
other.m_writer = nullptr; |
| 7995 |
m_fmt = other.m_fmt; |
| 7996 |
other.m_fmt = XmlFormatting::None; |
| 7997 |
return *this; |
| 7998 |
} |
| 7999 |
|
| 8000 |
|
| 8001 |
XmlWriter::ScopedElement::~ScopedElement() { |
| 8002 |
if (m_writer) { |
| 8003 |
m_writer->endElement(m_fmt); |
| 8004 |
} |
| 8005 |
} |
| 8006 |
|
| 8007 |
XmlWriter::ScopedElement& |
| 8008 |
XmlWriter::ScopedElement::writeText( StringRef text, XmlFormatting fmt ) { |
| 8009 |
m_writer->writeText( text, fmt ); |
| 8010 |
return *this; |
| 8011 |
} |
| 8012 |
|
| 8013 |
XmlWriter::ScopedElement& |
| 8014 |
XmlWriter::ScopedElement::writeAttribute( StringRef name, |
| 8015 |
StringRef attribute ) { |
| 8016 |
m_writer->writeAttribute( name, attribute ); |
| 8017 |
return *this; |
| 8018 |
} |
| 8019 |
|
| 8020 |
|
| 8021 |
XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) |
| 8022 |
{ |
| 8023 |
writeDeclaration(); |
| 8024 |
} |
| 8025 |
|
| 8026 |
XmlWriter::~XmlWriter() { |
| 8027 |
while (!m_tags.empty()) { |
| 8028 |
endElement(); |
| 8029 |
} |
| 8030 |
newlineIfNecessary(); |
| 8031 |
} |
| 8032 |
|
| 8033 |
XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) { |
| 8034 |
ensureTagClosed(); |
| 8035 |
newlineIfNecessary(); |
| 8036 |
if (shouldIndent(fmt)) { |
| 8037 |
m_os << m_indent; |
| 8038 |
m_indent += " "; |
| 8039 |
} |
| 8040 |
m_os << '<' << name; |
| 8041 |
m_tags.push_back( name ); |
| 8042 |
m_tagIsOpen = true; |
| 8043 |
applyFormatting(fmt); |
| 8044 |
return *this; |
| 8045 |
} |
| 8046 |
|
| 8047 |
XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) { |
| 8048 |
ScopedElement scoped( this, fmt ); |
| 8049 |
startElement( name, fmt ); |
| 8050 |
return scoped; |
| 8051 |
} |
| 8052 |
|
| 8053 |
XmlWriter& XmlWriter::endElement(XmlFormatting fmt) { |
| 8054 |
m_indent = m_indent.substr(0, m_indent.size() - 2); |
| 8055 |
|
| 8056 |
if( m_tagIsOpen ) { |
| 8057 |
m_os << "/>"; |
| 8058 |
m_tagIsOpen = false; |
| 8059 |
} else { |
| 8060 |
newlineIfNecessary(); |
| 8061 |
if (shouldIndent(fmt)) { |
| 8062 |
m_os << m_indent; |
| 8063 |
} |
| 8064 |
m_os << "</" << m_tags.back() << '>'; |
| 8065 |
} |
| 8066 |
m_os << std::flush; |
| 8067 |
applyFormatting(fmt); |
| 8068 |
m_tags.pop_back(); |
| 8069 |
return *this; |
| 8070 |
} |
| 8071 |
|
| 8072 |
XmlWriter& XmlWriter::writeAttribute( StringRef name, |
| 8073 |
StringRef attribute ) { |
| 8074 |
if( !name.empty() && !attribute.empty() ) |
| 8075 |
m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; |
| 8076 |
return *this; |
| 8077 |
} |
| 8078 |
|
| 8079 |
XmlWriter& XmlWriter::writeAttribute( StringRef name, bool attribute ) { |
| 8080 |
writeAttribute(name, (attribute ? "true"_sr : "false"_sr)); |
| 8081 |
return *this; |
| 8082 |
} |
| 8083 |
|
| 8084 |
XmlWriter& XmlWriter::writeAttribute( StringRef name, |
| 8085 |
char const* attribute ) { |
| 8086 |
writeAttribute( name, StringRef( attribute ) ); |
| 8087 |
return *this; |
| 8088 |
} |
| 8089 |
|
| 8090 |
XmlWriter& XmlWriter::writeText( StringRef text, XmlFormatting fmt ) { |
| 8091 |
CATCH_ENFORCE(!m_tags.empty(), "Cannot write text as top level element"); |
| 8092 |
if( !text.empty() ){ |
| 8093 |
bool tagWasOpen = m_tagIsOpen; |
| 8094 |
ensureTagClosed(); |
| 8095 |
if (tagWasOpen && shouldIndent(fmt)) { |
| 8096 |
m_os << m_indent; |
| 8097 |
} |
| 8098 |
m_os << XmlEncode( text, XmlEncode::ForTextNodes ); |
| 8099 |
applyFormatting(fmt); |
| 8100 |
} |
| 8101 |
return *this; |
| 8102 |
} |
| 8103 |
|
| 8104 |
XmlWriter& XmlWriter::writeComment( StringRef text, XmlFormatting fmt ) { |
| 8105 |
ensureTagClosed(); |
| 8106 |
if (shouldIndent(fmt)) { |
| 8107 |
m_os << m_indent; |
| 8108 |
} |
| 8109 |
m_os << "<!-- " << text << " -->"; |
| 8110 |
applyFormatting(fmt); |
| 8111 |
return *this; |
| 8112 |
} |
| 8113 |
|
| 8114 |
void XmlWriter::writeStylesheetRef( StringRef url ) { |
| 8115 |
m_os << R"(<?xml-stylesheet type="text/xsl" href=")" << url << R"("?>)" << '\n'; |
| 8116 |
} |
| 8117 |
|
| 8118 |
void XmlWriter::ensureTagClosed() { |
| 8119 |
if( m_tagIsOpen ) { |
| 8120 |
m_os << '>' << std::flush; |
| 8121 |
newlineIfNecessary(); |
| 8122 |
m_tagIsOpen = false; |
| 8123 |
} |
| 8124 |
} |
| 8125 |
|
| 8126 |
void XmlWriter::applyFormatting(XmlFormatting fmt) { |
| 8127 |
m_needsNewline = shouldNewline(fmt); |
| 8128 |
} |
| 8129 |
|
| 8130 |
void XmlWriter::writeDeclaration() { |
| 8131 |
m_os << R"(<?xml version="1.0" encoding="UTF-8"?>)" << '\n'; |
| 8132 |
} |
| 8133 |
|
| 8134 |
void XmlWriter::newlineIfNecessary() { |
| 8135 |
if( m_needsNewline ) { |
| 8136 |
m_os << '\n' << std::flush; |
| 8137 |
m_needsNewline = false; |
| 8138 |
} |
| 8139 |
} |
| 8140 |
} |
| 8141 |
|
| 8142 |
|
| 8143 |
|
| 8144 |
|
| 8145 |
|
| 8146 |
namespace Catch { |
| 8147 |
namespace Matchers { |
| 8148 |
|
| 8149 |
std::string MatcherUntypedBase::toString() const { |
| 8150 |
if (m_cachedToString.empty()) { |
| 8151 |
m_cachedToString = describe(); |
| 8152 |
} |
| 8153 |
return m_cachedToString; |
| 8154 |
} |
| 8155 |
|
| 8156 |
MatcherUntypedBase::~MatcherUntypedBase() = default; |
| 8157 |
|
| 8158 |
} // namespace Matchers |
| 8159 |
} // namespace Catch |
| 8160 |
|
| 8161 |
|
| 8162 |
|
| 8163 |
|
| 8164 |
namespace Catch { |
| 8165 |
namespace Matchers { |
| 8166 |
|
| 8167 |
std::string IsEmptyMatcher::describe() const { |
| 8168 |
return "is empty"; |
| 8169 |
} |
| 8170 |
|
| 8171 |
std::string HasSizeMatcher::describe() const { |
| 8172 |
ReusableStringStream sstr; |
| 8173 |
sstr << "has size == " << m_target_size; |
| 8174 |
return sstr.str(); |
| 8175 |
} |
| 8176 |
|
| 8177 |
IsEmptyMatcher IsEmpty() { |
| 8178 |
return {}; |
| 8179 |
} |
| 8180 |
|
| 8181 |
HasSizeMatcher SizeIs(std::size_t sz) { |
| 8182 |
return HasSizeMatcher{ sz }; |
| 8183 |
} |
| 8184 |
|
| 8185 |
} // end namespace Matchers |
| 8186 |
} // end namespace Catch |
| 8187 |
|
| 8188 |
|
| 8189 |
|
| 8190 |
namespace Catch { |
| 8191 |
namespace Matchers { |
| 8192 |
|
| 8193 |
bool ExceptionMessageMatcher::match(std::exception const& ex) const { |
| 8194 |
return ex.what() == m_message; |
| 8195 |
} |
| 8196 |
|
| 8197 |
std::string ExceptionMessageMatcher::describe() const { |
| 8198 |
return "exception message matches \"" + m_message + '"'; |
| 8199 |
} |
| 8200 |
|
| 8201 |
ExceptionMessageMatcher Message(std::string const& message) { |
| 8202 |
return ExceptionMessageMatcher(message); |
| 8203 |
} |
| 8204 |
|
| 8205 |
} // namespace Matchers |
| 8206 |
} // namespace Catch |
| 8207 |
|
| 8208 |
|
| 8209 |
|
| 8210 |
#include <algorithm> |
| 8211 |
#include <cmath> |
| 8212 |
#include <cstdlib> |
| 8213 |
#include <cstdint> |
| 8214 |
#include <sstream> |
| 8215 |
#include <iomanip> |
| 8216 |
#include <limits> |
| 8217 |
|
| 8218 |
|
| 8219 |
namespace Catch { |
| 8220 |
namespace { |
| 8221 |
|
| 8222 |
template <typename FP> |
| 8223 |
bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) { |
| 8224 |
// Comparison with NaN should always be false. |
| 8225 |
// This way we can rule it out before getting into the ugly details |
| 8226 |
if (Catch::isnan(lhs) || Catch::isnan(rhs)) { |
| 8227 |
return false; |
| 8228 |
} |
| 8229 |
|
| 8230 |
// This should also handle positive and negative zeros, infinities |
| 8231 |
const auto ulpDist = ulpDistance(lhs, rhs); |
| 8232 |
|
| 8233 |
return ulpDist <= maxUlpDiff; |
| 8234 |
} |
| 8235 |
|
| 8236 |
|
| 8237 |
template <typename FP> |
| 8238 |
FP step(FP start, FP direction, uint64_t steps) { |
| 8239 |
for (uint64_t i = 0; i < steps; ++i) { |
| 8240 |
start = Catch::nextafter(start, direction); |
| 8241 |
} |
| 8242 |
return start; |
| 8243 |
} |
| 8244 |
|
| 8245 |
// Performs equivalent check of std::fabs(lhs - rhs) <= margin |
| 8246 |
// But without the subtraction to allow for INFINITY in comparison |
| 8247 |
bool marginComparison(double lhs, double rhs, double margin) { |
| 8248 |
return (lhs + margin >= rhs) && (rhs + margin >= lhs); |
| 8249 |
} |
| 8250 |
|
| 8251 |
template <typename FloatingPoint> |
| 8252 |
void write(std::ostream& out, FloatingPoint num) { |
| 8253 |
out << std::scientific |
| 8254 |
<< std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1) |
| 8255 |
<< num; |
| 8256 |
} |
| 8257 |
|
| 8258 |
} // end anonymous namespace |
| 8259 |
|
| 8260 |
namespace Matchers { |
| 8261 |
namespace Detail { |
| 8262 |
|
| 8263 |
enum class FloatingPointKind : uint8_t { |
| 8264 |
Float, |
| 8265 |
Double |
| 8266 |
}; |
| 8267 |
|
| 8268 |
} // end namespace Detail |
| 8269 |
|
| 8270 |
|
| 8271 |
WithinAbsMatcher::WithinAbsMatcher(double target, double margin) |
| 8272 |
:m_target{ target }, m_margin{ margin } { |
| 8273 |
CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.' |
| 8274 |
<< " Margin has to be non-negative."); |
| 8275 |
} |
| 8276 |
|
| 8277 |
// Performs equivalent check of std::fabs(lhs - rhs) <= margin |
| 8278 |
// But without the subtraction to allow for INFINITY in comparison |
| 8279 |
bool WithinAbsMatcher::match(double const& matchee) const { |
| 8280 |
return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee); |
| 8281 |
} |
| 8282 |
|
| 8283 |
std::string WithinAbsMatcher::describe() const { |
| 8284 |
return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target); |
| 8285 |
} |
| 8286 |
|
| 8287 |
|
| 8288 |
WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, Detail::FloatingPointKind baseType) |
| 8289 |
:m_target{ target }, m_ulps{ ulps }, m_type{ baseType } { |
| 8290 |
CATCH_ENFORCE(m_type == Detail::FloatingPointKind::Double |
| 8291 |
|| m_ulps < (std::numeric_limits<uint32_t>::max)(), |
| 8292 |
"Provided ULP is impossibly large for a float comparison."); |
| 8293 |
CATCH_ENFORCE( std::numeric_limits<double>::is_iec559, |
| 8294 |
"WithinUlp matcher only supports platforms with " |
| 8295 |
"IEEE-754 compatible floating point representation" ); |
| 8296 |
} |
| 8297 |
|
| 8298 |
#if defined(__clang__) |
| 8299 |
#pragma clang diagnostic push |
| 8300 |
// Clang <3.5 reports on the default branch in the switch below |
| 8301 |
#pragma clang diagnostic ignored "-Wunreachable-code" |
| 8302 |
#endif |
| 8303 |
|
| 8304 |
bool WithinUlpsMatcher::match(double const& matchee) const { |
| 8305 |
switch (m_type) { |
| 8306 |
case Detail::FloatingPointKind::Float: |
| 8307 |
return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps); |
| 8308 |
case Detail::FloatingPointKind::Double: |
| 8309 |
return almostEqualUlps<double>(matchee, m_target, m_ulps); |
| 8310 |
default: |
| 8311 |
CATCH_INTERNAL_ERROR( "Unknown Detail::FloatingPointKind value" ); |
| 8312 |
} |
| 8313 |
} |
| 8314 |
|
| 8315 |
#if defined(__clang__) |
| 8316 |
#pragma clang diagnostic pop |
| 8317 |
#endif |
| 8318 |
|
| 8319 |
std::string WithinUlpsMatcher::describe() const { |
| 8320 |
std::stringstream ret; |
| 8321 |
|
| 8322 |
ret << "is within " << m_ulps << " ULPs of "; |
| 8323 |
|
| 8324 |
if (m_type == Detail::FloatingPointKind::Float) { |
| 8325 |
write(ret, static_cast<float>(m_target)); |
| 8326 |
ret << 'f'; |
| 8327 |
} else { |
| 8328 |
write(ret, m_target); |
| 8329 |
} |
| 8330 |
|
| 8331 |
ret << " (["; |
| 8332 |
if (m_type == Detail::FloatingPointKind::Double) { |
| 8333 |
write( ret, |
| 8334 |
step( m_target, |
| 8335 |
-std::numeric_limits<double>::infinity(), |
| 8336 |
m_ulps ) ); |
| 8337 |
ret << ", "; |
| 8338 |
write( ret, |
| 8339 |
step( m_target, |
| 8340 |
std::numeric_limits<double>::infinity(), |
| 8341 |
m_ulps ) ); |
| 8342 |
} else { |
| 8343 |
// We have to cast INFINITY to float because of MinGW, see #1782 |
| 8344 |
write( ret, |
| 8345 |
step( static_cast<float>( m_target ), |
| 8346 |
-std::numeric_limits<float>::infinity(), |
| 8347 |
m_ulps ) ); |
| 8348 |
ret << ", "; |
| 8349 |
write( ret, |
| 8350 |
step( static_cast<float>( m_target ), |
| 8351 |
std::numeric_limits<float>::infinity(), |
| 8352 |
m_ulps ) ); |
| 8353 |
} |
| 8354 |
ret << "])"; |
| 8355 |
|
| 8356 |
return ret.str(); |
| 8357 |
} |
| 8358 |
|
| 8359 |
WithinRelMatcher::WithinRelMatcher(double target, double epsilon): |
| 8360 |
m_target(target), |
| 8361 |
m_epsilon(epsilon){ |
| 8362 |
CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense."); |
| 8363 |
CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense."); |
| 8364 |
} |
| 8365 |
|
| 8366 |
bool WithinRelMatcher::match(double const& matchee) const { |
| 8367 |
const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target)); |
| 8368 |
return marginComparison(matchee, m_target, |
| 8369 |
std::isinf(relMargin)? 0 : relMargin); |
| 8370 |
} |
| 8371 |
|
| 8372 |
std::string WithinRelMatcher::describe() const { |
| 8373 |
Catch::ReusableStringStream sstr; |
| 8374 |
sstr << "and " << ::Catch::Detail::stringify(m_target) << " are within " << m_epsilon * 100. << "% of each other"; |
| 8375 |
return sstr.str(); |
| 8376 |
} |
| 8377 |
|
| 8378 |
|
| 8379 |
WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) { |
| 8380 |
return WithinUlpsMatcher(target, maxUlpDiff, Detail::FloatingPointKind::Double); |
| 8381 |
} |
| 8382 |
|
| 8383 |
WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) { |
| 8384 |
return WithinUlpsMatcher(target, maxUlpDiff, Detail::FloatingPointKind::Float); |
| 8385 |
} |
| 8386 |
|
| 8387 |
WithinAbsMatcher WithinAbs(double target, double margin) { |
| 8388 |
return WithinAbsMatcher(target, margin); |
| 8389 |
} |
| 8390 |
|
| 8391 |
WithinRelMatcher WithinRel(double target, double eps) { |
| 8392 |
return WithinRelMatcher(target, eps); |
| 8393 |
} |
| 8394 |
|
| 8395 |
WithinRelMatcher WithinRel(double target) { |
| 8396 |
return WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100); |
| 8397 |
} |
| 8398 |
|
| 8399 |
WithinRelMatcher WithinRel(float target, float eps) { |
| 8400 |
return WithinRelMatcher(target, eps); |
| 8401 |
} |
| 8402 |
|
| 8403 |
WithinRelMatcher WithinRel(float target) { |
| 8404 |
return WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100); |
| 8405 |
} |
| 8406 |
|
| 8407 |
|
| 8408 |
|
| 8409 |
bool IsNaNMatcher::match( double const& matchee ) const { |
| 8410 |
return std::isnan( matchee ); |
| 8411 |
} |
| 8412 |
|
| 8413 |
std::string IsNaNMatcher::describe() const { |
| 8414 |
using namespace std::string_literals; |
| 8415 |
return "is NaN"s; |
| 8416 |
} |
| 8417 |
|
| 8418 |
IsNaNMatcher IsNaN() { return IsNaNMatcher(); } |
| 8419 |
|
| 8420 |
} // namespace Matchers |
| 8421 |
} // namespace Catch |
| 8422 |
|
| 8423 |
|
| 8424 |
|
| 8425 |
|
| 8426 |
std::string Catch::Matchers::Detail::finalizeDescription(const std::string& desc) { |
| 8427 |
if (desc.empty()) { |
| 8428 |
return "matches undescribed predicate"; |
| 8429 |
} else { |
| 8430 |
return "matches predicate: \"" + desc + '"'; |
| 8431 |
} |
| 8432 |
} |
| 8433 |
|
| 8434 |
|
| 8435 |
|
| 8436 |
namespace Catch { |
| 8437 |
namespace Matchers { |
| 8438 |
std::string AllTrueMatcher::describe() const { return "contains only true"; } |
| 8439 |
|
| 8440 |
AllTrueMatcher AllTrue() { return AllTrueMatcher{}; } |
| 8441 |
|
| 8442 |
std::string NoneTrueMatcher::describe() const { return "contains no true"; } |
| 8443 |
|
| 8444 |
NoneTrueMatcher NoneTrue() { return NoneTrueMatcher{}; } |
| 8445 |
|
| 8446 |
std::string AnyTrueMatcher::describe() const { return "contains at least one true"; } |
| 8447 |
|
| 8448 |
AnyTrueMatcher AnyTrue() { return AnyTrueMatcher{}; } |
| 8449 |
} // namespace Matchers |
| 8450 |
} // namespace Catch |
| 8451 |
|
| 8452 |
|
| 8453 |
|
| 8454 |
#include <regex> |
| 8455 |
|
| 8456 |
namespace Catch { |
| 8457 |
namespace Matchers { |
| 8458 |
|
| 8459 |
CasedString::CasedString( std::string const& str, CaseSensitive caseSensitivity ) |
| 8460 |
: m_caseSensitivity( caseSensitivity ), |
| 8461 |
m_str( adjustString( str ) ) |
| 8462 |
{} |
| 8463 |
std::string CasedString::adjustString( std::string const& str ) const { |
| 8464 |
return m_caseSensitivity == CaseSensitive::No |
| 8465 |
? toLower( str ) |
| 8466 |
: str; |
| 8467 |
} |
| 8468 |
StringRef CasedString::caseSensitivitySuffix() const { |
| 8469 |
return m_caseSensitivity == CaseSensitive::Yes |
| 8470 |
? StringRef() |
| 8471 |
: " (case insensitive)"_sr; |
| 8472 |
} |
| 8473 |
|
| 8474 |
|
| 8475 |
StringMatcherBase::StringMatcherBase( StringRef operation, CasedString const& comparator ) |
| 8476 |
: m_comparator( comparator ), |
| 8477 |
m_operation( operation ) { |
| 8478 |
} |
| 8479 |
|
| 8480 |
std::string StringMatcherBase::describe() const { |
| 8481 |
std::string description; |
| 8482 |
description.reserve(5 + m_operation.size() + m_comparator.m_str.size() + |
| 8483 |
m_comparator.caseSensitivitySuffix().size()); |
| 8484 |
description += m_operation; |
| 8485 |
description += ": \""; |
| 8486 |
description += m_comparator.m_str; |
| 8487 |
description += '"'; |
| 8488 |
description += m_comparator.caseSensitivitySuffix(); |
| 8489 |
return description; |
| 8490 |
} |
| 8491 |
|
| 8492 |
StringEqualsMatcher::StringEqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals"_sr, comparator ) {} |
| 8493 |
|
| 8494 |
bool StringEqualsMatcher::match( std::string const& source ) const { |
| 8495 |
return m_comparator.adjustString( source ) == m_comparator.m_str; |
| 8496 |
} |
| 8497 |
|
| 8498 |
|
| 8499 |
StringContainsMatcher::StringContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains"_sr, comparator ) {} |
| 8500 |
|
| 8501 |
bool StringContainsMatcher::match( std::string const& source ) const { |
| 8502 |
return contains( m_comparator.adjustString( source ), m_comparator.m_str ); |
| 8503 |
} |
| 8504 |
|
| 8505 |
|
| 8506 |
StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with"_sr, comparator ) {} |
| 8507 |
|
| 8508 |
bool StartsWithMatcher::match( std::string const& source ) const { |
| 8509 |
return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); |
| 8510 |
} |
| 8511 |
|
| 8512 |
|
| 8513 |
EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with"_sr, comparator ) {} |
| 8514 |
|
| 8515 |
bool EndsWithMatcher::match( std::string const& source ) const { |
| 8516 |
return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); |
| 8517 |
} |
| 8518 |
|
| 8519 |
|
| 8520 |
|
| 8521 |
RegexMatcher::RegexMatcher(std::string regex, CaseSensitive caseSensitivity): m_regex(CATCH_MOVE(regex)), m_caseSensitivity(caseSensitivity) {} |
| 8522 |
|
| 8523 |
bool RegexMatcher::match(std::string const& matchee) const { |
| 8524 |
auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway |
| 8525 |
if (m_caseSensitivity == CaseSensitive::No) { |
| 8526 |
flags |= std::regex::icase; |
| 8527 |
} |
| 8528 |
auto reg = std::regex(m_regex, flags); |
| 8529 |
return std::regex_match(matchee, reg); |
| 8530 |
} |
| 8531 |
|
| 8532 |
std::string RegexMatcher::describe() const { |
| 8533 |
return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Yes)? " case sensitively" : " case insensitively"); |
| 8534 |
} |
| 8535 |
|
| 8536 |
|
| 8537 |
StringEqualsMatcher Equals( std::string const& str, CaseSensitive caseSensitivity ) { |
| 8538 |
return StringEqualsMatcher( CasedString( str, caseSensitivity) ); |
| 8539 |
} |
| 8540 |
StringContainsMatcher ContainsSubstring( std::string const& str, CaseSensitive caseSensitivity ) { |
| 8541 |
return StringContainsMatcher( CasedString( str, caseSensitivity) ); |
| 8542 |
} |
| 8543 |
EndsWithMatcher EndsWith( std::string const& str, CaseSensitive caseSensitivity ) { |
| 8544 |
return EndsWithMatcher( CasedString( str, caseSensitivity) ); |
| 8545 |
} |
| 8546 |
StartsWithMatcher StartsWith( std::string const& str, CaseSensitive caseSensitivity ) { |
| 8547 |
return StartsWithMatcher( CasedString( str, caseSensitivity) ); |
| 8548 |
} |
| 8549 |
|
| 8550 |
RegexMatcher Matches(std::string const& regex, CaseSensitive caseSensitivity) { |
| 8551 |
return RegexMatcher(regex, caseSensitivity); |
| 8552 |
} |
| 8553 |
|
| 8554 |
} // namespace Matchers |
| 8555 |
} // namespace Catch |
| 8556 |
|
| 8557 |
|
| 8558 |
|
| 8559 |
namespace Catch { |
| 8560 |
namespace Matchers { |
| 8561 |
MatcherGenericBase::~MatcherGenericBase() = default; |
| 8562 |
|
| 8563 |
namespace Detail { |
| 8564 |
|
| 8565 |
std::string describe_multi_matcher(StringRef combine, std::string const* descriptions_begin, std::string const* descriptions_end) { |
| 8566 |
std::string description; |
| 8567 |
std::size_t combined_size = 4; |
| 8568 |
for ( auto desc = descriptions_begin; desc != descriptions_end; ++desc ) { |
| 8569 |
combined_size += desc->size(); |
| 8570 |
} |
| 8571 |
combined_size += static_cast<size_t>(descriptions_end - descriptions_begin - 1) * combine.size(); |
| 8572 |
|
| 8573 |
description.reserve(combined_size); |
| 8574 |
|
| 8575 |
description += "( "; |
| 8576 |
bool first = true; |
| 8577 |
for( auto desc = descriptions_begin; desc != descriptions_end; ++desc ) { |
| 8578 |
if( first ) |
| 8579 |
first = false; |
| 8580 |
else |
| 8581 |
description += combine; |
| 8582 |
description += *desc; |
| 8583 |
} |
| 8584 |
description += " )"; |
| 8585 |
return description; |
| 8586 |
} |
| 8587 |
|
| 8588 |
} // namespace Detail |
| 8589 |
} // namespace Matchers |
| 8590 |
} // namespace Catch |
| 8591 |
|
| 8592 |
|
| 8593 |
|
| 8594 |
|
| 8595 |
namespace Catch { |
| 8596 |
|
| 8597 |
// This is the general overload that takes a any string matcher |
| 8598 |
// There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers |
| 8599 |
// the Equals matcher (so the header does not mention matchers) |
| 8600 |
void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher ) { |
| 8601 |
std::string exceptionMessage = Catch::translateActiveException(); |
| 8602 |
MatchExpr<std::string, StringMatcher const&> expr( CATCH_MOVE(exceptionMessage), matcher ); |
| 8603 |
handler.handleExpr( expr ); |
| 8604 |
} |
| 8605 |
|
| 8606 |
} // namespace Catch |
| 8607 |
|
| 8608 |
|
| 8609 |
|
| 8610 |
#include <ostream> |
| 8611 |
|
| 8612 |
namespace Catch { |
| 8613 |
|
| 8614 |
AutomakeReporter::~AutomakeReporter() = default; |
| 8615 |
|
| 8616 |
void AutomakeReporter::testCaseEnded(TestCaseStats const& _testCaseStats) { |
| 8617 |
// Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR. |
| 8618 |
m_stream << ":test-result: "; |
| 8619 |
if ( _testCaseStats.totals.testCases.skipped > 0 ) { |
| 8620 |
m_stream << "SKIP"; |
| 8621 |
} else if (_testCaseStats.totals.assertions.allPassed()) { |
| 8622 |
m_stream << "PASS"; |
| 8623 |
} else if (_testCaseStats.totals.assertions.allOk()) { |
| 8624 |
m_stream << "XFAIL"; |
| 8625 |
} else { |
| 8626 |
m_stream << "FAIL"; |
| 8627 |
} |
| 8628 |
m_stream << ' ' << _testCaseStats.testInfo->name << '\n'; |
| 8629 |
StreamingReporterBase::testCaseEnded(_testCaseStats); |
| 8630 |
} |
| 8631 |
|
| 8632 |
void AutomakeReporter::skipTest(TestCaseInfo const& testInfo) { |
| 8633 |
m_stream << ":test-result: SKIP " << testInfo.name << '\n'; |
| 8634 |
} |
| 8635 |
|
| 8636 |
} // end namespace Catch |
| 8637 |
|
| 8638 |
|
| 8639 |
|
| 8640 |
|
| 8641 |
|
| 8642 |
|
| 8643 |
namespace Catch { |
| 8644 |
ReporterBase::ReporterBase( ReporterConfig&& config ): |
| 8645 |
IEventListener( config.fullConfig() ), |
| 8646 |
m_wrapped_stream( CATCH_MOVE(config).takeStream() ), |
| 8647 |
m_stream( m_wrapped_stream->stream() ), |
| 8648 |
m_colour( makeColourImpl( config.colourMode(), m_wrapped_stream.get() ) ), |
| 8649 |
m_customOptions( config.customOptions() ) |
| 8650 |
{} |
| 8651 |
|
| 8652 |
ReporterBase::~ReporterBase() = default; |
| 8653 |
|
| 8654 |
void ReporterBase::listReporters( |
| 8655 |
std::vector<ReporterDescription> const& descriptions ) { |
| 8656 |
defaultListReporters(m_stream, descriptions, m_config->verbosity()); |
| 8657 |
} |
| 8658 |
|
| 8659 |
void ReporterBase::listListeners( |
| 8660 |
std::vector<ListenerDescription> const& descriptions ) { |
| 8661 |
defaultListListeners( m_stream, descriptions ); |
| 8662 |
} |
| 8663 |
|
| 8664 |
void ReporterBase::listTests(std::vector<TestCaseHandle> const& tests) { |
| 8665 |
defaultListTests(m_stream, |
| 8666 |
m_colour.get(), |
| 8667 |
tests, |
| 8668 |
m_config->hasTestFilters(), |
| 8669 |
m_config->verbosity()); |
| 8670 |
} |
| 8671 |
|
| 8672 |
void ReporterBase::listTags(std::vector<TagInfo> const& tags) { |
| 8673 |
defaultListTags( m_stream, tags, m_config->hasTestFilters() ); |
| 8674 |
} |
| 8675 |
|
| 8676 |
} // namespace Catch |
| 8677 |
|
| 8678 |
|
| 8679 |
|
| 8680 |
|
| 8681 |
#include <ostream> |
| 8682 |
|
| 8683 |
namespace Catch { |
| 8684 |
namespace { |
| 8685 |
|
| 8686 |
// Colour::LightGrey |
| 8687 |
static constexpr Colour::Code compactDimColour = Colour::FileName; |
| 8688 |
|
| 8689 |
#ifdef CATCH_PLATFORM_MAC |
| 8690 |
static constexpr Catch::StringRef compactFailedString = "FAILED"_sr; |
| 8691 |
static constexpr Catch::StringRef compactPassedString = "PASSED"_sr; |
| 8692 |
#else |
| 8693 |
static constexpr Catch::StringRef compactFailedString = "failed"_sr; |
| 8694 |
static constexpr Catch::StringRef compactPassedString = "passed"_sr; |
| 8695 |
#endif |
| 8696 |
|
| 8697 |
// Implementation of CompactReporter formatting |
| 8698 |
class AssertionPrinter { |
| 8699 |
public: |
| 8700 |
AssertionPrinter& operator= (AssertionPrinter const&) = delete; |
| 8701 |
AssertionPrinter(AssertionPrinter const&) = delete; |
| 8702 |
AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages, ColourImpl* colourImpl_) |
| 8703 |
: stream(_stream) |
| 8704 |
, result(_stats.assertionResult) |
| 8705 |
, messages(_stats.infoMessages) |
| 8706 |
, itMessage(_stats.infoMessages.begin()) |
| 8707 |
, printInfoMessages(_printInfoMessages) |
| 8708 |
, colourImpl(colourImpl_) |
| 8709 |
{} |
| 8710 |
|
| 8711 |
void print() { |
| 8712 |
printSourceInfo(); |
| 8713 |
|
| 8714 |
itMessage = messages.begin(); |
| 8715 |
|
| 8716 |
switch (result.getResultType()) { |
| 8717 |
case ResultWas::Ok: |
| 8718 |
printResultType(Colour::ResultSuccess, compactPassedString); |
| 8719 |
printOriginalExpression(); |
| 8720 |
printReconstructedExpression(); |
| 8721 |
if (!result.hasExpression()) |
| 8722 |
printRemainingMessages(Colour::None); |
| 8723 |
else |
| 8724 |
printRemainingMessages(); |
| 8725 |
break; |
| 8726 |
case ResultWas::ExpressionFailed: |
| 8727 |
if (result.isOk()) |
| 8728 |
printResultType(Colour::ResultSuccess, compactFailedString + " - but was ok"_sr); |
| 8729 |
else |
| 8730 |
printResultType(Colour::Error, compactFailedString); |
| 8731 |
printOriginalExpression(); |
| 8732 |
printReconstructedExpression(); |
| 8733 |
printRemainingMessages(); |
| 8734 |
break; |
| 8735 |
case ResultWas::ThrewException: |
| 8736 |
printResultType(Colour::Error, compactFailedString); |
| 8737 |
printIssue("unexpected exception with message:"); |
| 8738 |
printMessage(); |
| 8739 |
printExpressionWas(); |
| 8740 |
printRemainingMessages(); |
| 8741 |
break; |
| 8742 |
case ResultWas::FatalErrorCondition: |
| 8743 |
printResultType(Colour::Error, compactFailedString); |
| 8744 |
printIssue("fatal error condition with message:"); |
| 8745 |
printMessage(); |
| 8746 |
printExpressionWas(); |
| 8747 |
printRemainingMessages(); |
| 8748 |
break; |
| 8749 |
case ResultWas::DidntThrowException: |
| 8750 |
printResultType(Colour::Error, compactFailedString); |
| 8751 |
printIssue("expected exception, got none"); |
| 8752 |
printExpressionWas(); |
| 8753 |
printRemainingMessages(); |
| 8754 |
break; |
| 8755 |
case ResultWas::Info: |
| 8756 |
printResultType(Colour::None, "info"_sr); |
| 8757 |
printMessage(); |
| 8758 |
printRemainingMessages(); |
| 8759 |
break; |
| 8760 |
case ResultWas::Warning: |
| 8761 |
printResultType(Colour::None, "warning"_sr); |
| 8762 |
printMessage(); |
| 8763 |
printRemainingMessages(); |
| 8764 |
break; |
| 8765 |
case ResultWas::ExplicitFailure: |
| 8766 |
printResultType(Colour::Error, compactFailedString); |
| 8767 |
printIssue("explicitly"); |
| 8768 |
printRemainingMessages(Colour::None); |
| 8769 |
break; |
| 8770 |
case ResultWas::ExplicitSkip: |
| 8771 |
printResultType(Colour::Skip, "skipped"_sr); |
| 8772 |
printMessage(); |
| 8773 |
printRemainingMessages(); |
| 8774 |
break; |
| 8775 |
// These cases are here to prevent compiler warnings |
| 8776 |
case ResultWas::Unknown: |
| 8777 |
case ResultWas::FailureBit: |
| 8778 |
case ResultWas::Exception: |
| 8779 |
printResultType(Colour::Error, "** internal error **"); |
| 8780 |
break; |
| 8781 |
} |
| 8782 |
} |
| 8783 |
|
| 8784 |
private: |
| 8785 |
void printSourceInfo() const { |
| 8786 |
stream << colourImpl->guardColour( Colour::FileName ) |
| 8787 |
<< result.getSourceInfo() << ':'; |
| 8788 |
} |
| 8789 |
|
| 8790 |
void printResultType(Colour::Code colour, StringRef passOrFail) const { |
| 8791 |
if (!passOrFail.empty()) { |
| 8792 |
stream << colourImpl->guardColour(colour) << ' ' << passOrFail; |
| 8793 |
stream << ':'; |
| 8794 |
} |
| 8795 |
} |
| 8796 |
|
| 8797 |
void printIssue(char const* issue) const { |
| 8798 |
stream << ' ' << issue; |
| 8799 |
} |
| 8800 |
|
| 8801 |
void printExpressionWas() { |
| 8802 |
if (result.hasExpression()) { |
| 8803 |
stream << ';'; |
| 8804 |
{ |
| 8805 |
stream << colourImpl->guardColour(compactDimColour) << " expression was:"; |
| 8806 |
} |
| 8807 |
printOriginalExpression(); |
| 8808 |
} |
| 8809 |
} |
| 8810 |
|
| 8811 |
void printOriginalExpression() const { |
| 8812 |
if (result.hasExpression()) { |
| 8813 |
stream << ' ' << result.getExpression(); |
| 8814 |
} |
| 8815 |
} |
| 8816 |
|
| 8817 |
void printReconstructedExpression() const { |
| 8818 |
if (result.hasExpandedExpression()) { |
| 8819 |
stream << colourImpl->guardColour(compactDimColour) << " for: "; |
| 8820 |
stream << result.getExpandedExpression(); |
| 8821 |
} |
| 8822 |
} |
| 8823 |
|
| 8824 |
void printMessage() { |
| 8825 |
if (itMessage != messages.end()) { |
| 8826 |
stream << " '" << itMessage->message << '\''; |
| 8827 |
++itMessage; |
| 8828 |
} |
| 8829 |
} |
| 8830 |
|
| 8831 |
void printRemainingMessages(Colour::Code colour = compactDimColour) { |
| 8832 |
if (itMessage == messages.end()) |
| 8833 |
return; |
| 8834 |
|
| 8835 |
const auto itEnd = messages.cend(); |
| 8836 |
const auto N = static_cast<std::size_t>(itEnd - itMessage); |
| 8837 |
|
| 8838 |
stream << colourImpl->guardColour( colour ) << " with " |
| 8839 |
<< pluralise( N, "message"_sr ) << ':'; |
| 8840 |
|
| 8841 |
while (itMessage != itEnd) { |
| 8842 |
// If this assertion is a warning ignore any INFO messages |
| 8843 |
if (printInfoMessages || itMessage->type != ResultWas::Info) { |
| 8844 |
printMessage(); |
| 8845 |
if (itMessage != itEnd) { |
| 8846 |
stream << colourImpl->guardColour(compactDimColour) << " and"; |
| 8847 |
} |
| 8848 |
continue; |
| 8849 |
} |
| 8850 |
++itMessage; |
| 8851 |
} |
| 8852 |
} |
| 8853 |
|
| 8854 |
private: |
| 8855 |
std::ostream& stream; |
| 8856 |
AssertionResult const& result; |
| 8857 |
std::vector<MessageInfo> const& messages; |
| 8858 |
std::vector<MessageInfo>::const_iterator itMessage; |
| 8859 |
bool printInfoMessages; |
| 8860 |
ColourImpl* colourImpl; |
| 8861 |
}; |
| 8862 |
|
| 8863 |
} // anon namespace |
| 8864 |
|
| 8865 |
std::string CompactReporter::getDescription() { |
| 8866 |
return "Reports test results on a single line, suitable for IDEs"; |
| 8867 |
} |
| 8868 |
|
| 8869 |
void CompactReporter::noMatchingTestCases( StringRef unmatchedSpec ) { |
| 8870 |
m_stream << "No test cases matched '" << unmatchedSpec << "'\n"; |
| 8871 |
} |
| 8872 |
|
| 8873 |
void CompactReporter::testRunStarting( TestRunInfo const& ) { |
| 8874 |
if ( m_config->testSpec().hasFilters() ) { |
| 8875 |
m_stream << m_colour->guardColour( Colour::BrightYellow ) |
| 8876 |
<< "Filters: " |
| 8877 |
<< m_config->testSpec() |
| 8878 |
<< '\n'; |
| 8879 |
} |
| 8880 |
m_stream << "RNG seed: " << getSeed() << '\n'; |
| 8881 |
} |
| 8882 |
|
| 8883 |
void CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) { |
| 8884 |
AssertionResult const& result = _assertionStats.assertionResult; |
| 8885 |
|
| 8886 |
bool printInfoMessages = true; |
| 8887 |
|
| 8888 |
// Drop out if result was successful and we're not printing those |
| 8889 |
if( !m_config->includeSuccessfulResults() && result.isOk() ) { |
| 8890 |
if( result.getResultType() != ResultWas::Warning && result.getResultType() != ResultWas::ExplicitSkip ) |
| 8891 |
return; |
| 8892 |
printInfoMessages = false; |
| 8893 |
} |
| 8894 |
|
| 8895 |
AssertionPrinter printer( m_stream, _assertionStats, printInfoMessages, m_colour.get() ); |
| 8896 |
printer.print(); |
| 8897 |
|
| 8898 |
m_stream << '\n' << std::flush; |
| 8899 |
} |
| 8900 |
|
| 8901 |
void CompactReporter::sectionEnded(SectionStats const& _sectionStats) { |
| 8902 |
double dur = _sectionStats.durationInSeconds; |
| 8903 |
if ( shouldShowDuration( *m_config, dur ) ) { |
| 8904 |
m_stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << '\n' << std::flush; |
| 8905 |
} |
| 8906 |
} |
| 8907 |
|
| 8908 |
void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) { |
| 8909 |
printTestRunTotals( m_stream, *m_colour, _testRunStats.totals ); |
| 8910 |
m_stream << "\n\n" << std::flush; |
| 8911 |
StreamingReporterBase::testRunEnded( _testRunStats ); |
| 8912 |
} |
| 8913 |
|
| 8914 |
CompactReporter::~CompactReporter() = default; |
| 8915 |
|
| 8916 |
} // end namespace Catch |
| 8917 |
|
| 8918 |
|
| 8919 |
|
| 8920 |
|
| 8921 |
#include <cstdio> |
| 8922 |
|
| 8923 |
#if defined(_MSC_VER) |
| 8924 |
#pragma warning(push) |
| 8925 |
#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch |
| 8926 |
// Note that 4062 (not all labels are handled and default is missing) is enabled |
| 8927 |
#endif |
| 8928 |
|
| 8929 |
#if defined(__clang__) |
| 8930 |
# pragma clang diagnostic push |
| 8931 |
// For simplicity, benchmarking-only helpers are always enabled |
| 8932 |
# pragma clang diagnostic ignored "-Wunused-function" |
| 8933 |
#endif |
| 8934 |
|
| 8935 |
|
| 8936 |
|
| 8937 |
namespace Catch { |
| 8938 |
|
| 8939 |
namespace { |
| 8940 |
|
| 8941 |
// Formatter impl for ConsoleReporter |
| 8942 |
class ConsoleAssertionPrinter { |
| 8943 |
public: |
| 8944 |
ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete; |
| 8945 |
ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete; |
| 8946 |
ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, ColourImpl* colourImpl_, bool _printInfoMessages) |
| 8947 |
: stream(_stream), |
| 8948 |
stats(_stats), |
| 8949 |
result(_stats.assertionResult), |
| 8950 |
colour(Colour::None), |
| 8951 |
messages(_stats.infoMessages), |
| 8952 |
colourImpl(colourImpl_), |
| 8953 |
printInfoMessages(_printInfoMessages) { |
| 8954 |
switch (result.getResultType()) { |
| 8955 |
case ResultWas::Ok: |
| 8956 |
colour = Colour::Success; |
| 8957 |
passOrFail = "PASSED"_sr; |
| 8958 |
//if( result.hasMessage() ) |
| 8959 |
if (messages.size() == 1) |
| 8960 |
messageLabel = "with message"_sr; |
| 8961 |
if (messages.size() > 1) |
| 8962 |
messageLabel = "with messages"_sr; |
| 8963 |
break; |
| 8964 |
case ResultWas::ExpressionFailed: |
| 8965 |
if (result.isOk()) { |
| 8966 |
colour = Colour::Success; |
| 8967 |
passOrFail = "FAILED - but was ok"_sr; |
| 8968 |
} else { |
| 8969 |
colour = Colour::Error; |
| 8970 |
passOrFail = "FAILED"_sr; |
| 8971 |
} |
| 8972 |
if (messages.size() == 1) |
| 8973 |
messageLabel = "with message"_sr; |
| 8974 |
if (messages.size() > 1) |
| 8975 |
messageLabel = "with messages"_sr; |
| 8976 |
break; |
| 8977 |
case ResultWas::ThrewException: |
| 8978 |
colour = Colour::Error; |
| 8979 |
passOrFail = "FAILED"_sr; |
| 8980 |
// todo switch |
| 8981 |
switch (messages.size()) { case 0: |
| 8982 |
messageLabel = "due to unexpected exception with "_sr; |
| 8983 |
break; |
| 8984 |
case 1: |
| 8985 |
messageLabel = "due to unexpected exception with message"_sr; |
| 8986 |
break; |
| 8987 |
default: |
| 8988 |
messageLabel = "due to unexpected exception with messages"_sr; |
| 8989 |
break; |
| 8990 |
} |
| 8991 |
break; |
| 8992 |
case ResultWas::FatalErrorCondition: |
| 8993 |
colour = Colour::Error; |
| 8994 |
passOrFail = "FAILED"_sr; |
| 8995 |
messageLabel = "due to a fatal error condition"_sr; |
| 8996 |
break; |
| 8997 |
case ResultWas::DidntThrowException: |
| 8998 |
colour = Colour::Error; |
| 8999 |
passOrFail = "FAILED"_sr; |
| 9000 |
messageLabel = "because no exception was thrown where one was expected"_sr; |
| 9001 |
break; |
| 9002 |
case ResultWas::Info: |
| 9003 |
messageLabel = "info"_sr; |
| 9004 |
break; |
| 9005 |
case ResultWas::Warning: |
| 9006 |
messageLabel = "warning"_sr; |
| 9007 |
break; |
| 9008 |
case ResultWas::ExplicitFailure: |
| 9009 |
passOrFail = "FAILED"_sr; |
| 9010 |
colour = Colour::Error; |
| 9011 |
if (messages.size() == 1) |
| 9012 |
messageLabel = "explicitly with message"_sr; |
| 9013 |
if (messages.size() > 1) |
| 9014 |
messageLabel = "explicitly with messages"_sr; |
| 9015 |
break; |
| 9016 |
case ResultWas::ExplicitSkip: |
| 9017 |
colour = Colour::Skip; |
| 9018 |
passOrFail = "SKIPPED"_sr; |
| 9019 |
if (messages.size() == 1) |
| 9020 |
messageLabel = "explicitly with message"_sr; |
| 9021 |
if (messages.size() > 1) |
| 9022 |
messageLabel = "explicitly with messages"_sr; |
| 9023 |
break; |
| 9024 |
// These cases are here to prevent compiler warnings |
| 9025 |
case ResultWas::Unknown: |
| 9026 |
case ResultWas::FailureBit: |
| 9027 |
case ResultWas::Exception: |
| 9028 |
passOrFail = "** internal error **"_sr; |
| 9029 |
colour = Colour::Error; |
| 9030 |
break; |
| 9031 |
} |
| 9032 |
} |
| 9033 |
|
| 9034 |
void print() const { |
| 9035 |
printSourceInfo(); |
| 9036 |
if (stats.totals.assertions.total() > 0) { |
| 9037 |
printResultType(); |
| 9038 |
printOriginalExpression(); |
| 9039 |
printReconstructedExpression(); |
| 9040 |
} else { |
| 9041 |
stream << '\n'; |
| 9042 |
} |
| 9043 |
printMessage(); |
| 9044 |
} |
| 9045 |
|
| 9046 |
private: |
| 9047 |
void printResultType() const { |
| 9048 |
if (!passOrFail.empty()) { |
| 9049 |
stream << colourImpl->guardColour(colour) << passOrFail << ":\n"; |
| 9050 |
} |
| 9051 |
} |
| 9052 |
void printOriginalExpression() const { |
| 9053 |
if (result.hasExpression()) { |
| 9054 |
stream << colourImpl->guardColour( Colour::OriginalExpression ) |
| 9055 |
<< " " << result.getExpressionInMacro() << '\n'; |
| 9056 |
} |
| 9057 |
} |
| 9058 |
void printReconstructedExpression() const { |
| 9059 |
if (result.hasExpandedExpression()) { |
| 9060 |
stream << "with expansion:\n"; |
| 9061 |
stream << colourImpl->guardColour( Colour::ReconstructedExpression ) |
| 9062 |
<< TextFlow::Column( result.getExpandedExpression() ) |
| 9063 |
.indent( 2 ) |
| 9064 |
<< '\n'; |
| 9065 |
} |
| 9066 |
} |
| 9067 |
void printMessage() const { |
| 9068 |
if (!messageLabel.empty()) |
| 9069 |
stream << messageLabel << ':' << '\n'; |
| 9070 |
for (auto const& msg : messages) { |
| 9071 |
// If this assertion is a warning ignore any INFO messages |
| 9072 |
if (printInfoMessages || msg.type != ResultWas::Info) |
| 9073 |
stream << TextFlow::Column(msg.message).indent(2) << '\n'; |
| 9074 |
} |
| 9075 |
} |
| 9076 |
void printSourceInfo() const { |
| 9077 |
stream << colourImpl->guardColour( Colour::FileName ) |
| 9078 |
<< result.getSourceInfo() << ": "; |
| 9079 |
} |
| 9080 |
|
| 9081 |
std::ostream& stream; |
| 9082 |
AssertionStats const& stats; |
| 9083 |
AssertionResult const& result; |
| 9084 |
Colour::Code colour; |
| 9085 |
StringRef passOrFail; |
| 9086 |
StringRef messageLabel; |
| 9087 |
std::vector<MessageInfo> const& messages; |
| 9088 |
ColourImpl* colourImpl; |
| 9089 |
bool printInfoMessages; |
| 9090 |
}; |
| 9091 |
|
| 9092 |
std::size_t makeRatio( std::uint64_t number, std::uint64_t total ) { |
| 9093 |
const auto ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0; |
| 9094 |
return (ratio == 0 && number > 0) ? 1 : static_cast<std::size_t>(ratio); |
| 9095 |
} |
| 9096 |
|
| 9097 |
std::size_t& |
| 9098 |
findMax( std::size_t& i, std::size_t& j, std::size_t& k, std::size_t& l ) { |
| 9099 |
if (i > j && i > k && i > l) |
| 9100 |
return i; |
| 9101 |
else if (j > k && j > l) |
| 9102 |
return j; |
| 9103 |
else if (k > l) |
| 9104 |
return k; |
| 9105 |
else |
| 9106 |
return l; |
| 9107 |
} |
| 9108 |
|
| 9109 |
struct ColumnBreak {}; |
| 9110 |
struct RowBreak {}; |
| 9111 |
struct OutputFlush {}; |
| 9112 |
|
| 9113 |
class Duration { |
| 9114 |
enum class Unit : uint8_t { |
| 9115 |
Auto, |
| 9116 |
Nanoseconds, |
| 9117 |
Microseconds, |
| 9118 |
Milliseconds, |
| 9119 |
Seconds, |
| 9120 |
Minutes |
| 9121 |
}; |
| 9122 |
static const uint64_t s_nanosecondsInAMicrosecond = 1000; |
| 9123 |
static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond; |
| 9124 |
static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond; |
| 9125 |
static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond; |
| 9126 |
|
| 9127 |
double m_inNanoseconds; |
| 9128 |
Unit m_units; |
| 9129 |
|
| 9130 |
public: |
| 9131 |
explicit Duration(double inNanoseconds, Unit units = Unit::Auto) |
| 9132 |
: m_inNanoseconds(inNanoseconds), |
| 9133 |
m_units(units) { |
| 9134 |
if (m_units == Unit::Auto) { |
| 9135 |
if (m_inNanoseconds < s_nanosecondsInAMicrosecond) |
| 9136 |
m_units = Unit::Nanoseconds; |
| 9137 |
else if (m_inNanoseconds < s_nanosecondsInAMillisecond) |
| 9138 |
m_units = Unit::Microseconds; |
| 9139 |
else if (m_inNanoseconds < s_nanosecondsInASecond) |
| 9140 |
m_units = Unit::Milliseconds; |
| 9141 |
else if (m_inNanoseconds < s_nanosecondsInAMinute) |
| 9142 |
m_units = Unit::Seconds; |
| 9143 |
else |
| 9144 |
m_units = Unit::Minutes; |
| 9145 |
} |
| 9146 |
|
| 9147 |
} |
| 9148 |
|
| 9149 |
auto value() const -> double { |
| 9150 |
switch (m_units) { |
| 9151 |
case Unit::Microseconds: |
| 9152 |
return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond); |
| 9153 |
case Unit::Milliseconds: |
| 9154 |
return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond); |
| 9155 |
case Unit::Seconds: |
| 9156 |
return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond); |
| 9157 |
case Unit::Minutes: |
| 9158 |
return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute); |
| 9159 |
default: |
| 9160 |
return m_inNanoseconds; |
| 9161 |
} |
| 9162 |
} |
| 9163 |
StringRef unitsAsString() const { |
| 9164 |
switch (m_units) { |
| 9165 |
case Unit::Nanoseconds: |
| 9166 |
return "ns"_sr; |
| 9167 |
case Unit::Microseconds: |
| 9168 |
return "us"_sr; |
| 9169 |
case Unit::Milliseconds: |
| 9170 |
return "ms"_sr; |
| 9171 |
case Unit::Seconds: |
| 9172 |
return "s"_sr; |
| 9173 |
case Unit::Minutes: |
| 9174 |
return "m"_sr; |
| 9175 |
default: |
| 9176 |
return "** internal error **"_sr; |
| 9177 |
} |
| 9178 |
|
| 9179 |
} |
| 9180 |
friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& { |
| 9181 |
return os << duration.value() << ' ' << duration.unitsAsString(); |
| 9182 |
} |
| 9183 |
}; |
| 9184 |
} // end anon namespace |
| 9185 |
|
| 9186 |
enum class Justification : uint8_t { |
| 9187 |
Left, |
| 9188 |
Right |
| 9189 |
}; |
| 9190 |
|
| 9191 |
struct ColumnInfo { |
| 9192 |
std::string name; |
| 9193 |
std::size_t width; |
| 9194 |
Justification justification; |
| 9195 |
}; |
| 9196 |
|
| 9197 |
class TablePrinter { |
| 9198 |
std::ostream& m_os; |
| 9199 |
std::vector<ColumnInfo> m_columnInfos; |
| 9200 |
ReusableStringStream m_oss; |
| 9201 |
int m_currentColumn = -1; |
| 9202 |
bool m_isOpen = false; |
| 9203 |
|
| 9204 |
public: |
| 9205 |
TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos ) |
| 9206 |
: m_os( os ), |
| 9207 |
m_columnInfos( CATCH_MOVE( columnInfos ) ) {} |
| 9208 |
|
| 9209 |
auto columnInfos() const -> std::vector<ColumnInfo> const& { |
| 9210 |
return m_columnInfos; |
| 9211 |
} |
| 9212 |
|
| 9213 |
void open() { |
| 9214 |
if (!m_isOpen) { |
| 9215 |
m_isOpen = true; |
| 9216 |
*this << RowBreak(); |
| 9217 |
|
| 9218 |
TextFlow::Columns headerCols; |
| 9219 |
for (auto const& info : m_columnInfos) { |
| 9220 |
assert(info.width > 2); |
| 9221 |
headerCols += TextFlow::Column(info.name).width(info.width - 2); |
| 9222 |
headerCols += TextFlow::Spacer( 2 ); |
| 9223 |
} |
| 9224 |
m_os << headerCols << '\n'; |
| 9225 |
|
| 9226 |
m_os << lineOfChars('-') << '\n'; |
| 9227 |
} |
| 9228 |
} |
| 9229 |
void close() { |
| 9230 |
if (m_isOpen) { |
| 9231 |
*this << RowBreak(); |
| 9232 |
m_os << '\n' << std::flush; |
| 9233 |
m_isOpen = false; |
| 9234 |
} |
| 9235 |
} |
| 9236 |
|
| 9237 |
template<typename T> |
| 9238 |
friend TablePrinter& operator<< (TablePrinter& tp, T const& value) { |
| 9239 |
tp.m_oss << value; |
| 9240 |
return tp; |
| 9241 |
} |
| 9242 |
|
| 9243 |
friend TablePrinter& operator<< (TablePrinter& tp, ColumnBreak) { |
| 9244 |
auto colStr = tp.m_oss.str(); |
| 9245 |
const auto strSize = colStr.size(); |
| 9246 |
tp.m_oss.str(""); |
| 9247 |
tp.open(); |
| 9248 |
if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) { |
| 9249 |
tp.m_currentColumn = -1; |
| 9250 |
tp.m_os << '\n'; |
| 9251 |
} |
| 9252 |
tp.m_currentColumn++; |
| 9253 |
|
| 9254 |
auto colInfo = tp.m_columnInfos[tp.m_currentColumn]; |
| 9255 |
auto padding = (strSize + 1 < colInfo.width) |
| 9256 |
? std::string(colInfo.width - (strSize + 1), ' ') |
| 9257 |
: std::string(); |
| 9258 |
if (colInfo.justification == Justification::Left) |
| 9259 |
tp.m_os << colStr << padding << ' '; |
| 9260 |
else |
| 9261 |
tp.m_os << padding << colStr << ' '; |
| 9262 |
return tp; |
| 9263 |
} |
| 9264 |
|
| 9265 |
friend TablePrinter& operator<< (TablePrinter& tp, RowBreak) { |
| 9266 |
if (tp.m_currentColumn > 0) { |
| 9267 |
tp.m_os << '\n'; |
| 9268 |
tp.m_currentColumn = -1; |
| 9269 |
} |
| 9270 |
return tp; |
| 9271 |
} |
| 9272 |
|
| 9273 |
friend TablePrinter& operator<<(TablePrinter& tp, OutputFlush) { |
| 9274 |
tp.m_os << std::flush; |
| 9275 |
return tp; |
| 9276 |
} |
| 9277 |
}; |
| 9278 |
|
| 9279 |
ConsoleReporter::ConsoleReporter(ReporterConfig&& config): |
| 9280 |
StreamingReporterBase( CATCH_MOVE( config ) ), |
| 9281 |
m_tablePrinter(Detail::make_unique<TablePrinter>(m_stream, |
| 9282 |
[&config]() -> std::vector<ColumnInfo> { |
| 9283 |
if (config.fullConfig()->benchmarkNoAnalysis()) |
| 9284 |
{ |
| 9285 |
return{ |
| 9286 |
{ "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, Justification::Left }, |
| 9287 |
{ " samples", 14, Justification::Right }, |
| 9288 |
{ " iterations", 14, Justification::Right }, |
| 9289 |
{ " mean", 14, Justification::Right } |
| 9290 |
}; |
| 9291 |
} |
| 9292 |
else |
| 9293 |
{ |
| 9294 |
return{ |
| 9295 |
{ "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, Justification::Left }, |
| 9296 |
{ "samples mean std dev", 14, Justification::Right }, |
| 9297 |
{ "iterations low mean low std dev", 14, Justification::Right }, |
| 9298 |
{ "est run time high mean high std dev", 14, Justification::Right } |
| 9299 |
}; |
| 9300 |
} |
| 9301 |
}())) {} |
| 9302 |
ConsoleReporter::~ConsoleReporter() = default; |
| 9303 |
|
| 9304 |
std::string ConsoleReporter::getDescription() { |
| 9305 |
return "Reports test results as plain lines of text"; |
| 9306 |
} |
| 9307 |
|
| 9308 |
void ConsoleReporter::noMatchingTestCases( StringRef unmatchedSpec ) { |
| 9309 |
m_stream << "No test cases matched '" << unmatchedSpec << "'\n"; |
| 9310 |
} |
| 9311 |
|
| 9312 |
void ConsoleReporter::reportInvalidTestSpec( StringRef arg ) { |
| 9313 |
m_stream << "Invalid Filter: " << arg << '\n'; |
| 9314 |
} |
| 9315 |
|
| 9316 |
void ConsoleReporter::assertionStarting(AssertionInfo const&) {} |
| 9317 |
|
| 9318 |
void ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) { |
| 9319 |
AssertionResult const& result = _assertionStats.assertionResult; |
| 9320 |
|
| 9321 |
bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); |
| 9322 |
|
| 9323 |
// Drop out if result was successful but we're not printing them. |
| 9324 |
// TODO: Make configurable whether skips should be printed |
| 9325 |
if (!includeResults && result.getResultType() != ResultWas::Warning && result.getResultType() != ResultWas::ExplicitSkip) |
| 9326 |
return; |
| 9327 |
|
| 9328 |
lazyPrint(); |
| 9329 |
|
| 9330 |
ConsoleAssertionPrinter printer(m_stream, _assertionStats, m_colour.get(), includeResults); |
| 9331 |
printer.print(); |
| 9332 |
m_stream << '\n' << std::flush; |
| 9333 |
} |
| 9334 |
|
| 9335 |
void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) { |
| 9336 |
m_tablePrinter->close(); |
| 9337 |
m_headerPrinted = false; |
| 9338 |
StreamingReporterBase::sectionStarting(_sectionInfo); |
| 9339 |
} |
| 9340 |
void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) { |
| 9341 |
m_tablePrinter->close(); |
| 9342 |
if (_sectionStats.missingAssertions) { |
| 9343 |
lazyPrint(); |
| 9344 |
auto guard = |
| 9345 |
m_colour->guardColour( Colour::ResultError ).engage( m_stream ); |
| 9346 |
if (m_sectionStack.size() > 1) |
| 9347 |
m_stream << "\nNo assertions in section"; |
| 9348 |
else |
| 9349 |
m_stream << "\nNo assertions in test case"; |
| 9350 |
m_stream << " '" << _sectionStats.sectionInfo.name << "'\n\n" << std::flush; |
| 9351 |
} |
| 9352 |
double dur = _sectionStats.durationInSeconds; |
| 9353 |
if (shouldShowDuration(*m_config, dur)) { |
| 9354 |
m_stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << '\n' << std::flush; |
| 9355 |
} |
| 9356 |
if (m_headerPrinted) { |
| 9357 |
m_headerPrinted = false; |
| 9358 |
} |
| 9359 |
StreamingReporterBase::sectionEnded(_sectionStats); |
| 9360 |
} |
| 9361 |
|
| 9362 |
void ConsoleReporter::benchmarkPreparing( StringRef name ) { |
| 9363 |
lazyPrintWithoutClosingBenchmarkTable(); |
| 9364 |
|
| 9365 |
auto nameCol = TextFlow::Column( static_cast<std::string>( name ) ) |
| 9366 |
.width( m_tablePrinter->columnInfos()[0].width - 2 ); |
| 9367 |
|
| 9368 |
bool firstLine = true; |
| 9369 |
for (auto line : nameCol) { |
| 9370 |
if (!firstLine) |
| 9371 |
(*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak(); |
| 9372 |
else |
| 9373 |
firstLine = false; |
| 9374 |
|
| 9375 |
(*m_tablePrinter) << line << ColumnBreak(); |
| 9376 |
} |
| 9377 |
} |
| 9378 |
|
| 9379 |
void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) { |
| 9380 |
(*m_tablePrinter) << info.samples << ColumnBreak() |
| 9381 |
<< info.iterations << ColumnBreak(); |
| 9382 |
if ( !m_config->benchmarkNoAnalysis() ) { |
| 9383 |
( *m_tablePrinter ) |
| 9384 |
<< Duration( info.estimatedDuration ) << ColumnBreak(); |
| 9385 |
} |
| 9386 |
( *m_tablePrinter ) << OutputFlush{}; |
| 9387 |
} |
| 9388 |
void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) { |
| 9389 |
if (m_config->benchmarkNoAnalysis()) |
| 9390 |
{ |
| 9391 |
(*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak(); |
| 9392 |
} |
| 9393 |
else |
| 9394 |
{ |
| 9395 |
(*m_tablePrinter) << ColumnBreak() |
| 9396 |
<< Duration(stats.mean.point.count()) << ColumnBreak() |
| 9397 |
<< Duration(stats.mean.lower_bound.count()) << ColumnBreak() |
| 9398 |
<< Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak() |
| 9399 |
<< Duration(stats.standardDeviation.point.count()) << ColumnBreak() |
| 9400 |
<< Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak() |
| 9401 |
<< Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak(); |
| 9402 |
} |
| 9403 |
} |
| 9404 |
|
| 9405 |
void ConsoleReporter::benchmarkFailed( StringRef error ) { |
| 9406 |
auto guard = m_colour->guardColour( Colour::Red ).engage( m_stream ); |
| 9407 |
(*m_tablePrinter) |
| 9408 |
<< "Benchmark failed (" << error << ')' |
| 9409 |
<< ColumnBreak() << RowBreak(); |
| 9410 |
} |
| 9411 |
|
| 9412 |
void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) { |
| 9413 |
m_tablePrinter->close(); |
| 9414 |
StreamingReporterBase::testCaseEnded(_testCaseStats); |
| 9415 |
m_headerPrinted = false; |
| 9416 |
} |
| 9417 |
void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) { |
| 9418 |
printTotalsDivider(_testRunStats.totals); |
| 9419 |
printTestRunTotals( m_stream, *m_colour, _testRunStats.totals ); |
| 9420 |
m_stream << '\n' << std::flush; |
| 9421 |
StreamingReporterBase::testRunEnded(_testRunStats); |
| 9422 |
} |
| 9423 |
void ConsoleReporter::testRunStarting(TestRunInfo const& _testRunInfo) { |
| 9424 |
StreamingReporterBase::testRunStarting(_testRunInfo); |
| 9425 |
if ( m_config->testSpec().hasFilters() ) { |
| 9426 |
m_stream << m_colour->guardColour( Colour::BrightYellow ) << "Filters: " |
| 9427 |
<< m_config->testSpec() << '\n'; |
| 9428 |
} |
| 9429 |
m_stream << "Randomness seeded to: " << getSeed() << '\n'; |
| 9430 |
} |
| 9431 |
|
| 9432 |
void ConsoleReporter::lazyPrint() { |
| 9433 |
|
| 9434 |
m_tablePrinter->close(); |
| 9435 |
lazyPrintWithoutClosingBenchmarkTable(); |
| 9436 |
} |
| 9437 |
|
| 9438 |
void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() { |
| 9439 |
|
| 9440 |
if ( !m_testRunInfoPrinted ) { |
| 9441 |
lazyPrintRunInfo(); |
| 9442 |
} |
| 9443 |
if (!m_headerPrinted) { |
| 9444 |
printTestCaseAndSectionHeader(); |
| 9445 |
m_headerPrinted = true; |
| 9446 |
} |
| 9447 |
} |
| 9448 |
void ConsoleReporter::lazyPrintRunInfo() { |
| 9449 |
m_stream << '\n' |
| 9450 |
<< lineOfChars( '~' ) << '\n' |
| 9451 |
<< m_colour->guardColour( Colour::SecondaryText ) |
| 9452 |
<< currentTestRunInfo.name << " is a Catch2 v" << libraryVersion() |
| 9453 |
<< " host application.\n" |
| 9454 |
<< "Run with -? for options\n\n"; |
| 9455 |
|
| 9456 |
m_testRunInfoPrinted = true; |
| 9457 |
} |
| 9458 |
void ConsoleReporter::printTestCaseAndSectionHeader() { |
| 9459 |
assert(!m_sectionStack.empty()); |
| 9460 |
printOpenHeader(currentTestCaseInfo->name); |
| 9461 |
|
| 9462 |
if (m_sectionStack.size() > 1) { |
| 9463 |
auto guard = m_colour->guardColour( Colour::Headers ).engage( m_stream ); |
| 9464 |
|
| 9465 |
auto |
| 9466 |
it = m_sectionStack.begin() + 1, // Skip first section (test case) |
| 9467 |
itEnd = m_sectionStack.end(); |
| 9468 |
for (; it != itEnd; ++it) |
| 9469 |
printHeaderString(it->name, 2); |
| 9470 |
} |
| 9471 |
|
| 9472 |
SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; |
| 9473 |
|
| 9474 |
|
| 9475 |
m_stream << lineOfChars( '-' ) << '\n' |
| 9476 |
<< m_colour->guardColour( Colour::FileName ) << lineInfo << '\n' |
| 9477 |
<< lineOfChars( '.' ) << "\n\n" |
| 9478 |
<< std::flush; |
| 9479 |
} |
| 9480 |
|
| 9481 |
void ConsoleReporter::printClosedHeader(std::string const& _name) { |
| 9482 |
printOpenHeader(_name); |
| 9483 |
m_stream << lineOfChars('.') << '\n'; |
| 9484 |
} |
| 9485 |
void ConsoleReporter::printOpenHeader(std::string const& _name) { |
| 9486 |
m_stream << lineOfChars('-') << '\n'; |
| 9487 |
{ |
| 9488 |
auto guard = m_colour->guardColour( Colour::Headers ).engage( m_stream ); |
| 9489 |
printHeaderString(_name); |
| 9490 |
} |
| 9491 |
} |
| 9492 |
|
| 9493 |
void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) { |
| 9494 |
// We want to get a bit fancy with line breaking here, so that subsequent |
| 9495 |
// lines start after ":" if one is present, e.g. |
| 9496 |
// ``` |
| 9497 |
// blablabla: Fancy |
| 9498 |
// linebreaking |
| 9499 |
// ``` |
| 9500 |
// but we also want to avoid problems with overly long indentation causing |
| 9501 |
// the text to take up too many lines, e.g. |
| 9502 |
// ``` |
| 9503 |
// blablabla: F |
| 9504 |
// a |
| 9505 |
// n |
| 9506 |
// c |
| 9507 |
// y |
| 9508 |
// . |
| 9509 |
// . |
| 9510 |
// . |
| 9511 |
// ``` |
| 9512 |
// So we limit the prefix indentation check to first quarter of the possible |
| 9513 |
// width |
| 9514 |
std::size_t idx = _string.find( ": " ); |
| 9515 |
if ( idx != std::string::npos && idx < CATCH_CONFIG_CONSOLE_WIDTH / 4 ) { |
| 9516 |
idx += 2; |
| 9517 |
} else { |
| 9518 |
idx = 0; |
| 9519 |
} |
| 9520 |
m_stream << TextFlow::Column( _string ) |
| 9521 |
.indent( indent + idx ) |
| 9522 |
.initialIndent( indent ) |
| 9523 |
<< '\n'; |
| 9524 |
} |
| 9525 |
|
| 9526 |
void ConsoleReporter::printTotalsDivider(Totals const& totals) { |
| 9527 |
if (totals.testCases.total() > 0) { |
| 9528 |
std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total()); |
| 9529 |
std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total()); |
| 9530 |
std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total()); |
| 9531 |
std::size_t skippedRatio = makeRatio(totals.testCases.skipped, totals.testCases.total()); |
| 9532 |
while (failedRatio + failedButOkRatio + passedRatio + skippedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1) |
| 9533 |
findMax(failedRatio, failedButOkRatio, passedRatio, skippedRatio)++; |
| 9534 |
while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1) |
| 9535 |
findMax(failedRatio, failedButOkRatio, passedRatio, skippedRatio)--; |
| 9536 |
|
| 9537 |
m_stream << m_colour->guardColour( Colour::Error ) |
| 9538 |
<< std::string( failedRatio, '=' ) |
| 9539 |
<< m_colour->guardColour( Colour::ResultExpectedFailure ) |
| 9540 |
<< std::string( failedButOkRatio, '=' ); |
| 9541 |
if ( totals.testCases.allPassed() ) { |
| 9542 |
m_stream << m_colour->guardColour( Colour::ResultSuccess ) |
| 9543 |
<< std::string( passedRatio, '=' ); |
| 9544 |
} else { |
| 9545 |
m_stream << m_colour->guardColour( Colour::Success ) |
| 9546 |
<< std::string( passedRatio, '=' ); |
| 9547 |
} |
| 9548 |
m_stream << m_colour->guardColour( Colour::Skip ) |
| 9549 |
<< std::string( skippedRatio, '=' ); |
| 9550 |
} else { |
| 9551 |
m_stream << m_colour->guardColour( Colour::Warning ) |
| 9552 |
<< std::string( CATCH_CONFIG_CONSOLE_WIDTH - 1, '=' ); |
| 9553 |
} |
| 9554 |
m_stream << '\n'; |
| 9555 |
} |
| 9556 |
|
| 9557 |
} // end namespace Catch |
| 9558 |
|
| 9559 |
#if defined(_MSC_VER) |
| 9560 |
#pragma warning(pop) |
| 9561 |
#endif |
| 9562 |
|
| 9563 |
#if defined(__clang__) |
| 9564 |
# pragma clang diagnostic pop |
| 9565 |
#endif |
| 9566 |
|
| 9567 |
|
| 9568 |
|
| 9569 |
|
| 9570 |
#include <algorithm> |
| 9571 |
#include <cassert> |
| 9572 |
|
| 9573 |
namespace Catch { |
| 9574 |
namespace { |
| 9575 |
struct BySectionInfo { |
| 9576 |
BySectionInfo( SectionInfo const& other ): m_other( other ) {} |
| 9577 |
BySectionInfo( BySectionInfo const& other ) = default; |
| 9578 |
bool operator()( |
| 9579 |
Detail::unique_ptr<CumulativeReporterBase::SectionNode> const& |
| 9580 |
node ) const { |
| 9581 |
return ( |
| 9582 |
( node->stats.sectionInfo.name == m_other.name ) && |
| 9583 |
( node->stats.sectionInfo.lineInfo == m_other.lineInfo ) ); |
| 9584 |
} |
| 9585 |
void operator=( BySectionInfo const& ) = delete; |
| 9586 |
|
| 9587 |
private: |
| 9588 |
SectionInfo const& m_other; |
| 9589 |
}; |
| 9590 |
|
| 9591 |
} // namespace |
| 9592 |
|
| 9593 |
namespace Detail { |
| 9594 |
AssertionOrBenchmarkResult::AssertionOrBenchmarkResult( |
| 9595 |
AssertionStats const& assertion ): |
| 9596 |
m_assertion( assertion ) {} |
| 9597 |
|
| 9598 |
AssertionOrBenchmarkResult::AssertionOrBenchmarkResult( |
| 9599 |
BenchmarkStats<> const& benchmark ): |
| 9600 |
m_benchmark( benchmark ) {} |
| 9601 |
|
| 9602 |
bool AssertionOrBenchmarkResult::isAssertion() const { |
| 9603 |
return m_assertion.some(); |
| 9604 |
} |
| 9605 |
bool AssertionOrBenchmarkResult::isBenchmark() const { |
| 9606 |
return m_benchmark.some(); |
| 9607 |
} |
| 9608 |
|
| 9609 |
AssertionStats const& AssertionOrBenchmarkResult::asAssertion() const { |
| 9610 |
assert(m_assertion.some()); |
| 9611 |
|
| 9612 |
return *m_assertion; |
| 9613 |
} |
| 9614 |
BenchmarkStats<> const& AssertionOrBenchmarkResult::asBenchmark() const { |
| 9615 |
assert(m_benchmark.some()); |
| 9616 |
|
| 9617 |
return *m_benchmark; |
| 9618 |
} |
| 9619 |
|
| 9620 |
} |
| 9621 |
|
| 9622 |
CumulativeReporterBase::~CumulativeReporterBase() = default; |
| 9623 |
|
| 9624 |
void CumulativeReporterBase::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) { |
| 9625 |
m_sectionStack.back()->assertionsAndBenchmarks.emplace_back(benchmarkStats); |
| 9626 |
} |
| 9627 |
|
| 9628 |
void |
| 9629 |
CumulativeReporterBase::sectionStarting( SectionInfo const& sectionInfo ) { |
| 9630 |
// We need a copy, because SectionStats expect to take ownership |
| 9631 |
SectionStats incompleteStats( SectionInfo(sectionInfo), Counts(), 0, false ); |
| 9632 |
SectionNode* node; |
| 9633 |
if ( m_sectionStack.empty() ) { |
| 9634 |
if ( !m_rootSection ) { |
| 9635 |
m_rootSection = |
| 9636 |
Detail::make_unique<SectionNode>( incompleteStats ); |
| 9637 |
} |
| 9638 |
node = m_rootSection.get(); |
| 9639 |
} else { |
| 9640 |
SectionNode& parentNode = *m_sectionStack.back(); |
| 9641 |
auto it = std::find_if( parentNode.childSections.begin(), |
| 9642 |
parentNode.childSections.end(), |
| 9643 |
BySectionInfo( sectionInfo ) ); |
| 9644 |
if ( it == parentNode.childSections.end() ) { |
| 9645 |
auto newNode = |
| 9646 |
Detail::make_unique<SectionNode>( incompleteStats ); |
| 9647 |
node = newNode.get(); |
| 9648 |
parentNode.childSections.push_back( CATCH_MOVE( newNode ) ); |
| 9649 |
} else { |
| 9650 |
node = it->get(); |
| 9651 |
} |
| 9652 |
} |
| 9653 |
|
| 9654 |
m_deepestSection = node; |
| 9655 |
m_sectionStack.push_back( node ); |
| 9656 |
} |
| 9657 |
|
| 9658 |
void CumulativeReporterBase::assertionEnded( |
| 9659 |
AssertionStats const& assertionStats ) { |
| 9660 |
assert( !m_sectionStack.empty() ); |
| 9661 |
// AssertionResult holds a pointer to a temporary DecomposedExpression, |
| 9662 |
// which getExpandedExpression() calls to build the expression string. |
| 9663 |
// Our section stack copy of the assertionResult will likely outlive the |
| 9664 |
// temporary, so it must be expanded or discarded now to avoid calling |
| 9665 |
// a destroyed object later. |
| 9666 |
if ( m_shouldStoreFailedAssertions && |
| 9667 |
!assertionStats.assertionResult.isOk() ) { |
| 9668 |
static_cast<void>( |
| 9669 |
assertionStats.assertionResult.getExpandedExpression() ); |
| 9670 |
} |
| 9671 |
if ( m_shouldStoreSuccesfulAssertions && |
| 9672 |
assertionStats.assertionResult.isOk() ) { |
| 9673 |
static_cast<void>( |
| 9674 |
assertionStats.assertionResult.getExpandedExpression() ); |
| 9675 |
} |
| 9676 |
SectionNode& sectionNode = *m_sectionStack.back(); |
| 9677 |
sectionNode.assertionsAndBenchmarks.emplace_back( assertionStats ); |
| 9678 |
} |
| 9679 |
|
| 9680 |
void CumulativeReporterBase::sectionEnded( SectionStats const& sectionStats ) { |
| 9681 |
assert( !m_sectionStack.empty() ); |
| 9682 |
SectionNode& node = *m_sectionStack.back(); |
| 9683 |
node.stats = sectionStats; |
| 9684 |
m_sectionStack.pop_back(); |
| 9685 |
} |
| 9686 |
|
| 9687 |
void CumulativeReporterBase::testCaseEnded( |
| 9688 |
TestCaseStats const& testCaseStats ) { |
| 9689 |
auto node = Detail::make_unique<TestCaseNode>( testCaseStats ); |
| 9690 |
assert( m_sectionStack.size() == 0 ); |
| 9691 |
node->children.push_back( CATCH_MOVE(m_rootSection) ); |
| 9692 |
m_testCases.push_back( CATCH_MOVE(node) ); |
| 9693 |
|
| 9694 |
assert( m_deepestSection ); |
| 9695 |
m_deepestSection->stdOut = testCaseStats.stdOut; |
| 9696 |
m_deepestSection->stdErr = testCaseStats.stdErr; |
| 9697 |
} |
| 9698 |
|
| 9699 |
|
| 9700 |
void CumulativeReporterBase::testRunEnded( TestRunStats const& testRunStats ) { |
| 9701 |
assert(!m_testRun && "CumulativeReporterBase assumes there can only be one test run"); |
| 9702 |
m_testRun = Detail::make_unique<TestRunNode>( testRunStats ); |
| 9703 |
m_testRun->children.swap( m_testCases ); |
| 9704 |
testRunEndedCumulative(); |
| 9705 |
} |
| 9706 |
|
| 9707 |
bool CumulativeReporterBase::SectionNode::hasAnyAssertions() const { |
| 9708 |
return std::any_of( |
| 9709 |
assertionsAndBenchmarks.begin(), |
| 9710 |
assertionsAndBenchmarks.end(), |
| 9711 |
[]( Detail::AssertionOrBenchmarkResult const& res ) { |
| 9712 |
return res.isAssertion(); |
| 9713 |
} ); |
| 9714 |
} |
| 9715 |
|
| 9716 |
} // end namespace Catch |
| 9717 |
|
| 9718 |
|
| 9719 |
|
| 9720 |
|
| 9721 |
namespace Catch { |
| 9722 |
|
| 9723 |
void EventListenerBase::fatalErrorEncountered( StringRef ) {} |
| 9724 |
|
| 9725 |
void EventListenerBase::benchmarkPreparing( StringRef ) {} |
| 9726 |
void EventListenerBase::benchmarkStarting( BenchmarkInfo const& ) {} |
| 9727 |
void EventListenerBase::benchmarkEnded( BenchmarkStats<> const& ) {} |
| 9728 |
void EventListenerBase::benchmarkFailed( StringRef ) {} |
| 9729 |
|
| 9730 |
void EventListenerBase::assertionStarting( AssertionInfo const& ) {} |
| 9731 |
|
| 9732 |
void EventListenerBase::assertionEnded( AssertionStats const& ) {} |
| 9733 |
void EventListenerBase::listReporters( |
| 9734 |
std::vector<ReporterDescription> const& ) {} |
| 9735 |
void EventListenerBase::listListeners( |
| 9736 |
std::vector<ListenerDescription> const& ) {} |
| 9737 |
void EventListenerBase::listTests( std::vector<TestCaseHandle> const& ) {} |
| 9738 |
void EventListenerBase::listTags( std::vector<TagInfo> const& ) {} |
| 9739 |
void EventListenerBase::noMatchingTestCases( StringRef ) {} |
| 9740 |
void EventListenerBase::reportInvalidTestSpec( StringRef ) {} |
| 9741 |
void EventListenerBase::testRunStarting( TestRunInfo const& ) {} |
| 9742 |
void EventListenerBase::testCaseStarting( TestCaseInfo const& ) {} |
| 9743 |
void EventListenerBase::testCasePartialStarting(TestCaseInfo const&, uint64_t) {} |
| 9744 |
void EventListenerBase::sectionStarting( SectionInfo const& ) {} |
| 9745 |
void EventListenerBase::sectionEnded( SectionStats const& ) {} |
| 9746 |
void EventListenerBase::testCasePartialEnded(TestCaseStats const&, uint64_t) {} |
| 9747 |
void EventListenerBase::testCaseEnded( TestCaseStats const& ) {} |
| 9748 |
void EventListenerBase::testRunEnded( TestRunStats const& ) {} |
| 9749 |
void EventListenerBase::skipTest( TestCaseInfo const& ) {} |
| 9750 |
} // namespace Catch |
| 9751 |
|
| 9752 |
|
| 9753 |
|
| 9754 |
|
| 9755 |
#include <algorithm> |
| 9756 |
#include <cfloat> |
| 9757 |
#include <cstdio> |
| 9758 |
#include <ostream> |
| 9759 |
#include <iomanip> |
| 9760 |
|
| 9761 |
namespace Catch { |
| 9762 |
|
| 9763 |
namespace { |
| 9764 |
void listTestNamesOnly(std::ostream& out, |
| 9765 |
std::vector<TestCaseHandle> const& tests) { |
| 9766 |
for (auto const& test : tests) { |
| 9767 |
auto const& testCaseInfo = test.getTestCaseInfo(); |
| 9768 |
|
| 9769 |
if (startsWith(testCaseInfo.name, '#')) { |
| 9770 |
out << '"' << testCaseInfo.name << '"'; |
| 9771 |
} else { |
| 9772 |
out << testCaseInfo.name; |
| 9773 |
} |
| 9774 |
|
| 9775 |
out << '\n'; |
| 9776 |
} |
| 9777 |
out << std::flush; |
| 9778 |
} |
| 9779 |
} // end unnamed namespace |
| 9780 |
|
| 9781 |
|
| 9782 |
// Because formatting using c++ streams is stateful, drop down to C is |
| 9783 |
// required Alternatively we could use stringstream, but its performance |
| 9784 |
// is... not good. |
| 9785 |
std::string getFormattedDuration( double duration ) { |
| 9786 |
// Max exponent + 1 is required to represent the whole part |
| 9787 |
// + 1 for decimal point |
| 9788 |
// + 3 for the 3 decimal places |
| 9789 |
// + 1 for null terminator |
| 9790 |
const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; |
| 9791 |
char buffer[maxDoubleSize]; |
| 9792 |
|
| 9793 |
// Save previous errno, to prevent sprintf from overwriting it |
| 9794 |
ErrnoGuard guard; |
| 9795 |
#ifdef _MSC_VER |
| 9796 |
size_t printedLength = static_cast<size_t>( |
| 9797 |
sprintf_s( buffer, "%.3f", duration ) ); |
| 9798 |
#else |
| 9799 |
size_t printedLength = static_cast<size_t>( |
| 9800 |
std::snprintf( buffer, maxDoubleSize, "%.3f", duration ) ); |
| 9801 |
#endif |
| 9802 |
return std::string( buffer, printedLength ); |
| 9803 |
} |
| 9804 |
|
| 9805 |
bool shouldShowDuration( IConfig const& config, double duration ) { |
| 9806 |
if ( config.showDurations() == ShowDurations::Always ) { |
| 9807 |
return true; |
| 9808 |
} |
| 9809 |
if ( config.showDurations() == ShowDurations::Never ) { |
| 9810 |
return false; |
| 9811 |
} |
| 9812 |
const double min = config.minDuration(); |
| 9813 |
return min >= 0 && duration >= min; |
| 9814 |
} |
| 9815 |
|
| 9816 |
std::string serializeFilters( std::vector<std::string> const& filters ) { |
| 9817 |
// We add a ' ' separator between each filter |
| 9818 |
size_t serialized_size = filters.size() - 1; |
| 9819 |
for (auto const& filter : filters) { |
| 9820 |
serialized_size += filter.size(); |
| 9821 |
} |
| 9822 |
|
| 9823 |
std::string serialized; |
| 9824 |
serialized.reserve(serialized_size); |
| 9825 |
bool first = true; |
| 9826 |
|
| 9827 |
for (auto const& filter : filters) { |
| 9828 |
if (!first) { |
| 9829 |
serialized.push_back(' '); |
| 9830 |
} |
| 9831 |
first = false; |
| 9832 |
serialized.append(filter); |
| 9833 |
} |
| 9834 |
|
| 9835 |
return serialized; |
| 9836 |
} |
| 9837 |
|
| 9838 |
std::ostream& operator<<( std::ostream& out, lineOfChars value ) { |
| 9839 |
for ( size_t idx = 0; idx < CATCH_CONFIG_CONSOLE_WIDTH - 1; ++idx ) { |
| 9840 |
out.put( value.c ); |
| 9841 |
} |
| 9842 |
return out; |
| 9843 |
} |
| 9844 |
|
| 9845 |
void |
| 9846 |
defaultListReporters( std::ostream& out, |
| 9847 |
std::vector<ReporterDescription> const& descriptions, |
| 9848 |
Verbosity verbosity ) { |
| 9849 |
out << "Available reporters:\n"; |
| 9850 |
const auto maxNameLen = |
| 9851 |
std::max_element( descriptions.begin(), |
| 9852 |
descriptions.end(), |
| 9853 |
[]( ReporterDescription const& lhs, |
| 9854 |
ReporterDescription const& rhs ) { |
| 9855 |
return lhs.name.size() < rhs.name.size(); |
| 9856 |
} ) |
| 9857 |
->name.size(); |
| 9858 |
|
| 9859 |
for ( auto const& desc : descriptions ) { |
| 9860 |
if ( verbosity == Verbosity::Quiet ) { |
| 9861 |
out << TextFlow::Column( desc.name ) |
| 9862 |
.indent( 2 ) |
| 9863 |
.width( 5 + maxNameLen ) |
| 9864 |
<< '\n'; |
| 9865 |
} else { |
| 9866 |
out << TextFlow::Column( desc.name + ':' ) |
| 9867 |
.indent( 2 ) |
| 9868 |
.width( 5 + maxNameLen ) + |
| 9869 |
TextFlow::Column( desc.description ) |
| 9870 |
.initialIndent( 0 ) |
| 9871 |
.indent( 2 ) |
| 9872 |
.width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 ) |
| 9873 |
<< '\n'; |
| 9874 |
} |
| 9875 |
} |
| 9876 |
out << '\n' << std::flush; |
| 9877 |
} |
| 9878 |
|
| 9879 |
void defaultListListeners( std::ostream& out, |
| 9880 |
std::vector<ListenerDescription> const& descriptions ) { |
| 9881 |
out << "Registered listeners:\n"; |
| 9882 |
|
| 9883 |
if(descriptions.empty()) { |
| 9884 |
return; |
| 9885 |
} |
| 9886 |
|
| 9887 |
const auto maxNameLen = |
| 9888 |
std::max_element( descriptions.begin(), |
| 9889 |
descriptions.end(), |
| 9890 |
[]( ListenerDescription const& lhs, |
| 9891 |
ListenerDescription const& rhs ) { |
| 9892 |
return lhs.name.size() < rhs.name.size(); |
| 9893 |
} ) |
| 9894 |
->name.size(); |
| 9895 |
|
| 9896 |
for ( auto const& desc : descriptions ) { |
| 9897 |
out << TextFlow::Column( static_cast<std::string>( desc.name ) + |
| 9898 |
':' ) |
| 9899 |
.indent( 2 ) |
| 9900 |
.width( maxNameLen + 5 ) + |
| 9901 |
TextFlow::Column( desc.description ) |
| 9902 |
.initialIndent( 0 ) |
| 9903 |
.indent( 2 ) |
| 9904 |
.width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 ) |
| 9905 |
<< '\n'; |
| 9906 |
} |
| 9907 |
|
| 9908 |
out << '\n' << std::flush; |
| 9909 |
} |
| 9910 |
|
| 9911 |
void defaultListTags( std::ostream& out, |
| 9912 |
std::vector<TagInfo> const& tags, |
| 9913 |
bool isFiltered ) { |
| 9914 |
if ( isFiltered ) { |
| 9915 |
out << "Tags for matching test cases:\n"; |
| 9916 |
} else { |
| 9917 |
out << "All available tags:\n"; |
| 9918 |
} |
| 9919 |
|
| 9920 |
for ( auto const& tagCount : tags ) { |
| 9921 |
ReusableStringStream rss; |
| 9922 |
rss << " " << std::setw( 2 ) << tagCount.count << " "; |
| 9923 |
auto str = rss.str(); |
| 9924 |
auto wrapper = TextFlow::Column( tagCount.all() ) |
| 9925 |
.initialIndent( 0 ) |
| 9926 |
.indent( str.size() ) |
| 9927 |
.width( CATCH_CONFIG_CONSOLE_WIDTH - 10 ); |
| 9928 |
out << str << wrapper << '\n'; |
| 9929 |
} |
| 9930 |
out << pluralise(tags.size(), "tag"_sr) << "\n\n" << std::flush; |
| 9931 |
} |
| 9932 |
|
| 9933 |
void defaultListTests(std::ostream& out, ColourImpl* streamColour, std::vector<TestCaseHandle> const& tests, bool isFiltered, Verbosity verbosity) { |
| 9934 |
// We special case this to provide the equivalent of old |
| 9935 |
// `--list-test-names-only`, which could then be used by the |
| 9936 |
// `--input-file` option. |
| 9937 |
if (verbosity == Verbosity::Quiet) { |
| 9938 |
listTestNamesOnly(out, tests); |
| 9939 |
return; |
| 9940 |
} |
| 9941 |
|
| 9942 |
if (isFiltered) { |
| 9943 |
out << "Matching test cases:\n"; |
| 9944 |
} else { |
| 9945 |
out << "All available test cases:\n"; |
| 9946 |
} |
| 9947 |
|
| 9948 |
for (auto const& test : tests) { |
| 9949 |
auto const& testCaseInfo = test.getTestCaseInfo(); |
| 9950 |
Colour::Code colour = testCaseInfo.isHidden() |
| 9951 |
? Colour::SecondaryText |
| 9952 |
: Colour::None; |
| 9953 |
auto colourGuard = streamColour->guardColour( colour ).engage( out ); |
| 9954 |
|
| 9955 |
out << TextFlow::Column(testCaseInfo.name).indent(2) << '\n'; |
| 9956 |
if (verbosity >= Verbosity::High) { |
| 9957 |
out << TextFlow::Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4) << '\n'; |
| 9958 |
} |
| 9959 |
if (!testCaseInfo.tags.empty() && |
| 9960 |
verbosity > Verbosity::Quiet) { |
| 9961 |
out << TextFlow::Column(testCaseInfo.tagsAsString()).indent(6) << '\n'; |
| 9962 |
} |
| 9963 |
} |
| 9964 |
|
| 9965 |
if (isFiltered) { |
| 9966 |
out << pluralise(tests.size(), "matching test case"_sr); |
| 9967 |
} else { |
| 9968 |
out << pluralise(tests.size(), "test case"_sr); |
| 9969 |
} |
| 9970 |
out << "\n\n" << std::flush; |
| 9971 |
} |
| 9972 |
|
| 9973 |
namespace { |
| 9974 |
class SummaryColumn { |
| 9975 |
public: |
| 9976 |
SummaryColumn( std::string suffix, Colour::Code colour ): |
| 9977 |
m_suffix( CATCH_MOVE( suffix ) ), m_colour( colour ) {} |
| 9978 |
|
| 9979 |
SummaryColumn&& addRow( std::uint64_t count ) && { |
| 9980 |
std::string row = std::to_string(count); |
| 9981 |
auto const new_width = std::max( m_width, row.size() ); |
| 9982 |
if ( new_width > m_width ) { |
| 9983 |
for ( auto& oldRow : m_rows ) { |
| 9984 |
oldRow.insert( 0, new_width - m_width, ' ' ); |
| 9985 |
} |
| 9986 |
} else { |
| 9987 |
row.insert( 0, m_width - row.size(), ' ' ); |
| 9988 |
} |
| 9989 |
m_width = new_width; |
| 9990 |
m_rows.push_back( row ); |
| 9991 |
return std::move( *this ); |
| 9992 |
} |
| 9993 |
|
| 9994 |
std::string const& getSuffix() const { return m_suffix; } |
| 9995 |
Colour::Code getColour() const { return m_colour; } |
| 9996 |
std::string const& getRow( std::size_t index ) const { |
| 9997 |
return m_rows[index]; |
| 9998 |
} |
| 9999 |
|
| 10000 |
private: |
| 10001 |
std::string m_suffix; |
| 10002 |
Colour::Code m_colour; |
| 10003 |
std::size_t m_width = 0; |
| 10004 |
std::vector<std::string> m_rows; |
| 10005 |
}; |
| 10006 |
|
| 10007 |
void printSummaryRow( std::ostream& stream, |
| 10008 |
ColourImpl& colour, |
| 10009 |
StringRef label, |
| 10010 |
std::vector<SummaryColumn> const& cols, |
| 10011 |
std::size_t row ) { |
| 10012 |
for ( auto const& col : cols ) { |
| 10013 |
auto const& value = col.getRow( row ); |
| 10014 |
auto const& suffix = col.getSuffix(); |
| 10015 |
if ( suffix.empty() ) { |
| 10016 |
stream << label << ": "; |
| 10017 |
if ( value != "0" ) { |
| 10018 |
stream << value; |
| 10019 |
} else { |
| 10020 |
stream << colour.guardColour( Colour::Warning ) |
| 10021 |
<< "- none -"; |
| 10022 |
} |
| 10023 |
} else if ( value != "0" ) { |
| 10024 |
stream << colour.guardColour( Colour::LightGrey ) << " | " |
| 10025 |
<< colour.guardColour( col.getColour() ) << value |
| 10026 |
<< ' ' << suffix; |
| 10027 |
} |
| 10028 |
} |
| 10029 |
stream << '\n'; |
| 10030 |
} |
| 10031 |
} // namespace |
| 10032 |
|
| 10033 |
void printTestRunTotals( std::ostream& stream, |
| 10034 |
ColourImpl& streamColour, |
| 10035 |
Totals const& totals ) { |
| 10036 |
if ( totals.testCases.total() == 0 ) { |
| 10037 |
stream << streamColour.guardColour( Colour::Warning ) |
| 10038 |
<< "No tests ran\n"; |
| 10039 |
return; |
| 10040 |
} |
| 10041 |
|
| 10042 |
if ( totals.assertions.total() > 0 && totals.testCases.allPassed() ) { |
| 10043 |
stream << streamColour.guardColour( Colour::ResultSuccess ) |
| 10044 |
<< "All tests passed"; |
| 10045 |
stream << " (" |
| 10046 |
<< pluralise( totals.assertions.passed, "assertion"_sr ) |
| 10047 |
<< " in " |
| 10048 |
<< pluralise( totals.testCases.passed, "test case"_sr ) |
| 10049 |
<< ')' << '\n'; |
| 10050 |
return; |
| 10051 |
} |
| 10052 |
|
| 10053 |
std::vector<SummaryColumn> columns; |
| 10054 |
// Don't include "skipped assertions" in total count |
| 10055 |
const auto totalAssertionCount = |
| 10056 |
totals.assertions.total() - totals.assertions.skipped; |
| 10057 |
columns.push_back( SummaryColumn( "", Colour::None ) |
| 10058 |
.addRow( totals.testCases.total() ) |
| 10059 |
.addRow( totalAssertionCount ) ); |
| 10060 |
columns.push_back( SummaryColumn( "passed", Colour::Success ) |
| 10061 |
.addRow( totals.testCases.passed ) |
| 10062 |
.addRow( totals.assertions.passed ) ); |
| 10063 |
columns.push_back( SummaryColumn( "failed", Colour::ResultError ) |
| 10064 |
.addRow( totals.testCases.failed ) |
| 10065 |
.addRow( totals.assertions.failed ) ); |
| 10066 |
columns.push_back( SummaryColumn( "skipped", Colour::Skip ) |
| 10067 |
.addRow( totals.testCases.skipped ) |
| 10068 |
// Don't print "skipped assertions" |
| 10069 |
.addRow( 0 ) ); |
| 10070 |
columns.push_back( |
| 10071 |
SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) |
| 10072 |
.addRow( totals.testCases.failedButOk ) |
| 10073 |
.addRow( totals.assertions.failedButOk ) ); |
| 10074 |
printSummaryRow( stream, streamColour, "test cases"_sr, columns, 0 ); |
| 10075 |
printSummaryRow( stream, streamColour, "assertions"_sr, columns, 1 ); |
| 10076 |
} |
| 10077 |
|
| 10078 |
} // namespace Catch |
| 10079 |
|
| 10080 |
|
| 10081 |
// |
| 10082 |
|
| 10083 |
namespace Catch { |
| 10084 |
namespace { |
| 10085 |
void writeSourceInfo( JsonObjectWriter& writer, |
| 10086 |
SourceLineInfo const& sourceInfo ) { |
| 10087 |
auto source_location_writer = |
| 10088 |
writer.write( "source-location"_sr ).writeObject(); |
| 10089 |
source_location_writer.write( "filename"_sr ) |
| 10090 |
.write( sourceInfo.file ); |
| 10091 |
source_location_writer.write( "line"_sr ).write( sourceInfo.line ); |
| 10092 |
} |
| 10093 |
|
| 10094 |
void writeTags( JsonArrayWriter writer, std::vector<Tag> const& tags ) { |
| 10095 |
for ( auto const& tag : tags ) { |
| 10096 |
writer.write( tag.original ); |
| 10097 |
} |
| 10098 |
} |
| 10099 |
|
| 10100 |
void writeProperties( JsonArrayWriter writer, |
| 10101 |
TestCaseInfo const& info ) { |
| 10102 |
if ( info.isHidden() ) { writer.write( "is-hidden"_sr ); } |
| 10103 |
if ( info.okToFail() ) { writer.write( "ok-to-fail"_sr ); } |
| 10104 |
if ( info.expectedToFail() ) { |
| 10105 |
writer.write( "expected-to-fail"_sr ); |
| 10106 |
} |
| 10107 |
if ( info.throws() ) { writer.write( "throws"_sr ); } |
| 10108 |
} |
| 10109 |
|
| 10110 |
} // namespace |
| 10111 |
|
| 10112 |
JsonReporter::JsonReporter( ReporterConfig&& config ): |
| 10113 |
StreamingReporterBase{ CATCH_MOVE( config ) } { |
| 10114 |
|
| 10115 |
m_preferences.shouldRedirectStdOut = true; |
| 10116 |
// TBD: Do we want to report all assertions? XML reporter does |
| 10117 |
// not, but for machine-parseable reporters I think the answer |
| 10118 |
// should be yes. |
| 10119 |
m_preferences.shouldReportAllAssertions = true; |
| 10120 |
|
| 10121 |
m_objectWriters.emplace( m_stream ); |
| 10122 |
m_writers.emplace( Writer::Object ); |
| 10123 |
auto& writer = m_objectWriters.top(); |
| 10124 |
|
| 10125 |
writer.write( "version"_sr ).write( 1 ); |
| 10126 |
|
| 10127 |
{ |
| 10128 |
auto metadata_writer = writer.write( "metadata"_sr ).writeObject(); |
| 10129 |
metadata_writer.write( "name"_sr ).write( m_config->name() ); |
| 10130 |
metadata_writer.write( "rng-seed"_sr ).write( m_config->rngSeed() ); |
| 10131 |
metadata_writer.write( "catch2-version"_sr ) |
| 10132 |
.write( libraryVersion() ); |
| 10133 |
if ( m_config->testSpec().hasFilters() ) { |
| 10134 |
metadata_writer.write( "filters"_sr ) |
| 10135 |
.write( m_config->testSpec() ); |
| 10136 |
} |
| 10137 |
} |
| 10138 |
} |
| 10139 |
|
| 10140 |
JsonReporter::~JsonReporter() { |
| 10141 |
endListing(); |
| 10142 |
// TODO: Ensure this closes the top level object, add asserts |
| 10143 |
assert( m_writers.size() == 1 && "Only the top level object should be open" ); |
| 10144 |
assert( m_writers.top() == Writer::Object ); |
| 10145 |
endObject(); |
| 10146 |
m_stream << '\n' << std::flush; |
| 10147 |
assert( m_writers.empty() ); |
| 10148 |
} |
| 10149 |
|
| 10150 |
JsonArrayWriter& JsonReporter::startArray() { |
| 10151 |
m_arrayWriters.emplace( m_arrayWriters.top().writeArray() ); |
| 10152 |
m_writers.emplace( Writer::Array ); |
| 10153 |
return m_arrayWriters.top(); |
| 10154 |
} |
| 10155 |
JsonArrayWriter& JsonReporter::startArray( StringRef key ) { |
| 10156 |
m_arrayWriters.emplace( |
| 10157 |
m_objectWriters.top().write( key ).writeArray() ); |
| 10158 |
m_writers.emplace( Writer::Array ); |
| 10159 |
return m_arrayWriters.top(); |
| 10160 |
} |
| 10161 |
|
| 10162 |
JsonObjectWriter& JsonReporter::startObject() { |
| 10163 |
m_objectWriters.emplace( m_arrayWriters.top().writeObject() ); |
| 10164 |
m_writers.emplace( Writer::Object ); |
| 10165 |
return m_objectWriters.top(); |
| 10166 |
} |
| 10167 |
JsonObjectWriter& JsonReporter::startObject( StringRef key ) { |
| 10168 |
m_objectWriters.emplace( |
| 10169 |
m_objectWriters.top().write( key ).writeObject() ); |
| 10170 |
m_writers.emplace( Writer::Object ); |
| 10171 |
return m_objectWriters.top(); |
| 10172 |
} |
| 10173 |
|
| 10174 |
void JsonReporter::endObject() { |
| 10175 |
assert( isInside( Writer::Object ) ); |
| 10176 |
m_objectWriters.pop(); |
| 10177 |
m_writers.pop(); |
| 10178 |
} |
| 10179 |
void JsonReporter::endArray() { |
| 10180 |
assert( isInside( Writer::Array ) ); |
| 10181 |
m_arrayWriters.pop(); |
| 10182 |
m_writers.pop(); |
| 10183 |
} |
| 10184 |
|
| 10185 |
bool JsonReporter::isInside( Writer writer ) { |
| 10186 |
return !m_writers.empty() && m_writers.top() == writer; |
| 10187 |
} |
| 10188 |
|
| 10189 |
void JsonReporter::startListing() { |
| 10190 |
if ( !m_startedListing ) { startObject( "listings"_sr ); } |
| 10191 |
m_startedListing = true; |
| 10192 |
} |
| 10193 |
void JsonReporter::endListing() { |
| 10194 |
if ( m_startedListing ) { endObject(); } |
| 10195 |
m_startedListing = false; |
| 10196 |
} |
| 10197 |
|
| 10198 |
std::string JsonReporter::getDescription() { |
| 10199 |
return "Outputs listings as JSON. Test listing is Work-in-Progress!"; |
| 10200 |
} |
| 10201 |
|
| 10202 |
void JsonReporter::testRunStarting( TestRunInfo const& runInfo ) { |
| 10203 |
StreamingReporterBase::testRunStarting( runInfo ); |
| 10204 |
endListing(); |
| 10205 |
|
| 10206 |
assert( isInside( Writer::Object ) ); |
| 10207 |
startObject( "test-run"_sr ); |
| 10208 |
startArray( "test-cases"_sr ); |
| 10209 |
} |
| 10210 |
|
| 10211 |
static void writeCounts( JsonObjectWriter&& writer, Counts const& counts ) { |
| 10212 |
writer.write( "passed"_sr ).write( counts.passed ); |
| 10213 |
writer.write( "failed"_sr ).write( counts.failed ); |
| 10214 |
writer.write( "fail-but-ok"_sr ).write( counts.failedButOk ); |
| 10215 |
writer.write( "skipped"_sr ).write( counts.skipped ); |
| 10216 |
} |
| 10217 |
|
| 10218 |
void JsonReporter::testRunEnded(TestRunStats const& runStats) { |
| 10219 |
assert( isInside( Writer::Array ) ); |
| 10220 |
// End "test-cases" |
| 10221 |
endArray(); |
| 10222 |
|
| 10223 |
{ |
| 10224 |
auto totals = |
| 10225 |
m_objectWriters.top().write( "totals"_sr ).writeObject(); |
| 10226 |
writeCounts( totals.write( "assertions"_sr ).writeObject(), |
| 10227 |
runStats.totals.assertions ); |
| 10228 |
writeCounts( totals.write( "test-cases"_sr ).writeObject(), |
| 10229 |
runStats.totals.testCases ); |
| 10230 |
} |
| 10231 |
|
| 10232 |
// End the "test-run" object |
| 10233 |
endObject(); |
| 10234 |
} |
| 10235 |
|
| 10236 |
void JsonReporter::testCaseStarting( TestCaseInfo const& tcInfo ) { |
| 10237 |
StreamingReporterBase::testCaseStarting( tcInfo ); |
| 10238 |
|
| 10239 |
assert( isInside( Writer::Array ) && |
| 10240 |
"We should be in the 'test-cases' array" ); |
| 10241 |
startObject(); |
| 10242 |
// "test-info" prelude |
| 10243 |
{ |
| 10244 |
auto testInfo = |
| 10245 |
m_objectWriters.top().write( "test-info"_sr ).writeObject(); |
| 10246 |
// TODO: handle testName vs className!! |
| 10247 |
testInfo.write( "name"_sr ).write( tcInfo.name ); |
| 10248 |
writeSourceInfo(testInfo, tcInfo.lineInfo); |
| 10249 |
writeTags( testInfo.write( "tags"_sr ).writeArray(), tcInfo.tags ); |
| 10250 |
writeProperties( testInfo.write( "properties"_sr ).writeArray(), |
| 10251 |
tcInfo ); |
| 10252 |
} |
| 10253 |
|
| 10254 |
|
| 10255 |
// Start the array for individual test runs (testCasePartial pairs) |
| 10256 |
startArray( "runs"_sr ); |
| 10257 |
} |
| 10258 |
|
| 10259 |
void JsonReporter::testCaseEnded( TestCaseStats const& tcStats ) { |
| 10260 |
StreamingReporterBase::testCaseEnded( tcStats ); |
| 10261 |
|
| 10262 |
// We need to close the 'runs' array before finishing the test case |
| 10263 |
assert( isInside( Writer::Array ) ); |
| 10264 |
endArray(); |
| 10265 |
|
| 10266 |
{ |
| 10267 |
auto totals = |
| 10268 |
m_objectWriters.top().write( "totals"_sr ).writeObject(); |
| 10269 |
writeCounts( totals.write( "assertions"_sr ).writeObject(), |
| 10270 |
tcStats.totals.assertions ); |
| 10271 |
// We do not write the test case totals, because there will always be just one test case here. |
| 10272 |
// TODO: overall "result" -> success, skip, fail here? Or in partial result? |
| 10273 |
} |
| 10274 |
// We do not write out stderr/stdout, because we instead wrote those out in partial runs |
| 10275 |
|
| 10276 |
// TODO: aborting? |
| 10277 |
|
| 10278 |
// And we also close this test case's object |
| 10279 |
assert( isInside( Writer::Object ) ); |
| 10280 |
endObject(); |
| 10281 |
} |
| 10282 |
|
| 10283 |
void JsonReporter::testCasePartialStarting( TestCaseInfo const& /*tcInfo*/, |
| 10284 |
uint64_t index ) { |
| 10285 |
startObject(); |
| 10286 |
m_objectWriters.top().write( "run-idx"_sr ).write( index ); |
| 10287 |
startArray( "path"_sr ); |
| 10288 |
// TODO: we want to delay most of the printing to the 'root' section |
| 10289 |
// TODO: childSection key name? |
| 10290 |
} |
| 10291 |
|
| 10292 |
void JsonReporter::testCasePartialEnded( TestCaseStats const& tcStats, |
| 10293 |
uint64_t /*index*/ ) { |
| 10294 |
// Fixme: the top level section handles this. |
| 10295 |
//// path object |
| 10296 |
endArray(); |
| 10297 |
if ( !tcStats.stdOut.empty() ) { |
| 10298 |
m_objectWriters.top() |
| 10299 |
.write( "captured-stdout"_sr ) |
| 10300 |
.write( tcStats.stdOut ); |
| 10301 |
} |
| 10302 |
if ( !tcStats.stdErr.empty() ) { |
| 10303 |
m_objectWriters.top() |
| 10304 |
.write( "captured-stderr"_sr ) |
| 10305 |
.write( tcStats.stdErr ); |
| 10306 |
} |
| 10307 |
{ |
| 10308 |
auto totals = |
| 10309 |
m_objectWriters.top().write( "totals"_sr ).writeObject(); |
| 10310 |
writeCounts( totals.write( "assertions"_sr ).writeObject(), |
| 10311 |
tcStats.totals.assertions ); |
| 10312 |
// We do not write the test case totals, because there will |
| 10313 |
// always be just one test case here. |
| 10314 |
// TODO: overall "result" -> success, skip, fail here? Or in |
| 10315 |
// partial result? |
| 10316 |
} |
| 10317 |
// TODO: aborting? |
| 10318 |
// run object |
| 10319 |
endObject(); |
| 10320 |
} |
| 10321 |
|
| 10322 |
void JsonReporter::sectionStarting( SectionInfo const& sectionInfo ) { |
| 10323 |
assert( isInside( Writer::Array ) && |
| 10324 |
"Section should always start inside an object" ); |
| 10325 |
// We want to nest top level sections, even though it shares name |
| 10326 |
// and source loc with the TEST_CASE |
| 10327 |
auto& sectionObject = startObject(); |
| 10328 |
sectionObject.write( "kind"_sr ).write( "section"_sr ); |
| 10329 |
sectionObject.write( "name"_sr ).write( sectionInfo.name ); |
| 10330 |
writeSourceInfo( m_objectWriters.top(), sectionInfo.lineInfo ); |
| 10331 |
|
| 10332 |
|
| 10333 |
// TBD: Do we want to create this event lazily? It would become |
| 10334 |
// rather complex, but we could do it, and it would look |
| 10335 |
// better for empty sections. OTOH, empty sections should |
| 10336 |
// be rare. |
| 10337 |
startArray( "path"_sr ); |
| 10338 |
} |
| 10339 |
void JsonReporter::sectionEnded( SectionStats const& /*sectionStats */) { |
| 10340 |
// End the subpath array |
| 10341 |
endArray(); |
| 10342 |
// TODO: metadata |
| 10343 |
// TODO: what info do we have here? |
| 10344 |
|
| 10345 |
// End the section object |
| 10346 |
endObject(); |
| 10347 |
} |
| 10348 |
|
| 10349 |
void JsonReporter::assertionStarting( AssertionInfo const& /*assertionInfo*/ ) {} |
| 10350 |
void JsonReporter::assertionEnded( AssertionStats const& assertionStats ) { |
| 10351 |
// TODO: There is lot of different things to handle here, but |
| 10352 |
// we can fill it in later, after we show that the basic |
| 10353 |
// outline and streaming reporter impl works well enough. |
| 10354 |
//if ( !m_config->includeSuccessfulResults() |
| 10355 |
// && assertionStats.assertionResult.isOk() ) { |
| 10356 |
// return; |
| 10357 |
//} |
| 10358 |
assert( isInside( Writer::Array ) ); |
| 10359 |
auto assertionObject = m_arrayWriters.top().writeObject(); |
| 10360 |
|
| 10361 |
assertionObject.write( "kind"_sr ).write( "assertion"_sr ); |
| 10362 |
writeSourceInfo( assertionObject, |
| 10363 |
assertionStats.assertionResult.getSourceInfo() ); |
| 10364 |
assertionObject.write( "status"_sr ) |
| 10365 |
.write( assertionStats.assertionResult.isOk() ); |
| 10366 |
// TODO: handling of result. |
| 10367 |
// TODO: messages |
| 10368 |
// TODO: totals? |
| 10369 |
} |
| 10370 |
|
| 10371 |
|
| 10372 |
void JsonReporter::benchmarkPreparing( StringRef name ) { (void)name; } |
| 10373 |
void JsonReporter::benchmarkStarting( BenchmarkInfo const& ) {} |
| 10374 |
void JsonReporter::benchmarkEnded( BenchmarkStats<> const& ) {} |
| 10375 |
void JsonReporter::benchmarkFailed( StringRef error ) { (void)error; } |
| 10376 |
|
| 10377 |
void JsonReporter::listReporters( |
| 10378 |
std::vector<ReporterDescription> const& descriptions ) { |
| 10379 |
startListing(); |
| 10380 |
|
| 10381 |
auto writer = |
| 10382 |
m_objectWriters.top().write( "reporters"_sr ).writeArray(); |
| 10383 |
for ( auto const& desc : descriptions ) { |
| 10384 |
auto desc_writer = writer.writeObject(); |
| 10385 |
desc_writer.write( "name"_sr ).write( desc.name ); |
| 10386 |
desc_writer.write( "description"_sr ).write( desc.description ); |
| 10387 |
} |
| 10388 |
} |
| 10389 |
void JsonReporter::listListeners( |
| 10390 |
std::vector<ListenerDescription> const& descriptions ) { |
| 10391 |
startListing(); |
| 10392 |
|
| 10393 |
auto writer = |
| 10394 |
m_objectWriters.top().write( "listeners"_sr ).writeArray(); |
| 10395 |
|
| 10396 |
for ( auto const& desc : descriptions ) { |
| 10397 |
auto desc_writer = writer.writeObject(); |
| 10398 |
desc_writer.write( "name"_sr ).write( desc.name ); |
| 10399 |
desc_writer.write( "description"_sr ).write( desc.description ); |
| 10400 |
} |
| 10401 |
} |
| 10402 |
void JsonReporter::listTests( std::vector<TestCaseHandle> const& tests ) { |
| 10403 |
startListing(); |
| 10404 |
|
| 10405 |
auto writer = m_objectWriters.top().write( "tests"_sr ).writeArray(); |
| 10406 |
|
| 10407 |
for ( auto const& test : tests ) { |
| 10408 |
auto desc_writer = writer.writeObject(); |
| 10409 |
auto const& info = test.getTestCaseInfo(); |
| 10410 |
|
| 10411 |
desc_writer.write( "name"_sr ).write( info.name ); |
| 10412 |
desc_writer.write( "class-name"_sr ).write( info.className ); |
| 10413 |
{ |
| 10414 |
auto tag_writer = desc_writer.write( "tags"_sr ).writeArray(); |
| 10415 |
for ( auto const& tag : info.tags ) { |
| 10416 |
tag_writer.write( tag.original ); |
| 10417 |
} |
| 10418 |
} |
| 10419 |
writeSourceInfo( desc_writer, info.lineInfo ); |
| 10420 |
} |
| 10421 |
} |
| 10422 |
void JsonReporter::listTags( std::vector<TagInfo> const& tags ) { |
| 10423 |
startListing(); |
| 10424 |
|
| 10425 |
auto writer = m_objectWriters.top().write( "tags"_sr ).writeArray(); |
| 10426 |
for ( auto const& tag : tags ) { |
| 10427 |
auto tag_writer = writer.writeObject(); |
| 10428 |
{ |
| 10429 |
auto aliases_writer = |
| 10430 |
tag_writer.write( "aliases"_sr ).writeArray(); |
| 10431 |
for ( auto alias : tag.spellings ) { |
| 10432 |
aliases_writer.write( alias ); |
| 10433 |
} |
| 10434 |
} |
| 10435 |
tag_writer.write( "count"_sr ).write( tag.count ); |
| 10436 |
} |
| 10437 |
} |
| 10438 |
} // namespace Catch |
| 10439 |
|
| 10440 |
|
| 10441 |
|
| 10442 |
|
| 10443 |
#include <cassert> |
| 10444 |
#include <ctime> |
| 10445 |
#include <algorithm> |
| 10446 |
#include <iomanip> |
| 10447 |
|
| 10448 |
namespace Catch { |
| 10449 |
|
| 10450 |
namespace { |
| 10451 |
std::string getCurrentTimestamp() { |
| 10452 |
time_t rawtime; |
| 10453 |
std::time(&rawtime); |
| 10454 |
|
| 10455 |
std::tm timeInfo = {}; |
| 10456 |
#if defined (_MSC_VER) || defined (__MINGW32__) |
| 10457 |
gmtime_s(&timeInfo, &rawtime); |
| 10458 |
#elif defined (CATCH_PLATFORM_PLAYSTATION) |
| 10459 |
gmtime_s(&rawtime, &timeInfo); |
| 10460 |
#elif defined (__IAR_SYSTEMS_ICC__) |
| 10461 |
timeInfo = *std::gmtime(&rawtime); |
| 10462 |
#else |
| 10463 |
gmtime_r(&rawtime, &timeInfo); |
| 10464 |
#endif |
| 10465 |
|
| 10466 |
auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); |
| 10467 |
char timeStamp[timeStampSize]; |
| 10468 |
const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; |
| 10469 |
|
| 10470 |
std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); |
| 10471 |
|
| 10472 |
return std::string(timeStamp, timeStampSize - 1); |
| 10473 |
} |
| 10474 |
|
| 10475 |
std::string fileNameTag(std::vector<Tag> const& tags) { |
| 10476 |
auto it = std::find_if(begin(tags), |
| 10477 |
end(tags), |
| 10478 |
[] (Tag const& tag) { |
| 10479 |
return tag.original.size() > 0 |
| 10480 |
&& tag.original[0] == '#'; }); |
| 10481 |
if (it != tags.end()) { |
| 10482 |
return static_cast<std::string>( |
| 10483 |
it->original.substr(1, it->original.size() - 1) |
| 10484 |
); |
| 10485 |
} |
| 10486 |
return std::string(); |
| 10487 |
} |
| 10488 |
|
| 10489 |
// Formats the duration in seconds to 3 decimal places. |
| 10490 |
// This is done because some genius defined Maven Surefire schema |
| 10491 |
// in a way that only accepts 3 decimal places, and tools like |
| 10492 |
// Jenkins use that schema for validation JUnit reporter output. |
| 10493 |
std::string formatDuration( double seconds ) { |
| 10494 |
ReusableStringStream rss; |
| 10495 |
rss << std::fixed << std::setprecision( 3 ) << seconds; |
| 10496 |
return rss.str(); |
| 10497 |
} |
| 10498 |
|
| 10499 |
static void normalizeNamespaceMarkers(std::string& str) { |
| 10500 |
std::size_t pos = str.find( "::" ); |
| 10501 |
while ( pos != std::string::npos ) { |
| 10502 |
str.replace( pos, 2, "." ); |
| 10503 |
pos += 1; |
| 10504 |
pos = str.find( "::", pos ); |
| 10505 |
} |
| 10506 |
} |
| 10507 |
|
| 10508 |
} // anonymous namespace |
| 10509 |
|
| 10510 |
JunitReporter::JunitReporter( ReporterConfig&& _config ) |
| 10511 |
: CumulativeReporterBase( CATCH_MOVE(_config) ), |
| 10512 |
xml( m_stream ) |
| 10513 |
{ |
| 10514 |
m_preferences.shouldRedirectStdOut = true; |
| 10515 |
m_preferences.shouldReportAllAssertions = false; |
| 10516 |
m_shouldStoreSuccesfulAssertions = false; |
| 10517 |
} |
| 10518 |
|
| 10519 |
std::string JunitReporter::getDescription() { |
| 10520 |
return "Reports test results in an XML format that looks like Ant's junitreport target"; |
| 10521 |
} |
| 10522 |
|
| 10523 |
void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) { |
| 10524 |
CumulativeReporterBase::testRunStarting( runInfo ); |
| 10525 |
xml.startElement( "testsuites" ); |
| 10526 |
suiteTimer.start(); |
| 10527 |
stdOutForSuite.clear(); |
| 10528 |
stdErrForSuite.clear(); |
| 10529 |
unexpectedExceptions = 0; |
| 10530 |
} |
| 10531 |
|
| 10532 |
void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) { |
| 10533 |
m_okToFail = testCaseInfo.okToFail(); |
| 10534 |
} |
| 10535 |
|
| 10536 |
void JunitReporter::assertionEnded( AssertionStats const& assertionStats ) { |
| 10537 |
if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) |
| 10538 |
unexpectedExceptions++; |
| 10539 |
CumulativeReporterBase::assertionEnded( assertionStats ); |
| 10540 |
} |
| 10541 |
|
| 10542 |
void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { |
| 10543 |
stdOutForSuite += testCaseStats.stdOut; |
| 10544 |
stdErrForSuite += testCaseStats.stdErr; |
| 10545 |
CumulativeReporterBase::testCaseEnded( testCaseStats ); |
| 10546 |
} |
| 10547 |
|
| 10548 |
void JunitReporter::testRunEndedCumulative() { |
| 10549 |
const auto suiteTime = suiteTimer.getElapsedSeconds(); |
| 10550 |
writeRun( *m_testRun, suiteTime ); |
| 10551 |
xml.endElement(); |
| 10552 |
} |
| 10553 |
|
| 10554 |
void JunitReporter::writeRun( TestRunNode const& testRunNode, double suiteTime ) { |
| 10555 |
XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); |
| 10556 |
|
| 10557 |
TestRunStats const& stats = testRunNode.value; |
| 10558 |
xml.writeAttribute( "name"_sr, stats.runInfo.name ); |
| 10559 |
xml.writeAttribute( "errors"_sr, unexpectedExceptions ); |
| 10560 |
xml.writeAttribute( "failures"_sr, stats.totals.assertions.failed-unexpectedExceptions ); |
| 10561 |
xml.writeAttribute( "skipped"_sr, stats.totals.assertions.skipped ); |
| 10562 |
xml.writeAttribute( "tests"_sr, stats.totals.assertions.total() ); |
| 10563 |
xml.writeAttribute( "hostname"_sr, "tbd"_sr ); // !TBD |
| 10564 |
if( m_config->showDurations() == ShowDurations::Never ) |
| 10565 |
xml.writeAttribute( "time"_sr, ""_sr ); |
| 10566 |
else |
| 10567 |
xml.writeAttribute( "time"_sr, formatDuration( suiteTime ) ); |
| 10568 |
xml.writeAttribute( "timestamp"_sr, getCurrentTimestamp() ); |
| 10569 |
|
| 10570 |
// Write properties |
| 10571 |
{ |
| 10572 |
auto properties = xml.scopedElement("properties"); |
| 10573 |
xml.scopedElement("property") |
| 10574 |
.writeAttribute("name"_sr, "random-seed"_sr) |
| 10575 |
.writeAttribute("value"_sr, m_config->rngSeed()); |
| 10576 |
if (m_config->testSpec().hasFilters()) { |
| 10577 |
xml.scopedElement("property") |
| 10578 |
.writeAttribute("name"_sr, "filters"_sr) |
| 10579 |
.writeAttribute("value"_sr, m_config->testSpec()); |
| 10580 |
} |
| 10581 |
} |
| 10582 |
|
| 10583 |
// Write test cases |
| 10584 |
for( auto const& child : testRunNode.children ) |
| 10585 |
writeTestCase( *child ); |
| 10586 |
|
| 10587 |
xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline ); |
| 10588 |
xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline ); |
| 10589 |
} |
| 10590 |
|
| 10591 |
void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) { |
| 10592 |
TestCaseStats const& stats = testCaseNode.value; |
| 10593 |
|
| 10594 |
// All test cases have exactly one section - which represents the |
| 10595 |
// test case itself. That section may have 0-n nested sections |
| 10596 |
assert( testCaseNode.children.size() == 1 ); |
| 10597 |
SectionNode const& rootSection = *testCaseNode.children.front(); |
| 10598 |
|
| 10599 |
std::string className = |
| 10600 |
static_cast<std::string>( stats.testInfo->className ); |
| 10601 |
|
| 10602 |
if( className.empty() ) { |
| 10603 |
className = fileNameTag(stats.testInfo->tags); |
| 10604 |
if ( className.empty() ) { |
| 10605 |
className = "global"; |
| 10606 |
} |
| 10607 |
} |
| 10608 |
|
| 10609 |
if ( !m_config->name().empty() ) |
| 10610 |
className = static_cast<std::string>(m_config->name()) + '.' + className; |
| 10611 |
|
| 10612 |
normalizeNamespaceMarkers(className); |
| 10613 |
|
| 10614 |
writeSection( className, "", rootSection, stats.testInfo->okToFail() ); |
| 10615 |
} |
| 10616 |
|
| 10617 |
void JunitReporter::writeSection( std::string const& className, |
| 10618 |
std::string const& rootName, |
| 10619 |
SectionNode const& sectionNode, |
| 10620 |
bool testOkToFail) { |
| 10621 |
std::string name = trim( sectionNode.stats.sectionInfo.name ); |
| 10622 |
if( !rootName.empty() ) |
| 10623 |
name = rootName + '/' + name; |
| 10624 |
|
| 10625 |
if ( sectionNode.stats.assertions.total() > 0 |
| 10626 |
|| !sectionNode.stdOut.empty() |
| 10627 |
|| !sectionNode.stdErr.empty() ) { |
| 10628 |
XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); |
| 10629 |
if( className.empty() ) { |
| 10630 |
xml.writeAttribute( "classname"_sr, name ); |
| 10631 |
xml.writeAttribute( "name"_sr, "root"_sr ); |
| 10632 |
} |
| 10633 |
else { |
| 10634 |
xml.writeAttribute( "classname"_sr, className ); |
| 10635 |
xml.writeAttribute( "name"_sr, name ); |
| 10636 |
} |
| 10637 |
xml.writeAttribute( "time"_sr, formatDuration( sectionNode.stats.durationInSeconds ) ); |
| 10638 |
// This is not ideal, but it should be enough to mimic gtest's |
| 10639 |
// junit output. |
| 10640 |
// Ideally the JUnit reporter would also handle `skipTest` |
| 10641 |
// events and write those out appropriately. |
| 10642 |
xml.writeAttribute( "status"_sr, "run"_sr ); |
| 10643 |
|
| 10644 |
if (sectionNode.stats.assertions.failedButOk) { |
| 10645 |
xml.scopedElement("skipped") |
| 10646 |
.writeAttribute("message", "TEST_CASE tagged with !mayfail"); |
| 10647 |
} |
| 10648 |
|
| 10649 |
writeAssertions( sectionNode ); |
| 10650 |
|
| 10651 |
|
| 10652 |
if( !sectionNode.stdOut.empty() ) |
| 10653 |
xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline ); |
| 10654 |
if( !sectionNode.stdErr.empty() ) |
| 10655 |
xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline ); |
| 10656 |
} |
| 10657 |
for( auto const& childNode : sectionNode.childSections ) |
| 10658 |
if( className.empty() ) |
| 10659 |
writeSection( name, "", *childNode, testOkToFail ); |
| 10660 |
else |
| 10661 |
writeSection( className, name, *childNode, testOkToFail ); |
| 10662 |
} |
| 10663 |
|
| 10664 |
void JunitReporter::writeAssertions( SectionNode const& sectionNode ) { |
| 10665 |
for (auto const& assertionOrBenchmark : sectionNode.assertionsAndBenchmarks) { |
| 10666 |
if (assertionOrBenchmark.isAssertion()) { |
| 10667 |
writeAssertion(assertionOrBenchmark.asAssertion()); |
| 10668 |
} |
| 10669 |
} |
| 10670 |
} |
| 10671 |
|
| 10672 |
void JunitReporter::writeAssertion( AssertionStats const& stats ) { |
| 10673 |
AssertionResult const& result = stats.assertionResult; |
| 10674 |
if ( !result.isOk() || |
| 10675 |
result.getResultType() == ResultWas::ExplicitSkip ) { |
| 10676 |
std::string elementName; |
| 10677 |
switch( result.getResultType() ) { |
| 10678 |
case ResultWas::ThrewException: |
| 10679 |
case ResultWas::FatalErrorCondition: |
| 10680 |
elementName = "error"; |
| 10681 |
break; |
| 10682 |
case ResultWas::ExplicitFailure: |
| 10683 |
case ResultWas::ExpressionFailed: |
| 10684 |
case ResultWas::DidntThrowException: |
| 10685 |
elementName = "failure"; |
| 10686 |
break; |
| 10687 |
case ResultWas::ExplicitSkip: |
| 10688 |
elementName = "skipped"; |
| 10689 |
break; |
| 10690 |
// We should never see these here: |
| 10691 |
case ResultWas::Info: |
| 10692 |
case ResultWas::Warning: |
| 10693 |
case ResultWas::Ok: |
| 10694 |
case ResultWas::Unknown: |
| 10695 |
case ResultWas::FailureBit: |
| 10696 |
case ResultWas::Exception: |
| 10697 |
elementName = "internalError"; |
| 10698 |
break; |
| 10699 |
} |
| 10700 |
|
| 10701 |
XmlWriter::ScopedElement e = xml.scopedElement( elementName ); |
| 10702 |
|
| 10703 |
xml.writeAttribute( "message"_sr, result.getExpression() ); |
| 10704 |
xml.writeAttribute( "type"_sr, result.getTestMacroName() ); |
| 10705 |
|
| 10706 |
ReusableStringStream rss; |
| 10707 |
if ( result.getResultType() == ResultWas::ExplicitSkip ) { |
| 10708 |
rss << "SKIPPED\n"; |
| 10709 |
} else { |
| 10710 |
rss << "FAILED" << ":\n"; |
| 10711 |
if (result.hasExpression()) { |
| 10712 |
rss << " "; |
| 10713 |
rss << result.getExpressionInMacro(); |
| 10714 |
rss << '\n'; |
| 10715 |
} |
| 10716 |
if (result.hasExpandedExpression()) { |
| 10717 |
rss << "with expansion:\n"; |
| 10718 |
rss << TextFlow::Column(result.getExpandedExpression()).indent(2) << '\n'; |
| 10719 |
} |
| 10720 |
} |
| 10721 |
|
| 10722 |
if( result.hasMessage() ) |
| 10723 |
rss << result.getMessage() << '\n'; |
| 10724 |
for( auto const& msg : stats.infoMessages ) |
| 10725 |
if( msg.type == ResultWas::Info ) |
| 10726 |
rss << msg.message << '\n'; |
| 10727 |
|
| 10728 |
rss << "at " << result.getSourceInfo(); |
| 10729 |
xml.writeText( rss.str(), XmlFormatting::Newline ); |
| 10730 |
} |
| 10731 |
} |
| 10732 |
|
| 10733 |
} // end namespace Catch |
| 10734 |
|
| 10735 |
|
| 10736 |
|
| 10737 |
|
| 10738 |
#include <ostream> |
| 10739 |
|
| 10740 |
namespace Catch { |
| 10741 |
void MultiReporter::updatePreferences(IEventListener const& reporterish) { |
| 10742 |
m_preferences.shouldRedirectStdOut |= |
| 10743 |
reporterish.getPreferences().shouldRedirectStdOut; |
| 10744 |
m_preferences.shouldReportAllAssertions |= |
| 10745 |
reporterish.getPreferences().shouldReportAllAssertions; |
| 10746 |
} |
| 10747 |
|
| 10748 |
void MultiReporter::addListener( IEventListenerPtr&& listener ) { |
| 10749 |
updatePreferences(*listener); |
| 10750 |
m_reporterLikes.insert(m_reporterLikes.begin() + m_insertedListeners, CATCH_MOVE(listener) ); |
| 10751 |
++m_insertedListeners; |
| 10752 |
} |
| 10753 |
|
| 10754 |
void MultiReporter::addReporter( IEventListenerPtr&& reporter ) { |
| 10755 |
updatePreferences(*reporter); |
| 10756 |
|
| 10757 |
// We will need to output the captured stdout if there are reporters |
| 10758 |
// that do not want it captured. |
| 10759 |
// We do not consider listeners, because it is generally assumed that |
| 10760 |
// listeners are output-transparent, even though they can ask for stdout |
| 10761 |
// capture to do something with it. |
| 10762 |
m_haveNoncapturingReporters |= !reporter->getPreferences().shouldRedirectStdOut; |
| 10763 |
|
| 10764 |
// Reporters can always be placed to the back without breaking the |
| 10765 |
// reporting order |
| 10766 |
m_reporterLikes.push_back( CATCH_MOVE( reporter ) ); |
| 10767 |
} |
| 10768 |
|
| 10769 |
void MultiReporter::noMatchingTestCases( StringRef unmatchedSpec ) { |
| 10770 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10771 |
reporterish->noMatchingTestCases( unmatchedSpec ); |
| 10772 |
} |
| 10773 |
} |
| 10774 |
|
| 10775 |
void MultiReporter::fatalErrorEncountered( StringRef error ) { |
| 10776 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10777 |
reporterish->fatalErrorEncountered( error ); |
| 10778 |
} |
| 10779 |
} |
| 10780 |
|
| 10781 |
void MultiReporter::reportInvalidTestSpec( StringRef arg ) { |
| 10782 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10783 |
reporterish->reportInvalidTestSpec( arg ); |
| 10784 |
} |
| 10785 |
} |
| 10786 |
|
| 10787 |
void MultiReporter::benchmarkPreparing( StringRef name ) { |
| 10788 |
for (auto& reporterish : m_reporterLikes) { |
| 10789 |
reporterish->benchmarkPreparing(name); |
| 10790 |
} |
| 10791 |
} |
| 10792 |
void MultiReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) { |
| 10793 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10794 |
reporterish->benchmarkStarting( benchmarkInfo ); |
| 10795 |
} |
| 10796 |
} |
| 10797 |
void MultiReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) { |
| 10798 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10799 |
reporterish->benchmarkEnded( benchmarkStats ); |
| 10800 |
} |
| 10801 |
} |
| 10802 |
|
| 10803 |
void MultiReporter::benchmarkFailed( StringRef error ) { |
| 10804 |
for (auto& reporterish : m_reporterLikes) { |
| 10805 |
reporterish->benchmarkFailed(error); |
| 10806 |
} |
| 10807 |
} |
| 10808 |
|
| 10809 |
void MultiReporter::testRunStarting( TestRunInfo const& testRunInfo ) { |
| 10810 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10811 |
reporterish->testRunStarting( testRunInfo ); |
| 10812 |
} |
| 10813 |
} |
| 10814 |
|
| 10815 |
void MultiReporter::testCaseStarting( TestCaseInfo const& testInfo ) { |
| 10816 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10817 |
reporterish->testCaseStarting( testInfo ); |
| 10818 |
} |
| 10819 |
} |
| 10820 |
|
| 10821 |
void |
| 10822 |
MultiReporter::testCasePartialStarting( TestCaseInfo const& testInfo, |
| 10823 |
uint64_t partNumber ) { |
| 10824 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10825 |
reporterish->testCasePartialStarting( testInfo, partNumber ); |
| 10826 |
} |
| 10827 |
} |
| 10828 |
|
| 10829 |
void MultiReporter::sectionStarting( SectionInfo const& sectionInfo ) { |
| 10830 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10831 |
reporterish->sectionStarting( sectionInfo ); |
| 10832 |
} |
| 10833 |
} |
| 10834 |
|
| 10835 |
void MultiReporter::assertionStarting( AssertionInfo const& assertionInfo ) { |
| 10836 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10837 |
reporterish->assertionStarting( assertionInfo ); |
| 10838 |
} |
| 10839 |
} |
| 10840 |
|
| 10841 |
void MultiReporter::assertionEnded( AssertionStats const& assertionStats ) { |
| 10842 |
const bool reportByDefault = |
| 10843 |
assertionStats.assertionResult.getResultType() != ResultWas::Ok || |
| 10844 |
m_config->includeSuccessfulResults(); |
| 10845 |
|
| 10846 |
for ( auto & reporterish : m_reporterLikes ) { |
| 10847 |
if ( reportByDefault || |
| 10848 |
reporterish->getPreferences().shouldReportAllAssertions ) { |
| 10849 |
reporterish->assertionEnded( assertionStats ); |
| 10850 |
} |
| 10851 |
} |
| 10852 |
} |
| 10853 |
|
| 10854 |
void MultiReporter::sectionEnded( SectionStats const& sectionStats ) { |
| 10855 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10856 |
reporterish->sectionEnded( sectionStats ); |
| 10857 |
} |
| 10858 |
} |
| 10859 |
|
| 10860 |
void MultiReporter::testCasePartialEnded( TestCaseStats const& testStats, |
| 10861 |
uint64_t partNumber ) { |
| 10862 |
if ( m_preferences.shouldRedirectStdOut && |
| 10863 |
m_haveNoncapturingReporters ) { |
| 10864 |
if ( !testStats.stdOut.empty() ) { |
| 10865 |
Catch::cout() << testStats.stdOut << std::flush; |
| 10866 |
} |
| 10867 |
if ( !testStats.stdErr.empty() ) { |
| 10868 |
Catch::cerr() << testStats.stdErr << std::flush; |
| 10869 |
} |
| 10870 |
} |
| 10871 |
|
| 10872 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10873 |
reporterish->testCasePartialEnded( testStats, partNumber ); |
| 10874 |
} |
| 10875 |
} |
| 10876 |
|
| 10877 |
void MultiReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { |
| 10878 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10879 |
reporterish->testCaseEnded( testCaseStats ); |
| 10880 |
} |
| 10881 |
} |
| 10882 |
|
| 10883 |
void MultiReporter::testRunEnded( TestRunStats const& testRunStats ) { |
| 10884 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10885 |
reporterish->testRunEnded( testRunStats ); |
| 10886 |
} |
| 10887 |
} |
| 10888 |
|
| 10889 |
|
| 10890 |
void MultiReporter::skipTest( TestCaseInfo const& testInfo ) { |
| 10891 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10892 |
reporterish->skipTest( testInfo ); |
| 10893 |
} |
| 10894 |
} |
| 10895 |
|
| 10896 |
void MultiReporter::listReporters(std::vector<ReporterDescription> const& descriptions) { |
| 10897 |
for (auto& reporterish : m_reporterLikes) { |
| 10898 |
reporterish->listReporters(descriptions); |
| 10899 |
} |
| 10900 |
} |
| 10901 |
|
| 10902 |
void MultiReporter::listListeners( |
| 10903 |
std::vector<ListenerDescription> const& descriptions ) { |
| 10904 |
for ( auto& reporterish : m_reporterLikes ) { |
| 10905 |
reporterish->listListeners( descriptions ); |
| 10906 |
} |
| 10907 |
} |
| 10908 |
|
| 10909 |
void MultiReporter::listTests(std::vector<TestCaseHandle> const& tests) { |
| 10910 |
for (auto& reporterish : m_reporterLikes) { |
| 10911 |
reporterish->listTests(tests); |
| 10912 |
} |
| 10913 |
} |
| 10914 |
|
| 10915 |
void MultiReporter::listTags(std::vector<TagInfo> const& tags) { |
| 10916 |
for (auto& reporterish : m_reporterLikes) { |
| 10917 |
reporterish->listTags(tags); |
| 10918 |
} |
| 10919 |
} |
| 10920 |
|
| 10921 |
} // end namespace Catch |
| 10922 |
|
| 10923 |
|
| 10924 |
|
| 10925 |
|
| 10926 |
|
| 10927 |
namespace Catch { |
| 10928 |
namespace Detail { |
| 10929 |
|
| 10930 |
void registerReporterImpl( std::string const& name, |
| 10931 |
IReporterFactoryPtr reporterPtr ) { |
| 10932 |
CATCH_TRY { |
| 10933 |
getMutableRegistryHub().registerReporter( |
| 10934 |
name, CATCH_MOVE( reporterPtr ) ); |
| 10935 |
} |
| 10936 |
CATCH_CATCH_ALL { |
| 10937 |
// Do not throw when constructing global objects, instead |
| 10938 |
// register the exception to be processed later |
| 10939 |
getMutableRegistryHub().registerStartupException(); |
| 10940 |
} |
| 10941 |
} |
| 10942 |
|
| 10943 |
void registerListenerImpl( Detail::unique_ptr<EventListenerFactory> listenerFactory ) { |
| 10944 |
getMutableRegistryHub().registerListener( CATCH_MOVE(listenerFactory) ); |
| 10945 |
} |
| 10946 |
|
| 10947 |
|
| 10948 |
} // namespace Detail |
| 10949 |
} // namespace Catch |
| 10950 |
|
| 10951 |
|
| 10952 |
|
| 10953 |
|
| 10954 |
#include <map> |
| 10955 |
|
| 10956 |
namespace Catch { |
| 10957 |
|
| 10958 |
namespace { |
| 10959 |
std::string createMetadataString(IConfig const& config) { |
| 10960 |
ReusableStringStream sstr; |
| 10961 |
if ( config.testSpec().hasFilters() ) { |
| 10962 |
sstr << "filters='" |
| 10963 |
<< config.testSpec() |
| 10964 |
<< "' "; |
| 10965 |
} |
| 10966 |
sstr << "rng-seed=" << config.rngSeed(); |
| 10967 |
return sstr.str(); |
| 10968 |
} |
| 10969 |
} |
| 10970 |
|
| 10971 |
void SonarQubeReporter::testRunStarting(TestRunInfo const& testRunInfo) { |
| 10972 |
CumulativeReporterBase::testRunStarting(testRunInfo); |
| 10973 |
|
| 10974 |
xml.writeComment( createMetadataString( *m_config ) ); |
| 10975 |
xml.startElement("testExecutions"); |
| 10976 |
xml.writeAttribute("version"_sr, '1'); |
| 10977 |
} |
| 10978 |
|
| 10979 |
void SonarQubeReporter::writeRun( TestRunNode const& runNode ) { |
| 10980 |
std::map<StringRef, std::vector<TestCaseNode const*>> testsPerFile; |
| 10981 |
|
| 10982 |
for ( auto const& child : runNode.children ) { |
| 10983 |
testsPerFile[child->value.testInfo->lineInfo.file].push_back( |
| 10984 |
child.get() ); |
| 10985 |
} |
| 10986 |
|
| 10987 |
for ( auto const& kv : testsPerFile ) { |
| 10988 |
writeTestFile( kv.first, kv.second ); |
| 10989 |
} |
| 10990 |
} |
| 10991 |
|
| 10992 |
void SonarQubeReporter::writeTestFile(StringRef filename, std::vector<TestCaseNode const*> const& testCaseNodes) { |
| 10993 |
XmlWriter::ScopedElement e = xml.scopedElement("file"); |
| 10994 |
xml.writeAttribute("path"_sr, filename); |
| 10995 |
|
| 10996 |
for (auto const& child : testCaseNodes) |
| 10997 |
writeTestCase(*child); |
| 10998 |
} |
| 10999 |
|
| 11000 |
void SonarQubeReporter::writeTestCase(TestCaseNode const& testCaseNode) { |
| 11001 |
// All test cases have exactly one section - which represents the |
| 11002 |
// test case itself. That section may have 0-n nested sections |
| 11003 |
assert(testCaseNode.children.size() == 1); |
| 11004 |
SectionNode const& rootSection = *testCaseNode.children.front(); |
| 11005 |
writeSection("", rootSection, testCaseNode.value.testInfo->okToFail()); |
| 11006 |
} |
| 11007 |
|
| 11008 |
void SonarQubeReporter::writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail) { |
| 11009 |
std::string name = trim(sectionNode.stats.sectionInfo.name); |
| 11010 |
if (!rootName.empty()) |
| 11011 |
name = rootName + '/' + name; |
| 11012 |
|
| 11013 |
if ( sectionNode.stats.assertions.total() > 0 |
| 11014 |
|| !sectionNode.stdOut.empty() |
| 11015 |
|| !sectionNode.stdErr.empty() ) { |
| 11016 |
XmlWriter::ScopedElement e = xml.scopedElement("testCase"); |
| 11017 |
xml.writeAttribute("name"_sr, name); |
| 11018 |
xml.writeAttribute("duration"_sr, static_cast<long>(sectionNode.stats.durationInSeconds * 1000)); |
| 11019 |
|
| 11020 |
writeAssertions(sectionNode, okToFail); |
| 11021 |
} |
| 11022 |
|
| 11023 |
for (auto const& childNode : sectionNode.childSections) |
| 11024 |
writeSection(name, *childNode, okToFail); |
| 11025 |
} |
| 11026 |
|
| 11027 |
void SonarQubeReporter::writeAssertions(SectionNode const& sectionNode, bool okToFail) { |
| 11028 |
for (auto const& assertionOrBenchmark : sectionNode.assertionsAndBenchmarks) { |
| 11029 |
if (assertionOrBenchmark.isAssertion()) { |
| 11030 |
writeAssertion(assertionOrBenchmark.asAssertion(), okToFail); |
| 11031 |
} |
| 11032 |
} |
| 11033 |
} |
| 11034 |
|
| 11035 |
void SonarQubeReporter::writeAssertion(AssertionStats const& stats, bool okToFail) { |
| 11036 |
AssertionResult const& result = stats.assertionResult; |
| 11037 |
if ( !result.isOk() || |
| 11038 |
result.getResultType() == ResultWas::ExplicitSkip ) { |
| 11039 |
std::string elementName; |
| 11040 |
if (okToFail) { |
| 11041 |
elementName = "skipped"; |
| 11042 |
} else { |
| 11043 |
switch (result.getResultType()) { |
| 11044 |
case ResultWas::ThrewException: |
| 11045 |
case ResultWas::FatalErrorCondition: |
| 11046 |
elementName = "error"; |
| 11047 |
break; |
| 11048 |
case ResultWas::ExplicitFailure: |
| 11049 |
case ResultWas::ExpressionFailed: |
| 11050 |
case ResultWas::DidntThrowException: |
| 11051 |
elementName = "failure"; |
| 11052 |
break; |
| 11053 |
case ResultWas::ExplicitSkip: |
| 11054 |
elementName = "skipped"; |
| 11055 |
break; |
| 11056 |
// We should never see these here: |
| 11057 |
case ResultWas::Info: |
| 11058 |
case ResultWas::Warning: |
| 11059 |
case ResultWas::Ok: |
| 11060 |
case ResultWas::Unknown: |
| 11061 |
case ResultWas::FailureBit: |
| 11062 |
case ResultWas::Exception: |
| 11063 |
elementName = "internalError"; |
| 11064 |
break; |
| 11065 |
} |
| 11066 |
} |
| 11067 |
|
| 11068 |
XmlWriter::ScopedElement e = xml.scopedElement(elementName); |
| 11069 |
|
| 11070 |
ReusableStringStream messageRss; |
| 11071 |
messageRss << result.getTestMacroName() << '(' << result.getExpression() << ')'; |
| 11072 |
xml.writeAttribute("message"_sr, messageRss.str()); |
| 11073 |
|
| 11074 |
ReusableStringStream textRss; |
| 11075 |
if ( result.getResultType() == ResultWas::ExplicitSkip ) { |
| 11076 |
textRss << "SKIPPED\n"; |
| 11077 |
} else { |
| 11078 |
textRss << "FAILED:\n"; |
| 11079 |
if (result.hasExpression()) { |
| 11080 |
textRss << '\t' << result.getExpressionInMacro() << '\n'; |
| 11081 |
} |
| 11082 |
if (result.hasExpandedExpression()) { |
| 11083 |
textRss << "with expansion:\n\t" << result.getExpandedExpression() << '\n'; |
| 11084 |
} |
| 11085 |
} |
| 11086 |
|
| 11087 |
if (result.hasMessage()) |
| 11088 |
textRss << result.getMessage() << '\n'; |
| 11089 |
|
| 11090 |
for (auto const& msg : stats.infoMessages) |
| 11091 |
if (msg.type == ResultWas::Info) |
| 11092 |
textRss << msg.message << '\n'; |
| 11093 |
|
| 11094 |
textRss << "at " << result.getSourceInfo(); |
| 11095 |
xml.writeText(textRss.str(), XmlFormatting::Newline); |
| 11096 |
} |
| 11097 |
} |
| 11098 |
|
| 11099 |
} // end namespace Catch |
| 11100 |
|
| 11101 |
|
| 11102 |
|
| 11103 |
namespace Catch { |
| 11104 |
|
| 11105 |
StreamingReporterBase::~StreamingReporterBase() = default; |
| 11106 |
|
| 11107 |
void |
| 11108 |
StreamingReporterBase::testRunStarting( TestRunInfo const& _testRunInfo ) { |
| 11109 |
currentTestRunInfo = _testRunInfo; |
| 11110 |
} |
| 11111 |
|
| 11112 |
void StreamingReporterBase::testRunEnded( TestRunStats const& ) { |
| 11113 |
currentTestCaseInfo = nullptr; |
| 11114 |
} |
| 11115 |
|
| 11116 |
} // end namespace Catch |
| 11117 |
|
| 11118 |
|
| 11119 |
|
| 11120 |
#include <algorithm> |
| 11121 |
#include <ostream> |
| 11122 |
|
| 11123 |
namespace Catch { |
| 11124 |
|
| 11125 |
namespace { |
| 11126 |
// Yes, this has to be outside the class and namespaced by naming. |
| 11127 |
// Making older compiler happy is hard. |
| 11128 |
static constexpr StringRef tapFailedString = "not ok"_sr; |
| 11129 |
static constexpr StringRef tapPassedString = "ok"_sr; |
| 11130 |
static constexpr Colour::Code tapDimColour = Colour::FileName; |
| 11131 |
|
| 11132 |
class TapAssertionPrinter { |
| 11133 |
public: |
| 11134 |
TapAssertionPrinter& operator= (TapAssertionPrinter const&) = delete; |
| 11135 |
TapAssertionPrinter(TapAssertionPrinter const&) = delete; |
| 11136 |
TapAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter, ColourImpl* colour_) |
| 11137 |
: stream(_stream) |
| 11138 |
, result(_stats.assertionResult) |
| 11139 |
, messages(_stats.infoMessages) |
| 11140 |
, itMessage(_stats.infoMessages.begin()) |
| 11141 |
, printInfoMessages(true) |
| 11142 |
, counter(_counter) |
| 11143 |
, colourImpl( colour_ ) {} |
| 11144 |
|
| 11145 |
void print() { |
| 11146 |
itMessage = messages.begin(); |
| 11147 |
|
| 11148 |
switch (result.getResultType()) { |
| 11149 |
case ResultWas::Ok: |
| 11150 |
printResultType(tapPassedString); |
| 11151 |
printOriginalExpression(); |
| 11152 |
printReconstructedExpression(); |
| 11153 |
if (!result.hasExpression()) |
| 11154 |
printRemainingMessages(Colour::None); |
| 11155 |
else |
| 11156 |
printRemainingMessages(); |
| 11157 |
break; |
| 11158 |
case ResultWas::ExpressionFailed: |
| 11159 |
if (result.isOk()) { |
| 11160 |
printResultType(tapPassedString); |
| 11161 |
} else { |
| 11162 |
printResultType(tapFailedString); |
| 11163 |
} |
| 11164 |
printOriginalExpression(); |
| 11165 |
printReconstructedExpression(); |
| 11166 |
if (result.isOk()) { |
| 11167 |
printIssue(" # TODO"); |
| 11168 |
} |
| 11169 |
printRemainingMessages(); |
| 11170 |
break; |
| 11171 |
case ResultWas::ThrewException: |
| 11172 |
printResultType(tapFailedString); |
| 11173 |
printIssue("unexpected exception with message:"_sr); |
| 11174 |
printMessage(); |
| 11175 |
printExpressionWas(); |
| 11176 |
printRemainingMessages(); |
| 11177 |
break; |
| 11178 |
case ResultWas::FatalErrorCondition: |
| 11179 |
printResultType(tapFailedString); |
| 11180 |
printIssue("fatal error condition with message:"_sr); |
| 11181 |
printMessage(); |
| 11182 |
printExpressionWas(); |
| 11183 |
printRemainingMessages(); |
| 11184 |
break; |
| 11185 |
case ResultWas::DidntThrowException: |
| 11186 |
printResultType(tapFailedString); |
| 11187 |
printIssue("expected exception, got none"_sr); |
| 11188 |
printExpressionWas(); |
| 11189 |
printRemainingMessages(); |
| 11190 |
break; |
| 11191 |
case ResultWas::Info: |
| 11192 |
printResultType("info"_sr); |
| 11193 |
printMessage(); |
| 11194 |
printRemainingMessages(); |
| 11195 |
break; |
| 11196 |
case ResultWas::Warning: |
| 11197 |
printResultType("warning"_sr); |
| 11198 |
printMessage(); |
| 11199 |
printRemainingMessages(); |
| 11200 |
break; |
| 11201 |
case ResultWas::ExplicitFailure: |
| 11202 |
printResultType(tapFailedString); |
| 11203 |
printIssue("explicitly"_sr); |
| 11204 |
printRemainingMessages(Colour::None); |
| 11205 |
break; |
| 11206 |
case ResultWas::ExplicitSkip: |
| 11207 |
printResultType(tapPassedString); |
| 11208 |
printIssue(" # SKIP"_sr); |
| 11209 |
printMessage(); |
| 11210 |
printRemainingMessages(); |
| 11211 |
break; |
| 11212 |
// These cases are here to prevent compiler warnings |
| 11213 |
case ResultWas::Unknown: |
| 11214 |
case ResultWas::FailureBit: |
| 11215 |
case ResultWas::Exception: |
| 11216 |
printResultType("** internal error **"_sr); |
| 11217 |
break; |
| 11218 |
} |
| 11219 |
} |
| 11220 |
|
| 11221 |
private: |
| 11222 |
void printResultType(StringRef passOrFail) const { |
| 11223 |
if (!passOrFail.empty()) { |
| 11224 |
stream << passOrFail << ' ' << counter << " -"; |
| 11225 |
} |
| 11226 |
} |
| 11227 |
|
| 11228 |
void printIssue(StringRef issue) const { |
| 11229 |
stream << ' ' << issue; |
| 11230 |
} |
| 11231 |
|
| 11232 |
void printExpressionWas() { |
| 11233 |
if (result.hasExpression()) { |
| 11234 |
stream << ';'; |
| 11235 |
stream << colourImpl->guardColour( tapDimColour ) |
| 11236 |
<< " expression was:"; |
| 11237 |
printOriginalExpression(); |
| 11238 |
} |
| 11239 |
} |
| 11240 |
|
| 11241 |
void printOriginalExpression() const { |
| 11242 |
if (result.hasExpression()) { |
| 11243 |
stream << ' ' << result.getExpression(); |
| 11244 |
} |
| 11245 |
} |
| 11246 |
|
| 11247 |
void printReconstructedExpression() const { |
| 11248 |
if (result.hasExpandedExpression()) { |
| 11249 |
stream << colourImpl->guardColour( tapDimColour ) << " for: "; |
| 11250 |
|
| 11251 |
std::string expr = result.getExpandedExpression(); |
| 11252 |
std::replace(expr.begin(), expr.end(), '\n', ' '); |
| 11253 |
stream << expr; |
| 11254 |
} |
| 11255 |
} |
| 11256 |
|
| 11257 |
void printMessage() { |
| 11258 |
if (itMessage != messages.end()) { |
| 11259 |
stream << " '" << itMessage->message << '\''; |
| 11260 |
++itMessage; |
| 11261 |
} |
| 11262 |
} |
| 11263 |
|
| 11264 |
void printRemainingMessages(Colour::Code colour = tapDimColour) { |
| 11265 |
if (itMessage == messages.end()) { |
| 11266 |
return; |
| 11267 |
} |
| 11268 |
|
| 11269 |
// using messages.end() directly (or auto) yields compilation error: |
| 11270 |
std::vector<MessageInfo>::const_iterator itEnd = messages.end(); |
| 11271 |
const std::size_t N = static_cast<std::size_t>(itEnd - itMessage); |
| 11272 |
|
| 11273 |
stream << colourImpl->guardColour( colour ) << " with " |
| 11274 |
<< pluralise( N, "message"_sr ) << ':'; |
| 11275 |
|
| 11276 |
for (; itMessage != itEnd; ) { |
| 11277 |
// If this assertion is a warning ignore any INFO messages |
| 11278 |
if (printInfoMessages || itMessage->type != ResultWas::Info) { |
| 11279 |
stream << " '" << itMessage->message << '\''; |
| 11280 |
if (++itMessage != itEnd) { |
| 11281 |
stream << colourImpl->guardColour(tapDimColour) << " and"; |
| 11282 |
} |
| 11283 |
} |
| 11284 |
} |
| 11285 |
} |
| 11286 |
|
| 11287 |
private: |
| 11288 |
std::ostream& stream; |
| 11289 |
AssertionResult const& result; |
| 11290 |
std::vector<MessageInfo> const& messages; |
| 11291 |
std::vector<MessageInfo>::const_iterator itMessage; |
| 11292 |
bool printInfoMessages; |
| 11293 |
std::size_t counter; |
| 11294 |
ColourImpl* colourImpl; |
| 11295 |
}; |
| 11296 |
|
| 11297 |
} // End anonymous namespace |
| 11298 |
|
| 11299 |
void TAPReporter::testRunStarting( TestRunInfo const& ) { |
| 11300 |
if ( m_config->testSpec().hasFilters() ) { |
| 11301 |
m_stream << "# filters: " << m_config->testSpec() << '\n'; |
| 11302 |
} |
| 11303 |
m_stream << "# rng-seed: " << m_config->rngSeed() << '\n'; |
| 11304 |
} |
| 11305 |
|
| 11306 |
void TAPReporter::noMatchingTestCases( StringRef unmatchedSpec ) { |
| 11307 |
m_stream << "# No test cases matched '" << unmatchedSpec << "'\n"; |
| 11308 |
} |
| 11309 |
|
| 11310 |
void TAPReporter::assertionEnded(AssertionStats const& _assertionStats) { |
| 11311 |
++counter; |
| 11312 |
|
| 11313 |
m_stream << "# " << currentTestCaseInfo->name << '\n'; |
| 11314 |
TapAssertionPrinter printer(m_stream, _assertionStats, counter, m_colour.get()); |
| 11315 |
printer.print(); |
| 11316 |
|
| 11317 |
m_stream << '\n' << std::flush; |
| 11318 |
} |
| 11319 |
|
| 11320 |
void TAPReporter::testRunEnded(TestRunStats const& _testRunStats) { |
| 11321 |
m_stream << "1.." << _testRunStats.totals.assertions.total(); |
| 11322 |
if (_testRunStats.totals.testCases.total() == 0) { |
| 11323 |
m_stream << " # Skipped: No tests ran."; |
| 11324 |
} |
| 11325 |
m_stream << "\n\n" << std::flush; |
| 11326 |
StreamingReporterBase::testRunEnded(_testRunStats); |
| 11327 |
} |
| 11328 |
|
| 11329 |
|
| 11330 |
|
| 11331 |
|
| 11332 |
} // end namespace Catch |
| 11333 |
|
| 11334 |
|
| 11335 |
|
| 11336 |
|
| 11337 |
#include <cassert> |
| 11338 |
#include <ostream> |
| 11339 |
|
| 11340 |
namespace Catch { |
| 11341 |
|
| 11342 |
namespace { |
| 11343 |
// if string has a : in first line will set indent to follow it on |
| 11344 |
// subsequent lines |
| 11345 |
void printHeaderString(std::ostream& os, std::string const& _string, std::size_t indent = 0) { |
| 11346 |
std::size_t i = _string.find(": "); |
| 11347 |
if (i != std::string::npos) |
| 11348 |
i += 2; |
| 11349 |
else |
| 11350 |
i = 0; |
| 11351 |
os << TextFlow::Column(_string) |
| 11352 |
.indent(indent + i) |
| 11353 |
.initialIndent(indent) << '\n'; |
| 11354 |
} |
| 11355 |
|
| 11356 |
std::string escape(StringRef str) { |
| 11357 |
std::string escaped = static_cast<std::string>(str); |
| 11358 |
replaceInPlace(escaped, "|", "||"); |
| 11359 |
replaceInPlace(escaped, "'", "|'"); |
| 11360 |
replaceInPlace(escaped, "\n", "|n"); |
| 11361 |
replaceInPlace(escaped, "\r", "|r"); |
| 11362 |
replaceInPlace(escaped, "[", "|["); |
| 11363 |
replaceInPlace(escaped, "]", "|]"); |
| 11364 |
return escaped; |
| 11365 |
} |
| 11366 |
} // end anonymous namespace |
| 11367 |
|
| 11368 |
|
| 11369 |
TeamCityReporter::~TeamCityReporter() = default; |
| 11370 |
|
| 11371 |
void TeamCityReporter::testRunStarting( TestRunInfo const& runInfo ) { |
| 11372 |
m_stream << "##teamcity[testSuiteStarted name='" << escape( runInfo.name ) |
| 11373 |
<< "']\n"; |
| 11374 |
} |
| 11375 |
|
| 11376 |
void TeamCityReporter::testRunEnded( TestRunStats const& runStats ) { |
| 11377 |
m_stream << "##teamcity[testSuiteFinished name='" |
| 11378 |
<< escape( runStats.runInfo.name ) << "']\n"; |
| 11379 |
} |
| 11380 |
|
| 11381 |
void TeamCityReporter::assertionEnded(AssertionStats const& assertionStats) { |
| 11382 |
AssertionResult const& result = assertionStats.assertionResult; |
| 11383 |
if ( !result.isOk() || |
| 11384 |
result.getResultType() == ResultWas::ExplicitSkip ) { |
| 11385 |
|
| 11386 |
ReusableStringStream msg; |
| 11387 |
if (!m_headerPrintedForThisSection) |
| 11388 |
printSectionHeader(msg.get()); |
| 11389 |
m_headerPrintedForThisSection = true; |
| 11390 |
|
| 11391 |
msg << result.getSourceInfo() << '\n'; |
| 11392 |
|
| 11393 |
switch (result.getResultType()) { |
| 11394 |
case ResultWas::ExpressionFailed: |
| 11395 |
msg << "expression failed"; |
| 11396 |
break; |
| 11397 |
case ResultWas::ThrewException: |
| 11398 |
msg << "unexpected exception"; |
| 11399 |
break; |
| 11400 |
case ResultWas::FatalErrorCondition: |
| 11401 |
msg << "fatal error condition"; |
| 11402 |
break; |
| 11403 |
case ResultWas::DidntThrowException: |
| 11404 |
msg << "no exception was thrown where one was expected"; |
| 11405 |
break; |
| 11406 |
case ResultWas::ExplicitFailure: |
| 11407 |
msg << "explicit failure"; |
| 11408 |
break; |
| 11409 |
case ResultWas::ExplicitSkip: |
| 11410 |
msg << "explicit skip"; |
| 11411 |
break; |
| 11412 |
|
| 11413 |
// We shouldn't get here because of the isOk() test |
| 11414 |
case ResultWas::Ok: |
| 11415 |
case ResultWas::Info: |
| 11416 |
case ResultWas::Warning: |
| 11417 |
CATCH_ERROR("Internal error in TeamCity reporter"); |
| 11418 |
// These cases are here to prevent compiler warnings |
| 11419 |
case ResultWas::Unknown: |
| 11420 |
case ResultWas::FailureBit: |
| 11421 |
case ResultWas::Exception: |
| 11422 |
CATCH_ERROR("Not implemented"); |
| 11423 |
} |
| 11424 |
if (assertionStats.infoMessages.size() == 1) |
| 11425 |
msg << " with message:"; |
| 11426 |
if (assertionStats.infoMessages.size() > 1) |
| 11427 |
msg << " with messages:"; |
| 11428 |
for (auto const& messageInfo : assertionStats.infoMessages) |
| 11429 |
msg << "\n \"" << messageInfo.message << '"'; |
| 11430 |
|
| 11431 |
|
| 11432 |
if (result.hasExpression()) { |
| 11433 |
msg << |
| 11434 |
"\n " << result.getExpressionInMacro() << "\n" |
| 11435 |
"with expansion:\n" |
| 11436 |
" " << result.getExpandedExpression() << '\n'; |
| 11437 |
} |
| 11438 |
|
| 11439 |
if ( result.getResultType() == ResultWas::ExplicitSkip ) { |
| 11440 |
m_stream << "##teamcity[testIgnored"; |
| 11441 |
} else if ( currentTestCaseInfo->okToFail() ) { |
| 11442 |
msg << "- failure ignore as test marked as 'ok to fail'\n"; |
| 11443 |
m_stream << "##teamcity[testIgnored"; |
| 11444 |
} else { |
| 11445 |
m_stream << "##teamcity[testFailed"; |
| 11446 |
} |
| 11447 |
m_stream << " name='" << escape( currentTestCaseInfo->name ) << '\'' |
| 11448 |
<< " message='" << escape( msg.str() ) << '\'' << "]\n"; |
| 11449 |
} |
| 11450 |
m_stream.flush(); |
| 11451 |
} |
| 11452 |
|
| 11453 |
void TeamCityReporter::testCaseStarting(TestCaseInfo const& testInfo) { |
| 11454 |
m_testTimer.start(); |
| 11455 |
StreamingReporterBase::testCaseStarting(testInfo); |
| 11456 |
m_stream << "##teamcity[testStarted name='" |
| 11457 |
<< escape(testInfo.name) << "']\n"; |
| 11458 |
m_stream.flush(); |
| 11459 |
} |
| 11460 |
|
| 11461 |
void TeamCityReporter::testCaseEnded(TestCaseStats const& testCaseStats) { |
| 11462 |
StreamingReporterBase::testCaseEnded(testCaseStats); |
| 11463 |
auto const& testCaseInfo = *testCaseStats.testInfo; |
| 11464 |
if (!testCaseStats.stdOut.empty()) |
| 11465 |
m_stream << "##teamcity[testStdOut name='" |
| 11466 |
<< escape(testCaseInfo.name) |
| 11467 |
<< "' out='" << escape(testCaseStats.stdOut) << "']\n"; |
| 11468 |
if (!testCaseStats.stdErr.empty()) |
| 11469 |
m_stream << "##teamcity[testStdErr name='" |
| 11470 |
<< escape(testCaseInfo.name) |
| 11471 |
<< "' out='" << escape(testCaseStats.stdErr) << "']\n"; |
| 11472 |
m_stream << "##teamcity[testFinished name='" |
| 11473 |
<< escape(testCaseInfo.name) << "' duration='" |
| 11474 |
<< m_testTimer.getElapsedMilliseconds() << "']\n"; |
| 11475 |
m_stream.flush(); |
| 11476 |
} |
| 11477 |
|
| 11478 |
void TeamCityReporter::printSectionHeader(std::ostream& os) { |
| 11479 |
assert(!m_sectionStack.empty()); |
| 11480 |
|
| 11481 |
if (m_sectionStack.size() > 1) { |
| 11482 |
os << lineOfChars('-') << '\n'; |
| 11483 |
|
| 11484 |
std::vector<SectionInfo>::const_iterator |
| 11485 |
it = m_sectionStack.begin() + 1, // Skip first section (test case) |
| 11486 |
itEnd = m_sectionStack.end(); |
| 11487 |
for (; it != itEnd; ++it) |
| 11488 |
printHeaderString(os, it->name); |
| 11489 |
os << lineOfChars('-') << '\n'; |
| 11490 |
} |
| 11491 |
|
| 11492 |
SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; |
| 11493 |
|
| 11494 |
os << lineInfo << '\n'; |
| 11495 |
os << lineOfChars('.') << "\n\n"; |
| 11496 |
} |
| 11497 |
|
| 11498 |
} // end namespace Catch |
| 11499 |
|
| 11500 |
|
| 11501 |
|
| 11502 |
|
| 11503 |
#if defined(_MSC_VER) |
| 11504 |
#pragma warning(push) |
| 11505 |
#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch |
| 11506 |
// Note that 4062 (not all labels are handled |
| 11507 |
// and default is missing) is enabled |
| 11508 |
#endif |
| 11509 |
|
| 11510 |
namespace Catch { |
| 11511 |
XmlReporter::XmlReporter( ReporterConfig&& _config ) |
| 11512 |
: StreamingReporterBase( CATCH_MOVE(_config) ), |
| 11513 |
m_xml(m_stream) |
| 11514 |
{ |
| 11515 |
m_preferences.shouldRedirectStdOut = true; |
| 11516 |
m_preferences.shouldReportAllAssertions = true; |
| 11517 |
} |
| 11518 |
|
| 11519 |
XmlReporter::~XmlReporter() = default; |
| 11520 |
|
| 11521 |
std::string XmlReporter::getDescription() { |
| 11522 |
return "Reports test results as an XML document"; |
| 11523 |
} |
| 11524 |
|
| 11525 |
std::string XmlReporter::getStylesheetRef() const { |
| 11526 |
return std::string(); |
| 11527 |
} |
| 11528 |
|
| 11529 |
void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) { |
| 11530 |
m_xml |
| 11531 |
.writeAttribute( "filename"_sr, sourceInfo.file ) |
| 11532 |
.writeAttribute( "line"_sr, sourceInfo.line ); |
| 11533 |
} |
| 11534 |
|
| 11535 |
void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) { |
| 11536 |
StreamingReporterBase::testRunStarting( testInfo ); |
| 11537 |
std::string stylesheetRef = getStylesheetRef(); |
| 11538 |
if( !stylesheetRef.empty() ) |
| 11539 |
m_xml.writeStylesheetRef( stylesheetRef ); |
| 11540 |
m_xml.startElement("Catch2TestRun") |
| 11541 |
.writeAttribute("name"_sr, m_config->name()) |
| 11542 |
.writeAttribute("rng-seed"_sr, m_config->rngSeed()) |
| 11543 |
.writeAttribute("xml-format-version"_sr, 3) |
| 11544 |
.writeAttribute("catch2-version"_sr, libraryVersion()); |
| 11545 |
if ( m_config->testSpec().hasFilters() ) { |
| 11546 |
m_xml.writeAttribute( "filters"_sr, m_config->testSpec() ); |
| 11547 |
} |
| 11548 |
} |
| 11549 |
|
| 11550 |
void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) { |
| 11551 |
StreamingReporterBase::testCaseStarting(testInfo); |
| 11552 |
m_xml.startElement( "TestCase" ) |
| 11553 |
.writeAttribute( "name"_sr, trim( StringRef(testInfo.name) ) ) |
| 11554 |
.writeAttribute( "tags"_sr, testInfo.tagsAsString() ); |
| 11555 |
|
| 11556 |
writeSourceInfo( testInfo.lineInfo ); |
| 11557 |
|
| 11558 |
if ( m_config->showDurations() == ShowDurations::Always ) |
| 11559 |
m_testCaseTimer.start(); |
| 11560 |
m_xml.ensureTagClosed(); |
| 11561 |
} |
| 11562 |
|
| 11563 |
void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) { |
| 11564 |
StreamingReporterBase::sectionStarting( sectionInfo ); |
| 11565 |
if( m_sectionDepth++ > 0 ) { |
| 11566 |
m_xml.startElement( "Section" ) |
| 11567 |
.writeAttribute( "name"_sr, trim( StringRef(sectionInfo.name) ) ); |
| 11568 |
writeSourceInfo( sectionInfo.lineInfo ); |
| 11569 |
m_xml.ensureTagClosed(); |
| 11570 |
} |
| 11571 |
} |
| 11572 |
|
| 11573 |
void XmlReporter::assertionStarting( AssertionInfo const& ) { } |
| 11574 |
|
| 11575 |
void XmlReporter::assertionEnded( AssertionStats const& assertionStats ) { |
| 11576 |
|
| 11577 |
AssertionResult const& result = assertionStats.assertionResult; |
| 11578 |
|
| 11579 |
bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); |
| 11580 |
|
| 11581 |
if( includeResults || result.getResultType() == ResultWas::Warning ) { |
| 11582 |
// Print any info messages in <Info> tags. |
| 11583 |
for( auto const& msg : assertionStats.infoMessages ) { |
| 11584 |
if( msg.type == ResultWas::Info && includeResults ) { |
| 11585 |
auto t = m_xml.scopedElement( "Info" ); |
| 11586 |
writeSourceInfo( msg.lineInfo ); |
| 11587 |
t.writeText( msg.message ); |
| 11588 |
} else if ( msg.type == ResultWas::Warning ) { |
| 11589 |
auto t = m_xml.scopedElement( "Warning" ); |
| 11590 |
writeSourceInfo( msg.lineInfo ); |
| 11591 |
t.writeText( msg.message ); |
| 11592 |
} |
| 11593 |
} |
| 11594 |
} |
| 11595 |
|
| 11596 |
// Drop out if result was successful but we're not printing them. |
| 11597 |
if ( !includeResults && result.getResultType() != ResultWas::Warning && |
| 11598 |
result.getResultType() != ResultWas::ExplicitSkip ) { |
| 11599 |
return; |
| 11600 |
} |
| 11601 |
|
| 11602 |
// Print the expression if there is one. |
| 11603 |
if( result.hasExpression() ) { |
| 11604 |
m_xml.startElement( "Expression" ) |
| 11605 |
.writeAttribute( "success"_sr, result.succeeded() ) |
| 11606 |
.writeAttribute( "type"_sr, result.getTestMacroName() ); |
| 11607 |
|
| 11608 |
writeSourceInfo( result.getSourceInfo() ); |
| 11609 |
|
| 11610 |
m_xml.scopedElement( "Original" ) |
| 11611 |
.writeText( result.getExpression() ); |
| 11612 |
m_xml.scopedElement( "Expanded" ) |
| 11613 |
.writeText( result.getExpandedExpression() ); |
| 11614 |
} |
| 11615 |
|
| 11616 |
// And... Print a result applicable to each result type. |
| 11617 |
switch( result.getResultType() ) { |
| 11618 |
case ResultWas::ThrewException: |
| 11619 |
m_xml.startElement( "Exception" ); |
| 11620 |
writeSourceInfo( result.getSourceInfo() ); |
| 11621 |
m_xml.writeText( result.getMessage() ); |
| 11622 |
m_xml.endElement(); |
| 11623 |
break; |
| 11624 |
case ResultWas::FatalErrorCondition: |
| 11625 |
m_xml.startElement( "FatalErrorCondition" ); |
| 11626 |
writeSourceInfo( result.getSourceInfo() ); |
| 11627 |
m_xml.writeText( result.getMessage() ); |
| 11628 |
m_xml.endElement(); |
| 11629 |
break; |
| 11630 |
case ResultWas::Info: |
| 11631 |
m_xml.scopedElement( "Info" ) |
| 11632 |
.writeText( result.getMessage() ); |
| 11633 |
break; |
| 11634 |
case ResultWas::Warning: |
| 11635 |
// Warning will already have been written |
| 11636 |
break; |
| 11637 |
case ResultWas::ExplicitFailure: |
| 11638 |
m_xml.startElement( "Failure" ); |
| 11639 |
writeSourceInfo( result.getSourceInfo() ); |
| 11640 |
m_xml.writeText( result.getMessage() ); |
| 11641 |
m_xml.endElement(); |
| 11642 |
break; |
| 11643 |
case ResultWas::ExplicitSkip: |
| 11644 |
m_xml.startElement( "Skip" ); |
| 11645 |
writeSourceInfo( result.getSourceInfo() ); |
| 11646 |
m_xml.writeText( result.getMessage() ); |
| 11647 |
m_xml.endElement(); |
| 11648 |
break; |
| 11649 |
default: |
| 11650 |
break; |
| 11651 |
} |
| 11652 |
|
| 11653 |
if( result.hasExpression() ) |
| 11654 |
m_xml.endElement(); |
| 11655 |
} |
| 11656 |
|
| 11657 |
void XmlReporter::sectionEnded( SectionStats const& sectionStats ) { |
| 11658 |
StreamingReporterBase::sectionEnded( sectionStats ); |
| 11659 |
if ( --m_sectionDepth > 0 ) { |
| 11660 |
{ |
| 11661 |
XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); |
| 11662 |
e.writeAttribute( "successes"_sr, sectionStats.assertions.passed ); |
| 11663 |
e.writeAttribute( "failures"_sr, sectionStats.assertions.failed ); |
| 11664 |
e.writeAttribute( "expectedFailures"_sr, sectionStats.assertions.failedButOk ); |
| 11665 |
e.writeAttribute( "skipped"_sr, sectionStats.assertions.skipped > 0 ); |
| 11666 |
|
| 11667 |
if ( m_config->showDurations() == ShowDurations::Always ) |
| 11668 |
e.writeAttribute( "durationInSeconds"_sr, sectionStats.durationInSeconds ); |
| 11669 |
} |
| 11670 |
// Ends assertion tag |
| 11671 |
m_xml.endElement(); |
| 11672 |
} |
| 11673 |
} |
| 11674 |
|
| 11675 |
void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { |
| 11676 |
StreamingReporterBase::testCaseEnded( testCaseStats ); |
| 11677 |
XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); |
| 11678 |
e.writeAttribute( "success"_sr, testCaseStats.totals.assertions.allOk() ); |
| 11679 |
e.writeAttribute( "skips"_sr, testCaseStats.totals.assertions.skipped ); |
| 11680 |
|
| 11681 |
if ( m_config->showDurations() == ShowDurations::Always ) |
| 11682 |
e.writeAttribute( "durationInSeconds"_sr, m_testCaseTimer.getElapsedSeconds() ); |
| 11683 |
if( !testCaseStats.stdOut.empty() ) |
| 11684 |
m_xml.scopedElement( "StdOut" ).writeText( trim( StringRef(testCaseStats.stdOut) ), XmlFormatting::Newline ); |
| 11685 |
if( !testCaseStats.stdErr.empty() ) |
| 11686 |
m_xml.scopedElement( "StdErr" ).writeText( trim( StringRef(testCaseStats.stdErr) ), XmlFormatting::Newline ); |
| 11687 |
|
| 11688 |
m_xml.endElement(); |
| 11689 |
} |
| 11690 |
|
| 11691 |
void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) { |
| 11692 |
StreamingReporterBase::testRunEnded( testRunStats ); |
| 11693 |
m_xml.scopedElement( "OverallResults" ) |
| 11694 |
.writeAttribute( "successes"_sr, testRunStats.totals.assertions.passed ) |
| 11695 |
.writeAttribute( "failures"_sr, testRunStats.totals.assertions.failed ) |
| 11696 |
.writeAttribute( "expectedFailures"_sr, testRunStats.totals.assertions.failedButOk ) |
| 11697 |
.writeAttribute( "skips"_sr, testRunStats.totals.assertions.skipped ); |
| 11698 |
m_xml.scopedElement( "OverallResultsCases") |
| 11699 |
.writeAttribute( "successes"_sr, testRunStats.totals.testCases.passed ) |
| 11700 |
.writeAttribute( "failures"_sr, testRunStats.totals.testCases.failed ) |
| 11701 |
.writeAttribute( "expectedFailures"_sr, testRunStats.totals.testCases.failedButOk ) |
| 11702 |
.writeAttribute( "skips"_sr, testRunStats.totals.testCases.skipped ); |
| 11703 |
m_xml.endElement(); |
| 11704 |
} |
| 11705 |
|
| 11706 |
void XmlReporter::benchmarkPreparing( StringRef name ) { |
| 11707 |
m_xml.startElement("BenchmarkResults") |
| 11708 |
.writeAttribute("name"_sr, name); |
| 11709 |
} |
| 11710 |
|
| 11711 |
void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) { |
| 11712 |
m_xml.writeAttribute("samples"_sr, info.samples) |
| 11713 |
.writeAttribute("resamples"_sr, info.resamples) |
| 11714 |
.writeAttribute("iterations"_sr, info.iterations) |
| 11715 |
.writeAttribute("clockResolution"_sr, info.clockResolution) |
| 11716 |
.writeAttribute("estimatedDuration"_sr, info.estimatedDuration) |
| 11717 |
.writeComment("All values in nano seconds"_sr); |
| 11718 |
} |
| 11719 |
|
| 11720 |
void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) { |
| 11721 |
m_xml.scopedElement("mean") |
| 11722 |
.writeAttribute("value"_sr, benchmarkStats.mean.point.count()) |
| 11723 |
.writeAttribute("lowerBound"_sr, benchmarkStats.mean.lower_bound.count()) |
| 11724 |
.writeAttribute("upperBound"_sr, benchmarkStats.mean.upper_bound.count()) |
| 11725 |
.writeAttribute("ci"_sr, benchmarkStats.mean.confidence_interval); |
| 11726 |
m_xml.scopedElement("standardDeviation") |
| 11727 |
.writeAttribute("value"_sr, benchmarkStats.standardDeviation.point.count()) |
| 11728 |
.writeAttribute("lowerBound"_sr, benchmarkStats.standardDeviation.lower_bound.count()) |
| 11729 |
.writeAttribute("upperBound"_sr, benchmarkStats.standardDeviation.upper_bound.count()) |
| 11730 |
.writeAttribute("ci"_sr, benchmarkStats.standardDeviation.confidence_interval); |
| 11731 |
m_xml.scopedElement("outliers") |
| 11732 |
.writeAttribute("variance"_sr, benchmarkStats.outlierVariance) |
| 11733 |
.writeAttribute("lowMild"_sr, benchmarkStats.outliers.low_mild) |
| 11734 |
.writeAttribute("lowSevere"_sr, benchmarkStats.outliers.low_severe) |
| 11735 |
.writeAttribute("highMild"_sr, benchmarkStats.outliers.high_mild) |
| 11736 |
.writeAttribute("highSevere"_sr, benchmarkStats.outliers.high_severe); |
| 11737 |
m_xml.endElement(); |
| 11738 |
} |
| 11739 |
|
| 11740 |
void XmlReporter::benchmarkFailed(StringRef error) { |
| 11741 |
m_xml.scopedElement("failed"). |
| 11742 |
writeAttribute("message"_sr, error); |
| 11743 |
m_xml.endElement(); |
| 11744 |
} |
| 11745 |
|
| 11746 |
void XmlReporter::listReporters(std::vector<ReporterDescription> const& descriptions) { |
| 11747 |
auto outerTag = m_xml.scopedElement("AvailableReporters"); |
| 11748 |
for (auto const& reporter : descriptions) { |
| 11749 |
auto inner = m_xml.scopedElement("Reporter"); |
| 11750 |
m_xml.startElement("Name", XmlFormatting::Indent) |
| 11751 |
.writeText(reporter.name, XmlFormatting::None) |
| 11752 |
.endElement(XmlFormatting::Newline); |
| 11753 |
m_xml.startElement("Description", XmlFormatting::Indent) |
| 11754 |
.writeText(reporter.description, XmlFormatting::None) |
| 11755 |
.endElement(XmlFormatting::Newline); |
| 11756 |
} |
| 11757 |
} |
| 11758 |
|
| 11759 |
void XmlReporter::listListeners(std::vector<ListenerDescription> const& descriptions) { |
| 11760 |
auto outerTag = m_xml.scopedElement( "RegisteredListeners" ); |
| 11761 |
for ( auto const& listener : descriptions ) { |
| 11762 |
auto inner = m_xml.scopedElement( "Listener" ); |
| 11763 |
m_xml.startElement( "Name", XmlFormatting::Indent ) |
| 11764 |
.writeText( listener.name, XmlFormatting::None ) |
| 11765 |
.endElement( XmlFormatting::Newline ); |
| 11766 |
m_xml.startElement( "Description", XmlFormatting::Indent ) |
| 11767 |
.writeText( listener.description, XmlFormatting::None ) |
| 11768 |
.endElement( XmlFormatting::Newline ); |
| 11769 |
} |
| 11770 |
} |
| 11771 |
|
| 11772 |
void XmlReporter::listTests(std::vector<TestCaseHandle> const& tests) { |
| 11773 |
auto outerTag = m_xml.scopedElement("MatchingTests"); |
| 11774 |
for (auto const& test : tests) { |
| 11775 |
auto innerTag = m_xml.scopedElement("TestCase"); |
| 11776 |
auto const& testInfo = test.getTestCaseInfo(); |
| 11777 |
m_xml.startElement("Name", XmlFormatting::Indent) |
| 11778 |
.writeText(testInfo.name, XmlFormatting::None) |
| 11779 |
.endElement(XmlFormatting::Newline); |
| 11780 |
m_xml.startElement("ClassName", XmlFormatting::Indent) |
| 11781 |
.writeText(testInfo.className, XmlFormatting::None) |
| 11782 |
.endElement(XmlFormatting::Newline); |
| 11783 |
m_xml.startElement("Tags", XmlFormatting::Indent) |
| 11784 |
.writeText(testInfo.tagsAsString(), XmlFormatting::None) |
| 11785 |
.endElement(XmlFormatting::Newline); |
| 11786 |
|
| 11787 |
auto sourceTag = m_xml.scopedElement("SourceInfo"); |
| 11788 |
m_xml.startElement("File", XmlFormatting::Indent) |
| 11789 |
.writeText(testInfo.lineInfo.file, XmlFormatting::None) |
| 11790 |
.endElement(XmlFormatting::Newline); |
| 11791 |
m_xml.startElement("Line", XmlFormatting::Indent) |
| 11792 |
.writeText(std::to_string(testInfo.lineInfo.line), XmlFormatting::None) |
| 11793 |
.endElement(XmlFormatting::Newline); |
| 11794 |
} |
| 11795 |
} |
| 11796 |
|
| 11797 |
void XmlReporter::listTags(std::vector<TagInfo> const& tags) { |
| 11798 |
auto outerTag = m_xml.scopedElement("TagsFromMatchingTests"); |
| 11799 |
for (auto const& tag : tags) { |
| 11800 |
auto innerTag = m_xml.scopedElement("Tag"); |
| 11801 |
m_xml.startElement("Count", XmlFormatting::Indent) |
| 11802 |
.writeText(std::to_string(tag.count), XmlFormatting::None) |
| 11803 |
.endElement(XmlFormatting::Newline); |
| 11804 |
auto aliasTag = m_xml.scopedElement("Aliases"); |
| 11805 |
for (auto const& alias : tag.spellings) { |
| 11806 |
m_xml.startElement("Alias", XmlFormatting::Indent) |
| 11807 |
.writeText(alias, XmlFormatting::None) |
| 11808 |
.endElement(XmlFormatting::Newline); |
| 11809 |
} |
| 11810 |
} |
| 11811 |
} |
| 11812 |
|
| 11813 |
} // end namespace Catch |
| 11814 |
|
| 11815 |
#if defined(_MSC_VER) |
| 11816 |
#pragma warning(pop) |
| 11817 |
#endif |