diff options
Diffstat (limited to '')
-rw-r--r-- | unit_tests/catch_amalgamated.cpp | 11811 |
1 files changed, 11811 insertions, 0 deletions
diff --git a/unit_tests/catch_amalgamated.cpp b/unit_tests/catch_amalgamated.cpp new file mode 100644 index 0000000..8288905 --- /dev/null +++ b/unit_tests/catch_amalgamated.cpp | |||
@@ -0,0 +1,11811 @@ | |||
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.7.1 | ||
10 | // Generated: 2024-09-17 10:36:45.608896 | ||
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 | ( 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 = (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 = | ||
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 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 { Big, Little }; | ||
1950 | |||
1951 | static Arch which() { | ||
1952 | int one = 1; | ||
1953 | // If the lowest byte we read is non-zero, we can assume | ||
1954 | // that little endian format is used. | ||
1955 | auto value = *reinterpret_cast<char*>(&one); | ||
1956 | return value ? Little : Big; | ||
1957 | } | ||
1958 | }; | ||
1959 | |||
1960 | template<typename T> | ||
1961 | std::string fpToString(T value, int precision) { | ||
1962 | if (Catch::isnan(value)) { | ||
1963 | return "nan"; | ||
1964 | } | ||
1965 | |||
1966 | ReusableStringStream rss; | ||
1967 | rss << std::setprecision(precision) | ||
1968 | << std::fixed | ||
1969 | << value; | ||
1970 | std::string d = rss.str(); | ||
1971 | std::size_t i = d.find_last_not_of('0'); | ||
1972 | if (i != std::string::npos && i != d.size() - 1) { | ||
1973 | if (d[i] == '.') | ||
1974 | i++; | ||
1975 | d = d.substr(0, i + 1); | ||
1976 | } | ||
1977 | return d; | ||
1978 | } | ||
1979 | } // end unnamed namespace | ||
1980 | |||
1981 | std::string convertIntoString(StringRef string, bool escapeInvisibles) { | ||
1982 | std::string ret; | ||
1983 | // This is enough for the "don't escape invisibles" case, and a good | ||
1984 | // lower bound on the "escape invisibles" case. | ||
1985 | ret.reserve(string.size() + 2); | ||
1986 | |||
1987 | if (!escapeInvisibles) { | ||
1988 | ret += '"'; | ||
1989 | ret += string; | ||
1990 | ret += '"'; | ||
1991 | return ret; | ||
1992 | } | ||
1993 | |||
1994 | ret += '"'; | ||
1995 | for (char c : string) { | ||
1996 | switch (c) { | ||
1997 | case '\r': | ||
1998 | ret.append("\\r"); | ||
1999 | break; | ||
2000 | case '\n': | ||
2001 | ret.append("\\n"); | ||
2002 | break; | ||
2003 | case '\t': | ||
2004 | ret.append("\\t"); | ||
2005 | break; | ||
2006 | case '\f': | ||
2007 | ret.append("\\f"); | ||
2008 | break; | ||
2009 | default: | ||
2010 | ret.push_back(c); | ||
2011 | break; | ||
2012 | } | ||
2013 | } | ||
2014 | ret += '"'; | ||
2015 | |||
2016 | return ret; | ||
2017 | } | ||
2018 | |||
2019 | std::string convertIntoString(StringRef string) { | ||
2020 | return convertIntoString(string, getCurrentContext().getConfig()->showInvisibles()); | ||
2021 | } | ||
2022 | |||
2023 | std::string rawMemoryToString( const void *object, std::size_t size ) { | ||
2024 | // Reverse order for little endian architectures | ||
2025 | int i = 0, end = static_cast<int>( size ), inc = 1; | ||
2026 | if( Endianness::which() == Endianness::Little ) { | ||
2027 | i = end-1; | ||
2028 | end = inc = -1; | ||
2029 | } | ||
2030 | |||
2031 | unsigned char const *bytes = static_cast<unsigned char const *>(object); | ||
2032 | ReusableStringStream rss; | ||
2033 | rss << "0x" << std::setfill('0') << std::hex; | ||
2034 | for( ; i != end; i += inc ) | ||
2035 | rss << std::setw(2) << static_cast<unsigned>(bytes[i]); | ||
2036 | return rss.str(); | ||
2037 | } | ||
2038 | } // end Detail namespace | ||
2039 | |||
2040 | |||
2041 | |||
2042 | //// ======================================================= //// | ||
2043 | // | ||
2044 | // Out-of-line defs for full specialization of StringMaker | ||
2045 | // | ||
2046 | //// ======================================================= //// | ||
2047 | |||
2048 | std::string StringMaker<std::string>::convert(const std::string& str) { | ||
2049 | return Detail::convertIntoString( str ); | ||
2050 | } | ||
2051 | |||
2052 | #ifdef CATCH_CONFIG_CPP17_STRING_VIEW | ||
2053 | std::string StringMaker<std::string_view>::convert(std::string_view str) { | ||
2054 | return Detail::convertIntoString( StringRef( str.data(), str.size() ) ); | ||
2055 | } | ||
2056 | #endif | ||
2057 | |||
2058 | std::string StringMaker<char const*>::convert(char const* str) { | ||
2059 | if (str) { | ||
2060 | return Detail::convertIntoString( str ); | ||
2061 | } else { | ||
2062 | return{ "{null string}" }; | ||
2063 | } | ||
2064 | } | ||
2065 | std::string StringMaker<char*>::convert(char* str) { // NOLINT(readability-non-const-parameter) | ||
2066 | if (str) { | ||
2067 | return Detail::convertIntoString( str ); | ||
2068 | } else { | ||
2069 | return{ "{null string}" }; | ||
2070 | } | ||
2071 | } | ||
2072 | |||
2073 | #ifdef CATCH_CONFIG_WCHAR | ||
2074 | std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) { | ||
2075 | std::string s; | ||
2076 | s.reserve(wstr.size()); | ||
2077 | for (auto c : wstr) { | ||
2078 | s += (c <= 0xff) ? static_cast<char>(c) : '?'; | ||
2079 | } | ||
2080 | return ::Catch::Detail::stringify(s); | ||
2081 | } | ||
2082 | |||
2083 | # ifdef CATCH_CONFIG_CPP17_STRING_VIEW | ||
2084 | std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) { | ||
2085 | return StringMaker<std::wstring>::convert(std::wstring(str)); | ||
2086 | } | ||
2087 | # endif | ||
2088 | |||
2089 | std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) { | ||
2090 | if (str) { | ||
2091 | return ::Catch::Detail::stringify(std::wstring{ str }); | ||
2092 | } else { | ||
2093 | return{ "{null string}" }; | ||
2094 | } | ||
2095 | } | ||
2096 | std::string StringMaker<wchar_t *>::convert(wchar_t * str) { | ||
2097 | if (str) { | ||
2098 | return ::Catch::Detail::stringify(std::wstring{ str }); | ||
2099 | } else { | ||
2100 | return{ "{null string}" }; | ||
2101 | } | ||
2102 | } | ||
2103 | #endif | ||
2104 | |||
2105 | #if defined(CATCH_CONFIG_CPP17_BYTE) | ||
2106 | #include <cstddef> | ||
2107 | std::string StringMaker<std::byte>::convert(std::byte value) { | ||
2108 | return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value)); | ||
2109 | } | ||
2110 | #endif // defined(CATCH_CONFIG_CPP17_BYTE) | ||
2111 | |||
2112 | std::string StringMaker<int>::convert(int value) { | ||
2113 | return ::Catch::Detail::stringify(static_cast<long long>(value)); | ||
2114 | } | ||
2115 | std::string StringMaker<long>::convert(long value) { | ||
2116 | return ::Catch::Detail::stringify(static_cast<long long>(value)); | ||
2117 | } | ||
2118 | std::string StringMaker<long long>::convert(long long value) { | ||
2119 | ReusableStringStream rss; | ||
2120 | rss << value; | ||
2121 | if (value > Detail::hexThreshold) { | ||
2122 | rss << " (0x" << std::hex << value << ')'; | ||
2123 | } | ||
2124 | return rss.str(); | ||
2125 | } | ||
2126 | |||
2127 | std::string StringMaker<unsigned int>::convert(unsigned int value) { | ||
2128 | return ::Catch::Detail::stringify(static_cast<unsigned long long>(value)); | ||
2129 | } | ||
2130 | std::string StringMaker<unsigned long>::convert(unsigned long value) { | ||
2131 | return ::Catch::Detail::stringify(static_cast<unsigned long long>(value)); | ||
2132 | } | ||
2133 | std::string StringMaker<unsigned long long>::convert(unsigned long long value) { | ||
2134 | ReusableStringStream rss; | ||
2135 | rss << value; | ||
2136 | if (value > Detail::hexThreshold) { | ||
2137 | rss << " (0x" << std::hex << value << ')'; | ||
2138 | } | ||
2139 | return rss.str(); | ||
2140 | } | ||
2141 | |||
2142 | std::string StringMaker<signed char>::convert(signed char value) { | ||
2143 | if (value == '\r') { | ||
2144 | return "'\\r'"; | ||
2145 | } else if (value == '\f') { | ||
2146 | return "'\\f'"; | ||
2147 | } else if (value == '\n') { | ||
2148 | return "'\\n'"; | ||
2149 | } else if (value == '\t') { | ||
2150 | return "'\\t'"; | ||
2151 | } else if ('\0' <= value && value < ' ') { | ||
2152 | return ::Catch::Detail::stringify(static_cast<unsigned int>(value)); | ||
2153 | } else { | ||
2154 | char chstr[] = "' '"; | ||
2155 | chstr[1] = value; | ||
2156 | return chstr; | ||
2157 | } | ||
2158 | } | ||
2159 | std::string StringMaker<char>::convert(char c) { | ||
2160 | return ::Catch::Detail::stringify(static_cast<signed char>(c)); | ||
2161 | } | ||
2162 | std::string StringMaker<unsigned char>::convert(unsigned char value) { | ||
2163 | return ::Catch::Detail::stringify(static_cast<char>(value)); | ||
2164 | } | ||
2165 | |||
2166 | int StringMaker<float>::precision = std::numeric_limits<float>::max_digits10; | ||
2167 | |||
2168 | std::string StringMaker<float>::convert(float value) { | ||
2169 | return Detail::fpToString(value, precision) + 'f'; | ||
2170 | } | ||
2171 | |||
2172 | int StringMaker<double>::precision = std::numeric_limits<double>::max_digits10; | ||
2173 | |||
2174 | std::string StringMaker<double>::convert(double value) { | ||
2175 | return Detail::fpToString(value, precision); | ||
2176 | } | ||
2177 | |||
2178 | } // end namespace Catch | ||
2179 | |||
2180 | |||
2181 | |||
2182 | namespace Catch { | ||
2183 | |||
2184 | Counts Counts::operator - ( Counts const& other ) const { | ||
2185 | Counts diff; | ||
2186 | diff.passed = passed - other.passed; | ||
2187 | diff.failed = failed - other.failed; | ||
2188 | diff.failedButOk = failedButOk - other.failedButOk; | ||
2189 | diff.skipped = skipped - other.skipped; | ||
2190 | return diff; | ||
2191 | } | ||
2192 | |||
2193 | Counts& Counts::operator += ( Counts const& other ) { | ||
2194 | passed += other.passed; | ||
2195 | failed += other.failed; | ||
2196 | failedButOk += other.failedButOk; | ||
2197 | skipped += other.skipped; | ||
2198 | return *this; | ||
2199 | } | ||
2200 | |||
2201 | std::uint64_t Counts::total() const { | ||
2202 | return passed + failed + failedButOk + skipped; | ||
2203 | } | ||
2204 | bool Counts::allPassed() const { | ||
2205 | return failed == 0 && failedButOk == 0 && skipped == 0; | ||
2206 | } | ||
2207 | bool Counts::allOk() const { | ||
2208 | return failed == 0; | ||
2209 | } | ||
2210 | |||
2211 | Totals Totals::operator - ( Totals const& other ) const { | ||
2212 | Totals diff; | ||
2213 | diff.assertions = assertions - other.assertions; | ||
2214 | diff.testCases = testCases - other.testCases; | ||
2215 | return diff; | ||
2216 | } | ||
2217 | |||
2218 | Totals& Totals::operator += ( Totals const& other ) { | ||
2219 | assertions += other.assertions; | ||
2220 | testCases += other.testCases; | ||
2221 | return *this; | ||
2222 | } | ||
2223 | |||
2224 | Totals Totals::delta( Totals const& prevTotals ) const { | ||
2225 | Totals diff = *this - prevTotals; | ||
2226 | if( diff.assertions.failed > 0 ) | ||
2227 | ++diff.testCases.failed; | ||
2228 | else if( diff.assertions.failedButOk > 0 ) | ||
2229 | ++diff.testCases.failedButOk; | ||
2230 | else if ( diff.assertions.skipped > 0 ) | ||
2231 | ++ diff.testCases.skipped; | ||
2232 | else | ||
2233 | ++diff.testCases.passed; | ||
2234 | return diff; | ||
2235 | } | ||
2236 | |||
2237 | } | ||
2238 | |||
2239 | |||
2240 | |||
2241 | |||
2242 | namespace Catch { | ||
2243 | namespace Detail { | ||
2244 | void registerTranslatorImpl( | ||
2245 | Detail::unique_ptr<IExceptionTranslator>&& translator ) { | ||
2246 | getMutableRegistryHub().registerTranslator( | ||
2247 | CATCH_MOVE( translator ) ); | ||
2248 | } | ||
2249 | } // namespace Detail | ||
2250 | } // namespace Catch | ||
2251 | |||
2252 | |||
2253 | #include <ostream> | ||
2254 | |||
2255 | namespace Catch { | ||
2256 | |||
2257 | Version::Version | ||
2258 | ( unsigned int _majorVersion, | ||
2259 | unsigned int _minorVersion, | ||
2260 | unsigned int _patchNumber, | ||
2261 | char const * const _branchName, | ||
2262 | unsigned int _buildNumber ) | ||
2263 | : majorVersion( _majorVersion ), | ||
2264 | minorVersion( _minorVersion ), | ||
2265 | patchNumber( _patchNumber ), | ||
2266 | branchName( _branchName ), | ||
2267 | buildNumber( _buildNumber ) | ||
2268 | {} | ||
2269 | |||
2270 | std::ostream& operator << ( std::ostream& os, Version const& version ) { | ||
2271 | os << version.majorVersion << '.' | ||
2272 | << version.minorVersion << '.' | ||
2273 | << version.patchNumber; | ||
2274 | // branchName is never null -> 0th char is \0 if it is empty | ||
2275 | if (version.branchName[0]) { | ||
2276 | os << '-' << version.branchName | ||
2277 | << '.' << version.buildNumber; | ||
2278 | } | ||
2279 | return os; | ||
2280 | } | ||
2281 | |||
2282 | Version const& libraryVersion() { | ||
2283 | static Version version( 3, 7, 1, "", 0 ); | ||
2284 | return version; | ||
2285 | } | ||
2286 | |||
2287 | } | ||
2288 | |||
2289 | |||
2290 | |||
2291 | |||
2292 | namespace Catch { | ||
2293 | |||
2294 | const char* GeneratorException::what() const noexcept { | ||
2295 | return m_msg; | ||
2296 | } | ||
2297 | |||
2298 | } // end namespace Catch | ||
2299 | |||
2300 | |||
2301 | |||
2302 | |||
2303 | namespace Catch { | ||
2304 | |||
2305 | IGeneratorTracker::~IGeneratorTracker() = default; | ||
2306 | |||
2307 | namespace Generators { | ||
2308 | |||
2309 | namespace Detail { | ||
2310 | |||
2311 | [[noreturn]] | ||
2312 | void throw_generator_exception(char const* msg) { | ||
2313 | Catch::throw_exception(GeneratorException{ msg }); | ||
2314 | } | ||
2315 | } // end namespace Detail | ||
2316 | |||
2317 | GeneratorUntypedBase::~GeneratorUntypedBase() = default; | ||
2318 | |||
2319 | IGeneratorTracker* acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo ) { | ||
2320 | return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo ); | ||
2321 | } | ||
2322 | |||
2323 | IGeneratorTracker* createGeneratorTracker( StringRef generatorName, | ||
2324 | SourceLineInfo lineInfo, | ||
2325 | GeneratorBasePtr&& generator ) { | ||
2326 | return getResultCapture().createGeneratorTracker( | ||
2327 | generatorName, lineInfo, CATCH_MOVE( generator ) ); | ||
2328 | } | ||
2329 | |||
2330 | } // namespace Generators | ||
2331 | } // namespace Catch | ||
2332 | |||
2333 | |||
2334 | |||
2335 | |||
2336 | #include <random> | ||
2337 | |||
2338 | namespace Catch { | ||
2339 | namespace Generators { | ||
2340 | namespace Detail { | ||
2341 | std::uint32_t getSeed() { return sharedRng()(); } | ||
2342 | } // namespace Detail | ||
2343 | |||
2344 | struct RandomFloatingGenerator<long double>::PImpl { | ||
2345 | PImpl( long double a, long double b, uint32_t seed ): | ||
2346 | rng( seed ), dist( a, b ) {} | ||
2347 | |||
2348 | Catch::SimplePcg32 rng; | ||
2349 | std::uniform_real_distribution<long double> dist; | ||
2350 | }; | ||
2351 | |||
2352 | RandomFloatingGenerator<long double>::RandomFloatingGenerator( | ||
2353 | long double a, long double b, std::uint32_t seed) : | ||
2354 | m_pimpl(Catch::Detail::make_unique<PImpl>(a, b, seed)) { | ||
2355 | static_cast<void>( next() ); | ||
2356 | } | ||
2357 | |||
2358 | RandomFloatingGenerator<long double>::~RandomFloatingGenerator() = | ||
2359 | default; | ||
2360 | bool RandomFloatingGenerator<long double>::next() { | ||
2361 | m_current_number = m_pimpl->dist( m_pimpl->rng ); | ||
2362 | return true; | ||
2363 | } | ||
2364 | } // namespace Generators | ||
2365 | } // namespace Catch | ||
2366 | |||
2367 | |||
2368 | |||
2369 | |||
2370 | namespace Catch { | ||
2371 | IResultCapture::~IResultCapture() = default; | ||
2372 | } | ||
2373 | |||
2374 | |||
2375 | |||
2376 | |||
2377 | namespace Catch { | ||
2378 | IConfig::~IConfig() = default; | ||
2379 | } | ||
2380 | |||
2381 | |||
2382 | |||
2383 | |||
2384 | namespace Catch { | ||
2385 | IExceptionTranslator::~IExceptionTranslator() = default; | ||
2386 | IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default; | ||
2387 | } | ||
2388 | |||
2389 | |||
2390 | |||
2391 | #include <string> | ||
2392 | |||
2393 | namespace Catch { | ||
2394 | namespace Generators { | ||
2395 | |||
2396 | bool GeneratorUntypedBase::countedNext() { | ||
2397 | auto ret = next(); | ||
2398 | if ( ret ) { | ||
2399 | m_stringReprCache.clear(); | ||
2400 | ++m_currentElementIndex; | ||
2401 | } | ||
2402 | return ret; | ||
2403 | } | ||
2404 | |||
2405 | StringRef GeneratorUntypedBase::currentElementAsString() const { | ||
2406 | if ( m_stringReprCache.empty() ) { | ||
2407 | m_stringReprCache = stringifyImpl(); | ||
2408 | } | ||
2409 | return m_stringReprCache; | ||
2410 | } | ||
2411 | |||
2412 | } // namespace Generators | ||
2413 | } // namespace Catch | ||
2414 | |||
2415 | |||
2416 | |||
2417 | |||
2418 | namespace Catch { | ||
2419 | IRegistryHub::~IRegistryHub() = default; | ||
2420 | IMutableRegistryHub::~IMutableRegistryHub() = default; | ||
2421 | } | ||
2422 | |||
2423 | |||
2424 | |||
2425 | #include <cassert> | ||
2426 | |||
2427 | namespace Catch { | ||
2428 | |||
2429 | ReporterConfig::ReporterConfig( | ||
2430 | IConfig const* _fullConfig, | ||
2431 | Detail::unique_ptr<IStream> _stream, | ||
2432 | ColourMode colourMode, | ||
2433 | std::map<std::string, std::string> customOptions ): | ||
2434 | m_stream( CATCH_MOVE(_stream) ), | ||
2435 | m_fullConfig( _fullConfig ), | ||
2436 | m_colourMode( colourMode ), | ||
2437 | m_customOptions( CATCH_MOVE( customOptions ) ) {} | ||
2438 | |||
2439 | Detail::unique_ptr<IStream> ReporterConfig::takeStream() && { | ||
2440 | assert( m_stream ); | ||
2441 | return CATCH_MOVE( m_stream ); | ||
2442 | } | ||
2443 | IConfig const * ReporterConfig::fullConfig() const { return m_fullConfig; } | ||
2444 | ColourMode ReporterConfig::colourMode() const { return m_colourMode; } | ||
2445 | |||
2446 | std::map<std::string, std::string> const& | ||
2447 | ReporterConfig::customOptions() const { | ||
2448 | return m_customOptions; | ||
2449 | } | ||
2450 | |||
2451 | ReporterConfig::~ReporterConfig() = default; | ||
2452 | |||
2453 | AssertionStats::AssertionStats( AssertionResult const& _assertionResult, | ||
2454 | std::vector<MessageInfo> const& _infoMessages, | ||
2455 | Totals const& _totals ) | ||
2456 | : assertionResult( _assertionResult ), | ||
2457 | infoMessages( _infoMessages ), | ||
2458 | totals( _totals ) | ||
2459 | { | ||
2460 | if( assertionResult.hasMessage() ) { | ||
2461 | // Copy message into messages list. | ||
2462 | // !TBD This should have been done earlier, somewhere | ||
2463 | MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); | ||
2464 | builder.m_info.message = static_cast<std::string>(assertionResult.getMessage()); | ||
2465 | |||
2466 | infoMessages.push_back( CATCH_MOVE(builder.m_info) ); | ||
2467 | } | ||
2468 | } | ||
2469 | |||
2470 | SectionStats::SectionStats( SectionInfo&& _sectionInfo, | ||
2471 | Counts const& _assertions, | ||
2472 | double _durationInSeconds, | ||
2473 | bool _missingAssertions ) | ||
2474 | : sectionInfo( CATCH_MOVE(_sectionInfo) ), | ||
2475 | assertions( _assertions ), | ||
2476 | durationInSeconds( _durationInSeconds ), | ||
2477 | missingAssertions( _missingAssertions ) | ||
2478 | {} | ||
2479 | |||
2480 | |||
2481 | TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo, | ||
2482 | Totals const& _totals, | ||
2483 | std::string&& _stdOut, | ||
2484 | std::string&& _stdErr, | ||
2485 | bool _aborting ) | ||
2486 | : testInfo( &_testInfo ), | ||
2487 | totals( _totals ), | ||
2488 | stdOut( CATCH_MOVE(_stdOut) ), | ||
2489 | stdErr( CATCH_MOVE(_stdErr) ), | ||
2490 | aborting( _aborting ) | ||
2491 | {} | ||
2492 | |||
2493 | |||
2494 | TestRunStats::TestRunStats( TestRunInfo const& _runInfo, | ||
2495 | Totals const& _totals, | ||
2496 | bool _aborting ) | ||
2497 | : runInfo( _runInfo ), | ||
2498 | totals( _totals ), | ||
2499 | aborting( _aborting ) | ||
2500 | {} | ||
2501 | |||
2502 | IEventListener::~IEventListener() = default; | ||
2503 | |||
2504 | } // end namespace Catch | ||
2505 | |||
2506 | |||
2507 | |||
2508 | |||
2509 | namespace Catch { | ||
2510 | IReporterFactory::~IReporterFactory() = default; | ||
2511 | EventListenerFactory::~EventListenerFactory() = default; | ||
2512 | } | ||
2513 | |||
2514 | |||
2515 | |||
2516 | |||
2517 | namespace Catch { | ||
2518 | ITestCaseRegistry::~ITestCaseRegistry() = default; | ||
2519 | } | ||
2520 | |||
2521 | |||
2522 | |||
2523 | namespace Catch { | ||
2524 | |||
2525 | AssertionHandler::AssertionHandler | ||
2526 | ( StringRef macroName, | ||
2527 | SourceLineInfo const& lineInfo, | ||
2528 | StringRef capturedExpression, | ||
2529 | ResultDisposition::Flags resultDisposition ) | ||
2530 | : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition }, | ||
2531 | m_resultCapture( getResultCapture() ) | ||
2532 | { | ||
2533 | m_resultCapture.notifyAssertionStarted( m_assertionInfo ); | ||
2534 | } | ||
2535 | |||
2536 | void AssertionHandler::handleExpr( ITransientExpression const& expr ) { | ||
2537 | m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction ); | ||
2538 | } | ||
2539 | void AssertionHandler::handleMessage(ResultWas::OfType resultType, std::string&& message) { | ||
2540 | m_resultCapture.handleMessage( m_assertionInfo, resultType, CATCH_MOVE(message), m_reaction ); | ||
2541 | } | ||
2542 | |||
2543 | auto AssertionHandler::allowThrows() const -> bool { | ||
2544 | return getCurrentContext().getConfig()->allowThrows(); | ||
2545 | } | ||
2546 | |||
2547 | void AssertionHandler::complete() { | ||
2548 | m_completed = true; | ||
2549 | if( m_reaction.shouldDebugBreak ) { | ||
2550 | |||
2551 | // If you find your debugger stopping you here then go one level up on the | ||
2552 | // call-stack for the code that caused it (typically a failed assertion) | ||
2553 | |||
2554 | // (To go back to the test and change execution, jump over the throw, next) | ||
2555 | CATCH_BREAK_INTO_DEBUGGER(); | ||
2556 | } | ||
2557 | if (m_reaction.shouldThrow) { | ||
2558 | throw_test_failure_exception(); | ||
2559 | } | ||
2560 | if ( m_reaction.shouldSkip ) { | ||
2561 | throw_test_skip_exception(); | ||
2562 | } | ||
2563 | } | ||
2564 | |||
2565 | void AssertionHandler::handleUnexpectedInflightException() { | ||
2566 | m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction ); | ||
2567 | } | ||
2568 | |||
2569 | void AssertionHandler::handleExceptionThrownAsExpected() { | ||
2570 | m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); | ||
2571 | } | ||
2572 | void AssertionHandler::handleExceptionNotThrownAsExpected() { | ||
2573 | m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); | ||
2574 | } | ||
2575 | |||
2576 | void AssertionHandler::handleUnexpectedExceptionNotThrown() { | ||
2577 | m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction ); | ||
2578 | } | ||
2579 | |||
2580 | void AssertionHandler::handleThrowingCallSkipped() { | ||
2581 | m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); | ||
2582 | } | ||
2583 | |||
2584 | // This is the overload that takes a string and infers the Equals matcher from it | ||
2585 | // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp | ||
2586 | void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str ) { | ||
2587 | handleExceptionMatchExpr( handler, Matchers::Equals( str ) ); | ||
2588 | } | ||
2589 | |||
2590 | } // namespace Catch | ||
2591 | |||
2592 | |||
2593 | |||
2594 | |||
2595 | #include <algorithm> | ||
2596 | |||
2597 | namespace Catch { | ||
2598 | namespace Detail { | ||
2599 | |||
2600 | bool CaseInsensitiveLess::operator()( StringRef lhs, | ||
2601 | StringRef rhs ) const { | ||
2602 | return std::lexicographical_compare( | ||
2603 | lhs.begin(), lhs.end(), | ||
2604 | rhs.begin(), rhs.end(), | ||
2605 | []( char l, char r ) { return toLower( l ) < toLower( r ); } ); | ||
2606 | } | ||
2607 | |||
2608 | bool | ||
2609 | CaseInsensitiveEqualTo::operator()( StringRef lhs, | ||
2610 | StringRef rhs ) const { | ||
2611 | return std::equal( | ||
2612 | lhs.begin(), lhs.end(), | ||
2613 | rhs.begin(), rhs.end(), | ||
2614 | []( char l, char r ) { return toLower( l ) == toLower( r ); } ); | ||
2615 | } | ||
2616 | |||
2617 | } // namespace Detail | ||
2618 | } // namespace Catch | ||
2619 | |||
2620 | |||
2621 | |||
2622 | |||
2623 | #include <algorithm> | ||
2624 | #include <ostream> | ||
2625 | |||
2626 | namespace { | ||
2627 | bool isOptPrefix( char c ) { | ||
2628 | return c == '-' | ||
2629 | #ifdef CATCH_PLATFORM_WINDOWS | ||
2630 | || c == '/' | ||
2631 | #endif | ||
2632 | ; | ||
2633 | } | ||
2634 | |||
2635 | Catch::StringRef normaliseOpt( Catch::StringRef optName ) { | ||
2636 | if ( optName[0] == '-' | ||
2637 | #if defined(CATCH_PLATFORM_WINDOWS) | ||
2638 | || optName[0] == '/' | ||
2639 | #endif | ||
2640 | ) { | ||
2641 | return optName.substr( 1, optName.size() ); | ||
2642 | } | ||
2643 | |||
2644 | return optName; | ||
2645 | } | ||
2646 | |||
2647 | static size_t find_first_separator(Catch::StringRef sr) { | ||
2648 | auto is_separator = []( char c ) { | ||
2649 | return c == ' ' || c == ':' || c == '='; | ||
2650 | }; | ||
2651 | size_t pos = 0; | ||
2652 | while (pos < sr.size()) { | ||
2653 | if (is_separator(sr[pos])) { return pos; } | ||
2654 | ++pos; | ||
2655 | } | ||
2656 | |||
2657 | return Catch::StringRef::npos; | ||
2658 | } | ||
2659 | |||
2660 | } // namespace | ||
2661 | |||
2662 | namespace Catch { | ||
2663 | namespace Clara { | ||
2664 | namespace Detail { | ||
2665 | |||
2666 | void TokenStream::loadBuffer() { | ||
2667 | m_tokenBuffer.clear(); | ||
2668 | |||
2669 | // Skip any empty strings | ||
2670 | while ( it != itEnd && it->empty() ) { | ||
2671 | ++it; | ||
2672 | } | ||
2673 | |||
2674 | if ( it != itEnd ) { | ||
2675 | StringRef next = *it; | ||
2676 | if ( isOptPrefix( next[0] ) ) { | ||
2677 | auto delimiterPos = find_first_separator(next); | ||
2678 | if ( delimiterPos != StringRef::npos ) { | ||
2679 | m_tokenBuffer.push_back( | ||
2680 | { TokenType::Option, | ||
2681 | next.substr( 0, delimiterPos ) } ); | ||
2682 | m_tokenBuffer.push_back( | ||
2683 | { TokenType::Argument, | ||
2684 | next.substr( delimiterPos + 1, next.size() ) } ); | ||
2685 | } else { | ||
2686 | if ( next.size() > 1 && next[1] != '-' && next.size() > 2 ) { | ||
2687 | // Combined short args, e.g. "-ab" for "-a -b" | ||
2688 | for ( size_t i = 1; i < next.size(); ++i ) { | ||
2689 | m_tokenBuffer.push_back( | ||
2690 | { TokenType::Option, | ||
2691 | next.substr( i, 1 ) } ); | ||
2692 | } | ||
2693 | } else { | ||
2694 | m_tokenBuffer.push_back( | ||
2695 | { TokenType::Option, next } ); | ||
2696 | } | ||
2697 | } | ||
2698 | } else { | ||
2699 | m_tokenBuffer.push_back( | ||
2700 | { TokenType::Argument, next } ); | ||
2701 | } | ||
2702 | } | ||
2703 | } | ||
2704 | |||
2705 | TokenStream::TokenStream( Args const& args ): | ||
2706 | TokenStream( args.m_args.begin(), args.m_args.end() ) {} | ||
2707 | |||
2708 | TokenStream::TokenStream( Iterator it_, Iterator itEnd_ ): | ||
2709 | it( it_ ), itEnd( itEnd_ ) { | ||
2710 | loadBuffer(); | ||
2711 | } | ||
2712 | |||
2713 | TokenStream& TokenStream::operator++() { | ||
2714 | if ( m_tokenBuffer.size() >= 2 ) { | ||
2715 | m_tokenBuffer.erase( m_tokenBuffer.begin() ); | ||
2716 | } else { | ||
2717 | if ( it != itEnd ) | ||
2718 | ++it; | ||
2719 | loadBuffer(); | ||
2720 | } | ||
2721 | return *this; | ||
2722 | } | ||
2723 | |||
2724 | ParserResult convertInto( std::string const& source, | ||
2725 | std::string& target ) { | ||
2726 | target = source; | ||
2727 | return ParserResult::ok( ParseResultType::Matched ); | ||
2728 | } | ||
2729 | |||
2730 | ParserResult convertInto( std::string const& source, | ||
2731 | bool& target ) { | ||
2732 | std::string srcLC = toLower( source ); | ||
2733 | |||
2734 | if ( srcLC == "y" || srcLC == "1" || srcLC == "true" || | ||
2735 | srcLC == "yes" || srcLC == "on" ) { | ||
2736 | target = true; | ||
2737 | } else if ( srcLC == "n" || srcLC == "0" || srcLC == "false" || | ||
2738 | srcLC == "no" || srcLC == "off" ) { | ||
2739 | target = false; | ||
2740 | } else { | ||
2741 | return ParserResult::runtimeError( | ||
2742 | "Expected a boolean value but did not recognise: '" + | ||
2743 | source + '\'' ); | ||
2744 | } | ||
2745 | return ParserResult::ok( ParseResultType::Matched ); | ||
2746 | } | ||
2747 | |||
2748 | size_t ParserBase::cardinality() const { return 1; } | ||
2749 | |||
2750 | InternalParseResult ParserBase::parse( Args const& args ) const { | ||
2751 | return parse( static_cast<std::string>(args.exeName()), TokenStream( args ) ); | ||
2752 | } | ||
2753 | |||
2754 | ParseState::ParseState( ParseResultType type, | ||
2755 | TokenStream remainingTokens ): | ||
2756 | m_type( type ), m_remainingTokens( CATCH_MOVE(remainingTokens) ) {} | ||
2757 | |||
2758 | ParserResult BoundFlagRef::setFlag( bool flag ) { | ||
2759 | m_ref = flag; | ||
2760 | return ParserResult::ok( ParseResultType::Matched ); | ||
2761 | } | ||
2762 | |||
2763 | ResultBase::~ResultBase() = default; | ||
2764 | |||
2765 | bool BoundRef::isContainer() const { return false; } | ||
2766 | |||
2767 | bool BoundRef::isFlag() const { return false; } | ||
2768 | |||
2769 | bool BoundFlagRefBase::isFlag() const { return true; } | ||
2770 | |||
2771 | } // namespace Detail | ||
2772 | |||
2773 | Detail::InternalParseResult Arg::parse(std::string const&, | ||
2774 | Detail::TokenStream tokens) const { | ||
2775 | auto validationResult = validate(); | ||
2776 | if (!validationResult) | ||
2777 | return Detail::InternalParseResult(validationResult); | ||
2778 | |||
2779 | auto token = *tokens; | ||
2780 | if (token.type != Detail::TokenType::Argument) | ||
2781 | return Detail::InternalParseResult::ok(Detail::ParseState( | ||
2782 | ParseResultType::NoMatch, CATCH_MOVE(tokens))); | ||
2783 | |||
2784 | assert(!m_ref->isFlag()); | ||
2785 | auto valueRef = | ||
2786 | static_cast<Detail::BoundValueRefBase*>(m_ref.get()); | ||
2787 | |||
2788 | auto result = valueRef->setValue(static_cast<std::string>(token.token)); | ||
2789 | if ( !result ) | ||
2790 | return Detail::InternalParseResult( result ); | ||
2791 | else | ||
2792 | return Detail::InternalParseResult::ok( | ||
2793 | Detail::ParseState( ParseResultType::Matched, | ||
2794 | CATCH_MOVE( ++tokens ) ) ); | ||
2795 | } | ||
2796 | |||
2797 | Opt::Opt(bool& ref) : | ||
2798 | ParserRefImpl(std::make_shared<Detail::BoundFlagRef>(ref)) {} | ||
2799 | |||
2800 | Detail::HelpColumns Opt::getHelpColumns() const { | ||
2801 | ReusableStringStream oss; | ||
2802 | bool first = true; | ||
2803 | for (auto const& opt : m_optNames) { | ||
2804 | if (first) | ||
2805 | first = false; | ||
2806 | else | ||
2807 | oss << ", "; | ||
2808 | oss << opt; | ||
2809 | } | ||
2810 | if (!m_hint.empty()) | ||
2811 | oss << " <" << m_hint << '>'; | ||
2812 | return { oss.str(), m_description }; | ||
2813 | } | ||
2814 | |||
2815 | bool Opt::isMatch(StringRef optToken) const { | ||
2816 | auto normalisedToken = normaliseOpt(optToken); | ||
2817 | for (auto const& name : m_optNames) { | ||
2818 | if (normaliseOpt(name) == normalisedToken) | ||
2819 | return true; | ||
2820 | } | ||
2821 | return false; | ||
2822 | } | ||
2823 | |||
2824 | Detail::InternalParseResult Opt::parse(std::string const&, | ||
2825 | Detail::TokenStream tokens) const { | ||
2826 | auto validationResult = validate(); | ||
2827 | if (!validationResult) | ||
2828 | return Detail::InternalParseResult(validationResult); | ||
2829 | |||
2830 | if (tokens && | ||
2831 | tokens->type == Detail::TokenType::Option) { | ||
2832 | auto const& token = *tokens; | ||
2833 | if (isMatch(token.token)) { | ||
2834 | if (m_ref->isFlag()) { | ||
2835 | auto flagRef = | ||
2836 | static_cast<Detail::BoundFlagRefBase*>( | ||
2837 | m_ref.get()); | ||
2838 | auto result = flagRef->setFlag(true); | ||
2839 | if (!result) | ||
2840 | return Detail::InternalParseResult(result); | ||
2841 | if (result.value() == | ||
2842 | ParseResultType::ShortCircuitAll) | ||
2843 | return Detail::InternalParseResult::ok(Detail::ParseState( | ||
2844 | result.value(), CATCH_MOVE(tokens))); | ||
2845 | } else { | ||
2846 | auto valueRef = | ||
2847 | static_cast<Detail::BoundValueRefBase*>( | ||
2848 | m_ref.get()); | ||
2849 | ++tokens; | ||
2850 | if (!tokens) | ||
2851 | return Detail::InternalParseResult::runtimeError( | ||
2852 | "Expected argument following " + | ||
2853 | token.token); | ||
2854 | auto const& argToken = *tokens; | ||
2855 | if (argToken.type != Detail::TokenType::Argument) | ||
2856 | return Detail::InternalParseResult::runtimeError( | ||
2857 | "Expected argument following " + | ||
2858 | token.token); | ||
2859 | const auto result = valueRef->setValue(static_cast<std::string>(argToken.token)); | ||
2860 | if (!result) | ||
2861 | return Detail::InternalParseResult(result); | ||
2862 | if (result.value() == | ||
2863 | ParseResultType::ShortCircuitAll) | ||
2864 | return Detail::InternalParseResult::ok(Detail::ParseState( | ||
2865 | result.value(), CATCH_MOVE(tokens))); | ||
2866 | } | ||
2867 | return Detail::InternalParseResult::ok(Detail::ParseState( | ||
2868 | ParseResultType::Matched, CATCH_MOVE(++tokens))); | ||
2869 | } | ||
2870 | } | ||
2871 | return Detail::InternalParseResult::ok( | ||
2872 | Detail::ParseState(ParseResultType::NoMatch, CATCH_MOVE(tokens))); | ||
2873 | } | ||
2874 | |||
2875 | Detail::Result Opt::validate() const { | ||
2876 | if (m_optNames.empty()) | ||
2877 | return Detail::Result::logicError("No options supplied to Opt"); | ||
2878 | for (auto const& name : m_optNames) { | ||
2879 | if (name.empty()) | ||
2880 | return Detail::Result::logicError( | ||
2881 | "Option name cannot be empty"); | ||
2882 | #ifdef CATCH_PLATFORM_WINDOWS | ||
2883 | if (name[0] != '-' && name[0] != '/') | ||
2884 | return Detail::Result::logicError( | ||
2885 | "Option name must begin with '-' or '/'"); | ||
2886 | #else | ||
2887 | if (name[0] != '-') | ||
2888 | return Detail::Result::logicError( | ||
2889 | "Option name must begin with '-'"); | ||
2890 | #endif | ||
2891 | } | ||
2892 | return ParserRefImpl::validate(); | ||
2893 | } | ||
2894 | |||
2895 | ExeName::ExeName() : | ||
2896 | m_name(std::make_shared<std::string>("<executable>")) {} | ||
2897 | |||
2898 | ExeName::ExeName(std::string& ref) : ExeName() { | ||
2899 | m_ref = std::make_shared<Detail::BoundValueRef<std::string>>(ref); | ||
2900 | } | ||
2901 | |||
2902 | Detail::InternalParseResult | ||
2903 | ExeName::parse(std::string const&, | ||
2904 | Detail::TokenStream tokens) const { | ||
2905 | return Detail::InternalParseResult::ok( | ||
2906 | Detail::ParseState(ParseResultType::NoMatch, CATCH_MOVE(tokens))); | ||
2907 | } | ||
2908 | |||
2909 | ParserResult ExeName::set(std::string const& newName) { | ||
2910 | auto lastSlash = newName.find_last_of("\\/"); | ||
2911 | auto filename = (lastSlash == std::string::npos) | ||
2912 | ? newName | ||
2913 | : newName.substr(lastSlash + 1); | ||
2914 | |||
2915 | *m_name = filename; | ||
2916 | if (m_ref) | ||
2917 | return m_ref->setValue(filename); | ||
2918 | else | ||
2919 | return ParserResult::ok(ParseResultType::Matched); | ||
2920 | } | ||
2921 | |||
2922 | |||
2923 | |||
2924 | |||
2925 | Parser& Parser::operator|=( Parser const& other ) { | ||
2926 | m_options.insert( m_options.end(), | ||
2927 | other.m_options.begin(), | ||
2928 | other.m_options.end() ); | ||
2929 | m_args.insert( | ||
2930 | m_args.end(), other.m_args.begin(), other.m_args.end() ); | ||
2931 | return *this; | ||
2932 | } | ||
2933 | |||
2934 | std::vector<Detail::HelpColumns> Parser::getHelpColumns() const { | ||
2935 | std::vector<Detail::HelpColumns> cols; | ||
2936 | cols.reserve( m_options.size() ); | ||
2937 | for ( auto const& o : m_options ) { | ||
2938 | cols.push_back(o.getHelpColumns()); | ||
2939 | } | ||
2940 | return cols; | ||
2941 | } | ||
2942 | |||
2943 | void Parser::writeToStream( std::ostream& os ) const { | ||
2944 | if ( !m_exeName.name().empty() ) { | ||
2945 | os << "usage:\n" | ||
2946 | << " " << m_exeName.name() << ' '; | ||
2947 | bool required = true, first = true; | ||
2948 | for ( auto const& arg : m_args ) { | ||
2949 | if ( first ) | ||
2950 | first = false; | ||
2951 | else | ||
2952 | os << ' '; | ||
2953 | if ( arg.isOptional() && required ) { | ||
2954 | os << '['; | ||
2955 | required = false; | ||
2956 | } | ||
2957 | os << '<' << arg.hint() << '>'; | ||
2958 | if ( arg.cardinality() == 0 ) | ||
2959 | os << " ... "; | ||
2960 | } | ||
2961 | if ( !required ) | ||
2962 | os << ']'; | ||
2963 | if ( !m_options.empty() ) | ||
2964 | os << " options"; | ||
2965 | os << "\n\nwhere options are:\n"; | ||
2966 | } | ||
2967 | |||
2968 | auto rows = getHelpColumns(); | ||
2969 | size_t consoleWidth = CATCH_CONFIG_CONSOLE_WIDTH; | ||
2970 | size_t optWidth = 0; | ||
2971 | for ( auto const& cols : rows ) | ||
2972 | optWidth = ( std::max )( optWidth, cols.left.size() + 2 ); | ||
2973 | |||
2974 | optWidth = ( std::min )( optWidth, consoleWidth / 2 ); | ||
2975 | |||
2976 | for ( auto& cols : rows ) { | ||
2977 | auto row = TextFlow::Column( CATCH_MOVE(cols.left) ) | ||
2978 | .width( optWidth ) | ||
2979 | .indent( 2 ) + | ||
2980 | TextFlow::Spacer( 4 ) + | ||
2981 | TextFlow::Column( static_cast<std::string>(cols.descriptions) ) | ||
2982 | .width( consoleWidth - 7 - optWidth ); | ||
2983 | os << row << '\n'; | ||
2984 | } | ||
2985 | } | ||
2986 | |||
2987 | Detail::Result Parser::validate() const { | ||
2988 | for ( auto const& opt : m_options ) { | ||
2989 | auto result = opt.validate(); | ||
2990 | if ( !result ) | ||
2991 | return result; | ||
2992 | } | ||
2993 | for ( auto const& arg : m_args ) { | ||
2994 | auto result = arg.validate(); | ||
2995 | if ( !result ) | ||
2996 | return result; | ||
2997 | } | ||
2998 | return Detail::Result::ok(); | ||
2999 | } | ||
3000 | |||
3001 | Detail::InternalParseResult | ||
3002 | Parser::parse( std::string const& exeName, | ||
3003 | Detail::TokenStream tokens ) const { | ||
3004 | |||
3005 | struct ParserInfo { | ||
3006 | ParserBase const* parser = nullptr; | ||
3007 | size_t count = 0; | ||
3008 | }; | ||
3009 | std::vector<ParserInfo> parseInfos; | ||
3010 | parseInfos.reserve( m_options.size() + m_args.size() ); | ||
3011 | for ( auto const& opt : m_options ) { | ||
3012 | parseInfos.push_back( { &opt, 0 } ); | ||
3013 | } | ||
3014 | for ( auto const& arg : m_args ) { | ||
3015 | parseInfos.push_back( { &arg, 0 } ); | ||
3016 | } | ||
3017 | |||
3018 | m_exeName.set( exeName ); | ||
3019 | |||
3020 | auto result = Detail::InternalParseResult::ok( | ||
3021 | Detail::ParseState( ParseResultType::NoMatch, CATCH_MOVE(tokens) ) ); | ||
3022 | while ( result.value().remainingTokens() ) { | ||
3023 | bool tokenParsed = false; | ||
3024 | |||
3025 | for ( auto& parseInfo : parseInfos ) { | ||
3026 | if ( parseInfo.parser->cardinality() == 0 || | ||
3027 | parseInfo.count < parseInfo.parser->cardinality() ) { | ||
3028 | result = parseInfo.parser->parse( | ||
3029 | exeName, CATCH_MOVE(result).value().remainingTokens() ); | ||
3030 | if ( !result ) | ||
3031 | return result; | ||
3032 | if ( result.value().type() != | ||
3033 | ParseResultType::NoMatch ) { | ||
3034 | tokenParsed = true; | ||
3035 | ++parseInfo.count; | ||
3036 | break; | ||
3037 | } | ||
3038 | } | ||
3039 | } | ||
3040 | |||
3041 | if ( result.value().type() == ParseResultType::ShortCircuitAll ) | ||
3042 | return result; | ||
3043 | if ( !tokenParsed ) | ||
3044 | return Detail::InternalParseResult::runtimeError( | ||
3045 | "Unrecognised token: " + | ||
3046 | result.value().remainingTokens()->token ); | ||
3047 | } | ||
3048 | // !TBD Check missing required options | ||
3049 | return result; | ||
3050 | } | ||
3051 | |||
3052 | Args::Args(int argc, char const* const* argv) : | ||
3053 | m_exeName(argv[0]), m_args(argv + 1, argv + argc) {} | ||
3054 | |||
3055 | Args::Args(std::initializer_list<StringRef> args) : | ||
3056 | m_exeName(*args.begin()), | ||
3057 | m_args(args.begin() + 1, args.end()) {} | ||
3058 | |||
3059 | |||
3060 | Help::Help( bool& showHelpFlag ): | ||
3061 | Opt( [&]( bool flag ) { | ||
3062 | showHelpFlag = flag; | ||
3063 | return ParserResult::ok( ParseResultType::ShortCircuitAll ); | ||
3064 | } ) { | ||
3065 | static_cast<Opt&> ( *this )( | ||
3066 | "display usage information" )["-?"]["-h"]["--help"] | ||
3067 | .optional(); | ||
3068 | } | ||
3069 | |||
3070 | } // namespace Clara | ||
3071 | } // namespace Catch | ||
3072 | |||
3073 | |||
3074 | |||
3075 | |||
3076 | #include <fstream> | ||
3077 | #include <string> | ||
3078 | |||
3079 | namespace Catch { | ||
3080 | |||
3081 | Clara::Parser makeCommandLineParser( ConfigData& config ) { | ||
3082 | |||
3083 | using namespace Clara; | ||
3084 | |||
3085 | auto const setWarning = [&]( std::string const& warning ) { | ||
3086 | if ( warning == "NoAssertions" ) { | ||
3087 | config.warnings = static_cast<WarnAbout::What>(config.warnings | WarnAbout::NoAssertions); | ||
3088 | return ParserResult::ok( ParseResultType::Matched ); | ||
3089 | } else if ( warning == "UnmatchedTestSpec" ) { | ||
3090 | config.warnings = static_cast<WarnAbout::What>(config.warnings | WarnAbout::UnmatchedTestSpec); | ||
3091 | return ParserResult::ok( ParseResultType::Matched ); | ||
3092 | } | ||
3093 | |||
3094 | return ParserResult ::runtimeError( | ||
3095 | "Unrecognised warning option: '" + warning + '\'' ); | ||
3096 | }; | ||
3097 | auto const loadTestNamesFromFile = [&]( std::string const& filename ) { | ||
3098 | std::ifstream f( filename.c_str() ); | ||
3099 | if( !f.is_open() ) | ||
3100 | return ParserResult::runtimeError( "Unable to load input file: '" + filename + '\'' ); | ||
3101 | |||
3102 | std::string line; | ||
3103 | while( std::getline( f, line ) ) { | ||
3104 | line = trim(line); | ||
3105 | if( !line.empty() && !startsWith( line, '#' ) ) { | ||
3106 | if( !startsWith( line, '"' ) ) | ||
3107 | line = '"' + CATCH_MOVE(line) + '"'; | ||
3108 | config.testsOrTags.push_back( line ); | ||
3109 | config.testsOrTags.emplace_back( "," ); | ||
3110 | } | ||
3111 | } | ||
3112 | //Remove comma in the end | ||
3113 | if(!config.testsOrTags.empty()) | ||
3114 | config.testsOrTags.erase( config.testsOrTags.end()-1 ); | ||
3115 | |||
3116 | return ParserResult::ok( ParseResultType::Matched ); | ||
3117 | }; | ||
3118 | auto const setTestOrder = [&]( std::string const& order ) { | ||
3119 | if( startsWith( "declared", order ) ) | ||
3120 | config.runOrder = TestRunOrder::Declared; | ||
3121 | else if( startsWith( "lexical", order ) ) | ||
3122 | config.runOrder = TestRunOrder::LexicographicallySorted; | ||
3123 | else if( startsWith( "random", order ) ) | ||
3124 | config.runOrder = TestRunOrder::Randomized; | ||
3125 | else | ||
3126 | return ParserResult::runtimeError( "Unrecognised ordering: '" + order + '\'' ); | ||
3127 | return ParserResult::ok( ParseResultType::Matched ); | ||
3128 | }; | ||
3129 | auto const setRngSeed = [&]( std::string const& seed ) { | ||
3130 | if( seed == "time" ) { | ||
3131 | config.rngSeed = generateRandomSeed(GenerateFrom::Time); | ||
3132 | return ParserResult::ok(ParseResultType::Matched); | ||
3133 | } else if (seed == "random-device") { | ||
3134 | config.rngSeed = generateRandomSeed(GenerateFrom::RandomDevice); | ||
3135 | return ParserResult::ok(ParseResultType::Matched); | ||
3136 | } | ||
3137 | |||
3138 | // TODO: ideally we should be parsing uint32_t directly | ||
3139 | // fix this later when we add new parse overload | ||
3140 | auto parsedSeed = parseUInt( seed, 0 ); | ||
3141 | if ( !parsedSeed ) { | ||
3142 | return ParserResult::runtimeError( "Could not parse '" + seed + "' as seed" ); | ||
3143 | } | ||
3144 | config.rngSeed = *parsedSeed; | ||
3145 | return ParserResult::ok( ParseResultType::Matched ); | ||
3146 | }; | ||
3147 | auto const setDefaultColourMode = [&]( std::string const& colourMode ) { | ||
3148 | Optional<ColourMode> maybeMode = Catch::Detail::stringToColourMode(toLower( colourMode )); | ||
3149 | if ( !maybeMode ) { | ||
3150 | return ParserResult::runtimeError( | ||
3151 | "colour mode must be one of: default, ansi, win32, " | ||
3152 | "or none. '" + | ||
3153 | colourMode + "' is not recognised" ); | ||
3154 | } | ||
3155 | auto mode = *maybeMode; | ||
3156 | if ( !isColourImplAvailable( mode ) ) { | ||
3157 | return ParserResult::runtimeError( | ||
3158 | "colour mode '" + colourMode + | ||
3159 | "' is not supported in this binary" ); | ||
3160 | } | ||
3161 | config.defaultColourMode = mode; | ||
3162 | return ParserResult::ok( ParseResultType::Matched ); | ||
3163 | }; | ||
3164 | auto const setWaitForKeypress = [&]( std::string const& keypress ) { | ||
3165 | auto keypressLc = toLower( keypress ); | ||
3166 | if (keypressLc == "never") | ||
3167 | config.waitForKeypress = WaitForKeypress::Never; | ||
3168 | else if( keypressLc == "start" ) | ||
3169 | config.waitForKeypress = WaitForKeypress::BeforeStart; | ||
3170 | else if( keypressLc == "exit" ) | ||
3171 | config.waitForKeypress = WaitForKeypress::BeforeExit; | ||
3172 | else if( keypressLc == "both" ) | ||
3173 | config.waitForKeypress = WaitForKeypress::BeforeStartAndExit; | ||
3174 | else | ||
3175 | return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" ); | ||
3176 | return ParserResult::ok( ParseResultType::Matched ); | ||
3177 | }; | ||
3178 | auto const setVerbosity = [&]( std::string const& verbosity ) { | ||
3179 | auto lcVerbosity = toLower( verbosity ); | ||
3180 | if( lcVerbosity == "quiet" ) | ||
3181 | config.verbosity = Verbosity::Quiet; | ||
3182 | else if( lcVerbosity == "normal" ) | ||
3183 | config.verbosity = Verbosity::Normal; | ||
3184 | else if( lcVerbosity == "high" ) | ||
3185 | config.verbosity = Verbosity::High; | ||
3186 | else | ||
3187 | return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + '\'' ); | ||
3188 | return ParserResult::ok( ParseResultType::Matched ); | ||
3189 | }; | ||
3190 | auto const setReporter = [&]( std::string const& userReporterSpec ) { | ||
3191 | if ( userReporterSpec.empty() ) { | ||
3192 | return ParserResult::runtimeError( "Received empty reporter spec." ); | ||
3193 | } | ||
3194 | |||
3195 | Optional<ReporterSpec> parsed = | ||
3196 | parseReporterSpec( userReporterSpec ); | ||
3197 | if ( !parsed ) { | ||
3198 | return ParserResult::runtimeError( | ||
3199 | "Could not parse reporter spec '" + userReporterSpec + | ||
3200 | "'" ); | ||
3201 | } | ||
3202 | |||
3203 | auto const& reporterSpec = *parsed; | ||
3204 | |||
3205 | auto const& factories = | ||
3206 | getRegistryHub().getReporterRegistry().getFactories(); | ||
3207 | auto result = factories.find( reporterSpec.name() ); | ||
3208 | |||
3209 | if ( result == factories.end() ) { | ||
3210 | return ParserResult::runtimeError( | ||
3211 | "Unrecognized reporter, '" + reporterSpec.name() + | ||
3212 | "'. Check available with --list-reporters" ); | ||
3213 | } | ||
3214 | |||
3215 | |||
3216 | const bool hadOutputFile = reporterSpec.outputFile().some(); | ||
3217 | config.reporterSpecifications.push_back( CATCH_MOVE( *parsed ) ); | ||
3218 | // It would be enough to check this only once at the very end, but | ||
3219 | // there is not a place where we could call this check, so do it | ||
3220 | // every time it could fail. For valid inputs, this is still called | ||
3221 | // at most once. | ||
3222 | if (!hadOutputFile) { | ||
3223 | int n_reporters_without_file = 0; | ||
3224 | for (auto const& spec : config.reporterSpecifications) { | ||
3225 | if (spec.outputFile().none()) { | ||
3226 | n_reporters_without_file++; | ||
3227 | } | ||
3228 | } | ||
3229 | if (n_reporters_without_file > 1) { | ||
3230 | return ParserResult::runtimeError( "Only one reporter may have unspecified output file." ); | ||
3231 | } | ||
3232 | } | ||
3233 | |||
3234 | return ParserResult::ok( ParseResultType::Matched ); | ||
3235 | }; | ||
3236 | auto const setShardCount = [&]( std::string const& shardCount ) { | ||
3237 | auto parsedCount = parseUInt( shardCount ); | ||
3238 | if ( !parsedCount ) { | ||
3239 | return ParserResult::runtimeError( | ||
3240 | "Could not parse '" + shardCount + "' as shard count" ); | ||
3241 | } | ||
3242 | if ( *parsedCount == 0 ) { | ||
3243 | return ParserResult::runtimeError( | ||
3244 | "Shard count must be positive" ); | ||
3245 | } | ||
3246 | config.shardCount = *parsedCount; | ||
3247 | return ParserResult::ok( ParseResultType::Matched ); | ||
3248 | }; | ||
3249 | |||
3250 | auto const setShardIndex = [&](std::string const& shardIndex) { | ||
3251 | auto parsedIndex = parseUInt( shardIndex ); | ||
3252 | if ( !parsedIndex ) { | ||
3253 | return ParserResult::runtimeError( | ||
3254 | "Could not parse '" + shardIndex + "' as shard index" ); | ||
3255 | } | ||
3256 | config.shardIndex = *parsedIndex; | ||
3257 | return ParserResult::ok( ParseResultType::Matched ); | ||
3258 | }; | ||
3259 | |||
3260 | auto cli | ||
3261 | = ExeName( config.processName ) | ||
3262 | | Help( config.showHelp ) | ||
3263 | | Opt( config.showSuccessfulTests ) | ||
3264 | ["-s"]["--success"] | ||
3265 | ( "include successful tests in output" ) | ||
3266 | | Opt( config.shouldDebugBreak ) | ||
3267 | ["-b"]["--break"] | ||
3268 | ( "break into debugger on failure" ) | ||
3269 | | Opt( config.noThrow ) | ||
3270 | ["-e"]["--nothrow"] | ||
3271 | ( "skip exception tests" ) | ||
3272 | | Opt( config.showInvisibles ) | ||
3273 | ["-i"]["--invisibles"] | ||
3274 | ( "show invisibles (tabs, newlines)" ) | ||
3275 | | Opt( config.defaultOutputFilename, "filename" ) | ||
3276 | ["-o"]["--out"] | ||
3277 | ( "default output filename" ) | ||
3278 | | Opt( accept_many, setReporter, "name[::key=value]*" ) | ||
3279 | ["-r"]["--reporter"] | ||
3280 | ( "reporter to use (defaults to console)" ) | ||
3281 | | Opt( config.name, "name" ) | ||
3282 | ["-n"]["--name"] | ||
3283 | ( "suite name" ) | ||
3284 | | Opt( [&]( bool ){ config.abortAfter = 1; } ) | ||
3285 | ["-a"]["--abort"] | ||
3286 | ( "abort at first failure" ) | ||
3287 | | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" ) | ||
3288 | ["-x"]["--abortx"] | ||
3289 | ( "abort after x failures" ) | ||
3290 | | Opt( accept_many, setWarning, "warning name" ) | ||
3291 | ["-w"]["--warn"] | ||
3292 | ( "enable warnings" ) | ||
3293 | | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" ) | ||
3294 | ["-d"]["--durations"] | ||
3295 | ( "show test durations" ) | ||
3296 | | Opt( config.minDuration, "seconds" ) | ||
3297 | ["-D"]["--min-duration"] | ||
3298 | ( "show test durations for tests taking at least the given number of seconds" ) | ||
3299 | | Opt( loadTestNamesFromFile, "filename" ) | ||
3300 | ["-f"]["--input-file"] | ||
3301 | ( "load test names to run from a file" ) | ||
3302 | | Opt( config.filenamesAsTags ) | ||
3303 | ["-#"]["--filenames-as-tags"] | ||
3304 | ( "adds a tag for the filename" ) | ||
3305 | | Opt( config.sectionsToRun, "section name" ) | ||
3306 | ["-c"]["--section"] | ||
3307 | ( "specify section to run" ) | ||
3308 | | Opt( setVerbosity, "quiet|normal|high" ) | ||
3309 | ["-v"]["--verbosity"] | ||
3310 | ( "set output verbosity" ) | ||
3311 | | Opt( config.listTests ) | ||
3312 | ["--list-tests"] | ||
3313 | ( "list all/matching test cases" ) | ||
3314 | | Opt( config.listTags ) | ||
3315 | ["--list-tags"] | ||
3316 | ( "list all/matching tags" ) | ||
3317 | | Opt( config.listReporters ) | ||
3318 | ["--list-reporters"] | ||
3319 | ( "list all available reporters" ) | ||
3320 | | Opt( config.listListeners ) | ||
3321 | ["--list-listeners"] | ||
3322 | ( "list all listeners" ) | ||
3323 | | Opt( setTestOrder, "decl|lex|rand" ) | ||
3324 | ["--order"] | ||
3325 | ( "test case order (defaults to decl)" ) | ||
3326 | | Opt( setRngSeed, "'time'|'random-device'|number" ) | ||
3327 | ["--rng-seed"] | ||
3328 | ( "set a specific seed for random numbers" ) | ||
3329 | | Opt( setDefaultColourMode, "ansi|win32|none|default" ) | ||
3330 | ["--colour-mode"] | ||
3331 | ( "what color mode should be used as default" ) | ||
3332 | | Opt( config.libIdentify ) | ||
3333 | ["--libidentify"] | ||
3334 | ( "report name and version according to libidentify standard" ) | ||
3335 | | Opt( setWaitForKeypress, "never|start|exit|both" ) | ||
3336 | ["--wait-for-keypress"] | ||
3337 | ( "waits for a keypress before exiting" ) | ||
3338 | | Opt( config.skipBenchmarks) | ||
3339 | ["--skip-benchmarks"] | ||
3340 | ( "disable running benchmarks") | ||
3341 | | Opt( config.benchmarkSamples, "samples" ) | ||
3342 | ["--benchmark-samples"] | ||
3343 | ( "number of samples to collect (default: 100)" ) | ||
3344 | | Opt( config.benchmarkResamples, "resamples" ) | ||
3345 | ["--benchmark-resamples"] | ||
3346 | ( "number of resamples for the bootstrap (default: 100000)" ) | ||
3347 | | Opt( config.benchmarkConfidenceInterval, "confidence interval" ) | ||
3348 | ["--benchmark-confidence-interval"] | ||
3349 | ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" ) | ||
3350 | | Opt( config.benchmarkNoAnalysis ) | ||
3351 | ["--benchmark-no-analysis"] | ||
3352 | ( "perform only measurements; do not perform any analysis" ) | ||
3353 | | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" ) | ||
3354 | ["--benchmark-warmup-time"] | ||
3355 | ( "amount of time in milliseconds spent on warming up each test (default: 100)" ) | ||
3356 | | Opt( setShardCount, "shard count" ) | ||
3357 | ["--shard-count"] | ||
3358 | ( "split the tests to execute into this many groups" ) | ||
3359 | | Opt( setShardIndex, "shard index" ) | ||
3360 | ["--shard-index"] | ||
3361 | ( "index of the group of tests to execute (see --shard-count)" ) | ||
3362 | | Opt( config.allowZeroTests ) | ||
3363 | ["--allow-running-no-tests"] | ||
3364 | ( "Treat 'No tests run' as a success" ) | ||
3365 | | Arg( config.testsOrTags, "test name|pattern|tags" ) | ||
3366 | ( "which test or tests to use" ); | ||
3367 | |||
3368 | return cli; | ||
3369 | } | ||
3370 | |||
3371 | } // end namespace Catch | ||
3372 | |||
3373 | |||
3374 | #if defined(__clang__) | ||
3375 | # pragma clang diagnostic push | ||
3376 | # pragma clang diagnostic ignored "-Wexit-time-destructors" | ||
3377 | #endif | ||
3378 | |||
3379 | |||
3380 | |||
3381 | #include <cassert> | ||
3382 | #include <ostream> | ||
3383 | #include <utility> | ||
3384 | |||
3385 | namespace Catch { | ||
3386 | |||
3387 | ColourImpl::~ColourImpl() = default; | ||
3388 | |||
3389 | ColourImpl::ColourGuard ColourImpl::guardColour( Colour::Code colourCode ) { | ||
3390 | return ColourGuard(colourCode, this ); | ||
3391 | } | ||
3392 | |||
3393 | void ColourImpl::ColourGuard::engageImpl( std::ostream& stream ) { | ||
3394 | assert( &stream == &m_colourImpl->m_stream->stream() && | ||
3395 | "Engaging colour guard for different stream than used by the " | ||
3396 | "parent colour implementation" ); | ||
3397 | static_cast<void>( stream ); | ||
3398 | |||
3399 | m_engaged = true; | ||
3400 | m_colourImpl->use( m_code ); | ||
3401 | } | ||
3402 | |||
3403 | ColourImpl::ColourGuard::ColourGuard( Colour::Code code, | ||
3404 | ColourImpl const* colour ): | ||
3405 | m_colourImpl( colour ), m_code( code ) { | ||
3406 | } | ||
3407 | ColourImpl::ColourGuard::ColourGuard( ColourGuard&& rhs ) noexcept: | ||
3408 | m_colourImpl( rhs.m_colourImpl ), | ||
3409 | m_code( rhs.m_code ), | ||
3410 | m_engaged( rhs.m_engaged ) { | ||
3411 | rhs.m_engaged = false; | ||
3412 | } | ||
3413 | ColourImpl::ColourGuard& | ||
3414 | ColourImpl::ColourGuard::operator=( ColourGuard&& rhs ) noexcept { | ||
3415 | using std::swap; | ||
3416 | swap( m_colourImpl, rhs.m_colourImpl ); | ||
3417 | swap( m_code, rhs.m_code ); | ||
3418 | swap( m_engaged, rhs.m_engaged ); | ||
3419 | |||
3420 | return *this; | ||
3421 | } | ||
3422 | ColourImpl::ColourGuard::~ColourGuard() { | ||
3423 | if ( m_engaged ) { | ||
3424 | m_colourImpl->use( Colour::None ); | ||
3425 | } | ||
3426 | } | ||
3427 | |||
3428 | ColourImpl::ColourGuard& | ||
3429 | ColourImpl::ColourGuard::engage( std::ostream& stream ) & { | ||
3430 | engageImpl( stream ); | ||
3431 | return *this; | ||
3432 | } | ||
3433 | |||
3434 | ColourImpl::ColourGuard&& | ||
3435 | ColourImpl::ColourGuard::engage( std::ostream& stream ) && { | ||
3436 | engageImpl( stream ); | ||
3437 | return CATCH_MOVE(*this); | ||
3438 | } | ||
3439 | |||
3440 | namespace { | ||
3441 | //! A do-nothing implementation of colour, used as fallback for unknown | ||
3442 | //! platforms, and when the user asks to deactivate all colours. | ||
3443 | class NoColourImpl final : public ColourImpl { | ||
3444 | public: | ||
3445 | NoColourImpl( IStream* stream ): ColourImpl( stream ) {} | ||
3446 | |||
3447 | private: | ||
3448 | void use( Colour::Code ) const override {} | ||
3449 | }; | ||
3450 | } // namespace | ||
3451 | |||
3452 | |||
3453 | } // namespace Catch | ||
3454 | |||
3455 | |||
3456 | #if defined ( CATCH_CONFIG_COLOUR_WIN32 ) ///////////////////////////////////////// | ||
3457 | |||
3458 | namespace Catch { | ||
3459 | namespace { | ||
3460 | |||
3461 | class Win32ColourImpl final : public ColourImpl { | ||
3462 | public: | ||
3463 | Win32ColourImpl(IStream* stream): | ||
3464 | ColourImpl(stream) { | ||
3465 | CONSOLE_SCREEN_BUFFER_INFO csbiInfo; | ||
3466 | GetConsoleScreenBufferInfo( GetStdHandle( STD_OUTPUT_HANDLE ), | ||
3467 | &csbiInfo ); | ||
3468 | originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); | ||
3469 | originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); | ||
3470 | } | ||
3471 | |||
3472 | static bool useImplementationForStream(IStream const& stream) { | ||
3473 | // Win32 text colour APIs can only be used on console streams | ||
3474 | // We cannot check that the output hasn't been redirected, | ||
3475 | // so we just check that the original stream is console stream. | ||
3476 | return stream.isConsole(); | ||
3477 | } | ||
3478 | |||
3479 | private: | ||
3480 | void use( Colour::Code _colourCode ) const override { | ||
3481 | switch( _colourCode ) { | ||
3482 | case Colour::None: return setTextAttribute( originalForegroundAttributes ); | ||
3483 | case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); | ||
3484 | case Colour::Red: return setTextAttribute( FOREGROUND_RED ); | ||
3485 | case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); | ||
3486 | case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); | ||
3487 | case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); | ||
3488 | case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); | ||
3489 | case Colour::Grey: return setTextAttribute( 0 ); | ||
3490 | |||
3491 | case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); | ||
3492 | case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); | ||
3493 | case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); | ||
3494 | case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); | ||
3495 | case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN ); | ||
3496 | |||
3497 | case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); | ||
3498 | |||
3499 | default: | ||
3500 | CATCH_ERROR( "Unknown colour requested" ); | ||
3501 | } | ||
3502 | } | ||
3503 | |||
3504 | void setTextAttribute( WORD _textAttribute ) const { | ||
3505 | SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), | ||
3506 | _textAttribute | | ||
3507 | originalBackgroundAttributes ); | ||
3508 | } | ||
3509 | WORD originalForegroundAttributes; | ||
3510 | WORD originalBackgroundAttributes; | ||
3511 | }; | ||
3512 | |||
3513 | } // end anon namespace | ||
3514 | } // end namespace Catch | ||
3515 | |||
3516 | #endif // Windows/ ANSI/ None | ||
3517 | |||
3518 | |||
3519 | #if defined( CATCH_PLATFORM_LINUX ) || defined( CATCH_PLATFORM_MAC ) | ||
3520 | # define CATCH_INTERNAL_HAS_ISATTY | ||
3521 | # include <unistd.h> | ||
3522 | #endif | ||
3523 | |||
3524 | namespace Catch { | ||
3525 | namespace { | ||
3526 | |||
3527 | class ANSIColourImpl final : public ColourImpl { | ||
3528 | public: | ||
3529 | ANSIColourImpl( IStream* stream ): ColourImpl( stream ) {} | ||
3530 | |||
3531 | static bool useImplementationForStream(IStream const& stream) { | ||
3532 | // This is kinda messy due to trying to support a bunch of | ||
3533 | // different platforms at once. | ||
3534 | // The basic idea is that if we are asked to do autodetection (as | ||
3535 | // opposed to being told to use posixy colours outright), then we | ||
3536 | // only want to use the colours if we are writing to console. | ||
3537 | // However, console might be redirected, so we make an attempt at | ||
3538 | // checking for that on platforms where we know how to do that. | ||
3539 | bool useColour = stream.isConsole(); | ||
3540 | #if defined( CATCH_INTERNAL_HAS_ISATTY ) && \ | ||
3541 | !( defined( __DJGPP__ ) && defined( __STRICT_ANSI__ ) ) | ||
3542 | ErrnoGuard _; // for isatty | ||
3543 | useColour = useColour && isatty( STDOUT_FILENO ); | ||
3544 | # endif | ||
3545 | # if defined( CATCH_PLATFORM_MAC ) || defined( CATCH_PLATFORM_IPHONE ) | ||
3546 | useColour = useColour && !isDebuggerActive(); | ||
3547 | # endif | ||
3548 | |||
3549 | return useColour; | ||
3550 | } | ||
3551 | |||
3552 | private: | ||
3553 | void use( Colour::Code _colourCode ) const override { | ||
3554 | auto setColour = [&out = | ||
3555 | m_stream->stream()]( char const* escapeCode ) { | ||
3556 | // The escape sequence must be flushed to console, otherwise | ||
3557 | // if stdin and stderr are intermixed, we'd get accidentally | ||
3558 | // coloured output. | ||
3559 | out << '\033' << escapeCode << std::flush; | ||
3560 | }; | ||
3561 | switch( _colourCode ) { | ||
3562 | case Colour::None: | ||
3563 | case Colour::White: return setColour( "[0m" ); | ||
3564 | case Colour::Red: return setColour( "[0;31m" ); | ||
3565 | case Colour::Green: return setColour( "[0;32m" ); | ||
3566 | case Colour::Blue: return setColour( "[0;34m" ); | ||
3567 | case Colour::Cyan: return setColour( "[0;36m" ); | ||
3568 | case Colour::Yellow: return setColour( "[0;33m" ); | ||
3569 | case Colour::Grey: return setColour( "[1;30m" ); | ||
3570 | |||
3571 | case Colour::LightGrey: return setColour( "[0;37m" ); | ||
3572 | case Colour::BrightRed: return setColour( "[1;31m" ); | ||
3573 | case Colour::BrightGreen: return setColour( "[1;32m" ); | ||
3574 | case Colour::BrightWhite: return setColour( "[1;37m" ); | ||
3575 | case Colour::BrightYellow: return setColour( "[1;33m" ); | ||
3576 | |||
3577 | case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); | ||
3578 | default: CATCH_INTERNAL_ERROR( "Unknown colour requested" ); | ||
3579 | } | ||
3580 | } | ||
3581 | }; | ||
3582 | |||
3583 | } // end anon namespace | ||
3584 | } // end namespace Catch | ||
3585 | |||
3586 | namespace Catch { | ||
3587 | |||
3588 | Detail::unique_ptr<ColourImpl> makeColourImpl( ColourMode colourSelection, | ||
3589 | IStream* stream ) { | ||
3590 | #if defined( CATCH_CONFIG_COLOUR_WIN32 ) | ||
3591 | if ( colourSelection == ColourMode::Win32 ) { | ||
3592 | return Detail::make_unique<Win32ColourImpl>( stream ); | ||
3593 | } | ||
3594 | #endif | ||
3595 | if ( colourSelection == ColourMode::ANSI ) { | ||
3596 | return Detail::make_unique<ANSIColourImpl>( stream ); | ||
3597 | } | ||
3598 | if ( colourSelection == ColourMode::None ) { | ||
3599 | return Detail::make_unique<NoColourImpl>( stream ); | ||
3600 | } | ||
3601 | |||
3602 | if ( colourSelection == ColourMode::PlatformDefault) { | ||
3603 | #if defined( CATCH_CONFIG_COLOUR_WIN32 ) | ||
3604 | if ( Win32ColourImpl::useImplementationForStream( *stream ) ) { | ||
3605 | return Detail::make_unique<Win32ColourImpl>( stream ); | ||
3606 | } | ||
3607 | #endif | ||
3608 | if ( ANSIColourImpl::useImplementationForStream( *stream ) ) { | ||
3609 | return Detail::make_unique<ANSIColourImpl>( stream ); | ||
3610 | } | ||
3611 | return Detail::make_unique<NoColourImpl>( stream ); | ||
3612 | } | ||
3613 | |||
3614 | CATCH_ERROR( "Could not create colour impl for selection " << static_cast<int>(colourSelection) ); | ||
3615 | } | ||
3616 | |||
3617 | bool isColourImplAvailable( ColourMode colourSelection ) { | ||
3618 | switch ( colourSelection ) { | ||
3619 | #if defined( CATCH_CONFIG_COLOUR_WIN32 ) | ||
3620 | case ColourMode::Win32: | ||
3621 | #endif | ||
3622 | case ColourMode::ANSI: | ||
3623 | case ColourMode::None: | ||
3624 | case ColourMode::PlatformDefault: | ||
3625 | return true; | ||
3626 | default: | ||
3627 | return false; | ||
3628 | } | ||
3629 | } | ||
3630 | |||
3631 | |||
3632 | } // end namespace Catch | ||
3633 | |||
3634 | #if defined(__clang__) | ||
3635 | # pragma clang diagnostic pop | ||
3636 | #endif | ||
3637 | |||
3638 | |||
3639 | |||
3640 | |||
3641 | namespace Catch { | ||
3642 | |||
3643 | Context* Context::currentContext = nullptr; | ||
3644 | |||
3645 | void cleanUpContext() { | ||
3646 | delete Context::currentContext; | ||
3647 | Context::currentContext = nullptr; | ||
3648 | } | ||
3649 | void Context::createContext() { | ||
3650 | currentContext = new Context(); | ||
3651 | } | ||
3652 | |||
3653 | Context& getCurrentMutableContext() { | ||
3654 | if ( !Context::currentContext ) { Context::createContext(); } | ||
3655 | // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn) | ||
3656 | return *Context::currentContext; | ||
3657 | } | ||
3658 | |||
3659 | SimplePcg32& sharedRng() { | ||
3660 | static SimplePcg32 s_rng; | ||
3661 | return s_rng; | ||
3662 | } | ||
3663 | |||
3664 | } | ||
3665 | |||
3666 | |||
3667 | |||
3668 | |||
3669 | |||
3670 | #include <ostream> | ||
3671 | |||
3672 | #if defined(CATCH_CONFIG_ANDROID_LOGWRITE) | ||
3673 | #include <android/log.h> | ||
3674 | |||
3675 | namespace Catch { | ||
3676 | void writeToDebugConsole( std::string const& text ) { | ||
3677 | __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() ); | ||
3678 | } | ||
3679 | } | ||
3680 | |||
3681 | #elif defined(CATCH_PLATFORM_WINDOWS) | ||
3682 | |||
3683 | namespace Catch { | ||
3684 | void writeToDebugConsole( std::string const& text ) { | ||
3685 | ::OutputDebugStringA( text.c_str() ); | ||
3686 | } | ||
3687 | } | ||
3688 | |||
3689 | #else | ||
3690 | |||
3691 | namespace Catch { | ||
3692 | void writeToDebugConsole( std::string const& text ) { | ||
3693 | // !TBD: Need a version for Mac/ XCode and other IDEs | ||
3694 | Catch::cout() << text; | ||
3695 | } | ||
3696 | } | ||
3697 | |||
3698 | #endif // Platform | ||
3699 | |||
3700 | |||
3701 | |||
3702 | #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) | ||
3703 | |||
3704 | # include <cassert> | ||
3705 | # include <sys/types.h> | ||
3706 | # include <unistd.h> | ||
3707 | # include <cstddef> | ||
3708 | # include <ostream> | ||
3709 | |||
3710 | #ifdef __apple_build_version__ | ||
3711 | // These headers will only compile with AppleClang (XCode) | ||
3712 | // For other compilers (Clang, GCC, ... ) we need to exclude them | ||
3713 | # include <sys/sysctl.h> | ||
3714 | #endif | ||
3715 | |||
3716 | namespace Catch { | ||
3717 | #ifdef __apple_build_version__ | ||
3718 | // The following function is taken directly from the following technical note: | ||
3719 | // https://developer.apple.com/library/archive/qa/qa1361/_index.html | ||
3720 | |||
3721 | // Returns true if the current process is being debugged (either | ||
3722 | // running under the debugger or has a debugger attached post facto). | ||
3723 | bool isDebuggerActive(){ | ||
3724 | int mib[4]; | ||
3725 | struct kinfo_proc info; | ||
3726 | std::size_t size; | ||
3727 | |||
3728 | // Initialize the flags so that, if sysctl fails for some bizarre | ||
3729 | // reason, we get a predictable result. | ||
3730 | |||
3731 | info.kp_proc.p_flag = 0; | ||
3732 | |||
3733 | // Initialize mib, which tells sysctl the info we want, in this case | ||
3734 | // we're looking for information about a specific process ID. | ||
3735 | |||
3736 | mib[0] = CTL_KERN; | ||
3737 | mib[1] = KERN_PROC; | ||
3738 | mib[2] = KERN_PROC_PID; | ||
3739 | mib[3] = getpid(); | ||
3740 | |||
3741 | // Call sysctl. | ||
3742 | |||
3743 | size = sizeof(info); | ||
3744 | if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) { | ||
3745 | Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n\n" << std::flush; | ||
3746 | return false; | ||
3747 | } | ||
3748 | |||
3749 | // We're being debugged if the P_TRACED flag is set. | ||
3750 | |||
3751 | return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); | ||
3752 | } | ||
3753 | #else | ||
3754 | bool isDebuggerActive() { | ||
3755 | // We need to find another way to determine this for non-appleclang compilers on macOS | ||
3756 | return false; | ||
3757 | } | ||
3758 | #endif | ||
3759 | } // namespace Catch | ||
3760 | |||
3761 | #elif defined(CATCH_PLATFORM_LINUX) | ||
3762 | #include <fstream> | ||
3763 | #include <string> | ||
3764 | |||
3765 | namespace Catch{ | ||
3766 | // The standard POSIX way of detecting a debugger is to attempt to | ||
3767 | // ptrace() the process, but this needs to be done from a child and not | ||
3768 | // this process itself to still allow attaching to this process later | ||
3769 | // if wanted, so is rather heavy. Under Linux we have the PID of the | ||
3770 | // "debugger" (which doesn't need to be gdb, of course, it could also | ||
3771 | // be strace, for example) in /proc/$PID/status, so just get it from | ||
3772 | // there instead. | ||
3773 | bool isDebuggerActive(){ | ||
3774 | // Libstdc++ has a bug, where std::ifstream sets errno to 0 | ||
3775 | // This way our users can properly assert over errno values | ||
3776 | ErrnoGuard guard; | ||
3777 | std::ifstream in("/proc/self/status"); | ||
3778 | for( std::string line; std::getline(in, line); ) { | ||
3779 | static const int PREFIX_LEN = 11; | ||
3780 | if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) { | ||
3781 | // We're traced if the PID is not 0 and no other PID starts | ||
3782 | // with 0 digit, so it's enough to check for just a single | ||
3783 | // character. | ||
3784 | return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; | ||
3785 | } | ||
3786 | } | ||
3787 | |||
3788 | return false; | ||
3789 | } | ||
3790 | } // namespace Catch | ||
3791 | #elif defined(_MSC_VER) | ||
3792 | extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); | ||
3793 | namespace Catch { | ||
3794 | bool isDebuggerActive() { | ||
3795 | return IsDebuggerPresent() != 0; | ||
3796 | } | ||
3797 | } | ||
3798 | #elif defined(__MINGW32__) | ||
3799 | extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); | ||
3800 | namespace Catch { | ||
3801 | bool isDebuggerActive() { | ||
3802 | return IsDebuggerPresent() != 0; | ||
3803 | } | ||
3804 | } | ||
3805 | #else | ||
3806 | namespace Catch { | ||
3807 | bool isDebuggerActive() { return false; } | ||
3808 | } | ||
3809 | #endif // Platform | ||
3810 | |||
3811 | |||
3812 | |||
3813 | |||
3814 | namespace Catch { | ||
3815 | |||
3816 | void ITransientExpression::streamReconstructedExpression( | ||
3817 | std::ostream& os ) const { | ||
3818 | // We can't make this function pure virtual to keep ITransientExpression | ||
3819 | // constexpr, so we write error message instead | ||
3820 | os << "Some class derived from ITransientExpression without overriding streamReconstructedExpression"; | ||
3821 | } | ||
3822 | |||
3823 | void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) { | ||
3824 | if( lhs.size() + rhs.size() < 40 && | ||
3825 | lhs.find('\n') == std::string::npos && | ||
3826 | rhs.find('\n') == std::string::npos ) | ||
3827 | os << lhs << ' ' << op << ' ' << rhs; | ||
3828 | else | ||
3829 | os << lhs << '\n' << op << '\n' << rhs; | ||
3830 | } | ||
3831 | } | ||
3832 | |||
3833 | |||
3834 | |||
3835 | #include <stdexcept> | ||
3836 | |||
3837 | |||
3838 | namespace Catch { | ||
3839 | #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) | ||
3840 | [[noreturn]] | ||
3841 | void throw_exception(std::exception const& e) { | ||
3842 | Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n" | ||
3843 | << "The message was: " << e.what() << '\n'; | ||
3844 | std::terminate(); | ||
3845 | } | ||
3846 | #endif | ||
3847 | |||
3848 | [[noreturn]] | ||
3849 | void throw_logic_error(std::string const& msg) { | ||
3850 | throw_exception(std::logic_error(msg)); | ||
3851 | } | ||
3852 | |||
3853 | [[noreturn]] | ||
3854 | void throw_domain_error(std::string const& msg) { | ||
3855 | throw_exception(std::domain_error(msg)); | ||
3856 | } | ||
3857 | |||
3858 | [[noreturn]] | ||
3859 | void throw_runtime_error(std::string const& msg) { | ||
3860 | throw_exception(std::runtime_error(msg)); | ||
3861 | } | ||
3862 | |||
3863 | |||
3864 | |||
3865 | } // namespace Catch; | ||
3866 | |||
3867 | |||
3868 | |||
3869 | #include <cassert> | ||
3870 | |||
3871 | namespace Catch { | ||
3872 | |||
3873 | IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() = default; | ||
3874 | |||
3875 | namespace Detail { | ||
3876 | |||
3877 | namespace { | ||
3878 | // Extracts the actual name part of an enum instance | ||
3879 | // In other words, it returns the Blue part of Bikeshed::Colour::Blue | ||
3880 | StringRef extractInstanceName(StringRef enumInstance) { | ||
3881 | // Find last occurrence of ":" | ||
3882 | size_t name_start = enumInstance.size(); | ||
3883 | while (name_start > 0 && enumInstance[name_start - 1] != ':') { | ||
3884 | --name_start; | ||
3885 | } | ||
3886 | return enumInstance.substr(name_start, enumInstance.size() - name_start); | ||
3887 | } | ||
3888 | } | ||
3889 | |||
3890 | std::vector<StringRef> parseEnums( StringRef enums ) { | ||
3891 | auto enumValues = splitStringRef( enums, ',' ); | ||
3892 | std::vector<StringRef> parsed; | ||
3893 | parsed.reserve( enumValues.size() ); | ||
3894 | for( auto const& enumValue : enumValues ) { | ||
3895 | parsed.push_back(trim(extractInstanceName(enumValue))); | ||
3896 | } | ||
3897 | return parsed; | ||
3898 | } | ||
3899 | |||
3900 | EnumInfo::~EnumInfo() = default; | ||
3901 | |||
3902 | StringRef EnumInfo::lookup( int value ) const { | ||
3903 | for( auto const& valueToName : m_values ) { | ||
3904 | if( valueToName.first == value ) | ||
3905 | return valueToName.second; | ||
3906 | } | ||
3907 | return "{** unexpected enum value **}"_sr; | ||
3908 | } | ||
3909 | |||
3910 | Catch::Detail::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) { | ||
3911 | auto enumInfo = Catch::Detail::make_unique<EnumInfo>(); | ||
3912 | enumInfo->m_name = enumName; | ||
3913 | enumInfo->m_values.reserve( values.size() ); | ||
3914 | |||
3915 | const auto valueNames = Catch::Detail::parseEnums( allValueNames ); | ||
3916 | assert( valueNames.size() == values.size() ); | ||
3917 | std::size_t i = 0; | ||
3918 | for( auto value : values ) | ||
3919 | enumInfo->m_values.emplace_back(value, valueNames[i++]); | ||
3920 | |||
3921 | return enumInfo; | ||
3922 | } | ||
3923 | |||
3924 | EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) { | ||
3925 | m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values)); | ||
3926 | return *m_enumInfos.back(); | ||
3927 | } | ||
3928 | |||
3929 | } // Detail | ||
3930 | } // Catch | ||
3931 | |||
3932 | |||
3933 | |||
3934 | |||
3935 | |||
3936 | #include <cerrno> | ||
3937 | |||
3938 | namespace Catch { | ||
3939 | ErrnoGuard::ErrnoGuard():m_oldErrno(errno){} | ||
3940 | ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; } | ||
3941 | } | ||
3942 | |||
3943 | |||
3944 | |||
3945 | #include <exception> | ||
3946 | |||
3947 | namespace Catch { | ||
3948 | |||
3949 | #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) | ||
3950 | namespace { | ||
3951 | static std::string tryTranslators( | ||
3952 | std::vector< | ||
3953 | Detail::unique_ptr<IExceptionTranslator const>> const& translators ) { | ||
3954 | if ( translators.empty() ) { | ||
3955 | std::rethrow_exception( std::current_exception() ); | ||
3956 | } else { | ||
3957 | return translators[0]->translate( translators.begin() + 1, | ||
3958 | translators.end() ); | ||
3959 | } | ||
3960 | } | ||
3961 | |||
3962 | } | ||
3963 | #endif //!defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) | ||
3964 | |||
3965 | ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() = default; | ||
3966 | |||
3967 | void ExceptionTranslatorRegistry::registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator ) { | ||
3968 | m_translators.push_back( CATCH_MOVE( translator ) ); | ||
3969 | } | ||
3970 | |||
3971 | #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) | ||
3972 | std::string ExceptionTranslatorRegistry::translateActiveException() const { | ||
3973 | // Compiling a mixed mode project with MSVC means that CLR | ||
3974 | // exceptions will be caught in (...) as well. However, these do | ||
3975 | // do not fill-in std::current_exception and thus lead to crash | ||
3976 | // when attempting rethrow. | ||
3977 | // /EHa switch also causes structured exceptions to be caught | ||
3978 | // here, but they fill-in current_exception properly, so | ||
3979 | // at worst the output should be a little weird, instead of | ||
3980 | // causing a crash. | ||
3981 | if ( std::current_exception() == nullptr ) { | ||
3982 | return "Non C++ exception. Possibly a CLR exception."; | ||
3983 | } | ||
3984 | |||
3985 | // First we try user-registered translators. If none of them can | ||
3986 | // handle the exception, it will be rethrown handled by our defaults. | ||
3987 | try { | ||
3988 | return tryTranslators(m_translators); | ||
3989 | } | ||
3990 | // To avoid having to handle TFE explicitly everywhere, we just | ||
3991 | // rethrow it so that it goes back up the caller. | ||
3992 | catch( TestFailureException& ) { | ||
3993 | std::rethrow_exception(std::current_exception()); | ||
3994 | } | ||
3995 | catch( TestSkipException& ) { | ||
3996 | std::rethrow_exception(std::current_exception()); | ||
3997 | } | ||
3998 | catch( std::exception const& ex ) { | ||
3999 | return ex.what(); | ||
4000 | } | ||
4001 | catch( std::string const& msg ) { | ||
4002 | return msg; | ||
4003 | } | ||
4004 | catch( const char* msg ) { | ||
4005 | return msg; | ||
4006 | } | ||
4007 | catch(...) { | ||
4008 | return "Unknown exception"; | ||
4009 | } | ||
4010 | } | ||
4011 | |||
4012 | #else // ^^ Exceptions are enabled // Exceptions are disabled vv | ||
4013 | std::string ExceptionTranslatorRegistry::translateActiveException() const { | ||
4014 | CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); | ||
4015 | } | ||
4016 | #endif | ||
4017 | |||
4018 | } | ||
4019 | |||
4020 | |||
4021 | |||
4022 | /** \file | ||
4023 | * This file provides platform specific implementations of FatalConditionHandler | ||
4024 | * | ||
4025 | * This means that there is a lot of conditional compilation, and platform | ||
4026 | * specific code. Currently, Catch2 supports a dummy handler (if no | ||
4027 | * handler is desired), and 2 platform specific handlers: | ||
4028 | * * Windows' SEH | ||
4029 | * * POSIX signals | ||
4030 | * | ||
4031 | * Consequently, various pieces of code below are compiled if either of | ||
4032 | * the platform specific handlers is enabled, or if none of them are | ||
4033 | * enabled. It is assumed that both cannot be enabled at the same time, | ||
4034 | * and doing so should cause a compilation error. | ||
4035 | * | ||
4036 | * If another platform specific handler is added, the compile guards | ||
4037 | * below will need to be updated taking these assumptions into account. | ||
4038 | */ | ||
4039 | |||
4040 | |||
4041 | |||
4042 | #include <algorithm> | ||
4043 | |||
4044 | #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS ) | ||
4045 | |||
4046 | namespace Catch { | ||
4047 | |||
4048 | // If neither SEH nor signal handling is required, the handler impls | ||
4049 | // do not have to do anything, and can be empty. | ||
4050 | void FatalConditionHandler::engage_platform() {} | ||
4051 | void FatalConditionHandler::disengage_platform() noexcept {} | ||
4052 | FatalConditionHandler::FatalConditionHandler() = default; | ||
4053 | FatalConditionHandler::~FatalConditionHandler() = default; | ||
4054 | |||
4055 | } // end namespace Catch | ||
4056 | |||
4057 | #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS | ||
4058 | |||
4059 | #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS ) | ||
4060 | #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time" | ||
4061 | #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS | ||
4062 | |||
4063 | #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) | ||
4064 | |||
4065 | namespace { | ||
4066 | //! Signals fatal error message to the run context | ||
4067 | void reportFatal( char const * const message ) { | ||
4068 | Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message ); | ||
4069 | } | ||
4070 | |||
4071 | //! Minimal size Catch2 needs for its own fatal error handling. | ||
4072 | //! Picked empirically, so it might not be sufficient on all | ||
4073 | //! platforms, and for all configurations. | ||
4074 | constexpr std::size_t minStackSizeForErrors = 32 * 1024; | ||
4075 | } // end unnamed namespace | ||
4076 | |||
4077 | #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS | ||
4078 | |||
4079 | #if defined( CATCH_CONFIG_WINDOWS_SEH ) | ||
4080 | |||
4081 | namespace Catch { | ||
4082 | |||
4083 | struct SignalDefs { DWORD id; const char* name; }; | ||
4084 | |||
4085 | // There is no 1-1 mapping between signals and windows exceptions. | ||
4086 | // Windows can easily distinguish between SO and SigSegV, | ||
4087 | // but SigInt, SigTerm, etc are handled differently. | ||
4088 | static SignalDefs signalDefs[] = { | ||
4089 | { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" }, | ||
4090 | { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" }, | ||
4091 | { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" }, | ||
4092 | { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" }, | ||
4093 | }; | ||
4094 | |||
4095 | static LONG CALLBACK topLevelExceptionFilter(PEXCEPTION_POINTERS ExceptionInfo) { | ||
4096 | for (auto const& def : signalDefs) { | ||
4097 | if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) { | ||
4098 | reportFatal(def.name); | ||
4099 | } | ||
4100 | } | ||
4101 | // If its not an exception we care about, pass it along. | ||
4102 | // This stops us from eating debugger breaks etc. | ||
4103 | return EXCEPTION_CONTINUE_SEARCH; | ||
4104 | } | ||
4105 | |||
4106 | // Since we do not support multiple instantiations, we put these | ||
4107 | // into global variables and rely on cleaning them up in outlined | ||
4108 | // constructors/destructors | ||
4109 | static LPTOP_LEVEL_EXCEPTION_FILTER previousTopLevelExceptionFilter = nullptr; | ||
4110 | |||
4111 | |||
4112 | // For MSVC, we reserve part of the stack memory for handling | ||
4113 | // memory overflow structured exception. | ||
4114 | FatalConditionHandler::FatalConditionHandler() { | ||
4115 | ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors); | ||
4116 | if (!SetThreadStackGuarantee(&guaranteeSize)) { | ||
4117 | // We do not want to fully error out, because needing | ||
4118 | // the stack reserve should be rare enough anyway. | ||
4119 | Catch::cerr() | ||
4120 | << "Failed to reserve piece of stack." | ||
4121 | << " Stack overflows will not be reported successfully."; | ||
4122 | } | ||
4123 | } | ||
4124 | |||
4125 | // We do not attempt to unset the stack guarantee, because | ||
4126 | // Windows does not support lowering the stack size guarantee. | ||
4127 | FatalConditionHandler::~FatalConditionHandler() = default; | ||
4128 | |||
4129 | |||
4130 | void FatalConditionHandler::engage_platform() { | ||
4131 | // Register as a the top level exception filter. | ||
4132 | previousTopLevelExceptionFilter = SetUnhandledExceptionFilter(topLevelExceptionFilter); | ||
4133 | } | ||
4134 | |||
4135 | void FatalConditionHandler::disengage_platform() noexcept { | ||
4136 | if (SetUnhandledExceptionFilter(previousTopLevelExceptionFilter) != topLevelExceptionFilter) { | ||
4137 | Catch::cerr() | ||
4138 | << "Unexpected SEH unhandled exception filter on disengage." | ||
4139 | << " The filter was restored, but might be rolled back unexpectedly."; | ||
4140 | } | ||
4141 | previousTopLevelExceptionFilter = nullptr; | ||
4142 | } | ||
4143 | |||
4144 | } // end namespace Catch | ||
4145 | |||
4146 | #endif // CATCH_CONFIG_WINDOWS_SEH | ||
4147 | |||
4148 | #if defined( CATCH_CONFIG_POSIX_SIGNALS ) | ||
4149 | |||
4150 | #include <signal.h> | ||
4151 | |||
4152 | namespace Catch { | ||
4153 | |||
4154 | struct SignalDefs { | ||
4155 | int id; | ||
4156 | const char* name; | ||
4157 | }; | ||
4158 | |||
4159 | static SignalDefs signalDefs[] = { | ||
4160 | { SIGINT, "SIGINT - Terminal interrupt signal" }, | ||
4161 | { SIGILL, "SIGILL - Illegal instruction signal" }, | ||
4162 | { SIGFPE, "SIGFPE - Floating point error signal" }, | ||
4163 | { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, | ||
4164 | { SIGTERM, "SIGTERM - Termination request signal" }, | ||
4165 | { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } | ||
4166 | }; | ||
4167 | |||
4168 | // Older GCCs trigger -Wmissing-field-initializers for T foo = {} | ||
4169 | // which is zero initialization, but not explicit. We want to avoid | ||
4170 | // that. | ||
4171 | #if defined(__GNUC__) | ||
4172 | # pragma GCC diagnostic push | ||
4173 | # pragma GCC diagnostic ignored "-Wmissing-field-initializers" | ||
4174 | #endif | ||
4175 | |||
4176 | static char* altStackMem = nullptr; | ||
4177 | static std::size_t altStackSize = 0; | ||
4178 | static stack_t oldSigStack{}; | ||
4179 | static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{}; | ||
4180 | |||
4181 | static void restorePreviousSignalHandlers() noexcept { | ||
4182 | // We set signal handlers back to the previous ones. Hopefully | ||
4183 | // nobody overwrote them in the meantime, and doesn't expect | ||
4184 | // their signal handlers to live past ours given that they | ||
4185 | // installed them after ours.. | ||
4186 | for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { | ||
4187 | sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); | ||
4188 | } | ||
4189 | // Return the old stack | ||
4190 | sigaltstack(&oldSigStack, nullptr); | ||
4191 | } | ||
4192 | |||
4193 | static void handleSignal( int sig ) { | ||
4194 | char const * name = "<unknown signal>"; | ||
4195 | for (auto const& def : signalDefs) { | ||
4196 | if (sig == def.id) { | ||
4197 | name = def.name; | ||
4198 | break; | ||
4199 | } | ||
4200 | } | ||
4201 | // We need to restore previous signal handlers and let them do | ||
4202 | // their thing, so that the users can have the debugger break | ||
4203 | // when a signal is raised, and so on. | ||
4204 | restorePreviousSignalHandlers(); | ||
4205 | reportFatal( name ); | ||
4206 | raise( sig ); | ||
4207 | } | ||
4208 | |||
4209 | FatalConditionHandler::FatalConditionHandler() { | ||
4210 | assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists"); | ||
4211 | if (altStackSize == 0) { | ||
4212 | altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors); | ||
4213 | } | ||
4214 | altStackMem = new char[altStackSize](); | ||
4215 | } | ||
4216 | |||
4217 | FatalConditionHandler::~FatalConditionHandler() { | ||
4218 | delete[] altStackMem; | ||
4219 | // We signal that another instance can be constructed by zeroing | ||
4220 | // out the pointer. | ||
4221 | altStackMem = nullptr; | ||
4222 | } | ||
4223 | |||
4224 | void FatalConditionHandler::engage_platform() { | ||
4225 | stack_t sigStack; | ||
4226 | sigStack.ss_sp = altStackMem; | ||
4227 | sigStack.ss_size = altStackSize; | ||
4228 | sigStack.ss_flags = 0; | ||
4229 | sigaltstack(&sigStack, &oldSigStack); | ||
4230 | struct sigaction sa = { }; | ||
4231 | |||
4232 | sa.sa_handler = handleSignal; | ||
4233 | sa.sa_flags = SA_ONSTACK; | ||
4234 | for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) { | ||
4235 | sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); | ||
4236 | } | ||
4237 | } | ||
4238 | |||
4239 | #if defined(__GNUC__) | ||
4240 | # pragma GCC diagnostic pop | ||
4241 | #endif | ||
4242 | |||
4243 | |||
4244 | void FatalConditionHandler::disengage_platform() noexcept { | ||
4245 | restorePreviousSignalHandlers(); | ||
4246 | } | ||
4247 | |||
4248 | } // end namespace Catch | ||
4249 | |||
4250 | #endif // CATCH_CONFIG_POSIX_SIGNALS | ||
4251 | |||
4252 | |||
4253 | |||
4254 | |||
4255 | #include <cstring> | ||
4256 | |||
4257 | namespace Catch { | ||
4258 | namespace Detail { | ||
4259 | |||
4260 | uint32_t convertToBits(float f) { | ||
4261 | static_assert(sizeof(float) == sizeof(uint32_t), "Important ULP matcher assumption violated"); | ||
4262 | uint32_t i; | ||
4263 | std::memcpy(&i, &f, sizeof(f)); | ||
4264 | return i; | ||
4265 | } | ||
4266 | |||
4267 | uint64_t convertToBits(double d) { | ||
4268 | static_assert(sizeof(double) == sizeof(uint64_t), "Important ULP matcher assumption violated"); | ||
4269 | uint64_t i; | ||
4270 | std::memcpy(&i, &d, sizeof(d)); | ||
4271 | return i; | ||
4272 | } | ||
4273 | |||
4274 | #if defined( __GNUC__ ) || defined( __clang__ ) | ||
4275 | # pragma GCC diagnostic push | ||
4276 | # pragma GCC diagnostic ignored "-Wfloat-equal" | ||
4277 | #endif | ||
4278 | bool directCompare( float lhs, float rhs ) { return lhs == rhs; } | ||
4279 | bool directCompare( double lhs, double rhs ) { return lhs == rhs; } | ||
4280 | #if defined( __GNUC__ ) || defined( __clang__ ) | ||
4281 | # pragma GCC diagnostic pop | ||
4282 | #endif | ||
4283 | |||
4284 | |||
4285 | } // end namespace Detail | ||
4286 | } // end namespace Catch | ||
4287 | |||
4288 | |||
4289 | |||
4290 | |||
4291 | |||
4292 | |||
4293 | #include <cstdlib> | ||
4294 | |||
4295 | namespace Catch { | ||
4296 | namespace Detail { | ||
4297 | |||
4298 | #if !defined (CATCH_CONFIG_GETENV) | ||
4299 | char const* getEnv( char const* ) { return nullptr; } | ||
4300 | #else | ||
4301 | |||
4302 | char const* getEnv( char const* varName ) { | ||
4303 | # if defined( _MSC_VER ) | ||
4304 | # pragma warning( push ) | ||
4305 | # pragma warning( disable : 4996 ) // use getenv_s instead of getenv | ||
4306 | # endif | ||
4307 | |||
4308 | return std::getenv( varName ); | ||
4309 | |||
4310 | # if defined( _MSC_VER ) | ||
4311 | # pragma warning( pop ) | ||
4312 | # endif | ||
4313 | } | ||
4314 | #endif | ||
4315 | } // namespace Detail | ||
4316 | } // namespace Catch | ||
4317 | |||
4318 | |||
4319 | |||
4320 | |||
4321 | #include <cstdio> | ||
4322 | #include <fstream> | ||
4323 | #include <sstream> | ||
4324 | #include <vector> | ||
4325 | |||
4326 | namespace Catch { | ||
4327 | |||
4328 | Catch::IStream::~IStream() = default; | ||
4329 | |||
4330 | namespace Detail { | ||
4331 | namespace { | ||
4332 | template<typename WriterF, std::size_t bufferSize=256> | ||
4333 | class StreamBufImpl final : public std::streambuf { | ||
4334 | char data[bufferSize]; | ||
4335 | WriterF m_writer; | ||
4336 | |||
4337 | public: | ||
4338 | StreamBufImpl() { | ||
4339 | setp( data, data + sizeof(data) ); | ||
4340 | } | ||
4341 | |||
4342 | ~StreamBufImpl() noexcept override { | ||
4343 | StreamBufImpl::sync(); | ||
4344 | } | ||
4345 | |||
4346 | private: | ||
4347 | int overflow( int c ) override { | ||
4348 | sync(); | ||
4349 | |||
4350 | if( c != EOF ) { | ||
4351 | if( pbase() == epptr() ) | ||
4352 | m_writer( std::string( 1, static_cast<char>( c ) ) ); | ||
4353 | else | ||
4354 | sputc( static_cast<char>( c ) ); | ||
4355 | } | ||
4356 | return 0; | ||
4357 | } | ||
4358 | |||
4359 | int sync() override { | ||
4360 | if( pbase() != pptr() ) { | ||
4361 | m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) ); | ||
4362 | setp( pbase(), epptr() ); | ||
4363 | } | ||
4364 | return 0; | ||
4365 | } | ||
4366 | }; | ||
4367 | |||
4368 | /////////////////////////////////////////////////////////////////////////// | ||
4369 | |||
4370 | struct OutputDebugWriter { | ||
4371 | |||
4372 | void operator()( std::string const& str ) { | ||
4373 | if ( !str.empty() ) { | ||
4374 | writeToDebugConsole( str ); | ||
4375 | } | ||
4376 | } | ||
4377 | }; | ||
4378 | |||
4379 | /////////////////////////////////////////////////////////////////////////// | ||
4380 | |||
4381 | class FileStream final : public IStream { | ||
4382 | std::ofstream m_ofs; | ||
4383 | public: | ||
4384 | FileStream( std::string const& filename ) { | ||
4385 | m_ofs.open( filename.c_str() ); | ||
4386 | CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << '\'' ); | ||
4387 | m_ofs << std::unitbuf; | ||
4388 | } | ||
4389 | public: // IStream | ||
4390 | std::ostream& stream() override { | ||
4391 | return m_ofs; | ||
4392 | } | ||
4393 | }; | ||
4394 | |||
4395 | /////////////////////////////////////////////////////////////////////////// | ||
4396 | |||
4397 | class CoutStream final : public IStream { | ||
4398 | std::ostream m_os; | ||
4399 | public: | ||
4400 | // Store the streambuf from cout up-front because | ||
4401 | // cout may get redirected when running tests | ||
4402 | CoutStream() : m_os( Catch::cout().rdbuf() ) {} | ||
4403 | |||
4404 | public: // IStream | ||
4405 | std::ostream& stream() override { return m_os; } | ||
4406 | bool isConsole() const override { return true; } | ||
4407 | }; | ||
4408 | |||
4409 | class CerrStream : public IStream { | ||
4410 | std::ostream m_os; | ||
4411 | |||
4412 | public: | ||
4413 | // Store the streambuf from cerr up-front because | ||
4414 | // cout may get redirected when running tests | ||
4415 | CerrStream(): m_os( Catch::cerr().rdbuf() ) {} | ||
4416 | |||
4417 | public: // IStream | ||
4418 | std::ostream& stream() override { return m_os; } | ||
4419 | bool isConsole() const override { return true; } | ||
4420 | }; | ||
4421 | |||
4422 | /////////////////////////////////////////////////////////////////////////// | ||
4423 | |||
4424 | class DebugOutStream final : public IStream { | ||
4425 | Detail::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf; | ||
4426 | std::ostream m_os; | ||
4427 | public: | ||
4428 | DebugOutStream() | ||
4429 | : m_streamBuf( Detail::make_unique<StreamBufImpl<OutputDebugWriter>>() ), | ||
4430 | m_os( m_streamBuf.get() ) | ||
4431 | {} | ||
4432 | |||
4433 | public: // IStream | ||
4434 | std::ostream& stream() override { return m_os; } | ||
4435 | }; | ||
4436 | |||
4437 | } // unnamed namespace | ||
4438 | } // namespace Detail | ||
4439 | |||
4440 | /////////////////////////////////////////////////////////////////////////// | ||
4441 | |||
4442 | auto makeStream( std::string const& filename ) -> Detail::unique_ptr<IStream> { | ||
4443 | if ( filename.empty() || filename == "-" ) { | ||
4444 | return Detail::make_unique<Detail::CoutStream>(); | ||
4445 | } | ||
4446 | if( filename[0] == '%' ) { | ||
4447 | if ( filename == "%debug" ) { | ||
4448 | return Detail::make_unique<Detail::DebugOutStream>(); | ||
4449 | } else if ( filename == "%stderr" ) { | ||
4450 | return Detail::make_unique<Detail::CerrStream>(); | ||
4451 | } else if ( filename == "%stdout" ) { | ||
4452 | return Detail::make_unique<Detail::CoutStream>(); | ||
4453 | } else { | ||
4454 | CATCH_ERROR( "Unrecognised stream: '" << filename << '\'' ); | ||
4455 | } | ||
4456 | } | ||
4457 | return Detail::make_unique<Detail::FileStream>( filename ); | ||
4458 | } | ||
4459 | |||
4460 | } | ||
4461 | |||
4462 | |||
4463 | |||
4464 | namespace Catch { | ||
4465 | void JsonUtils::indent( std::ostream& os, std::uint64_t level ) { | ||
4466 | for ( std::uint64_t i = 0; i < level; ++i ) { | ||
4467 | os << " "; | ||
4468 | } | ||
4469 | } | ||
4470 | void JsonUtils::appendCommaNewline( std::ostream& os, | ||
4471 | bool& should_comma, | ||
4472 | std::uint64_t level ) { | ||
4473 | if ( should_comma ) { os << ','; } | ||
4474 | should_comma = true; | ||
4475 | os << '\n'; | ||
4476 | indent( os, level ); | ||
4477 | } | ||
4478 | |||
4479 | JsonObjectWriter::JsonObjectWriter( std::ostream& os ): | ||
4480 | JsonObjectWriter{ os, 0 } {} | ||
4481 | |||
4482 | JsonObjectWriter::JsonObjectWriter( std::ostream& os, | ||
4483 | std::uint64_t indent_level ): | ||
4484 | m_os{ os }, m_indent_level{ indent_level } { | ||
4485 | m_os << '{'; | ||
4486 | } | ||
4487 | JsonObjectWriter::JsonObjectWriter( JsonObjectWriter&& source ) noexcept: | ||
4488 | m_os{ source.m_os }, | ||
4489 | m_indent_level{ source.m_indent_level }, | ||
4490 | m_should_comma{ source.m_should_comma }, | ||
4491 | m_active{ source.m_active } { | ||
4492 | source.m_active = false; | ||
4493 | } | ||
4494 | |||
4495 | JsonObjectWriter::~JsonObjectWriter() { | ||
4496 | if ( !m_active ) { return; } | ||
4497 | |||
4498 | m_os << '\n'; | ||
4499 | JsonUtils::indent( m_os, m_indent_level ); | ||
4500 | m_os << '}'; | ||
4501 | } | ||
4502 | |||
4503 | JsonValueWriter JsonObjectWriter::write( StringRef key ) { | ||
4504 | JsonUtils::appendCommaNewline( | ||
4505 | m_os, m_should_comma, m_indent_level + 1 ); | ||
4506 | |||
4507 | m_os << '"' << key << "\": "; | ||
4508 | return JsonValueWriter{ m_os, m_indent_level + 1 }; | ||
4509 | } | ||
4510 | |||
4511 | JsonArrayWriter::JsonArrayWriter( std::ostream& os ): | ||
4512 | JsonArrayWriter{ os, 0 } {} | ||
4513 | JsonArrayWriter::JsonArrayWriter( std::ostream& os, | ||
4514 | std::uint64_t indent_level ): | ||
4515 | m_os{ os }, m_indent_level{ indent_level } { | ||
4516 | m_os << '['; | ||
4517 | } | ||
4518 | JsonArrayWriter::JsonArrayWriter( JsonArrayWriter&& source ) noexcept: | ||
4519 | m_os{ source.m_os }, | ||
4520 | m_indent_level{ source.m_indent_level }, | ||
4521 | m_should_comma{ source.m_should_comma }, | ||
4522 | m_active{ source.m_active } { | ||
4523 | source.m_active = false; | ||
4524 | } | ||
4525 | JsonArrayWriter::~JsonArrayWriter() { | ||
4526 | if ( !m_active ) { return; } | ||
4527 | |||
4528 | m_os << '\n'; | ||
4529 | JsonUtils::indent( m_os, m_indent_level ); | ||
4530 | m_os << ']'; | ||
4531 | } | ||
4532 | |||
4533 | JsonObjectWriter JsonArrayWriter::writeObject() { | ||
4534 | JsonUtils::appendCommaNewline( | ||
4535 | m_os, m_should_comma, m_indent_level + 1 ); | ||
4536 | return JsonObjectWriter{ m_os, m_indent_level + 1 }; | ||
4537 | } | ||
4538 | |||
4539 | JsonArrayWriter JsonArrayWriter::writeArray() { | ||
4540 | JsonUtils::appendCommaNewline( | ||
4541 | m_os, m_should_comma, m_indent_level + 1 ); | ||
4542 | return JsonArrayWriter{ m_os, m_indent_level + 1 }; | ||
4543 | } | ||
4544 | |||
4545 | JsonArrayWriter& JsonArrayWriter::write( bool value ) { | ||
4546 | return writeImpl( value ); | ||
4547 | } | ||
4548 | |||
4549 | JsonValueWriter::JsonValueWriter( std::ostream& os ): | ||
4550 | JsonValueWriter{ os, 0 } {} | ||
4551 | |||
4552 | JsonValueWriter::JsonValueWriter( std::ostream& os, | ||
4553 | std::uint64_t indent_level ): | ||
4554 | m_os{ os }, m_indent_level{ indent_level } {} | ||
4555 | |||
4556 | JsonObjectWriter JsonValueWriter::writeObject() && { | ||
4557 | return JsonObjectWriter{ m_os, m_indent_level }; | ||
4558 | } | ||
4559 | |||
4560 | JsonArrayWriter JsonValueWriter::writeArray() && { | ||
4561 | return JsonArrayWriter{ m_os, m_indent_level }; | ||
4562 | } | ||
4563 | |||
4564 | void JsonValueWriter::write( Catch::StringRef value ) && { | ||
4565 | writeImpl( value, true ); | ||
4566 | } | ||
4567 | |||
4568 | void JsonValueWriter::write( bool value ) && { | ||
4569 | writeImpl( value ? "true"_sr : "false"_sr, false ); | ||
4570 | } | ||
4571 | |||
4572 | void JsonValueWriter::writeImpl( Catch::StringRef value, bool quote ) { | ||
4573 | if ( quote ) { m_os << '"'; } | ||
4574 | for (char c : value) { | ||
4575 | // Escape list taken from https://www.json.org/json-en.html, | ||
4576 | // string definition. | ||
4577 | // Note that while forward slash _can_ be escaped, it does | ||
4578 | // not have to be, if JSON is not further embedded somewhere | ||
4579 | // where forward slash is meaningful. | ||
4580 | if ( c == '"' ) { | ||
4581 | m_os << "\\\""; | ||
4582 | } else if ( c == '\\' ) { | ||
4583 | m_os << "\\\\"; | ||
4584 | } else if ( c == '\b' ) { | ||
4585 | m_os << "\\b"; | ||
4586 | } else if ( c == '\f' ) { | ||
4587 | m_os << "\\f"; | ||
4588 | } else if ( c == '\n' ) { | ||
4589 | m_os << "\\n"; | ||
4590 | } else if ( c == '\r' ) { | ||
4591 | m_os << "\\r"; | ||
4592 | } else if ( c == '\t' ) { | ||
4593 | m_os << "\\t"; | ||
4594 | } else { | ||
4595 | m_os << c; | ||
4596 | } | ||
4597 | } | ||
4598 | if ( quote ) { m_os << '"'; } | ||
4599 | } | ||
4600 | |||
4601 | } // namespace Catch | ||
4602 | |||
4603 | |||
4604 | |||
4605 | |||
4606 | namespace Catch { | ||
4607 | |||
4608 | auto operator << (std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream& { | ||
4609 | if (lazyExpr.m_isNegated) | ||
4610 | os << '!'; | ||
4611 | |||
4612 | if (lazyExpr) { | ||
4613 | if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression()) | ||
4614 | os << '(' << *lazyExpr.m_transientExpression << ')'; | ||
4615 | else | ||
4616 | os << *lazyExpr.m_transientExpression; | ||
4617 | } else { | ||
4618 | os << "{** error - unchecked empty expression requested **}"; | ||
4619 | } | ||
4620 | return os; | ||
4621 | } | ||
4622 | |||
4623 | } // namespace Catch | ||
4624 | |||
4625 | |||
4626 | |||
4627 | |||
4628 | #ifdef CATCH_CONFIG_WINDOWS_CRTDBG | ||
4629 | #include <crtdbg.h> | ||
4630 | |||
4631 | namespace Catch { | ||
4632 | |||
4633 | LeakDetector::LeakDetector() { | ||
4634 | int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); | ||
4635 | flag |= _CRTDBG_LEAK_CHECK_DF; | ||
4636 | flag |= _CRTDBG_ALLOC_MEM_DF; | ||
4637 | _CrtSetDbgFlag(flag); | ||
4638 | _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); | ||
4639 | _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); | ||
4640 | // Change this to leaking allocation's number to break there | ||
4641 | _CrtSetBreakAlloc(-1); | ||
4642 | } | ||
4643 | } | ||
4644 | |||
4645 | #else // ^^ Windows crt debug heap enabled // Windows crt debug heap disabled vv | ||
4646 | |||
4647 | Catch::LeakDetector::LeakDetector() = default; | ||
4648 | |||
4649 | #endif // CATCH_CONFIG_WINDOWS_CRTDBG | ||
4650 | |||
4651 | Catch::LeakDetector::~LeakDetector() { | ||
4652 | Catch::cleanUp(); | ||
4653 | } | ||
4654 | |||
4655 | |||
4656 | |||
4657 | |||
4658 | namespace Catch { | ||
4659 | namespace { | ||
4660 | |||
4661 | void listTests(IEventListener& reporter, IConfig const& config) { | ||
4662 | auto const& testSpec = config.testSpec(); | ||
4663 | auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config); | ||
4664 | reporter.listTests(matchedTestCases); | ||
4665 | } | ||
4666 | |||
4667 | void listTags(IEventListener& reporter, IConfig const& config) { | ||
4668 | auto const& testSpec = config.testSpec(); | ||
4669 | std::vector<TestCaseHandle> matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config); | ||
4670 | |||
4671 | std::map<StringRef, TagInfo, Detail::CaseInsensitiveLess> tagCounts; | ||
4672 | for (auto const& testCase : matchedTestCases) { | ||
4673 | for (auto const& tagName : testCase.getTestCaseInfo().tags) { | ||
4674 | auto it = tagCounts.find(tagName.original); | ||
4675 | if (it == tagCounts.end()) | ||
4676 | it = tagCounts.insert(std::make_pair(tagName.original, TagInfo())).first; | ||
4677 | it->second.add(tagName.original); | ||
4678 | } | ||
4679 | } | ||
4680 | |||
4681 | std::vector<TagInfo> infos; infos.reserve(tagCounts.size()); | ||
4682 | for (auto& tagc : tagCounts) { | ||
4683 | infos.push_back(CATCH_MOVE(tagc.second)); | ||
4684 | } | ||
4685 | |||
4686 | reporter.listTags(infos); | ||
4687 | } | ||
4688 | |||
4689 | void listReporters(IEventListener& reporter) { | ||
4690 | std::vector<ReporterDescription> descriptions; | ||
4691 | |||
4692 | auto const& factories = getRegistryHub().getReporterRegistry().getFactories(); | ||
4693 | descriptions.reserve(factories.size()); | ||
4694 | for (auto const& fac : factories) { | ||
4695 | descriptions.push_back({ fac.first, fac.second->getDescription() }); | ||
4696 | } | ||
4697 | |||
4698 | reporter.listReporters(descriptions); | ||
4699 | } | ||
4700 | |||
4701 | void listListeners(IEventListener& reporter) { | ||
4702 | std::vector<ListenerDescription> descriptions; | ||
4703 | |||
4704 | auto const& factories = | ||
4705 | getRegistryHub().getReporterRegistry().getListeners(); | ||
4706 | descriptions.reserve( factories.size() ); | ||
4707 | for ( auto const& fac : factories ) { | ||
4708 | descriptions.push_back( { fac->getName(), fac->getDescription() } ); | ||
4709 | } | ||
4710 | |||
4711 | reporter.listListeners( descriptions ); | ||
4712 | } | ||
4713 | |||
4714 | } // end anonymous namespace | ||
4715 | |||
4716 | void TagInfo::add( StringRef spelling ) { | ||
4717 | ++count; | ||
4718 | spellings.insert( spelling ); | ||
4719 | } | ||
4720 | |||
4721 | std::string TagInfo::all() const { | ||
4722 | // 2 per tag for brackets '[' and ']' | ||
4723 | size_t size = spellings.size() * 2; | ||
4724 | for (auto const& spelling : spellings) { | ||
4725 | size += spelling.size(); | ||
4726 | } | ||
4727 | |||
4728 | std::string out; out.reserve(size); | ||
4729 | for (auto const& spelling : spellings) { | ||
4730 | out += '['; | ||
4731 | out += spelling; | ||
4732 | out += ']'; | ||
4733 | } | ||
4734 | return out; | ||
4735 | } | ||
4736 | |||
4737 | bool list( IEventListener& reporter, Config const& config ) { | ||
4738 | bool listed = false; | ||
4739 | if (config.listTests()) { | ||
4740 | listed = true; | ||
4741 | listTests(reporter, config); | ||
4742 | } | ||
4743 | if (config.listTags()) { | ||
4744 | listed = true; | ||
4745 | listTags(reporter, config); | ||
4746 | } | ||
4747 | if (config.listReporters()) { | ||
4748 | listed = true; | ||
4749 | listReporters(reporter); | ||
4750 | } | ||
4751 | if ( config.listListeners() ) { | ||
4752 | listed = true; | ||
4753 | listListeners( reporter ); | ||
4754 | } | ||
4755 | return listed; | ||
4756 | } | ||
4757 | |||
4758 | } // end namespace Catch | ||
4759 | |||
4760 | |||
4761 | |||
4762 | namespace Catch { | ||
4763 | CATCH_INTERNAL_START_WARNINGS_SUPPRESSION | ||
4764 | CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS | ||
4765 | static LeakDetector leakDetector; | ||
4766 | CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION | ||
4767 | } | ||
4768 | |||
4769 | // Allow users of amalgamated .cpp file to remove our main and provide their own. | ||
4770 | #if !defined(CATCH_AMALGAMATED_CUSTOM_MAIN) | ||
4771 | |||
4772 | #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) | ||
4773 | // Standard C/C++ Win32 Unicode wmain entry point | ||
4774 | extern "C" int __cdecl wmain (int argc, wchar_t * argv[], wchar_t * []) { | ||
4775 | #else | ||
4776 | // Standard C/C++ main entry point | ||
4777 | int main (int argc, char * argv[]) { | ||
4778 | #endif | ||
4779 | |||
4780 | // We want to force the linker not to discard the global variable | ||
4781 | // and its constructor, as it (optionally) registers leak detector | ||
4782 | (void)&Catch::leakDetector; | ||
4783 | |||
4784 | return Catch::Session().run( argc, argv ); | ||
4785 | } | ||
4786 | |||
4787 | #endif // !defined(CATCH_AMALGAMATED_CUSTOM_MAIN | ||
4788 | |||
4789 | |||
4790 | |||
4791 | |||
4792 | namespace Catch { | ||
4793 | |||
4794 | MessageInfo::MessageInfo( StringRef _macroName, | ||
4795 | SourceLineInfo const& _lineInfo, | ||
4796 | ResultWas::OfType _type ) | ||
4797 | : macroName( _macroName ), | ||
4798 | lineInfo( _lineInfo ), | ||
4799 | type( _type ), | ||
4800 | sequence( ++globalCount ) | ||
4801 | {} | ||
4802 | |||
4803 | // This may need protecting if threading support is added | ||
4804 | unsigned int MessageInfo::globalCount = 0; | ||
4805 | |||
4806 | } // end namespace Catch | ||
4807 | |||
4808 | |||
4809 | |||
4810 | #include <cstdio> | ||
4811 | #include <cstring> | ||
4812 | #include <iosfwd> | ||
4813 | #include <sstream> | ||
4814 | |||
4815 | #if defined( CATCH_CONFIG_NEW_CAPTURE ) | ||
4816 | # if defined( _MSC_VER ) | ||
4817 | # include <io.h> //_dup and _dup2 | ||
4818 | # define dup _dup | ||
4819 | # define dup2 _dup2 | ||
4820 | # define fileno _fileno | ||
4821 | # else | ||
4822 | # include <unistd.h> // dup and dup2 | ||
4823 | # endif | ||
4824 | #endif | ||
4825 | |||
4826 | namespace Catch { | ||
4827 | |||
4828 | namespace { | ||
4829 | //! A no-op implementation, used if no reporter wants output | ||
4830 | //! redirection. | ||
4831 | class NoopRedirect : public OutputRedirect { | ||
4832 | void activateImpl() override {} | ||
4833 | void deactivateImpl() override {} | ||
4834 | std::string getStdout() override { return {}; } | ||
4835 | std::string getStderr() override { return {}; } | ||
4836 | void clearBuffers() override {} | ||
4837 | }; | ||
4838 | |||
4839 | /** | ||
4840 | * Redirects specific stream's rdbuf with another's. | ||
4841 | * | ||
4842 | * Redirection can be stopped and started on-demand, assumes | ||
4843 | * that the underlying stream's rdbuf aren't changed by other | ||
4844 | * users. | ||
4845 | */ | ||
4846 | class RedirectedStreamNew { | ||
4847 | std::ostream& m_originalStream; | ||
4848 | std::ostream& m_redirectionStream; | ||
4849 | std::streambuf* m_prevBuf; | ||
4850 | |||
4851 | public: | ||
4852 | RedirectedStreamNew( std::ostream& originalStream, | ||
4853 | std::ostream& redirectionStream ): | ||
4854 | m_originalStream( originalStream ), | ||
4855 | m_redirectionStream( redirectionStream ), | ||
4856 | m_prevBuf( m_originalStream.rdbuf() ) {} | ||
4857 | |||
4858 | void startRedirect() { | ||
4859 | m_originalStream.rdbuf( m_redirectionStream.rdbuf() ); | ||
4860 | } | ||
4861 | void stopRedirect() { m_originalStream.rdbuf( m_prevBuf ); } | ||
4862 | }; | ||
4863 | |||
4864 | /** | ||
4865 | * Redirects the `std::cout`, `std::cerr`, `std::clog` streams, | ||
4866 | * but does not touch the actual `stdout`/`stderr` file descriptors. | ||
4867 | */ | ||
4868 | class StreamRedirect : public OutputRedirect { | ||
4869 | ReusableStringStream m_redirectedOut, m_redirectedErr; | ||
4870 | RedirectedStreamNew m_cout, m_cerr, m_clog; | ||
4871 | |||
4872 | public: | ||
4873 | StreamRedirect(): | ||
4874 | m_cout( Catch::cout(), m_redirectedOut.get() ), | ||
4875 | m_cerr( Catch::cerr(), m_redirectedErr.get() ), | ||
4876 | m_clog( Catch::clog(), m_redirectedErr.get() ) {} | ||
4877 | |||
4878 | void activateImpl() override { | ||
4879 | m_cout.startRedirect(); | ||
4880 | m_cerr.startRedirect(); | ||
4881 | m_clog.startRedirect(); | ||
4882 | } | ||
4883 | void deactivateImpl() override { | ||
4884 | m_cout.stopRedirect(); | ||
4885 | m_cerr.stopRedirect(); | ||
4886 | m_clog.stopRedirect(); | ||
4887 | } | ||
4888 | std::string getStdout() override { return m_redirectedOut.str(); } | ||
4889 | std::string getStderr() override { return m_redirectedErr.str(); } | ||
4890 | void clearBuffers() override { | ||
4891 | m_redirectedOut.str( "" ); | ||
4892 | m_redirectedErr.str( "" ); | ||
4893 | } | ||
4894 | }; | ||
4895 | |||
4896 | #if defined( CATCH_CONFIG_NEW_CAPTURE ) | ||
4897 | |||
4898 | // Windows's implementation of std::tmpfile is terrible (it tries | ||
4899 | // to create a file inside system folder, thus requiring elevated | ||
4900 | // privileges for the binary), so we have to use tmpnam(_s) and | ||
4901 | // create the file ourselves there. | ||
4902 | class TempFile { | ||
4903 | public: | ||
4904 | TempFile( TempFile const& ) = delete; | ||
4905 | TempFile& operator=( TempFile const& ) = delete; | ||
4906 | TempFile( TempFile&& ) = delete; | ||
4907 | TempFile& operator=( TempFile&& ) = delete; | ||
4908 | |||
4909 | # if defined( _MSC_VER ) | ||
4910 | TempFile() { | ||
4911 | if ( tmpnam_s( m_buffer ) ) { | ||
4912 | CATCH_RUNTIME_ERROR( "Could not get a temp filename" ); | ||
4913 | } | ||
4914 | if ( fopen_s( &m_file, m_buffer, "wb+" ) ) { | ||
4915 | char buffer[100]; | ||
4916 | if ( strerror_s( buffer, errno ) ) { | ||
4917 | CATCH_RUNTIME_ERROR( | ||
4918 | "Could not translate errno to a string" ); | ||
4919 | } | ||
4920 | CATCH_RUNTIME_ERROR( "Could not open the temp file: '" | ||
4921 | << m_buffer | ||
4922 | << "' because: " << buffer ); | ||
4923 | } | ||
4924 | } | ||
4925 | # else | ||
4926 | TempFile() { | ||
4927 | m_file = std::tmpfile(); | ||
4928 | if ( !m_file ) { | ||
4929 | CATCH_RUNTIME_ERROR( "Could not create a temp file." ); | ||
4930 | } | ||
4931 | } | ||
4932 | # endif | ||
4933 | |||
4934 | ~TempFile() { | ||
4935 | // TBD: What to do about errors here? | ||
4936 | std::fclose( m_file ); | ||
4937 | // We manually create the file on Windows only, on Linux | ||
4938 | // it will be autodeleted | ||
4939 | # if defined( _MSC_VER ) | ||
4940 | std::remove( m_buffer ); | ||
4941 | # endif | ||
4942 | } | ||
4943 | |||
4944 | std::FILE* getFile() { return m_file; } | ||
4945 | std::string getContents() { | ||
4946 | ReusableStringStream sstr; | ||
4947 | constexpr long buffer_size = 100; | ||
4948 | char buffer[buffer_size + 1] = {}; | ||
4949 | long current_pos = ftell( m_file ); | ||
4950 | CATCH_ENFORCE( current_pos >= 0, | ||
4951 | "ftell failed, errno: " << errno ); | ||
4952 | std::rewind( m_file ); | ||
4953 | while ( current_pos > 0 ) { | ||
4954 | auto read_characters = | ||
4955 | std::fread( buffer, | ||
4956 | 1, | ||
4957 | std::min( buffer_size, current_pos ), | ||
4958 | m_file ); | ||
4959 | buffer[read_characters] = '\0'; | ||
4960 | sstr << buffer; | ||
4961 | current_pos -= static_cast<long>( read_characters ); | ||
4962 | } | ||
4963 | return sstr.str(); | ||
4964 | } | ||
4965 | |||
4966 | void clear() { std::rewind( m_file ); } | ||
4967 | |||
4968 | private: | ||
4969 | std::FILE* m_file = nullptr; | ||
4970 | char m_buffer[L_tmpnam] = { 0 }; | ||
4971 | }; | ||
4972 | |||
4973 | /** | ||
4974 | * Redirects the actual `stdout`/`stderr` file descriptors. | ||
4975 | * | ||
4976 | * Works by replacing the file descriptors numbered 1 and 2 | ||
4977 | * with an open temporary file. | ||
4978 | */ | ||
4979 | class FileRedirect : public OutputRedirect { | ||
4980 | TempFile m_outFile, m_errFile; | ||
4981 | int m_originalOut = -1; | ||
4982 | int m_originalErr = -1; | ||
4983 | |||
4984 | // Flushes cout/cerr/clog streams and stdout/stderr FDs | ||
4985 | void flushEverything() { | ||
4986 | Catch::cout() << std::flush; | ||
4987 | fflush( stdout ); | ||
4988 | // Since we support overriding these streams, we flush cerr | ||
4989 | // even though std::cerr is unbuffered | ||
4990 | Catch::cerr() << std::flush; | ||
4991 | Catch::clog() << std::flush; | ||
4992 | fflush( stderr ); | ||
4993 | } | ||
4994 | |||
4995 | public: | ||
4996 | FileRedirect(): | ||
4997 | m_originalOut( dup( fileno( stdout ) ) ), | ||
4998 | m_originalErr( dup( fileno( stderr ) ) ) { | ||
4999 | CATCH_ENFORCE( m_originalOut >= 0, "Could not dup stdout" ); | ||
5000 | CATCH_ENFORCE( m_originalErr >= 0, "Could not dup stderr" ); | ||
5001 | } | ||
5002 | |||
5003 | std::string getStdout() override { return m_outFile.getContents(); } | ||
5004 | std::string getStderr() override { return m_errFile.getContents(); } | ||
5005 | void clearBuffers() override { | ||
5006 | m_outFile.clear(); | ||
5007 | m_errFile.clear(); | ||
5008 | } | ||
5009 | |||
5010 | void activateImpl() override { | ||
5011 | // We flush before starting redirect, to ensure that we do | ||
5012 | // not capture the end of message sent before activation. | ||
5013 | flushEverything(); | ||
5014 | |||
5015 | int ret; | ||
5016 | ret = dup2( fileno( m_outFile.getFile() ), fileno( stdout ) ); | ||
5017 | CATCH_ENFORCE( ret >= 0, | ||
5018 | "dup2 to stdout has failed, errno: " << errno ); | ||
5019 | ret = dup2( fileno( m_errFile.getFile() ), fileno( stderr ) ); | ||
5020 | CATCH_ENFORCE( ret >= 0, | ||
5021 | "dup2 to stderr has failed, errno: " << errno ); | ||
5022 | } | ||
5023 | void deactivateImpl() override { | ||
5024 | // We flush before ending redirect, to ensure that we | ||
5025 | // capture all messages sent while the redirect was active. | ||
5026 | flushEverything(); | ||
5027 | |||
5028 | int ret; | ||
5029 | ret = dup2( m_originalOut, fileno( stdout ) ); | ||
5030 | CATCH_ENFORCE( | ||
5031 | ret >= 0, | ||
5032 | "dup2 of original stdout has failed, errno: " << errno ); | ||
5033 | ret = dup2( m_originalErr, fileno( stderr ) ); | ||
5034 | CATCH_ENFORCE( | ||
5035 | ret >= 0, | ||
5036 | "dup2 of original stderr has failed, errno: " << errno ); | ||
5037 | } | ||
5038 | }; | ||
5039 | |||
5040 | #endif // CATCH_CONFIG_NEW_CAPTURE | ||
5041 | |||
5042 | } // end namespace | ||
5043 | |||
5044 | bool isRedirectAvailable( OutputRedirect::Kind kind ) { | ||
5045 | switch ( kind ) { | ||
5046 | // These two are always available | ||
5047 | case OutputRedirect::None: | ||
5048 | case OutputRedirect::Streams: | ||
5049 | return true; | ||
5050 | #if defined( CATCH_CONFIG_NEW_CAPTURE ) | ||
5051 | case OutputRedirect::FileDescriptors: | ||
5052 | return true; | ||
5053 | #endif | ||
5054 | default: | ||
5055 | return false; | ||
5056 | } | ||
5057 | } | ||
5058 | |||
5059 | Detail::unique_ptr<OutputRedirect> makeOutputRedirect( bool actual ) { | ||
5060 | if ( actual ) { | ||
5061 | // TODO: Clean this up later | ||
5062 | #if defined( CATCH_CONFIG_NEW_CAPTURE ) | ||
5063 | return Detail::make_unique<FileRedirect>(); | ||
5064 | #else | ||
5065 | return Detail::make_unique<StreamRedirect>(); | ||
5066 | #endif | ||
5067 | } else { | ||
5068 | return Detail::make_unique<NoopRedirect>(); | ||
5069 | } | ||
5070 | } | ||
5071 | |||
5072 | RedirectGuard scopedActivate( OutputRedirect& redirectImpl ) { | ||
5073 | return RedirectGuard( true, redirectImpl ); | ||
5074 | } | ||
5075 | |||
5076 | RedirectGuard scopedDeactivate( OutputRedirect& redirectImpl ) { | ||
5077 | return RedirectGuard( false, redirectImpl ); | ||
5078 | } | ||
5079 | |||
5080 | OutputRedirect::~OutputRedirect() = default; | ||
5081 | |||
5082 | RedirectGuard::RedirectGuard( bool activate, OutputRedirect& redirectImpl ): | ||
5083 | m_redirect( &redirectImpl ), | ||
5084 | m_activate( activate ), | ||
5085 | m_previouslyActive( redirectImpl.isActive() ) { | ||
5086 | |||
5087 | // Skip cases where there is no actual state change. | ||
5088 | if ( m_activate == m_previouslyActive ) { return; } | ||
5089 | |||
5090 | if ( m_activate ) { | ||
5091 | m_redirect->activate(); | ||
5092 | } else { | ||
5093 | m_redirect->deactivate(); | ||
5094 | } | ||
5095 | } | ||
5096 | |||
5097 | RedirectGuard::~RedirectGuard() noexcept( false ) { | ||
5098 | if ( m_moved ) { return; } | ||
5099 | // Skip cases where there is no actual state change. | ||
5100 | if ( m_activate == m_previouslyActive ) { return; } | ||
5101 | |||
5102 | if ( m_activate ) { | ||
5103 | m_redirect->deactivate(); | ||
5104 | } else { | ||
5105 | m_redirect->activate(); | ||
5106 | } | ||
5107 | } | ||
5108 | |||
5109 | RedirectGuard::RedirectGuard( RedirectGuard&& rhs ) noexcept: | ||
5110 | m_redirect( rhs.m_redirect ), | ||
5111 | m_activate( rhs.m_activate ), | ||
5112 | m_previouslyActive( rhs.m_previouslyActive ), | ||
5113 | m_moved( false ) { | ||
5114 | rhs.m_moved = true; | ||
5115 | } | ||
5116 | |||
5117 | RedirectGuard& RedirectGuard::operator=( RedirectGuard&& rhs ) noexcept { | ||
5118 | m_redirect = rhs.m_redirect; | ||
5119 | m_activate = rhs.m_activate; | ||
5120 | m_previouslyActive = rhs.m_previouslyActive; | ||
5121 | m_moved = false; | ||
5122 | rhs.m_moved = true; | ||
5123 | return *this; | ||
5124 | } | ||
5125 | |||
5126 | } // namespace Catch | ||
5127 | |||
5128 | #if defined( CATCH_CONFIG_NEW_CAPTURE ) | ||
5129 | # if defined( _MSC_VER ) | ||
5130 | # undef dup | ||
5131 | # undef dup2 | ||
5132 | # undef fileno | ||
5133 | # endif | ||
5134 | #endif | ||
5135 | |||
5136 | |||
5137 | |||
5138 | |||
5139 | #include <limits> | ||
5140 | #include <stdexcept> | ||
5141 | |||
5142 | namespace Catch { | ||
5143 | |||
5144 | Optional<unsigned int> parseUInt(std::string const& input, int base) { | ||
5145 | auto trimmed = trim( input ); | ||
5146 | // std::stoull is annoying and accepts numbers starting with '-', | ||
5147 | // it just negates them into unsigned int | ||
5148 | if ( trimmed.empty() || trimmed[0] == '-' ) { | ||
5149 | return {}; | ||
5150 | } | ||
5151 | |||
5152 | CATCH_TRY { | ||
5153 | size_t pos = 0; | ||
5154 | const auto ret = std::stoull( trimmed, &pos, base ); | ||
5155 | |||
5156 | // We did not consume the whole input, so there is an issue | ||
5157 | // This can be bunch of different stuff, like multiple numbers | ||
5158 | // in the input, or invalid digits/characters and so on. Either | ||
5159 | // way, we do not want to return the partially parsed result. | ||
5160 | if ( pos != trimmed.size() ) { | ||
5161 | return {}; | ||
5162 | } | ||
5163 | // Too large | ||
5164 | if ( ret > std::numeric_limits<unsigned int>::max() ) { | ||
5165 | return {}; | ||
5166 | } | ||
5167 | return static_cast<unsigned int>(ret); | ||
5168 | } | ||
5169 | CATCH_CATCH_ANON( std::invalid_argument const& ) { | ||
5170 | // no conversion could be performed | ||
5171 | } | ||
5172 | CATCH_CATCH_ANON( std::out_of_range const& ) { | ||
5173 | // the input does not fit into an unsigned long long | ||
5174 | } | ||
5175 | return {}; | ||
5176 | } | ||
5177 | |||
5178 | } // namespace Catch | ||
5179 | |||
5180 | |||
5181 | |||
5182 | |||
5183 | #include <cmath> | ||
5184 | |||
5185 | namespace Catch { | ||
5186 | |||
5187 | #if !defined(CATCH_CONFIG_POLYFILL_ISNAN) | ||
5188 | bool isnan(float f) { | ||
5189 | return std::isnan(f); | ||
5190 | } | ||
5191 | bool isnan(double d) { | ||
5192 | return std::isnan(d); | ||
5193 | } | ||
5194 | #else | ||
5195 | // For now we only use this for embarcadero | ||
5196 | bool isnan(float f) { | ||
5197 | return std::_isnan(f); | ||
5198 | } | ||
5199 | bool isnan(double d) { | ||
5200 | return std::_isnan(d); | ||
5201 | } | ||
5202 | #endif | ||
5203 | |||
5204 | #if !defined( CATCH_CONFIG_GLOBAL_NEXTAFTER ) | ||
5205 | float nextafter( float x, float y ) { return std::nextafter( x, y ); } | ||
5206 | double nextafter( double x, double y ) { return std::nextafter( x, y ); } | ||
5207 | #else | ||
5208 | float nextafter( float x, float y ) { return ::nextafterf( x, y ); } | ||
5209 | double nextafter( double x, double y ) { return ::nextafter( x, y ); } | ||
5210 | #endif | ||
5211 | |||
5212 | } // end namespace Catch | ||
5213 | |||
5214 | |||
5215 | |||
5216 | namespace Catch { | ||
5217 | |||
5218 | namespace { | ||
5219 | |||
5220 | #if defined(_MSC_VER) | ||
5221 | #pragma warning(push) | ||
5222 | #pragma warning(disable:4146) // we negate uint32 during the rotate | ||
5223 | #endif | ||
5224 | // Safe rotr implementation thanks to John Regehr | ||
5225 | uint32_t rotate_right(uint32_t val, uint32_t count) { | ||
5226 | const uint32_t mask = 31; | ||
5227 | count &= mask; | ||
5228 | return (val >> count) | (val << (-count & mask)); | ||
5229 | } | ||
5230 | |||
5231 | #if defined(_MSC_VER) | ||
5232 | #pragma warning(pop) | ||
5233 | #endif | ||
5234 | |||
5235 | } | ||
5236 | |||
5237 | |||
5238 | SimplePcg32::SimplePcg32(result_type seed_) { | ||
5239 | seed(seed_); | ||
5240 | } | ||
5241 | |||
5242 | |||
5243 | void SimplePcg32::seed(result_type seed_) { | ||
5244 | m_state = 0; | ||
5245 | (*this)(); | ||
5246 | m_state += seed_; | ||
5247 | (*this)(); | ||
5248 | } | ||
5249 | |||
5250 | void SimplePcg32::discard(uint64_t skip) { | ||
5251 | // We could implement this to run in O(log n) steps, but this | ||
5252 | // should suffice for our use case. | ||
5253 | for (uint64_t s = 0; s < skip; ++s) { | ||
5254 | static_cast<void>((*this)()); | ||
5255 | } | ||
5256 | } | ||
5257 | |||
5258 | SimplePcg32::result_type SimplePcg32::operator()() { | ||
5259 | // prepare the output value | ||
5260 | const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u); | ||
5261 | const auto output = rotate_right(xorshifted, m_state >> 59u); | ||
5262 | |||
5263 | // advance state | ||
5264 | m_state = m_state * 6364136223846793005ULL + s_inc; | ||
5265 | |||
5266 | return output; | ||
5267 | } | ||
5268 | |||
5269 | bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) { | ||
5270 | return lhs.m_state == rhs.m_state; | ||
5271 | } | ||
5272 | |||
5273 | bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) { | ||
5274 | return lhs.m_state != rhs.m_state; | ||
5275 | } | ||
5276 | } | ||
5277 | |||
5278 | |||
5279 | |||
5280 | |||
5281 | |||
5282 | #include <ctime> | ||
5283 | #include <random> | ||
5284 | |||
5285 | namespace Catch { | ||
5286 | |||
5287 | std::uint32_t generateRandomSeed( GenerateFrom from ) { | ||
5288 | switch ( from ) { | ||
5289 | case GenerateFrom::Time: | ||
5290 | return static_cast<std::uint32_t>( std::time( nullptr ) ); | ||
5291 | |||
5292 | case GenerateFrom::Default: | ||
5293 | case GenerateFrom::RandomDevice: { | ||
5294 | std::random_device rd; | ||
5295 | return Detail::fillBitsFrom<std::uint32_t>( rd ); | ||
5296 | } | ||
5297 | |||
5298 | default: | ||
5299 | CATCH_ERROR("Unknown generation method"); | ||
5300 | } | ||
5301 | } | ||
5302 | |||
5303 | } // end namespace Catch | ||
5304 | |||
5305 | |||
5306 | |||
5307 | |||
5308 | namespace Catch { | ||
5309 | struct ReporterRegistry::ReporterRegistryImpl { | ||
5310 | std::vector<Detail::unique_ptr<EventListenerFactory>> listeners; | ||
5311 | std::map<std::string, IReporterFactoryPtr, Detail::CaseInsensitiveLess> | ||
5312 | factories; | ||
5313 | }; | ||
5314 | |||
5315 | ReporterRegistry::ReporterRegistry(): | ||
5316 | m_impl( Detail::make_unique<ReporterRegistryImpl>() ) { | ||
5317 | // Because it is impossible to move out of initializer list, | ||
5318 | // we have to add the elements manually | ||
5319 | m_impl->factories["Automake"] = | ||
5320 | Detail::make_unique<ReporterFactory<AutomakeReporter>>(); | ||
5321 | m_impl->factories["compact"] = | ||
5322 | Detail::make_unique<ReporterFactory<CompactReporter>>(); | ||
5323 | m_impl->factories["console"] = | ||
5324 | Detail::make_unique<ReporterFactory<ConsoleReporter>>(); | ||
5325 | m_impl->factories["JUnit"] = | ||
5326 | Detail::make_unique<ReporterFactory<JunitReporter>>(); | ||
5327 | m_impl->factories["SonarQube"] = | ||
5328 | Detail::make_unique<ReporterFactory<SonarQubeReporter>>(); | ||
5329 | m_impl->factories["TAP"] = | ||
5330 | Detail::make_unique<ReporterFactory<TAPReporter>>(); | ||
5331 | m_impl->factories["TeamCity"] = | ||
5332 | Detail::make_unique<ReporterFactory<TeamCityReporter>>(); | ||
5333 | m_impl->factories["XML"] = | ||
5334 | Detail::make_unique<ReporterFactory<XmlReporter>>(); | ||
5335 | m_impl->factories["JSON"] = | ||
5336 | Detail::make_unique<ReporterFactory<JsonReporter>>(); | ||
5337 | } | ||
5338 | |||
5339 | ReporterRegistry::~ReporterRegistry() = default; | ||
5340 | |||
5341 | IEventListenerPtr | ||
5342 | ReporterRegistry::create( std::string const& name, | ||
5343 | ReporterConfig&& config ) const { | ||
5344 | auto it = m_impl->factories.find( name ); | ||
5345 | if ( it == m_impl->factories.end() ) return nullptr; | ||
5346 | return it->second->create( CATCH_MOVE( config ) ); | ||
5347 | } | ||
5348 | |||
5349 | void ReporterRegistry::registerReporter( std::string const& name, | ||
5350 | IReporterFactoryPtr factory ) { | ||
5351 | CATCH_ENFORCE( name.find( "::" ) == name.npos, | ||
5352 | "'::' is not allowed in reporter name: '" + name + | ||
5353 | '\'' ); | ||
5354 | auto ret = m_impl->factories.emplace( name, CATCH_MOVE( factory ) ); | ||
5355 | CATCH_ENFORCE( ret.second, | ||
5356 | "reporter using '" + name + | ||
5357 | "' as name was already registered" ); | ||
5358 | } | ||
5359 | void ReporterRegistry::registerListener( | ||
5360 | Detail::unique_ptr<EventListenerFactory> factory ) { | ||
5361 | m_impl->listeners.push_back( CATCH_MOVE( factory ) ); | ||
5362 | } | ||
5363 | |||
5364 | std::map<std::string, | ||
5365 | IReporterFactoryPtr, | ||
5366 | Detail::CaseInsensitiveLess> const& | ||
5367 | ReporterRegistry::getFactories() const { | ||
5368 | return m_impl->factories; | ||
5369 | } | ||
5370 | |||
5371 | std::vector<Detail::unique_ptr<EventListenerFactory>> const& | ||
5372 | ReporterRegistry::getListeners() const { | ||
5373 | return m_impl->listeners; | ||
5374 | } | ||
5375 | } // namespace Catch | ||
5376 | |||
5377 | |||
5378 | |||
5379 | |||
5380 | |||
5381 | #include <algorithm> | ||
5382 | |||
5383 | namespace Catch { | ||
5384 | |||
5385 | namespace { | ||
5386 | struct kvPair { | ||
5387 | StringRef key, value; | ||
5388 | }; | ||
5389 | |||
5390 | kvPair splitKVPair(StringRef kvString) { | ||
5391 | auto splitPos = static_cast<size_t>( | ||
5392 | std::find( kvString.begin(), kvString.end(), '=' ) - | ||
5393 | kvString.begin() ); | ||
5394 | |||
5395 | return { kvString.substr( 0, splitPos ), | ||
5396 | kvString.substr( splitPos + 1, kvString.size() ) }; | ||
5397 | } | ||
5398 | } | ||
5399 | |||
5400 | namespace Detail { | ||
5401 | std::vector<std::string> splitReporterSpec( StringRef reporterSpec ) { | ||
5402 | static constexpr auto separator = "::"; | ||
5403 | static constexpr size_t separatorSize = 2; | ||
5404 | |||
5405 | size_t separatorPos = 0; | ||
5406 | auto findNextSeparator = [&reporterSpec]( size_t startPos ) { | ||
5407 | static_assert( | ||
5408 | separatorSize == 2, | ||
5409 | "The code below currently assumes 2 char separator" ); | ||
5410 | |||
5411 | auto currentPos = startPos; | ||
5412 | do { | ||
5413 | while ( currentPos < reporterSpec.size() && | ||
5414 | reporterSpec[currentPos] != separator[0] ) { | ||
5415 | ++currentPos; | ||
5416 | } | ||
5417 | if ( currentPos + 1 < reporterSpec.size() && | ||
5418 | reporterSpec[currentPos + 1] == separator[1] ) { | ||
5419 | return currentPos; | ||
5420 | } | ||
5421 | ++currentPos; | ||
5422 | } while ( currentPos < reporterSpec.size() ); | ||
5423 | |||
5424 | return static_cast<size_t>( -1 ); | ||
5425 | }; | ||
5426 | |||
5427 | std::vector<std::string> parts; | ||
5428 | |||
5429 | while ( separatorPos < reporterSpec.size() ) { | ||
5430 | const auto nextSeparator = findNextSeparator( separatorPos ); | ||
5431 | parts.push_back( static_cast<std::string>( reporterSpec.substr( | ||
5432 | separatorPos, nextSeparator - separatorPos ) ) ); | ||
5433 | |||
5434 | if ( nextSeparator == static_cast<size_t>( -1 ) ) { | ||
5435 | break; | ||
5436 | } | ||
5437 | separatorPos = nextSeparator + separatorSize; | ||
5438 | } | ||
5439 | |||
5440 | // Handle a separator at the end. | ||
5441 | // This is not a valid spec, but we want to do validation in a | ||
5442 | // centralized place | ||
5443 | if ( separatorPos == reporterSpec.size() ) { | ||
5444 | parts.emplace_back(); | ||
5445 | } | ||
5446 | |||
5447 | return parts; | ||
5448 | } | ||
5449 | |||
5450 | Optional<ColourMode> stringToColourMode( StringRef colourMode ) { | ||
5451 | if ( colourMode == "default" ) { | ||
5452 | return ColourMode::PlatformDefault; | ||
5453 | } else if ( colourMode == "ansi" ) { | ||
5454 | return ColourMode::ANSI; | ||
5455 | } else if ( colourMode == "win32" ) { | ||
5456 | return ColourMode::Win32; | ||
5457 | } else if ( colourMode == "none" ) { | ||
5458 | return ColourMode::None; | ||
5459 | } else { | ||
5460 | return {}; | ||
5461 | } | ||
5462 | } | ||
5463 | } // namespace Detail | ||
5464 | |||
5465 | |||
5466 | bool operator==( ReporterSpec const& lhs, ReporterSpec const& rhs ) { | ||
5467 | return lhs.m_name == rhs.m_name && | ||
5468 | lhs.m_outputFileName == rhs.m_outputFileName && | ||
5469 | lhs.m_colourMode == rhs.m_colourMode && | ||
5470 | lhs.m_customOptions == rhs.m_customOptions; | ||
5471 | } | ||
5472 | |||
5473 | Optional<ReporterSpec> parseReporterSpec( StringRef reporterSpec ) { | ||
5474 | auto parts = Detail::splitReporterSpec( reporterSpec ); | ||
5475 | |||
5476 | assert( parts.size() > 0 && "Split should never return empty vector" ); | ||
5477 | |||
5478 | std::map<std::string, std::string> kvPairs; | ||
5479 | Optional<std::string> outputFileName; | ||
5480 | Optional<ColourMode> colourMode; | ||
5481 | |||
5482 | // First part is always reporter name, so we skip it | ||
5483 | for ( size_t i = 1; i < parts.size(); ++i ) { | ||
5484 | auto kv = splitKVPair( parts[i] ); | ||
5485 | auto key = kv.key, value = kv.value; | ||
5486 | |||
5487 | if ( key.empty() || value.empty() ) { // NOLINT(bugprone-branch-clone) | ||
5488 | return {}; | ||
5489 | } else if ( key[0] == 'X' ) { | ||
5490 | // This is a reporter-specific option, we don't check these | ||
5491 | // apart from basic sanity checks | ||
5492 | if ( key.size() == 1 ) { | ||
5493 | return {}; | ||
5494 | } | ||
5495 | |||
5496 | auto ret = kvPairs.emplace( std::string(kv.key), std::string(kv.value) ); | ||
5497 | if ( !ret.second ) { | ||
5498 | // Duplicated key. We might want to handle this differently, | ||
5499 | // e.g. by overwriting the existing value? | ||
5500 | return {}; | ||
5501 | } | ||
5502 | } else if ( key == "out" ) { | ||
5503 | // Duplicated key | ||
5504 | if ( outputFileName ) { | ||
5505 | return {}; | ||
5506 | } | ||
5507 | outputFileName = static_cast<std::string>( value ); | ||
5508 | } else if ( key == "colour-mode" ) { | ||
5509 | // Duplicated key | ||
5510 | if ( colourMode ) { | ||
5511 | return {}; | ||
5512 | } | ||
5513 | colourMode = Detail::stringToColourMode( value ); | ||
5514 | // Parsing failed | ||
5515 | if ( !colourMode ) { | ||
5516 | return {}; | ||
5517 | } | ||
5518 | } else { | ||
5519 | // Unrecognized option | ||
5520 | return {}; | ||
5521 | } | ||
5522 | } | ||
5523 | |||
5524 | return ReporterSpec{ CATCH_MOVE( parts[0] ), | ||
5525 | CATCH_MOVE( outputFileName ), | ||
5526 | CATCH_MOVE( colourMode ), | ||
5527 | CATCH_MOVE( kvPairs ) }; | ||
5528 | } | ||
5529 | |||
5530 | ReporterSpec::ReporterSpec( | ||
5531 | std::string name, | ||
5532 | Optional<std::string> outputFileName, | ||
5533 | Optional<ColourMode> colourMode, | ||
5534 | std::map<std::string, std::string> customOptions ): | ||
5535 | m_name( CATCH_MOVE( name ) ), | ||
5536 | m_outputFileName( CATCH_MOVE( outputFileName ) ), | ||
5537 | m_colourMode( CATCH_MOVE( colourMode ) ), | ||
5538 | m_customOptions( CATCH_MOVE( customOptions ) ) {} | ||
5539 | |||
5540 | } // namespace Catch | ||
5541 | |||
5542 | |||
5543 | |||
5544 | #include <cstdio> | ||
5545 | #include <sstream> | ||
5546 | #include <vector> | ||
5547 | |||
5548 | namespace Catch { | ||
5549 | |||
5550 | // This class encapsulates the idea of a pool of ostringstreams that can be reused. | ||
5551 | struct StringStreams { | ||
5552 | std::vector<Detail::unique_ptr<std::ostringstream>> m_streams; | ||
5553 | std::vector<std::size_t> m_unused; | ||
5554 | std::ostringstream m_referenceStream; // Used for copy state/ flags from | ||
5555 | |||
5556 | auto add() -> std::size_t { | ||
5557 | if( m_unused.empty() ) { | ||
5558 | m_streams.push_back( Detail::make_unique<std::ostringstream>() ); | ||
5559 | return m_streams.size()-1; | ||
5560 | } | ||
5561 | else { | ||
5562 | auto index = m_unused.back(); | ||
5563 | m_unused.pop_back(); | ||
5564 | return index; | ||
5565 | } | ||
5566 | } | ||
5567 | |||
5568 | void release( std::size_t index ) { | ||
5569 | m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state | ||
5570 | m_unused.push_back(index); | ||
5571 | } | ||
5572 | }; | ||
5573 | |||
5574 | ReusableStringStream::ReusableStringStream() | ||
5575 | : m_index( Singleton<StringStreams>::getMutable().add() ), | ||
5576 | m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() ) | ||
5577 | {} | ||
5578 | |||
5579 | ReusableStringStream::~ReusableStringStream() { | ||
5580 | static_cast<std::ostringstream*>( m_oss )->str(""); | ||
5581 | m_oss->clear(); | ||
5582 | Singleton<StringStreams>::getMutable().release( m_index ); | ||
5583 | } | ||
5584 | |||
5585 | std::string ReusableStringStream::str() const { | ||
5586 | return static_cast<std::ostringstream*>( m_oss )->str(); | ||
5587 | } | ||
5588 | |||
5589 | void ReusableStringStream::str( std::string const& str ) { | ||
5590 | static_cast<std::ostringstream*>( m_oss )->str( str ); | ||
5591 | } | ||
5592 | |||
5593 | |||
5594 | } | ||
5595 | |||
5596 | |||
5597 | |||
5598 | |||
5599 | #include <cassert> | ||
5600 | #include <algorithm> | ||
5601 | |||
5602 | namespace Catch { | ||
5603 | |||
5604 | namespace Generators { | ||
5605 | namespace { | ||
5606 | struct GeneratorTracker final : TestCaseTracking::TrackerBase, | ||
5607 | IGeneratorTracker { | ||
5608 | GeneratorBasePtr m_generator; | ||
5609 | |||
5610 | GeneratorTracker( | ||
5611 | TestCaseTracking::NameAndLocation&& nameAndLocation, | ||
5612 | TrackerContext& ctx, | ||
5613 | ITracker* parent ): | ||
5614 | TrackerBase( CATCH_MOVE( nameAndLocation ), ctx, parent ) {} | ||
5615 | |||
5616 | static GeneratorTracker* | ||
5617 | acquire( TrackerContext& ctx, | ||
5618 | TestCaseTracking::NameAndLocationRef const& | ||
5619 | nameAndLocation ) { | ||
5620 | GeneratorTracker* tracker; | ||
5621 | |||
5622 | ITracker& currentTracker = ctx.currentTracker(); | ||
5623 | // Under specific circumstances, the generator we want | ||
5624 | // to acquire is also the current tracker. If this is | ||
5625 | // the case, we have to avoid looking through current | ||
5626 | // tracker's children, and instead return the current | ||
5627 | // tracker. | ||
5628 | // A case where this check is important is e.g. | ||
5629 | // for (int i = 0; i < 5; ++i) { | ||
5630 | // int n = GENERATE(1, 2); | ||
5631 | // } | ||
5632 | // | ||
5633 | // without it, the code above creates 5 nested generators. | ||
5634 | if ( currentTracker.nameAndLocation() == nameAndLocation ) { | ||
5635 | auto thisTracker = currentTracker.parent()->findChild( | ||
5636 | nameAndLocation ); | ||
5637 | assert( thisTracker ); | ||
5638 | assert( thisTracker->isGeneratorTracker() ); | ||
5639 | tracker = static_cast<GeneratorTracker*>( thisTracker ); | ||
5640 | } else if ( ITracker* childTracker = | ||
5641 | currentTracker.findChild( | ||
5642 | nameAndLocation ) ) { | ||
5643 | assert( childTracker ); | ||
5644 | assert( childTracker->isGeneratorTracker() ); | ||
5645 | tracker = | ||
5646 | static_cast<GeneratorTracker*>( childTracker ); | ||
5647 | } else { | ||
5648 | return nullptr; | ||
5649 | } | ||
5650 | |||
5651 | if ( !tracker->isComplete() ) { tracker->open(); } | ||
5652 | |||
5653 | return tracker; | ||
5654 | } | ||
5655 | |||
5656 | // TrackerBase interface | ||
5657 | bool isGeneratorTracker() const override { return true; } | ||
5658 | auto hasGenerator() const -> bool override { | ||
5659 | return !!m_generator; | ||
5660 | } | ||
5661 | void close() override { | ||
5662 | TrackerBase::close(); | ||
5663 | // If a generator has a child (it is followed by a section) | ||
5664 | // and none of its children have started, then we must wait | ||
5665 | // until later to start consuming its values. | ||
5666 | // This catches cases where `GENERATE` is placed between two | ||
5667 | // `SECTION`s. | ||
5668 | // **The check for m_children.empty cannot be removed**. | ||
5669 | // doing so would break `GENERATE` _not_ followed by | ||
5670 | // `SECTION`s. | ||
5671 | const bool should_wait_for_child = [&]() { | ||
5672 | // No children -> nobody to wait for | ||
5673 | if ( m_children.empty() ) { return false; } | ||
5674 | // If at least one child started executing, don't wait | ||
5675 | if ( std::find_if( | ||
5676 | m_children.begin(), | ||
5677 | m_children.end(), | ||
5678 | []( TestCaseTracking::ITrackerPtr const& | ||
5679 | tracker ) { | ||
5680 | return tracker->hasStarted(); | ||
5681 | } ) != m_children.end() ) { | ||
5682 | return false; | ||
5683 | } | ||
5684 | |||
5685 | // No children have started. We need to check if they | ||
5686 | // _can_ start, and thus we should wait for them, or | ||
5687 | // they cannot start (due to filters), and we shouldn't | ||
5688 | // wait for them | ||
5689 | ITracker* parent = m_parent; | ||
5690 | // This is safe: there is always at least one section | ||
5691 | // tracker in a test case tracking tree | ||
5692 | while ( !parent->isSectionTracker() ) { | ||
5693 | parent = parent->parent(); | ||
5694 | } | ||
5695 | assert( parent && | ||
5696 | "Missing root (test case) level section" ); | ||
5697 | |||
5698 | auto const& parentSection = | ||
5699 | static_cast<SectionTracker const&>( *parent ); | ||
5700 | auto const& filters = parentSection.getFilters(); | ||
5701 | // No filters -> no restrictions on running sections | ||
5702 | if ( filters.empty() ) { return true; } | ||
5703 | |||
5704 | for ( auto const& child : m_children ) { | ||
5705 | if ( child->isSectionTracker() && | ||
5706 | std::find( filters.begin(), | ||
5707 | filters.end(), | ||
5708 | static_cast<SectionTracker const&>( | ||
5709 | *child ) | ||
5710 | .trimmedName() ) != | ||
5711 | filters.end() ) { | ||
5712 | return true; | ||
5713 | } | ||
5714 | } | ||
5715 | return false; | ||
5716 | }(); | ||
5717 | |||
5718 | // This check is a bit tricky, because m_generator->next() | ||
5719 | // has a side-effect, where it consumes generator's current | ||
5720 | // value, but we do not want to invoke the side-effect if | ||
5721 | // this generator is still waiting for any child to start. | ||
5722 | assert( m_generator && "Tracker without generator" ); | ||
5723 | if ( should_wait_for_child || | ||
5724 | ( m_runState == CompletedSuccessfully && | ||
5725 | m_generator->countedNext() ) ) { | ||
5726 | m_children.clear(); | ||
5727 | m_runState = Executing; | ||
5728 | } | ||
5729 | } | ||
5730 | |||
5731 | // IGeneratorTracker interface | ||
5732 | auto getGenerator() const -> GeneratorBasePtr const& override { | ||
5733 | return m_generator; | ||
5734 | } | ||
5735 | void setGenerator( GeneratorBasePtr&& generator ) override { | ||
5736 | m_generator = CATCH_MOVE( generator ); | ||
5737 | } | ||
5738 | }; | ||
5739 | } // namespace | ||
5740 | } | ||
5741 | |||
5742 | RunContext::RunContext(IConfig const* _config, IEventListenerPtr&& reporter) | ||
5743 | : m_runInfo(_config->name()), | ||
5744 | m_config(_config), | ||
5745 | m_reporter(CATCH_MOVE(reporter)), | ||
5746 | m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal }, | ||
5747 | m_outputRedirect( makeOutputRedirect( m_reporter->getPreferences().shouldRedirectStdOut ) ), | ||
5748 | m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions ) | ||
5749 | { | ||
5750 | getCurrentMutableContext().setResultCapture( this ); | ||
5751 | m_reporter->testRunStarting(m_runInfo); | ||
5752 | } | ||
5753 | |||
5754 | RunContext::~RunContext() { | ||
5755 | m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting())); | ||
5756 | } | ||
5757 | |||
5758 | Totals RunContext::runTest(TestCaseHandle const& testCase) { | ||
5759 | const Totals prevTotals = m_totals; | ||
5760 | |||
5761 | auto const& testInfo = testCase.getTestCaseInfo(); | ||
5762 | m_reporter->testCaseStarting(testInfo); | ||
5763 | testCase.prepareTestCase(); | ||
5764 | m_activeTestCase = &testCase; | ||
5765 | |||
5766 | |||
5767 | ITracker& rootTracker = m_trackerContext.startRun(); | ||
5768 | assert(rootTracker.isSectionTracker()); | ||
5769 | static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun()); | ||
5770 | |||
5771 | // We intentionally only seed the internal RNG once per test case, | ||
5772 | // before it is first invoked. The reason for that is a complex | ||
5773 | // interplay of generator/section implementation details and the | ||
5774 | // Random*Generator types. | ||
5775 | // | ||
5776 | // The issue boils down to us needing to seed the Random*Generators | ||
5777 | // with different seed each, so that they return different sequences | ||
5778 | // of random numbers. We do this by giving them a number from the | ||
5779 | // shared RNG instance as their seed. | ||
5780 | // | ||
5781 | // However, this runs into an issue if the reseeding happens each | ||
5782 | // time the test case is entered (as opposed to first time only), | ||
5783 | // because multiple generators could get the same seed, e.g. in | ||
5784 | // ```cpp | ||
5785 | // TEST_CASE() { | ||
5786 | // auto i = GENERATE(take(10, random(0, 100)); | ||
5787 | // SECTION("A") { | ||
5788 | // auto j = GENERATE(take(10, random(0, 100)); | ||
5789 | // } | ||
5790 | // SECTION("B") { | ||
5791 | // auto k = GENERATE(take(10, random(0, 100)); | ||
5792 | // } | ||
5793 | // } | ||
5794 | // ``` | ||
5795 | // `i` and `j` would properly return values from different sequences, | ||
5796 | // but `i` and `k` would return the same sequence, because their seed | ||
5797 | // would be the same. | ||
5798 | // (The reason their seeds would be the same is that the generator | ||
5799 | // for k would be initialized when the test case is entered the second | ||
5800 | // time, after the shared RNG instance was reset to the same value | ||
5801 | // it had when the generator for i was initialized.) | ||
5802 | seedRng( *m_config ); | ||
5803 | |||
5804 | uint64_t testRuns = 0; | ||
5805 | std::string redirectedCout; | ||
5806 | std::string redirectedCerr; | ||
5807 | do { | ||
5808 | m_trackerContext.startCycle(); | ||
5809 | m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocationRef(testInfo.name, testInfo.lineInfo)); | ||
5810 | |||
5811 | m_reporter->testCasePartialStarting(testInfo, testRuns); | ||
5812 | |||
5813 | const auto beforeRunTotals = m_totals; | ||
5814 | runCurrentTest(); | ||
5815 | std::string oneRunCout = m_outputRedirect->getStdout(); | ||
5816 | std::string oneRunCerr = m_outputRedirect->getStderr(); | ||
5817 | m_outputRedirect->clearBuffers(); | ||
5818 | redirectedCout += oneRunCout; | ||
5819 | redirectedCerr += oneRunCerr; | ||
5820 | |||
5821 | const auto singleRunTotals = m_totals.delta(beforeRunTotals); | ||
5822 | auto statsForOneRun = TestCaseStats(testInfo, singleRunTotals, CATCH_MOVE(oneRunCout), CATCH_MOVE(oneRunCerr), aborting()); | ||
5823 | m_reporter->testCasePartialEnded(statsForOneRun, testRuns); | ||
5824 | |||
5825 | ++testRuns; | ||
5826 | } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting()); | ||
5827 | |||
5828 | Totals deltaTotals = m_totals.delta(prevTotals); | ||
5829 | if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) { | ||
5830 | deltaTotals.assertions.failed++; | ||
5831 | deltaTotals.testCases.passed--; | ||
5832 | deltaTotals.testCases.failed++; | ||
5833 | } | ||
5834 | m_totals.testCases += deltaTotals.testCases; | ||
5835 | testCase.tearDownTestCase(); | ||
5836 | m_reporter->testCaseEnded(TestCaseStats(testInfo, | ||
5837 | deltaTotals, | ||
5838 | CATCH_MOVE(redirectedCout), | ||
5839 | CATCH_MOVE(redirectedCerr), | ||
5840 | aborting())); | ||
5841 | |||
5842 | m_activeTestCase = nullptr; | ||
5843 | m_testCaseTracker = nullptr; | ||
5844 | |||
5845 | return deltaTotals; | ||
5846 | } | ||
5847 | |||
5848 | |||
5849 | void RunContext::assertionEnded(AssertionResult&& result) { | ||
5850 | if (result.getResultType() == ResultWas::Ok) { | ||
5851 | m_totals.assertions.passed++; | ||
5852 | m_lastAssertionPassed = true; | ||
5853 | } else if (result.getResultType() == ResultWas::ExplicitSkip) { | ||
5854 | m_totals.assertions.skipped++; | ||
5855 | m_lastAssertionPassed = true; | ||
5856 | } else if (!result.succeeded()) { | ||
5857 | m_lastAssertionPassed = false; | ||
5858 | if (result.isOk()) { | ||
5859 | } | ||
5860 | else if( m_activeTestCase->getTestCaseInfo().okToFail() ) | ||
5861 | m_totals.assertions.failedButOk++; | ||
5862 | else | ||
5863 | m_totals.assertions.failed++; | ||
5864 | } | ||
5865 | else { | ||
5866 | m_lastAssertionPassed = true; | ||
5867 | } | ||
5868 | |||
5869 | { | ||
5870 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
5871 | m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ); | ||
5872 | } | ||
5873 | |||
5874 | if ( result.getResultType() != ResultWas::Warning ) { | ||
5875 | m_messageScopes.clear(); | ||
5876 | } | ||
5877 | |||
5878 | // Reset working state. assertion info will be reset after | ||
5879 | // populateReaction is run if it is needed | ||
5880 | m_lastResult = CATCH_MOVE( result ); | ||
5881 | } | ||
5882 | void RunContext::resetAssertionInfo() { | ||
5883 | m_lastAssertionInfo.macroName = StringRef(); | ||
5884 | m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr; | ||
5885 | m_lastAssertionInfo.resultDisposition = ResultDisposition::Normal; | ||
5886 | } | ||
5887 | |||
5888 | void RunContext::notifyAssertionStarted( AssertionInfo const& info ) { | ||
5889 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
5890 | m_reporter->assertionStarting( info ); | ||
5891 | } | ||
5892 | |||
5893 | bool RunContext::sectionStarted( StringRef sectionName, | ||
5894 | SourceLineInfo const& sectionLineInfo, | ||
5895 | Counts& assertions ) { | ||
5896 | ITracker& sectionTracker = | ||
5897 | SectionTracker::acquire( m_trackerContext, | ||
5898 | TestCaseTracking::NameAndLocationRef( | ||
5899 | sectionName, sectionLineInfo ) ); | ||
5900 | |||
5901 | if (!sectionTracker.isOpen()) | ||
5902 | return false; | ||
5903 | m_activeSections.push_back(§ionTracker); | ||
5904 | |||
5905 | SectionInfo sectionInfo( sectionLineInfo, static_cast<std::string>(sectionName) ); | ||
5906 | m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; | ||
5907 | |||
5908 | { | ||
5909 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
5910 | m_reporter->sectionStarting( sectionInfo ); | ||
5911 | } | ||
5912 | |||
5913 | assertions = m_totals.assertions; | ||
5914 | |||
5915 | return true; | ||
5916 | } | ||
5917 | IGeneratorTracker* | ||
5918 | RunContext::acquireGeneratorTracker( StringRef generatorName, | ||
5919 | SourceLineInfo const& lineInfo ) { | ||
5920 | using namespace Generators; | ||
5921 | GeneratorTracker* tracker = GeneratorTracker::acquire( | ||
5922 | m_trackerContext, | ||
5923 | TestCaseTracking::NameAndLocationRef( | ||
5924 | generatorName, lineInfo ) ); | ||
5925 | m_lastAssertionInfo.lineInfo = lineInfo; | ||
5926 | return tracker; | ||
5927 | } | ||
5928 | |||
5929 | IGeneratorTracker* RunContext::createGeneratorTracker( | ||
5930 | StringRef generatorName, | ||
5931 | SourceLineInfo lineInfo, | ||
5932 | Generators::GeneratorBasePtr&& generator ) { | ||
5933 | |||
5934 | auto nameAndLoc = TestCaseTracking::NameAndLocation( static_cast<std::string>( generatorName ), lineInfo ); | ||
5935 | auto& currentTracker = m_trackerContext.currentTracker(); | ||
5936 | assert( | ||
5937 | currentTracker.nameAndLocation() != nameAndLoc && | ||
5938 | "Trying to create tracker for a genreator that already has one" ); | ||
5939 | |||
5940 | auto newTracker = Catch::Detail::make_unique<Generators::GeneratorTracker>( | ||
5941 | CATCH_MOVE(nameAndLoc), m_trackerContext, ¤tTracker ); | ||
5942 | auto ret = newTracker.get(); | ||
5943 | currentTracker.addChild( CATCH_MOVE( newTracker ) ); | ||
5944 | |||
5945 | ret->setGenerator( CATCH_MOVE( generator ) ); | ||
5946 | ret->open(); | ||
5947 | return ret; | ||
5948 | } | ||
5949 | |||
5950 | bool RunContext::testForMissingAssertions(Counts& assertions) { | ||
5951 | if (assertions.total() != 0) | ||
5952 | return false; | ||
5953 | if (!m_config->warnAboutMissingAssertions()) | ||
5954 | return false; | ||
5955 | if (m_trackerContext.currentTracker().hasChildren()) | ||
5956 | return false; | ||
5957 | m_totals.assertions.failed++; | ||
5958 | assertions.failed++; | ||
5959 | return true; | ||
5960 | } | ||
5961 | |||
5962 | void RunContext::sectionEnded(SectionEndInfo&& endInfo) { | ||
5963 | Counts assertions = m_totals.assertions - endInfo.prevAssertions; | ||
5964 | bool missingAssertions = testForMissingAssertions(assertions); | ||
5965 | |||
5966 | if (!m_activeSections.empty()) { | ||
5967 | m_activeSections.back()->close(); | ||
5968 | m_activeSections.pop_back(); | ||
5969 | } | ||
5970 | |||
5971 | { | ||
5972 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
5973 | m_reporter->sectionEnded( | ||
5974 | SectionStats( CATCH_MOVE( endInfo.sectionInfo ), | ||
5975 | assertions, | ||
5976 | endInfo.durationInSeconds, | ||
5977 | missingAssertions ) ); | ||
5978 | } | ||
5979 | |||
5980 | m_messages.clear(); | ||
5981 | m_messageScopes.clear(); | ||
5982 | } | ||
5983 | |||
5984 | void RunContext::sectionEndedEarly(SectionEndInfo&& endInfo) { | ||
5985 | if ( m_unfinishedSections.empty() ) { | ||
5986 | m_activeSections.back()->fail(); | ||
5987 | } else { | ||
5988 | m_activeSections.back()->close(); | ||
5989 | } | ||
5990 | m_activeSections.pop_back(); | ||
5991 | |||
5992 | m_unfinishedSections.push_back(CATCH_MOVE(endInfo)); | ||
5993 | } | ||
5994 | |||
5995 | void RunContext::benchmarkPreparing( StringRef name ) { | ||
5996 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
5997 | m_reporter->benchmarkPreparing( name ); | ||
5998 | } | ||
5999 | void RunContext::benchmarkStarting( BenchmarkInfo const& info ) { | ||
6000 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
6001 | m_reporter->benchmarkStarting( info ); | ||
6002 | } | ||
6003 | void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) { | ||
6004 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
6005 | m_reporter->benchmarkEnded( stats ); | ||
6006 | } | ||
6007 | void RunContext::benchmarkFailed( StringRef error ) { | ||
6008 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
6009 | m_reporter->benchmarkFailed( error ); | ||
6010 | } | ||
6011 | |||
6012 | void RunContext::pushScopedMessage(MessageInfo const & message) { | ||
6013 | m_messages.push_back(message); | ||
6014 | } | ||
6015 | |||
6016 | void RunContext::popScopedMessage(MessageInfo const & message) { | ||
6017 | m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end()); | ||
6018 | } | ||
6019 | |||
6020 | void RunContext::emplaceUnscopedMessage( MessageBuilder&& builder ) { | ||
6021 | m_messageScopes.emplace_back( CATCH_MOVE(builder) ); | ||
6022 | } | ||
6023 | |||
6024 | std::string RunContext::getCurrentTestName() const { | ||
6025 | return m_activeTestCase | ||
6026 | ? m_activeTestCase->getTestCaseInfo().name | ||
6027 | : std::string(); | ||
6028 | } | ||
6029 | |||
6030 | const AssertionResult * RunContext::getLastResult() const { | ||
6031 | return &(*m_lastResult); | ||
6032 | } | ||
6033 | |||
6034 | void RunContext::exceptionEarlyReported() { | ||
6035 | m_shouldReportUnexpected = false; | ||
6036 | } | ||
6037 | |||
6038 | void RunContext::handleFatalErrorCondition( StringRef message ) { | ||
6039 | // TODO: scoped deactivate here? Just give up and do best effort? | ||
6040 | // the deactivation can break things further, OTOH so can the | ||
6041 | // capture | ||
6042 | auto _ = scopedDeactivate( *m_outputRedirect ); | ||
6043 | |||
6044 | // First notify reporter that bad things happened | ||
6045 | m_reporter->fatalErrorEncountered( message ); | ||
6046 | |||
6047 | // Don't rebuild the result -- the stringification itself can cause more fatal errors | ||
6048 | // Instead, fake a result data. | ||
6049 | AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } ); | ||
6050 | tempResult.message = static_cast<std::string>(message); | ||
6051 | AssertionResult result(m_lastAssertionInfo, CATCH_MOVE(tempResult)); | ||
6052 | |||
6053 | assertionEnded(CATCH_MOVE(result) ); | ||
6054 | resetAssertionInfo(); | ||
6055 | |||
6056 | // Best effort cleanup for sections that have not been destructed yet | ||
6057 | // Since this is a fatal error, we have not had and won't have the opportunity to destruct them properly | ||
6058 | while (!m_activeSections.empty()) { | ||
6059 | auto nl = m_activeSections.back()->nameAndLocation(); | ||
6060 | SectionEndInfo endInfo{ SectionInfo(CATCH_MOVE(nl.location), CATCH_MOVE(nl.name)), {}, 0.0 }; | ||
6061 | sectionEndedEarly(CATCH_MOVE(endInfo)); | ||
6062 | } | ||
6063 | handleUnfinishedSections(); | ||
6064 | |||
6065 | // Recreate section for test case (as we will lose the one that was in scope) | ||
6066 | auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); | ||
6067 | SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); | ||
6068 | |||
6069 | Counts assertions; | ||
6070 | assertions.failed = 1; | ||
6071 | SectionStats testCaseSectionStats(CATCH_MOVE(testCaseSection), assertions, 0, false); | ||
6072 | m_reporter->sectionEnded( testCaseSectionStats ); | ||
6073 | |||
6074 | auto const& testInfo = m_activeTestCase->getTestCaseInfo(); | ||
6075 | |||
6076 | Totals deltaTotals; | ||
6077 | deltaTotals.testCases.failed = 1; | ||
6078 | deltaTotals.assertions.failed = 1; | ||
6079 | m_reporter->testCaseEnded(TestCaseStats(testInfo, | ||
6080 | deltaTotals, | ||
6081 | std::string(), | ||
6082 | std::string(), | ||
6083 | false)); | ||
6084 | m_totals.testCases.failed++; | ||
6085 | m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false)); | ||
6086 | } | ||
6087 | |||
6088 | bool RunContext::lastAssertionPassed() { | ||
6089 | return m_lastAssertionPassed; | ||
6090 | } | ||
6091 | |||
6092 | void RunContext::assertionPassed() { | ||
6093 | m_lastAssertionPassed = true; | ||
6094 | ++m_totals.assertions.passed; | ||
6095 | resetAssertionInfo(); | ||
6096 | m_messageScopes.clear(); | ||
6097 | } | ||
6098 | |||
6099 | bool RunContext::aborting() const { | ||
6100 | return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter()); | ||
6101 | } | ||
6102 | |||
6103 | void RunContext::runCurrentTest() { | ||
6104 | auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); | ||
6105 | SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); | ||
6106 | m_reporter->sectionStarting(testCaseSection); | ||
6107 | Counts prevAssertions = m_totals.assertions; | ||
6108 | double duration = 0; | ||
6109 | m_shouldReportUnexpected = true; | ||
6110 | m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal }; | ||
6111 | |||
6112 | Timer timer; | ||
6113 | CATCH_TRY { | ||
6114 | { | ||
6115 | auto _ = scopedActivate( *m_outputRedirect ); | ||
6116 | timer.start(); | ||
6117 | invokeActiveTestCase(); | ||
6118 | } | ||
6119 | duration = timer.getElapsedSeconds(); | ||
6120 | } CATCH_CATCH_ANON (TestFailureException&) { | ||
6121 | // This just means the test was aborted due to failure | ||
6122 | } CATCH_CATCH_ANON (TestSkipException&) { | ||
6123 | // This just means the test was explicitly skipped | ||
6124 | } CATCH_CATCH_ALL { | ||
6125 | // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions | ||
6126 | // are reported without translation at the point of origin. | ||
6127 | if( m_shouldReportUnexpected ) { | ||
6128 | AssertionReaction dummyReaction; | ||
6129 | handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction ); | ||
6130 | } | ||
6131 | } | ||
6132 | Counts assertions = m_totals.assertions - prevAssertions; | ||
6133 | bool missingAssertions = testForMissingAssertions(assertions); | ||
6134 | |||
6135 | m_testCaseTracker->close(); | ||
6136 | handleUnfinishedSections(); | ||
6137 | m_messages.clear(); | ||
6138 | m_messageScopes.clear(); | ||
6139 | |||
6140 | SectionStats testCaseSectionStats(CATCH_MOVE(testCaseSection), assertions, duration, missingAssertions); | ||
6141 | m_reporter->sectionEnded(testCaseSectionStats); | ||
6142 | } | ||
6143 | |||
6144 | void RunContext::invokeActiveTestCase() { | ||
6145 | // We need to engage a handler for signals/structured exceptions | ||
6146 | // before running the tests themselves, or the binary can crash | ||
6147 | // without failed test being reported. | ||
6148 | FatalConditionHandlerGuard _(&m_fatalConditionhandler); | ||
6149 | // We keep having issue where some compilers warn about an unused | ||
6150 | // variable, even though the type has non-trivial constructor and | ||
6151 | // destructor. This is annoying and ugly, but it makes them stfu. | ||
6152 | (void)_; | ||
6153 | |||
6154 | m_activeTestCase->invoke(); | ||
6155 | } | ||
6156 | |||
6157 | void RunContext::handleUnfinishedSections() { | ||
6158 | // If sections ended prematurely due to an exception we stored their | ||
6159 | // infos here so we can tear them down outside the unwind process. | ||
6160 | for ( auto it = m_unfinishedSections.rbegin(), | ||
6161 | itEnd = m_unfinishedSections.rend(); | ||
6162 | it != itEnd; | ||
6163 | ++it ) { | ||
6164 | sectionEnded( CATCH_MOVE( *it ) ); | ||
6165 | } | ||
6166 | m_unfinishedSections.clear(); | ||
6167 | } | ||
6168 | |||
6169 | void RunContext::handleExpr( | ||
6170 | AssertionInfo const& info, | ||
6171 | ITransientExpression const& expr, | ||
6172 | AssertionReaction& reaction | ||
6173 | ) { | ||
6174 | bool negated = isFalseTest( info.resultDisposition ); | ||
6175 | bool result = expr.getResult() != negated; | ||
6176 | |||
6177 | if( result ) { | ||
6178 | if (!m_includeSuccessfulResults) { | ||
6179 | assertionPassed(); | ||
6180 | } | ||
6181 | else { | ||
6182 | reportExpr(info, ResultWas::Ok, &expr, negated); | ||
6183 | } | ||
6184 | } | ||
6185 | else { | ||
6186 | reportExpr(info, ResultWas::ExpressionFailed, &expr, negated ); | ||
6187 | populateReaction( reaction ); | ||
6188 | } | ||
6189 | resetAssertionInfo(); | ||
6190 | } | ||
6191 | void RunContext::reportExpr( | ||
6192 | AssertionInfo const &info, | ||
6193 | ResultWas::OfType resultType, | ||
6194 | ITransientExpression const *expr, | ||
6195 | bool negated ) { | ||
6196 | |||
6197 | m_lastAssertionInfo = info; | ||
6198 | AssertionResultData data( resultType, LazyExpression( negated ) ); | ||
6199 | |||
6200 | AssertionResult assertionResult{ info, CATCH_MOVE( data ) }; | ||
6201 | assertionResult.m_resultData.lazyExpression.m_transientExpression = expr; | ||
6202 | |||
6203 | assertionEnded( CATCH_MOVE(assertionResult) ); | ||
6204 | } | ||
6205 | |||
6206 | void RunContext::handleMessage( | ||
6207 | AssertionInfo const& info, | ||
6208 | ResultWas::OfType resultType, | ||
6209 | std::string&& message, | ||
6210 | AssertionReaction& reaction | ||
6211 | ) { | ||
6212 | m_lastAssertionInfo = info; | ||
6213 | |||
6214 | AssertionResultData data( resultType, LazyExpression( false ) ); | ||
6215 | data.message = CATCH_MOVE( message ); | ||
6216 | AssertionResult assertionResult{ m_lastAssertionInfo, | ||
6217 | CATCH_MOVE( data ) }; | ||
6218 | |||
6219 | const auto isOk = assertionResult.isOk(); | ||
6220 | assertionEnded( CATCH_MOVE(assertionResult) ); | ||
6221 | if ( !isOk ) { | ||
6222 | populateReaction( reaction ); | ||
6223 | } else if ( resultType == ResultWas::ExplicitSkip ) { | ||
6224 | // TODO: Need to handle this explicitly, as ExplicitSkip is | ||
6225 | // considered "OK" | ||
6226 | reaction.shouldSkip = true; | ||
6227 | } | ||
6228 | resetAssertionInfo(); | ||
6229 | } | ||
6230 | void RunContext::handleUnexpectedExceptionNotThrown( | ||
6231 | AssertionInfo const& info, | ||
6232 | AssertionReaction& reaction | ||
6233 | ) { | ||
6234 | handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction); | ||
6235 | } | ||
6236 | |||
6237 | void RunContext::handleUnexpectedInflightException( | ||
6238 | AssertionInfo const& info, | ||
6239 | std::string&& message, | ||
6240 | AssertionReaction& reaction | ||
6241 | ) { | ||
6242 | m_lastAssertionInfo = info; | ||
6243 | |||
6244 | AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); | ||
6245 | data.message = CATCH_MOVE(message); | ||
6246 | AssertionResult assertionResult{ info, CATCH_MOVE(data) }; | ||
6247 | assertionEnded( CATCH_MOVE(assertionResult) ); | ||
6248 | populateReaction( reaction ); | ||
6249 | resetAssertionInfo(); | ||
6250 | } | ||
6251 | |||
6252 | void RunContext::populateReaction( AssertionReaction& reaction ) { | ||
6253 | reaction.shouldDebugBreak = m_config->shouldDebugBreak(); | ||
6254 | reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal); | ||
6255 | } | ||
6256 | |||
6257 | void RunContext::handleIncomplete( | ||
6258 | AssertionInfo const& info | ||
6259 | ) { | ||
6260 | using namespace std::string_literals; | ||
6261 | m_lastAssertionInfo = info; | ||
6262 | |||
6263 | AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); | ||
6264 | data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"s; | ||
6265 | AssertionResult assertionResult{ info, CATCH_MOVE( data ) }; | ||
6266 | assertionEnded( CATCH_MOVE(assertionResult) ); | ||
6267 | resetAssertionInfo(); | ||
6268 | } | ||
6269 | void RunContext::handleNonExpr( | ||
6270 | AssertionInfo const &info, | ||
6271 | ResultWas::OfType resultType, | ||
6272 | AssertionReaction &reaction | ||
6273 | ) { | ||
6274 | m_lastAssertionInfo = info; | ||
6275 | |||
6276 | AssertionResultData data( resultType, LazyExpression( false ) ); | ||
6277 | AssertionResult assertionResult{ info, CATCH_MOVE( data ) }; | ||
6278 | |||
6279 | const auto isOk = assertionResult.isOk(); | ||
6280 | assertionEnded( CATCH_MOVE(assertionResult) ); | ||
6281 | if ( !isOk ) { populateReaction( reaction ); } | ||
6282 | resetAssertionInfo(); | ||
6283 | } | ||
6284 | |||
6285 | |||
6286 | IResultCapture& getResultCapture() { | ||
6287 | if (auto* capture = getCurrentContext().getResultCapture()) | ||
6288 | return *capture; | ||
6289 | else | ||
6290 | CATCH_INTERNAL_ERROR("No result capture instance"); | ||
6291 | } | ||
6292 | |||
6293 | void seedRng(IConfig const& config) { | ||
6294 | sharedRng().seed(config.rngSeed()); | ||
6295 | } | ||
6296 | |||
6297 | unsigned int rngSeed() { | ||
6298 | return getCurrentContext().getConfig()->rngSeed(); | ||
6299 | } | ||
6300 | |||
6301 | } | ||
6302 | |||
6303 | |||
6304 | |||
6305 | namespace Catch { | ||
6306 | |||
6307 | Section::Section( SectionInfo&& info ): | ||
6308 | m_info( CATCH_MOVE( info ) ), | ||
6309 | m_sectionIncluded( | ||
6310 | getResultCapture().sectionStarted( m_info.name, m_info.lineInfo, m_assertions ) ) { | ||
6311 | // Non-"included" sections will not use the timing information | ||
6312 | // anyway, so don't bother with the potential syscall. | ||
6313 | if (m_sectionIncluded) { | ||
6314 | m_timer.start(); | ||
6315 | } | ||
6316 | } | ||
6317 | |||
6318 | Section::Section( SourceLineInfo const& _lineInfo, | ||
6319 | StringRef _name, | ||
6320 | const char* const ): | ||
6321 | m_info( { "invalid", static_cast<std::size_t>( -1 ) }, std::string{} ), | ||
6322 | m_sectionIncluded( | ||
6323 | getResultCapture().sectionStarted( _name, _lineInfo, m_assertions ) ) { | ||
6324 | // We delay initialization the SectionInfo member until we know | ||
6325 | // this section needs it, so we avoid allocating std::string for name. | ||
6326 | // We also delay timer start to avoid the potential syscall unless we | ||
6327 | // will actually use the result. | ||
6328 | if ( m_sectionIncluded ) { | ||
6329 | m_info.name = static_cast<std::string>( _name ); | ||
6330 | m_info.lineInfo = _lineInfo; | ||
6331 | m_timer.start(); | ||
6332 | } | ||
6333 | } | ||
6334 | |||
6335 | Section::~Section() { | ||
6336 | if( m_sectionIncluded ) { | ||
6337 | SectionEndInfo endInfo{ CATCH_MOVE(m_info), m_assertions, m_timer.getElapsedSeconds() }; | ||
6338 | if ( uncaught_exceptions() ) { | ||
6339 | getResultCapture().sectionEndedEarly( CATCH_MOVE(endInfo) ); | ||
6340 | } else { | ||
6341 | getResultCapture().sectionEnded( CATCH_MOVE( endInfo ) ); | ||
6342 | } | ||
6343 | } | ||
6344 | } | ||
6345 | |||
6346 | // This indicates whether the section should be executed or not | ||
6347 | Section::operator bool() const { | ||
6348 | return m_sectionIncluded; | ||
6349 | } | ||
6350 | |||
6351 | |||
6352 | } // end namespace Catch | ||
6353 | |||
6354 | |||
6355 | |||
6356 | #include <vector> | ||
6357 | |||
6358 | namespace Catch { | ||
6359 | |||
6360 | namespace { | ||
6361 | static auto getSingletons() -> std::vector<ISingleton*>*& { | ||
6362 | static std::vector<ISingleton*>* g_singletons = nullptr; | ||
6363 | if( !g_singletons ) | ||
6364 | g_singletons = new std::vector<ISingleton*>(); | ||
6365 | return g_singletons; | ||
6366 | } | ||
6367 | } | ||
6368 | |||
6369 | ISingleton::~ISingleton() = default; | ||
6370 | |||
6371 | void addSingleton(ISingleton* singleton ) { | ||
6372 | getSingletons()->push_back( singleton ); | ||
6373 | } | ||
6374 | void cleanupSingletons() { | ||
6375 | auto& singletons = getSingletons(); | ||
6376 | for( auto singleton : *singletons ) | ||
6377 | delete singleton; | ||
6378 | delete singletons; | ||
6379 | singletons = nullptr; | ||
6380 | } | ||
6381 | |||
6382 | } // namespace Catch | ||
6383 | |||
6384 | |||
6385 | |||
6386 | #include <cstring> | ||
6387 | #include <ostream> | ||
6388 | |||
6389 | namespace Catch { | ||
6390 | |||
6391 | bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept { | ||
6392 | return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0); | ||
6393 | } | ||
6394 | bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept { | ||
6395 | // We can assume that the same file will usually have the same pointer. | ||
6396 | // Thus, if the pointers are the same, there is no point in calling the strcmp | ||
6397 | return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0)); | ||
6398 | } | ||
6399 | |||
6400 | std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { | ||
6401 | #ifndef __GNUG__ | ||
6402 | os << info.file << '(' << info.line << ')'; | ||
6403 | #else | ||
6404 | os << info.file << ':' << info.line; | ||
6405 | #endif | ||
6406 | return os; | ||
6407 | } | ||
6408 | |||
6409 | } // end namespace Catch | ||
6410 | |||
6411 | |||
6412 | |||
6413 | |||
6414 | namespace Catch { | ||
6415 | #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) | ||
6416 | void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept { | ||
6417 | CATCH_TRY { | ||
6418 | m_exceptions.push_back(exception); | ||
6419 | } CATCH_CATCH_ALL { | ||
6420 | // If we run out of memory during start-up there's really not a lot more we can do about it | ||
6421 | std::terminate(); | ||
6422 | } | ||
6423 | } | ||
6424 | |||
6425 | std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept { | ||
6426 | return m_exceptions; | ||
6427 | } | ||
6428 | #endif | ||
6429 | |||
6430 | } // end namespace Catch | ||
6431 | |||
6432 | |||
6433 | |||
6434 | |||
6435 | |||
6436 | #include <iostream> | ||
6437 | |||
6438 | namespace Catch { | ||
6439 | |||
6440 | // If you #define this you must implement these functions | ||
6441 | #if !defined( CATCH_CONFIG_NOSTDOUT ) | ||
6442 | std::ostream& cout() { return std::cout; } | ||
6443 | std::ostream& cerr() { return std::cerr; } | ||
6444 | std::ostream& clog() { return std::clog; } | ||
6445 | #endif | ||
6446 | |||
6447 | } // namespace Catch | ||
6448 | |||
6449 | |||
6450 | |||
6451 | #include <ostream> | ||
6452 | #include <cstring> | ||
6453 | #include <cctype> | ||
6454 | #include <vector> | ||
6455 | |||
6456 | namespace Catch { | ||
6457 | |||
6458 | bool startsWith( std::string const& s, std::string const& prefix ) { | ||
6459 | return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin()); | ||
6460 | } | ||
6461 | bool startsWith( StringRef s, char prefix ) { | ||
6462 | return !s.empty() && s[0] == prefix; | ||
6463 | } | ||
6464 | bool endsWith( std::string const& s, std::string const& suffix ) { | ||
6465 | return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); | ||
6466 | } | ||
6467 | bool endsWith( std::string const& s, char suffix ) { | ||
6468 | return !s.empty() && s[s.size()-1] == suffix; | ||
6469 | } | ||
6470 | bool contains( std::string const& s, std::string const& infix ) { | ||
6471 | return s.find( infix ) != std::string::npos; | ||
6472 | } | ||
6473 | void toLowerInPlace( std::string& s ) { | ||
6474 | for ( char& c : s ) { | ||
6475 | c = toLower( c ); | ||
6476 | } | ||
6477 | } | ||
6478 | std::string toLower( std::string const& s ) { | ||
6479 | std::string lc = s; | ||
6480 | toLowerInPlace( lc ); | ||
6481 | return lc; | ||
6482 | } | ||
6483 | char toLower(char c) { | ||
6484 | return static_cast<char>(std::tolower(static_cast<unsigned char>(c))); | ||
6485 | } | ||
6486 | |||
6487 | std::string trim( std::string const& str ) { | ||
6488 | static char const* whitespaceChars = "\n\r\t "; | ||
6489 | std::string::size_type start = str.find_first_not_of( whitespaceChars ); | ||
6490 | std::string::size_type end = str.find_last_not_of( whitespaceChars ); | ||
6491 | |||
6492 | return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string(); | ||
6493 | } | ||
6494 | |||
6495 | StringRef trim(StringRef ref) { | ||
6496 | const auto is_ws = [](char c) { | ||
6497 | return c == ' ' || c == '\t' || c == '\n' || c == '\r'; | ||
6498 | }; | ||
6499 | size_t real_begin = 0; | ||
6500 | while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; } | ||
6501 | size_t real_end = ref.size(); | ||
6502 | while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; } | ||
6503 | |||
6504 | return ref.substr(real_begin, real_end - real_begin); | ||
6505 | } | ||
6506 | |||
6507 | bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { | ||
6508 | std::size_t i = str.find( replaceThis ); | ||
6509 | if (i == std::string::npos) { | ||
6510 | return false; | ||
6511 | } | ||
6512 | std::size_t copyBegin = 0; | ||
6513 | std::string origStr = CATCH_MOVE(str); | ||
6514 | str.clear(); | ||
6515 | // There is at least one replacement, so reserve with the best guess | ||
6516 | // we can make without actually counting the number of occurences. | ||
6517 | str.reserve(origStr.size() - replaceThis.size() + withThis.size()); | ||
6518 | do { | ||
6519 | str.append(origStr, copyBegin, i-copyBegin ); | ||
6520 | str += withThis; | ||
6521 | copyBegin = i + replaceThis.size(); | ||
6522 | if( copyBegin < origStr.size() ) | ||
6523 | i = origStr.find( replaceThis, copyBegin ); | ||
6524 | else | ||
6525 | i = std::string::npos; | ||
6526 | } while( i != std::string::npos ); | ||
6527 | if ( copyBegin < origStr.size() ) { | ||
6528 | str.append(origStr, copyBegin, origStr.size() ); | ||
6529 | } | ||
6530 | return true; | ||
6531 | } | ||
6532 | |||
6533 | std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) { | ||
6534 | std::vector<StringRef> subStrings; | ||
6535 | std::size_t start = 0; | ||
6536 | for(std::size_t pos = 0; pos < str.size(); ++pos ) { | ||
6537 | if( str[pos] == delimiter ) { | ||
6538 | if( pos - start > 1 ) | ||
6539 | subStrings.push_back( str.substr( start, pos-start ) ); | ||
6540 | start = pos+1; | ||
6541 | } | ||
6542 | } | ||
6543 | if( start < str.size() ) | ||
6544 | subStrings.push_back( str.substr( start, str.size()-start ) ); | ||
6545 | return subStrings; | ||
6546 | } | ||
6547 | |||
6548 | std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { | ||
6549 | os << pluraliser.m_count << ' ' << pluraliser.m_label; | ||
6550 | if( pluraliser.m_count != 1 ) | ||
6551 | os << 's'; | ||
6552 | return os; | ||
6553 | } | ||
6554 | |||
6555 | } | ||
6556 | |||
6557 | |||
6558 | |||
6559 | #include <algorithm> | ||
6560 | #include <ostream> | ||
6561 | #include <cstring> | ||
6562 | #include <cstdint> | ||
6563 | |||
6564 | namespace Catch { | ||
6565 | StringRef::StringRef( char const* rawChars ) noexcept | ||
6566 | : StringRef( rawChars, std::strlen(rawChars) ) | ||
6567 | {} | ||
6568 | |||
6569 | |||
6570 | bool StringRef::operator<(StringRef rhs) const noexcept { | ||
6571 | if (m_size < rhs.m_size) { | ||
6572 | return strncmp(m_start, rhs.m_start, m_size) <= 0; | ||
6573 | } | ||
6574 | return strncmp(m_start, rhs.m_start, rhs.m_size) < 0; | ||
6575 | } | ||
6576 | |||
6577 | int StringRef::compare( StringRef rhs ) const { | ||
6578 | auto cmpResult = | ||
6579 | strncmp( m_start, rhs.m_start, std::min( m_size, rhs.m_size ) ); | ||
6580 | |||
6581 | // This means that strncmp found a difference before the strings | ||
6582 | // ended, and we can return it directly | ||
6583 | if ( cmpResult != 0 ) { | ||
6584 | return cmpResult; | ||
6585 | } | ||
6586 | |||
6587 | // If strings are equal up to length, then their comparison results on | ||
6588 | // their size | ||
6589 | if ( m_size < rhs.m_size ) { | ||
6590 | return -1; | ||
6591 | } else if ( m_size > rhs.m_size ) { | ||
6592 | return 1; | ||
6593 | } else { | ||
6594 | return 0; | ||
6595 | } | ||
6596 | } | ||
6597 | |||
6598 | auto operator << ( std::ostream& os, StringRef str ) -> std::ostream& { | ||
6599 | return os.write(str.data(), static_cast<std::streamsize>(str.size())); | ||
6600 | } | ||
6601 | |||
6602 | std::string operator+(StringRef lhs, StringRef rhs) { | ||
6603 | std::string ret; | ||
6604 | ret.reserve(lhs.size() + rhs.size()); | ||
6605 | ret += lhs; | ||
6606 | ret += rhs; | ||
6607 | return ret; | ||
6608 | } | ||
6609 | |||
6610 | auto operator+=( std::string& lhs, StringRef rhs ) -> std::string& { | ||
6611 | lhs.append(rhs.data(), rhs.size()); | ||
6612 | return lhs; | ||
6613 | } | ||
6614 | |||
6615 | } // namespace Catch | ||
6616 | |||
6617 | |||
6618 | |||
6619 | namespace Catch { | ||
6620 | |||
6621 | TagAliasRegistry::~TagAliasRegistry() = default; | ||
6622 | |||
6623 | TagAlias const* TagAliasRegistry::find( std::string const& alias ) const { | ||
6624 | auto it = m_registry.find( alias ); | ||
6625 | if( it != m_registry.end() ) | ||
6626 | return &(it->second); | ||
6627 | else | ||
6628 | return nullptr; | ||
6629 | } | ||
6630 | |||
6631 | std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { | ||
6632 | std::string expandedTestSpec = unexpandedTestSpec; | ||
6633 | for( auto const& registryKvp : m_registry ) { | ||
6634 | std::size_t pos = expandedTestSpec.find( registryKvp.first ); | ||
6635 | if( pos != std::string::npos ) { | ||
6636 | expandedTestSpec = expandedTestSpec.substr( 0, pos ) + | ||
6637 | registryKvp.second.tag + | ||
6638 | expandedTestSpec.substr( pos + registryKvp.first.size() ); | ||
6639 | } | ||
6640 | } | ||
6641 | return expandedTestSpec; | ||
6642 | } | ||
6643 | |||
6644 | void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { | ||
6645 | CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'), | ||
6646 | "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo ); | ||
6647 | |||
6648 | CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second, | ||
6649 | "error: tag alias, '" << alias << "' already registered.\n" | ||
6650 | << "\tFirst seen at: " << find(alias)->lineInfo << "\n" | ||
6651 | << "\tRedefined at: " << lineInfo ); | ||
6652 | } | ||
6653 | |||
6654 | ITagAliasRegistry::~ITagAliasRegistry() = default; | ||
6655 | |||
6656 | ITagAliasRegistry const& ITagAliasRegistry::get() { | ||
6657 | return getRegistryHub().getTagAliasRegistry(); | ||
6658 | } | ||
6659 | |||
6660 | } // end namespace Catch | ||
6661 | |||
6662 | |||
6663 | |||
6664 | |||
6665 | namespace Catch { | ||
6666 | TestCaseInfoHasher::TestCaseInfoHasher( hash_t seed ): m_seed( seed ) {} | ||
6667 | |||
6668 | uint32_t TestCaseInfoHasher::operator()( TestCaseInfo const& t ) const { | ||
6669 | // FNV-1a hash algorithm that is designed for uniqueness: | ||
6670 | const hash_t prime = 1099511628211u; | ||
6671 | hash_t hash = 14695981039346656037u; | ||
6672 | for ( const char c : t.name ) { | ||
6673 | hash ^= c; | ||
6674 | hash *= prime; | ||
6675 | } | ||
6676 | for ( const char c : t.className ) { | ||
6677 | hash ^= c; | ||
6678 | hash *= prime; | ||
6679 | } | ||
6680 | for ( const Tag& tag : t.tags ) { | ||
6681 | for ( const char c : tag.original ) { | ||
6682 | hash ^= c; | ||
6683 | hash *= prime; | ||
6684 | } | ||
6685 | } | ||
6686 | hash ^= m_seed; | ||
6687 | hash *= prime; | ||
6688 | const uint32_t low{ static_cast<uint32_t>( hash ) }; | ||
6689 | const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) }; | ||
6690 | return low * high; | ||
6691 | } | ||
6692 | } // namespace Catch | ||
6693 | |||
6694 | |||
6695 | |||
6696 | |||
6697 | #include <algorithm> | ||
6698 | #include <set> | ||
6699 | |||
6700 | namespace Catch { | ||
6701 | |||
6702 | namespace { | ||
6703 | static void enforceNoDuplicateTestCases( | ||
6704 | std::vector<TestCaseHandle> const& tests ) { | ||
6705 | auto testInfoCmp = []( TestCaseInfo const* lhs, | ||
6706 | TestCaseInfo const* rhs ) { | ||
6707 | return *lhs < *rhs; | ||
6708 | }; | ||
6709 | std::set<TestCaseInfo const*, decltype( testInfoCmp )&> seenTests( | ||
6710 | testInfoCmp ); | ||
6711 | for ( auto const& test : tests ) { | ||
6712 | const auto infoPtr = &test.getTestCaseInfo(); | ||
6713 | const auto prev = seenTests.insert( infoPtr ); | ||
6714 | CATCH_ENFORCE( prev.second, | ||
6715 | "error: test case \"" | ||
6716 | << infoPtr->name << "\", with tags \"" | ||
6717 | << infoPtr->tagsAsString() | ||
6718 | << "\" already defined.\n" | ||
6719 | << "\tFirst seen at " | ||
6720 | << ( *prev.first )->lineInfo << "\n" | ||
6721 | << "\tRedefined at " << infoPtr->lineInfo ); | ||
6722 | } | ||
6723 | } | ||
6724 | |||
6725 | static bool matchTest( TestCaseHandle const& testCase, | ||
6726 | TestSpec const& testSpec, | ||
6727 | IConfig const& config ) { | ||
6728 | return testSpec.matches( testCase.getTestCaseInfo() ) && | ||
6729 | isThrowSafe( testCase, config ); | ||
6730 | } | ||
6731 | |||
6732 | } // end unnamed namespace | ||
6733 | |||
6734 | std::vector<TestCaseHandle> sortTests( IConfig const& config, std::vector<TestCaseHandle> const& unsortedTestCases ) { | ||
6735 | switch (config.runOrder()) { | ||
6736 | case TestRunOrder::Declared: | ||
6737 | return unsortedTestCases; | ||
6738 | |||
6739 | case TestRunOrder::LexicographicallySorted: { | ||
6740 | std::vector<TestCaseHandle> sorted = unsortedTestCases; | ||
6741 | std::sort( | ||
6742 | sorted.begin(), | ||
6743 | sorted.end(), | ||
6744 | []( TestCaseHandle const& lhs, TestCaseHandle const& rhs ) { | ||
6745 | return lhs.getTestCaseInfo() < rhs.getTestCaseInfo(); | ||
6746 | } | ||
6747 | ); | ||
6748 | return sorted; | ||
6749 | } | ||
6750 | case TestRunOrder::Randomized: { | ||
6751 | using TestWithHash = std::pair<TestCaseInfoHasher::hash_t, TestCaseHandle>; | ||
6752 | |||
6753 | TestCaseInfoHasher h{ config.rngSeed() }; | ||
6754 | std::vector<TestWithHash> indexed_tests; | ||
6755 | indexed_tests.reserve(unsortedTestCases.size()); | ||
6756 | |||
6757 | for (auto const& handle : unsortedTestCases) { | ||
6758 | indexed_tests.emplace_back(h(handle.getTestCaseInfo()), handle); | ||
6759 | } | ||
6760 | |||
6761 | std::sort( indexed_tests.begin(), | ||
6762 | indexed_tests.end(), | ||
6763 | []( TestWithHash const& lhs, TestWithHash const& rhs ) { | ||
6764 | if ( lhs.first == rhs.first ) { | ||
6765 | return lhs.second.getTestCaseInfo() < | ||
6766 | rhs.second.getTestCaseInfo(); | ||
6767 | } | ||
6768 | return lhs.first < rhs.first; | ||
6769 | } ); | ||
6770 | |||
6771 | std::vector<TestCaseHandle> randomized; | ||
6772 | randomized.reserve(indexed_tests.size()); | ||
6773 | |||
6774 | for (auto const& indexed : indexed_tests) { | ||
6775 | randomized.push_back(indexed.second); | ||
6776 | } | ||
6777 | |||
6778 | return randomized; | ||
6779 | } | ||
6780 | } | ||
6781 | |||
6782 | CATCH_INTERNAL_ERROR("Unknown test order value!"); | ||
6783 | } | ||
6784 | |||
6785 | bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config ) { | ||
6786 | return !testCase.getTestCaseInfo().throws() || config.allowThrows(); | ||
6787 | } | ||
6788 | |||
6789 | std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config ) { | ||
6790 | std::vector<TestCaseHandle> filtered; | ||
6791 | filtered.reserve( testCases.size() ); | ||
6792 | for (auto const& testCase : testCases) { | ||
6793 | if ((!testSpec.hasFilters() && !testCase.getTestCaseInfo().isHidden()) || | ||
6794 | (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) { | ||
6795 | filtered.push_back(testCase); | ||
6796 | } | ||
6797 | } | ||
6798 | return createShard(filtered, config.shardCount(), config.shardIndex()); | ||
6799 | } | ||
6800 | std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config ) { | ||
6801 | return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); | ||
6802 | } | ||
6803 | |||
6804 | TestRegistry::~TestRegistry() = default; | ||
6805 | |||
6806 | void TestRegistry::registerTest(Detail::unique_ptr<TestCaseInfo> testInfo, Detail::unique_ptr<ITestInvoker> testInvoker) { | ||
6807 | m_handles.emplace_back(testInfo.get(), testInvoker.get()); | ||
6808 | m_viewed_test_infos.push_back(testInfo.get()); | ||
6809 | m_owned_test_infos.push_back(CATCH_MOVE(testInfo)); | ||
6810 | m_invokers.push_back(CATCH_MOVE(testInvoker)); | ||
6811 | } | ||
6812 | |||
6813 | std::vector<TestCaseInfo*> const& TestRegistry::getAllInfos() const { | ||
6814 | return m_viewed_test_infos; | ||
6815 | } | ||
6816 | |||
6817 | std::vector<TestCaseHandle> const& TestRegistry::getAllTests() const { | ||
6818 | return m_handles; | ||
6819 | } | ||
6820 | std::vector<TestCaseHandle> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const { | ||
6821 | if( m_sortedFunctions.empty() ) | ||
6822 | enforceNoDuplicateTestCases( m_handles ); | ||
6823 | |||
6824 | if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { | ||
6825 | m_sortedFunctions = sortTests( config, m_handles ); | ||
6826 | m_currentSortOrder = config.runOrder(); | ||
6827 | } | ||
6828 | return m_sortedFunctions; | ||
6829 | } | ||
6830 | |||
6831 | } // end namespace Catch | ||
6832 | |||
6833 | |||
6834 | |||
6835 | |||
6836 | #include <algorithm> | ||
6837 | #include <cassert> | ||
6838 | |||
6839 | #if defined(__clang__) | ||
6840 | # pragma clang diagnostic push | ||
6841 | # pragma clang diagnostic ignored "-Wexit-time-destructors" | ||
6842 | #endif | ||
6843 | |||
6844 | namespace Catch { | ||
6845 | namespace TestCaseTracking { | ||
6846 | |||
6847 | NameAndLocation::NameAndLocation( std::string&& _name, SourceLineInfo const& _location ) | ||
6848 | : name( CATCH_MOVE(_name) ), | ||
6849 | location( _location ) | ||
6850 | {} | ||
6851 | |||
6852 | |||
6853 | ITracker::~ITracker() = default; | ||
6854 | |||
6855 | void ITracker::markAsNeedingAnotherRun() { | ||
6856 | m_runState = NeedsAnotherRun; | ||
6857 | } | ||
6858 | |||
6859 | void ITracker::addChild( ITrackerPtr&& child ) { | ||
6860 | m_children.push_back( CATCH_MOVE(child) ); | ||
6861 | } | ||
6862 | |||
6863 | ITracker* ITracker::findChild( NameAndLocationRef const& nameAndLocation ) { | ||
6864 | auto it = std::find_if( | ||
6865 | m_children.begin(), | ||
6866 | m_children.end(), | ||
6867 | [&nameAndLocation]( ITrackerPtr const& tracker ) { | ||
6868 | auto const& tnameAndLoc = tracker->nameAndLocation(); | ||
6869 | if ( tnameAndLoc.location.line != | ||
6870 | nameAndLocation.location.line ) { | ||
6871 | return false; | ||
6872 | } | ||
6873 | return tnameAndLoc == nameAndLocation; | ||
6874 | } ); | ||
6875 | return ( it != m_children.end() ) ? it->get() : nullptr; | ||
6876 | } | ||
6877 | |||
6878 | bool ITracker::isSectionTracker() const { return false; } | ||
6879 | bool ITracker::isGeneratorTracker() const { return false; } | ||
6880 | |||
6881 | bool ITracker::isOpen() const { | ||
6882 | return m_runState != NotStarted && !isComplete(); | ||
6883 | } | ||
6884 | |||
6885 | bool ITracker::hasStarted() const { return m_runState != NotStarted; } | ||
6886 | |||
6887 | void ITracker::openChild() { | ||
6888 | if (m_runState != ExecutingChildren) { | ||
6889 | m_runState = ExecutingChildren; | ||
6890 | if (m_parent) { | ||
6891 | m_parent->openChild(); | ||
6892 | } | ||
6893 | } | ||
6894 | } | ||
6895 | |||
6896 | ITracker& TrackerContext::startRun() { | ||
6897 | using namespace std::string_literals; | ||
6898 | m_rootTracker = Catch::Detail::make_unique<SectionTracker>( | ||
6899 | NameAndLocation( "{root}"s, CATCH_INTERNAL_LINEINFO ), | ||
6900 | *this, | ||
6901 | nullptr ); | ||
6902 | m_currentTracker = nullptr; | ||
6903 | m_runState = Executing; | ||
6904 | return *m_rootTracker; | ||
6905 | } | ||
6906 | |||
6907 | void TrackerContext::completeCycle() { | ||
6908 | m_runState = CompletedCycle; | ||
6909 | } | ||
6910 | |||
6911 | bool TrackerContext::completedCycle() const { | ||
6912 | return m_runState == CompletedCycle; | ||
6913 | } | ||
6914 | void TrackerContext::setCurrentTracker( ITracker* tracker ) { | ||
6915 | m_currentTracker = tracker; | ||
6916 | } | ||
6917 | |||
6918 | |||
6919 | TrackerBase::TrackerBase( NameAndLocation&& nameAndLocation, TrackerContext& ctx, ITracker* parent ): | ||
6920 | ITracker(CATCH_MOVE(nameAndLocation), parent), | ||
6921 | m_ctx( ctx ) | ||
6922 | {} | ||
6923 | |||
6924 | bool TrackerBase::isComplete() const { | ||
6925 | return m_runState == CompletedSuccessfully || m_runState == Failed; | ||
6926 | } | ||
6927 | |||
6928 | void TrackerBase::open() { | ||
6929 | m_runState = Executing; | ||
6930 | moveToThis(); | ||
6931 | if( m_parent ) | ||
6932 | m_parent->openChild(); | ||
6933 | } | ||
6934 | |||
6935 | void TrackerBase::close() { | ||
6936 | |||
6937 | // Close any still open children (e.g. generators) | ||
6938 | while( &m_ctx.currentTracker() != this ) | ||
6939 | m_ctx.currentTracker().close(); | ||
6940 | |||
6941 | switch( m_runState ) { | ||
6942 | case NeedsAnotherRun: | ||
6943 | break; | ||
6944 | |||
6945 | case Executing: | ||
6946 | m_runState = CompletedSuccessfully; | ||
6947 | break; | ||
6948 | case ExecutingChildren: | ||
6949 | if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) ) | ||
6950 | m_runState = CompletedSuccessfully; | ||
6951 | break; | ||
6952 | |||
6953 | case NotStarted: | ||
6954 | case CompletedSuccessfully: | ||
6955 | case Failed: | ||
6956 | CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState ); | ||
6957 | |||
6958 | default: | ||
6959 | CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState ); | ||
6960 | } | ||
6961 | moveToParent(); | ||
6962 | m_ctx.completeCycle(); | ||
6963 | } | ||
6964 | void TrackerBase::fail() { | ||
6965 | m_runState = Failed; | ||
6966 | if( m_parent ) | ||
6967 | m_parent->markAsNeedingAnotherRun(); | ||
6968 | moveToParent(); | ||
6969 | m_ctx.completeCycle(); | ||
6970 | } | ||
6971 | |||
6972 | void TrackerBase::moveToParent() { | ||
6973 | assert( m_parent ); | ||
6974 | m_ctx.setCurrentTracker( m_parent ); | ||
6975 | } | ||
6976 | void TrackerBase::moveToThis() { | ||
6977 | m_ctx.setCurrentTracker( this ); | ||
6978 | } | ||
6979 | |||
6980 | SectionTracker::SectionTracker( NameAndLocation&& nameAndLocation, TrackerContext& ctx, ITracker* parent ) | ||
6981 | : TrackerBase( CATCH_MOVE(nameAndLocation), ctx, parent ), | ||
6982 | m_trimmed_name(trim(StringRef(ITracker::nameAndLocation().name))) | ||
6983 | { | ||
6984 | if( parent ) { | ||
6985 | while ( !parent->isSectionTracker() ) { | ||
6986 | parent = parent->parent(); | ||
6987 | } | ||
6988 | |||
6989 | SectionTracker& parentSection = static_cast<SectionTracker&>( *parent ); | ||
6990 | addNextFilters( parentSection.m_filters ); | ||
6991 | } | ||
6992 | } | ||
6993 | |||
6994 | bool SectionTracker::isComplete() const { | ||
6995 | bool complete = true; | ||
6996 | |||
6997 | if (m_filters.empty() | ||
6998 | || m_filters[0].empty() | ||
6999 | || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) { | ||
7000 | complete = TrackerBase::isComplete(); | ||
7001 | } | ||
7002 | return complete; | ||
7003 | } | ||
7004 | |||
7005 | bool SectionTracker::isSectionTracker() const { return true; } | ||
7006 | |||
7007 | SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocationRef const& nameAndLocation ) { | ||
7008 | SectionTracker* tracker; | ||
7009 | |||
7010 | ITracker& currentTracker = ctx.currentTracker(); | ||
7011 | if ( ITracker* childTracker = | ||
7012 | currentTracker.findChild( nameAndLocation ) ) { | ||
7013 | assert( childTracker ); | ||
7014 | assert( childTracker->isSectionTracker() ); | ||
7015 | tracker = static_cast<SectionTracker*>( childTracker ); | ||
7016 | } else { | ||
7017 | auto newTracker = Catch::Detail::make_unique<SectionTracker>( | ||
7018 | NameAndLocation{ static_cast<std::string>(nameAndLocation.name), | ||
7019 | nameAndLocation.location }, | ||
7020 | ctx, | ||
7021 | ¤tTracker ); | ||
7022 | tracker = newTracker.get(); | ||
7023 | currentTracker.addChild( CATCH_MOVE( newTracker ) ); | ||
7024 | } | ||
7025 | |||
7026 | if ( !ctx.completedCycle() ) { | ||
7027 | tracker->tryOpen(); | ||
7028 | } | ||
7029 | |||
7030 | return *tracker; | ||
7031 | } | ||
7032 | |||
7033 | void SectionTracker::tryOpen() { | ||
7034 | if( !isComplete() ) | ||
7035 | open(); | ||
7036 | } | ||
7037 | |||
7038 | void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) { | ||
7039 | if( !filters.empty() ) { | ||
7040 | m_filters.reserve( m_filters.size() + filters.size() + 2 ); | ||
7041 | m_filters.emplace_back(StringRef{}); // Root - should never be consulted | ||
7042 | m_filters.emplace_back(StringRef{}); // Test Case - not a section filter | ||
7043 | m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); | ||
7044 | } | ||
7045 | } | ||
7046 | void SectionTracker::addNextFilters( std::vector<StringRef> const& filters ) { | ||
7047 | if( filters.size() > 1 ) | ||
7048 | m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() ); | ||
7049 | } | ||
7050 | |||
7051 | StringRef SectionTracker::trimmedName() const { | ||
7052 | return m_trimmed_name; | ||
7053 | } | ||
7054 | |||
7055 | } // namespace TestCaseTracking | ||
7056 | |||
7057 | } // namespace Catch | ||
7058 | |||
7059 | #if defined(__clang__) | ||
7060 | # pragma clang diagnostic pop | ||
7061 | #endif | ||
7062 | |||
7063 | |||
7064 | |||
7065 | |||
7066 | namespace Catch { | ||
7067 | |||
7068 | void throw_test_failure_exception() { | ||
7069 | #if !defined( CATCH_CONFIG_DISABLE_EXCEPTIONS ) | ||
7070 | throw TestFailureException{}; | ||
7071 | #else | ||
7072 | CATCH_ERROR( "Test failure requires aborting test!" ); | ||
7073 | #endif | ||
7074 | } | ||
7075 | |||
7076 | void throw_test_skip_exception() { | ||
7077 | #if !defined( CATCH_CONFIG_DISABLE_EXCEPTIONS ) | ||
7078 | throw Catch::TestSkipException(); | ||
7079 | #else | ||
7080 | CATCH_ERROR( "Explicitly skipping tests during runtime requires exceptions" ); | ||
7081 | #endif | ||
7082 | } | ||
7083 | |||
7084 | } // namespace Catch | ||
7085 | |||
7086 | |||
7087 | |||
7088 | #include <algorithm> | ||
7089 | #include <iterator> | ||
7090 | |||
7091 | namespace Catch { | ||
7092 | void ITestInvoker::prepareTestCase() {} | ||
7093 | void ITestInvoker::tearDownTestCase() {} | ||
7094 | ITestInvoker::~ITestInvoker() = default; | ||
7095 | |||
7096 | namespace { | ||
7097 | static StringRef extractClassName( StringRef classOrMethodName ) { | ||
7098 | if ( !startsWith( classOrMethodName, '&' ) ) { | ||
7099 | return classOrMethodName; | ||
7100 | } | ||
7101 | |||
7102 | // Remove the leading '&' to avoid having to special case it later | ||
7103 | const auto methodName = | ||
7104 | classOrMethodName.substr( 1, classOrMethodName.size() ); | ||
7105 | |||
7106 | auto reverseStart = std::make_reverse_iterator( methodName.end() ); | ||
7107 | auto reverseEnd = std::make_reverse_iterator( methodName.begin() ); | ||
7108 | |||
7109 | // We make a simplifying assumption that ":" is only present | ||
7110 | // in the input as part of "::" from C++ typenames (this is | ||
7111 | // relatively safe assumption because the input is generated | ||
7112 | // as stringification of type through preprocessor). | ||
7113 | auto lastColons = std::find( reverseStart, reverseEnd, ':' ) + 1; | ||
7114 | auto secondLastColons = | ||
7115 | std::find( lastColons + 1, reverseEnd, ':' ); | ||
7116 | |||
7117 | auto const startIdx = reverseEnd - secondLastColons; | ||
7118 | auto const classNameSize = secondLastColons - lastColons - 1; | ||
7119 | |||
7120 | return methodName.substr( | ||
7121 | static_cast<std::size_t>( startIdx ), | ||
7122 | static_cast<std::size_t>( classNameSize ) ); | ||
7123 | } | ||
7124 | |||
7125 | class TestInvokerAsFunction final : public ITestInvoker { | ||
7126 | using TestType = void ( * )(); | ||
7127 | TestType m_testAsFunction; | ||
7128 | |||
7129 | public: | ||
7130 | constexpr TestInvokerAsFunction( TestType testAsFunction ) noexcept: | ||
7131 | m_testAsFunction( testAsFunction ) {} | ||
7132 | |||
7133 | void invoke() const override { m_testAsFunction(); } | ||
7134 | }; | ||
7135 | |||
7136 | } // namespace | ||
7137 | |||
7138 | Detail::unique_ptr<ITestInvoker> makeTestInvoker( void(*testAsFunction)() ) { | ||
7139 | return Detail::make_unique<TestInvokerAsFunction>( testAsFunction ); | ||
7140 | } | ||
7141 | |||
7142 | AutoReg::AutoReg( Detail::unique_ptr<ITestInvoker> invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept { | ||
7143 | CATCH_TRY { | ||
7144 | getMutableRegistryHub() | ||
7145 | .registerTest( | ||
7146 | makeTestCaseInfo( | ||
7147 | extractClassName( classOrMethod ), | ||
7148 | nameAndTags, | ||
7149 | lineInfo), | ||
7150 | CATCH_MOVE(invoker) | ||
7151 | ); | ||
7152 | } CATCH_CATCH_ALL { | ||
7153 | // Do not throw when constructing global objects, instead register the exception to be processed later | ||
7154 | getMutableRegistryHub().registerStartupException(); | ||
7155 | } | ||
7156 | } | ||
7157 | } | ||
7158 | |||
7159 | |||
7160 | |||
7161 | |||
7162 | |||
7163 | namespace Catch { | ||
7164 | |||
7165 | TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} | ||
7166 | |||
7167 | TestSpecParser& TestSpecParser::parse( std::string const& arg ) { | ||
7168 | m_mode = None; | ||
7169 | m_exclusion = false; | ||
7170 | m_arg = m_tagAliases->expandAliases( arg ); | ||
7171 | m_escapeChars.clear(); | ||
7172 | m_substring.reserve(m_arg.size()); | ||
7173 | m_patternName.reserve(m_arg.size()); | ||
7174 | m_realPatternPos = 0; | ||
7175 | |||
7176 | for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) | ||
7177 | //if visitChar fails | ||
7178 | if( !visitChar( m_arg[m_pos] ) ){ | ||
7179 | m_testSpec.m_invalidSpecs.push_back(arg); | ||
7180 | break; | ||
7181 | } | ||
7182 | endMode(); | ||
7183 | return *this; | ||
7184 | } | ||
7185 | TestSpec TestSpecParser::testSpec() { | ||
7186 | addFilter(); | ||
7187 | return CATCH_MOVE(m_testSpec); | ||
7188 | } | ||
7189 | bool TestSpecParser::visitChar( char c ) { | ||
7190 | if( (m_mode != EscapedName) && (c == '\\') ) { | ||
7191 | escape(); | ||
7192 | addCharToPattern(c); | ||
7193 | return true; | ||
7194 | }else if((m_mode != EscapedName) && (c == ',') ) { | ||
7195 | return separate(); | ||
7196 | } | ||
7197 | |||
7198 | switch( m_mode ) { | ||
7199 | case None: | ||
7200 | if( processNoneChar( c ) ) | ||
7201 | return true; | ||
7202 | break; | ||
7203 | case Name: | ||
7204 | processNameChar( c ); | ||
7205 | break; | ||
7206 | case EscapedName: | ||
7207 | endMode(); | ||
7208 | addCharToPattern(c); | ||
7209 | return true; | ||
7210 | default: | ||
7211 | case Tag: | ||
7212 | case QuotedName: | ||
7213 | if( processOtherChar( c ) ) | ||
7214 | return true; | ||
7215 | break; | ||
7216 | } | ||
7217 | |||
7218 | m_substring += c; | ||
7219 | if( !isControlChar( c ) ) { | ||
7220 | m_patternName += c; | ||
7221 | m_realPatternPos++; | ||
7222 | } | ||
7223 | return true; | ||
7224 | } | ||
7225 | // Two of the processing methods return true to signal the caller to return | ||
7226 | // without adding the given character to the current pattern strings | ||
7227 | bool TestSpecParser::processNoneChar( char c ) { | ||
7228 | switch( c ) { | ||
7229 | case ' ': | ||
7230 | return true; | ||
7231 | case '~': | ||
7232 | m_exclusion = true; | ||
7233 | return false; | ||
7234 | case '[': | ||
7235 | startNewMode( Tag ); | ||
7236 | return false; | ||
7237 | case '"': | ||
7238 | startNewMode( QuotedName ); | ||
7239 | return false; | ||
7240 | default: | ||
7241 | startNewMode( Name ); | ||
7242 | return false; | ||
7243 | } | ||
7244 | } | ||
7245 | void TestSpecParser::processNameChar( char c ) { | ||
7246 | if( c == '[' ) { | ||
7247 | if( m_substring == "exclude:" ) | ||
7248 | m_exclusion = true; | ||
7249 | else | ||
7250 | endMode(); | ||
7251 | startNewMode( Tag ); | ||
7252 | } | ||
7253 | } | ||
7254 | bool TestSpecParser::processOtherChar( char c ) { | ||
7255 | if( !isControlChar( c ) ) | ||
7256 | return false; | ||
7257 | m_substring += c; | ||
7258 | endMode(); | ||
7259 | return true; | ||
7260 | } | ||
7261 | void TestSpecParser::startNewMode( Mode mode ) { | ||
7262 | m_mode = mode; | ||
7263 | } | ||
7264 | void TestSpecParser::endMode() { | ||
7265 | switch( m_mode ) { | ||
7266 | case Name: | ||
7267 | case QuotedName: | ||
7268 | return addNamePattern(); | ||
7269 | case Tag: | ||
7270 | return addTagPattern(); | ||
7271 | case EscapedName: | ||
7272 | revertBackToLastMode(); | ||
7273 | return; | ||
7274 | case None: | ||
7275 | default: | ||
7276 | return startNewMode( None ); | ||
7277 | } | ||
7278 | } | ||
7279 | void TestSpecParser::escape() { | ||
7280 | saveLastMode(); | ||
7281 | m_mode = EscapedName; | ||
7282 | m_escapeChars.push_back(m_realPatternPos); | ||
7283 | } | ||
7284 | bool TestSpecParser::isControlChar( char c ) const { | ||
7285 | switch( m_mode ) { | ||
7286 | default: | ||
7287 | return false; | ||
7288 | case None: | ||
7289 | return c == '~'; | ||
7290 | case Name: | ||
7291 | return c == '['; | ||
7292 | case EscapedName: | ||
7293 | return true; | ||
7294 | case QuotedName: | ||
7295 | return c == '"'; | ||
7296 | case Tag: | ||
7297 | return c == '[' || c == ']'; | ||
7298 | } | ||
7299 | } | ||
7300 | |||
7301 | void TestSpecParser::addFilter() { | ||
7302 | if( !m_currentFilter.m_required.empty() || !m_currentFilter.m_forbidden.empty() ) { | ||
7303 | m_testSpec.m_filters.push_back( CATCH_MOVE(m_currentFilter) ); | ||
7304 | m_currentFilter = TestSpec::Filter(); | ||
7305 | } | ||
7306 | } | ||
7307 | |||
7308 | void TestSpecParser::saveLastMode() { | ||
7309 | lastMode = m_mode; | ||
7310 | } | ||
7311 | |||
7312 | void TestSpecParser::revertBackToLastMode() { | ||
7313 | m_mode = lastMode; | ||
7314 | } | ||
7315 | |||
7316 | bool TestSpecParser::separate() { | ||
7317 | if( (m_mode==QuotedName) || (m_mode==Tag) ){ | ||
7318 | //invalid argument, signal failure to previous scope. | ||
7319 | m_mode = None; | ||
7320 | m_pos = m_arg.size(); | ||
7321 | m_substring.clear(); | ||
7322 | m_patternName.clear(); | ||
7323 | m_realPatternPos = 0; | ||
7324 | return false; | ||
7325 | } | ||
7326 | endMode(); | ||
7327 | addFilter(); | ||
7328 | return true; //success | ||
7329 | } | ||
7330 | |||
7331 | std::string TestSpecParser::preprocessPattern() { | ||
7332 | std::string token = m_patternName; | ||
7333 | for (std::size_t i = 0; i < m_escapeChars.size(); ++i) | ||
7334 | token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1); | ||
7335 | m_escapeChars.clear(); | ||
7336 | if (startsWith(token, "exclude:")) { | ||
7337 | m_exclusion = true; | ||
7338 | token = token.substr(8); | ||
7339 | } | ||
7340 | |||
7341 | m_patternName.clear(); | ||
7342 | m_realPatternPos = 0; | ||
7343 | |||
7344 | return token; | ||
7345 | } | ||
7346 | |||
7347 | void TestSpecParser::addNamePattern() { | ||
7348 | auto token = preprocessPattern(); | ||
7349 | |||
7350 | if (!token.empty()) { | ||
7351 | if (m_exclusion) { | ||
7352 | m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::NamePattern>(token, m_substring)); | ||
7353 | } else { | ||
7354 | m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::NamePattern>(token, m_substring)); | ||
7355 | } | ||
7356 | } | ||
7357 | m_substring.clear(); | ||
7358 | m_exclusion = false; | ||
7359 | m_mode = None; | ||
7360 | } | ||
7361 | |||
7362 | void TestSpecParser::addTagPattern() { | ||
7363 | auto token = preprocessPattern(); | ||
7364 | |||
7365 | if (!token.empty()) { | ||
7366 | // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo]) | ||
7367 | // we have to create a separate hide tag and shorten the real one | ||
7368 | if (token.size() > 1 && token[0] == '.') { | ||
7369 | token.erase(token.begin()); | ||
7370 | if (m_exclusion) { | ||
7371 | m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(".", m_substring)); | ||
7372 | } else { | ||
7373 | m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(".", m_substring)); | ||
7374 | } | ||
7375 | } | ||
7376 | if (m_exclusion) { | ||
7377 | m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring)); | ||
7378 | } else { | ||
7379 | m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring)); | ||
7380 | } | ||
7381 | } | ||
7382 | m_substring.clear(); | ||
7383 | m_exclusion = false; | ||
7384 | m_mode = None; | ||
7385 | } | ||
7386 | |||
7387 | } // namespace Catch | ||
7388 | |||
7389 | |||
7390 | |||
7391 | #include <algorithm> | ||
7392 | #include <cstring> | ||
7393 | #include <ostream> | ||
7394 | |||
7395 | namespace { | ||
7396 | bool isWhitespace( char c ) { | ||
7397 | return c == ' ' || c == '\t' || c == '\n' || c == '\r'; | ||
7398 | } | ||
7399 | |||
7400 | bool isBreakableBefore( char c ) { | ||
7401 | static const char chars[] = "[({<|"; | ||
7402 | return std::memchr( chars, c, sizeof( chars ) - 1 ) != nullptr; | ||
7403 | } | ||
7404 | |||
7405 | bool isBreakableAfter( char c ) { | ||
7406 | static const char chars[] = "])}>.,:;*+-=&/\\"; | ||
7407 | return std::memchr( chars, c, sizeof( chars ) - 1 ) != nullptr; | ||
7408 | } | ||
7409 | |||
7410 | } // namespace | ||
7411 | |||
7412 | namespace Catch { | ||
7413 | namespace TextFlow { | ||
7414 | void AnsiSkippingString::preprocessString() { | ||
7415 | for ( auto it = m_string.begin(); it != m_string.end(); ) { | ||
7416 | // try to read through an ansi sequence | ||
7417 | while ( it != m_string.end() && *it == '\033' && | ||
7418 | it + 1 != m_string.end() && *( it + 1 ) == '[' ) { | ||
7419 | auto cursor = it + 2; | ||
7420 | while ( cursor != m_string.end() && | ||
7421 | ( isdigit( *cursor ) || *cursor == ';' ) ) { | ||
7422 | ++cursor; | ||
7423 | } | ||
7424 | if ( cursor == m_string.end() || *cursor != 'm' ) { | ||
7425 | break; | ||
7426 | } | ||
7427 | // 'm' -> 0xff | ||
7428 | *cursor = AnsiSkippingString::sentinel; | ||
7429 | // if we've read an ansi sequence, set the iterator and | ||
7430 | // return to the top of the loop | ||
7431 | it = cursor + 1; | ||
7432 | } | ||
7433 | if ( it != m_string.end() ) { | ||
7434 | ++m_size; | ||
7435 | ++it; | ||
7436 | } | ||
7437 | } | ||
7438 | } | ||
7439 | |||
7440 | AnsiSkippingString::AnsiSkippingString( std::string const& text ): | ||
7441 | m_string( text ) { | ||
7442 | preprocessString(); | ||
7443 | } | ||
7444 | |||
7445 | AnsiSkippingString::AnsiSkippingString( std::string&& text ): | ||
7446 | m_string( CATCH_MOVE( text ) ) { | ||
7447 | preprocessString(); | ||
7448 | } | ||
7449 | |||
7450 | AnsiSkippingString::const_iterator AnsiSkippingString::begin() const { | ||
7451 | return const_iterator( m_string ); | ||
7452 | } | ||
7453 | |||
7454 | AnsiSkippingString::const_iterator AnsiSkippingString::end() const { | ||
7455 | return const_iterator( m_string, const_iterator::EndTag{} ); | ||
7456 | } | ||
7457 | |||
7458 | std::string AnsiSkippingString::substring( const_iterator begin, | ||
7459 | const_iterator end ) const { | ||
7460 | // There's one caveat here to an otherwise simple substring: when | ||
7461 | // making a begin iterator we might have skipped ansi sequences at | ||
7462 | // the start. If `begin` here is a begin iterator, skipped over | ||
7463 | // initial ansi sequences, we'll use the true beginning of the | ||
7464 | // string. Lastly: We need to transform any chars we replaced with | ||
7465 | // 0xff back to 'm' | ||
7466 | auto str = std::string( begin == this->begin() ? m_string.begin() | ||
7467 | : begin.m_it, | ||
7468 | end.m_it ); | ||
7469 | std::transform( str.begin(), str.end(), str.begin(), []( char c ) { | ||
7470 | return c == AnsiSkippingString::sentinel ? 'm' : c; | ||
7471 | } ); | ||
7472 | return str; | ||
7473 | } | ||
7474 | |||
7475 | void AnsiSkippingString::const_iterator::tryParseAnsiEscapes() { | ||
7476 | // check if we've landed on an ansi sequence, and if so read through | ||
7477 | // it | ||
7478 | while ( m_it != m_string->end() && *m_it == '\033' && | ||
7479 | m_it + 1 != m_string->end() && *( m_it + 1 ) == '[' ) { | ||
7480 | auto cursor = m_it + 2; | ||
7481 | while ( cursor != m_string->end() && | ||
7482 | ( isdigit( *cursor ) || *cursor == ';' ) ) { | ||
7483 | ++cursor; | ||
7484 | } | ||
7485 | if ( cursor == m_string->end() || | ||
7486 | *cursor != AnsiSkippingString::sentinel ) { | ||
7487 | break; | ||
7488 | } | ||
7489 | // if we've read an ansi sequence, set the iterator and | ||
7490 | // return to the top of the loop | ||
7491 | m_it = cursor + 1; | ||
7492 | } | ||
7493 | } | ||
7494 | |||
7495 | void AnsiSkippingString::const_iterator::advance() { | ||
7496 | assert( m_it != m_string->end() ); | ||
7497 | m_it++; | ||
7498 | tryParseAnsiEscapes(); | ||
7499 | } | ||
7500 | |||
7501 | void AnsiSkippingString::const_iterator::unadvance() { | ||
7502 | assert( m_it != m_string->begin() ); | ||
7503 | m_it--; | ||
7504 | // if *m_it is 0xff, scan back to the \033 and then m_it-- once more | ||
7505 | // (and repeat check) | ||
7506 | while ( *m_it == AnsiSkippingString::sentinel ) { | ||
7507 | while ( *m_it != '\033' ) { | ||
7508 | assert( m_it != m_string->begin() ); | ||
7509 | m_it--; | ||
7510 | } | ||
7511 | // if this happens, we must have been a begin iterator that had | ||
7512 | // skipped over ansi sequences at the start of a string | ||
7513 | assert( m_it != m_string->begin() ); | ||
7514 | assert( *m_it == '\033' ); | ||
7515 | m_it--; | ||
7516 | } | ||
7517 | } | ||
7518 | |||
7519 | static bool isBoundary( AnsiSkippingString const& line, | ||
7520 | AnsiSkippingString::const_iterator it ) { | ||
7521 | return it == line.end() || | ||
7522 | ( isWhitespace( *it ) && | ||
7523 | !isWhitespace( *it.oneBefore() ) ) || | ||
7524 | isBreakableBefore( *it ) || | ||
7525 | isBreakableAfter( *it.oneBefore() ); | ||
7526 | } | ||
7527 | |||
7528 | void Column::const_iterator::calcLength() { | ||
7529 | m_addHyphen = false; | ||
7530 | m_parsedTo = m_lineStart; | ||
7531 | AnsiSkippingString const& current_line = m_column.m_string; | ||
7532 | |||
7533 | if ( m_parsedTo == current_line.end() ) { | ||
7534 | m_lineEnd = m_parsedTo; | ||
7535 | return; | ||
7536 | } | ||
7537 | |||
7538 | assert( m_lineStart != current_line.end() ); | ||
7539 | if ( *m_lineStart == '\n' ) { ++m_parsedTo; } | ||
7540 | |||
7541 | const auto maxLineLength = m_column.m_width - indentSize(); | ||
7542 | std::size_t lineLength = 0; | ||
7543 | while ( m_parsedTo != current_line.end() && | ||
7544 | lineLength < maxLineLength && *m_parsedTo != '\n' ) { | ||
7545 | ++m_parsedTo; | ||
7546 | ++lineLength; | ||
7547 | } | ||
7548 | |||
7549 | // If we encountered a newline before the column is filled, | ||
7550 | // then we linebreak at the newline and consider this line | ||
7551 | // finished. | ||
7552 | if ( lineLength < maxLineLength ) { | ||
7553 | m_lineEnd = m_parsedTo; | ||
7554 | } else { | ||
7555 | // Look for a natural linebreak boundary in the column | ||
7556 | // (We look from the end, so that the first found boundary is | ||
7557 | // the right one) | ||
7558 | m_lineEnd = m_parsedTo; | ||
7559 | while ( lineLength > 0 && | ||
7560 | !isBoundary( current_line, m_lineEnd ) ) { | ||
7561 | --lineLength; | ||
7562 | --m_lineEnd; | ||
7563 | } | ||
7564 | while ( lineLength > 0 && | ||
7565 | isWhitespace( *m_lineEnd.oneBefore() ) ) { | ||
7566 | --lineLength; | ||
7567 | --m_lineEnd; | ||
7568 | } | ||
7569 | |||
7570 | // If we found one, then that is where we linebreak, otherwise | ||
7571 | // we have to split text with a hyphen | ||
7572 | if ( lineLength == 0 ) { | ||
7573 | m_addHyphen = true; | ||
7574 | m_lineEnd = m_parsedTo.oneBefore(); | ||
7575 | } | ||
7576 | } | ||
7577 | } | ||
7578 | |||
7579 | size_t Column::const_iterator::indentSize() const { | ||
7580 | auto initial = m_lineStart == m_column.m_string.begin() | ||
7581 | ? m_column.m_initialIndent | ||
7582 | : std::string::npos; | ||
7583 | return initial == std::string::npos ? m_column.m_indent : initial; | ||
7584 | } | ||
7585 | |||
7586 | std::string Column::const_iterator::addIndentAndSuffix( | ||
7587 | AnsiSkippingString::const_iterator start, | ||
7588 | AnsiSkippingString::const_iterator end ) const { | ||
7589 | std::string ret; | ||
7590 | const auto desired_indent = indentSize(); | ||
7591 | // ret.reserve( desired_indent + (end - start) + m_addHyphen ); | ||
7592 | ret.append( desired_indent, ' ' ); | ||
7593 | // ret.append( start, end ); | ||
7594 | ret += m_column.m_string.substring( start, end ); | ||
7595 | if ( m_addHyphen ) { ret.push_back( '-' ); } | ||
7596 | |||
7597 | return ret; | ||
7598 | } | ||
7599 | |||
7600 | Column::const_iterator::const_iterator( Column const& column ): | ||
7601 | m_column( column ), | ||
7602 | m_lineStart( column.m_string.begin() ), | ||
7603 | m_lineEnd( column.m_string.begin() ), | ||
7604 | m_parsedTo( column.m_string.begin() ) { | ||
7605 | assert( m_column.m_width > m_column.m_indent ); | ||
7606 | assert( m_column.m_initialIndent == std::string::npos || | ||
7607 | m_column.m_width > m_column.m_initialIndent ); | ||
7608 | calcLength(); | ||
7609 | if ( m_lineStart == m_lineEnd ) { | ||
7610 | m_lineStart = m_column.m_string.end(); | ||
7611 | } | ||
7612 | } | ||
7613 | |||
7614 | std::string Column::const_iterator::operator*() const { | ||
7615 | assert( m_lineStart <= m_parsedTo ); | ||
7616 | return addIndentAndSuffix( m_lineStart, m_lineEnd ); | ||
7617 | } | ||
7618 | |||
7619 | Column::const_iterator& Column::const_iterator::operator++() { | ||
7620 | m_lineStart = m_lineEnd; | ||
7621 | AnsiSkippingString const& current_line = m_column.m_string; | ||
7622 | if ( m_lineStart != current_line.end() && *m_lineStart == '\n' ) { | ||
7623 | m_lineStart++; | ||
7624 | } else { | ||
7625 | while ( m_lineStart != current_line.end() && | ||
7626 | isWhitespace( *m_lineStart ) ) { | ||
7627 | ++m_lineStart; | ||
7628 | } | ||
7629 | } | ||
7630 | |||
7631 | if ( m_lineStart != current_line.end() ) { calcLength(); } | ||
7632 | return *this; | ||
7633 | } | ||
7634 | |||
7635 | Column::const_iterator Column::const_iterator::operator++( int ) { | ||
7636 | const_iterator prev( *this ); | ||
7637 | operator++(); | ||
7638 | return prev; | ||
7639 | } | ||
7640 | |||
7641 | std::ostream& operator<<( std::ostream& os, Column const& col ) { | ||
7642 | bool first = true; | ||
7643 | for ( auto line : col ) { | ||
7644 | if ( first ) { | ||
7645 | first = false; | ||
7646 | } else { | ||
7647 | os << '\n'; | ||
7648 | } | ||
7649 | os << line; | ||
7650 | } | ||
7651 | return os; | ||
7652 | } | ||
7653 | |||
7654 | Column Spacer( size_t spaceWidth ) { | ||
7655 | Column ret{ "" }; | ||
7656 | ret.width( spaceWidth ); | ||
7657 | return ret; | ||
7658 | } | ||
7659 | |||
7660 | Columns::iterator::iterator( Columns const& columns, EndTag ): | ||
7661 | m_columns( columns.m_columns ), m_activeIterators( 0 ) { | ||
7662 | |||
7663 | m_iterators.reserve( m_columns.size() ); | ||
7664 | for ( auto const& col : m_columns ) { | ||
7665 | m_iterators.push_back( col.end() ); | ||
7666 | } | ||
7667 | } | ||
7668 | |||
7669 | Columns::iterator::iterator( Columns const& columns ): | ||
7670 | m_columns( columns.m_columns ), | ||
7671 | m_activeIterators( m_columns.size() ) { | ||
7672 | |||
7673 | m_iterators.reserve( m_columns.size() ); | ||
7674 | for ( auto const& col : m_columns ) { | ||
7675 | m_iterators.push_back( col.begin() ); | ||
7676 | } | ||
7677 | } | ||
7678 | |||
7679 | std::string Columns::iterator::operator*() const { | ||
7680 | std::string row, padding; | ||
7681 | |||
7682 | for ( size_t i = 0; i < m_columns.size(); ++i ) { | ||
7683 | const auto width = m_columns[i].width(); | ||
7684 | if ( m_iterators[i] != m_columns[i].end() ) { | ||
7685 | std::string col = *m_iterators[i]; | ||
7686 | row += padding; | ||
7687 | row += col; | ||
7688 | |||
7689 | padding.clear(); | ||
7690 | if ( col.size() < width ) { | ||
7691 | padding.append( width - col.size(), ' ' ); | ||
7692 | } | ||
7693 | } else { | ||
7694 | padding.append( width, ' ' ); | ||
7695 | } | ||
7696 | } | ||
7697 | return row; | ||
7698 | } | ||
7699 | |||
7700 | Columns::iterator& Columns::iterator::operator++() { | ||
7701 | for ( size_t i = 0; i < m_columns.size(); ++i ) { | ||
7702 | if ( m_iterators[i] != m_columns[i].end() ) { | ||
7703 | ++m_iterators[i]; | ||
7704 | } | ||
7705 | } | ||
7706 | return *this; | ||
7707 | } | ||
7708 | |||
7709 | Columns::iterator Columns::iterator::operator++( int ) { | ||
7710 | iterator prev( *this ); | ||
7711 | operator++(); | ||
7712 | return prev; | ||
7713 | } | ||
7714 | |||
7715 | std::ostream& operator<<( std::ostream& os, Columns const& cols ) { | ||
7716 | bool first = true; | ||
7717 | for ( auto line : cols ) { | ||
7718 | if ( first ) { | ||
7719 | first = false; | ||
7720 | } else { | ||
7721 | os << '\n'; | ||
7722 | } | ||
7723 | os << line; | ||
7724 | } | ||
7725 | return os; | ||
7726 | } | ||
7727 | |||
7728 | Columns operator+( Column const& lhs, Column const& rhs ) { | ||
7729 | Columns cols; | ||
7730 | cols += lhs; | ||
7731 | cols += rhs; | ||
7732 | return cols; | ||
7733 | } | ||
7734 | Columns operator+( Column&& lhs, Column&& rhs ) { | ||
7735 | Columns cols; | ||
7736 | cols += CATCH_MOVE( lhs ); | ||
7737 | cols += CATCH_MOVE( rhs ); | ||
7738 | return cols; | ||
7739 | } | ||
7740 | |||
7741 | Columns& operator+=( Columns& lhs, Column const& rhs ) { | ||
7742 | lhs.m_columns.push_back( rhs ); | ||
7743 | return lhs; | ||
7744 | } | ||
7745 | Columns& operator+=( Columns& lhs, Column&& rhs ) { | ||
7746 | lhs.m_columns.push_back( CATCH_MOVE( rhs ) ); | ||
7747 | return lhs; | ||
7748 | } | ||
7749 | Columns operator+( Columns const& lhs, Column const& rhs ) { | ||
7750 | auto combined( lhs ); | ||
7751 | combined += rhs; | ||
7752 | return combined; | ||
7753 | } | ||
7754 | Columns operator+( Columns&& lhs, Column&& rhs ) { | ||
7755 | lhs += CATCH_MOVE( rhs ); | ||
7756 | return CATCH_MOVE( lhs ); | ||
7757 | } | ||
7758 | |||
7759 | } // namespace TextFlow | ||
7760 | } // namespace Catch | ||
7761 | |||
7762 | |||
7763 | |||
7764 | |||
7765 | #include <exception> | ||
7766 | |||
7767 | namespace Catch { | ||
7768 | bool uncaught_exceptions() { | ||
7769 | #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) | ||
7770 | return false; | ||
7771 | #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) | ||
7772 | return std::uncaught_exceptions() > 0; | ||
7773 | #else | ||
7774 | return std::uncaught_exception(); | ||
7775 | #endif | ||
7776 | } | ||
7777 | } // end namespace Catch | ||
7778 | |||
7779 | |||
7780 | |||
7781 | namespace Catch { | ||
7782 | |||
7783 | WildcardPattern::WildcardPattern( std::string const& pattern, | ||
7784 | CaseSensitive caseSensitivity ) | ||
7785 | : m_caseSensitivity( caseSensitivity ), | ||
7786 | m_pattern( normaliseString( pattern ) ) | ||
7787 | { | ||
7788 | if( startsWith( m_pattern, '*' ) ) { | ||
7789 | m_pattern = m_pattern.substr( 1 ); | ||
7790 | m_wildcard = WildcardAtStart; | ||
7791 | } | ||
7792 | if( endsWith( m_pattern, '*' ) ) { | ||
7793 | m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); | ||
7794 | m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd ); | ||
7795 | } | ||
7796 | } | ||
7797 | |||
7798 | bool WildcardPattern::matches( std::string const& str ) const { | ||
7799 | switch( m_wildcard ) { | ||
7800 | case NoWildcard: | ||
7801 | return m_pattern == normaliseString( str ); | ||
7802 | case WildcardAtStart: | ||
7803 | return endsWith( normaliseString( str ), m_pattern ); | ||
7804 | case WildcardAtEnd: | ||
7805 | return startsWith( normaliseString( str ), m_pattern ); | ||
7806 | case WildcardAtBothEnds: | ||
7807 | return contains( normaliseString( str ), m_pattern ); | ||
7808 | default: | ||
7809 | CATCH_INTERNAL_ERROR( "Unknown enum" ); | ||
7810 | } | ||
7811 | } | ||
7812 | |||
7813 | std::string WildcardPattern::normaliseString( std::string const& str ) const { | ||
7814 | return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str ); | ||
7815 | } | ||
7816 | } | ||
7817 | |||
7818 | |||
7819 | // Note: swapping these two includes around causes MSVC to error out | ||
7820 | // while in /permissive- mode. No, I don't know why. | ||
7821 | // Tested on VS 2019, 18.{3, 4}.x | ||
7822 | |||
7823 | #include <cstdint> | ||
7824 | #include <iomanip> | ||
7825 | #include <type_traits> | ||
7826 | |||
7827 | namespace Catch { | ||
7828 | |||
7829 | namespace { | ||
7830 | |||
7831 | size_t trailingBytes(unsigned char c) { | ||
7832 | if ((c & 0xE0) == 0xC0) { | ||
7833 | return 2; | ||
7834 | } | ||
7835 | if ((c & 0xF0) == 0xE0) { | ||
7836 | return 3; | ||
7837 | } | ||
7838 | if ((c & 0xF8) == 0xF0) { | ||
7839 | return 4; | ||
7840 | } | ||
7841 | CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); | ||
7842 | } | ||
7843 | |||
7844 | uint32_t headerValue(unsigned char c) { | ||
7845 | if ((c & 0xE0) == 0xC0) { | ||
7846 | return c & 0x1F; | ||
7847 | } | ||
7848 | if ((c & 0xF0) == 0xE0) { | ||
7849 | return c & 0x0F; | ||
7850 | } | ||
7851 | if ((c & 0xF8) == 0xF0) { | ||
7852 | return c & 0x07; | ||
7853 | } | ||
7854 | CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); | ||
7855 | } | ||
7856 | |||
7857 | void hexEscapeChar(std::ostream& os, unsigned char c) { | ||
7858 | std::ios_base::fmtflags f(os.flags()); | ||
7859 | os << "\\x" | ||
7860 | << std::uppercase << std::hex << std::setfill('0') << std::setw(2) | ||
7861 | << static_cast<int>(c); | ||
7862 | os.flags(f); | ||
7863 | } | ||
7864 | |||
7865 | constexpr bool shouldNewline(XmlFormatting fmt) { | ||
7866 | return !!(static_cast<std::underlying_type_t<XmlFormatting>>(fmt & XmlFormatting::Newline)); | ||
7867 | } | ||
7868 | |||
7869 | constexpr bool shouldIndent(XmlFormatting fmt) { | ||
7870 | return !!(static_cast<std::underlying_type_t<XmlFormatting>>(fmt & XmlFormatting::Indent)); | ||
7871 | } | ||
7872 | |||
7873 | } // anonymous namespace | ||
7874 | |||
7875 | void XmlEncode::encodeTo( std::ostream& os ) const { | ||
7876 | // Apostrophe escaping not necessary if we always use " to write attributes | ||
7877 | // (see: http://www.w3.org/TR/xml/#syntax) | ||
7878 | |||
7879 | for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { | ||
7880 | unsigned char c = static_cast<unsigned char>(m_str[idx]); | ||
7881 | switch (c) { | ||
7882 | case '<': os << "<"; break; | ||
7883 | case '&': os << "&"; break; | ||
7884 | |||
7885 | case '>': | ||
7886 | // See: http://www.w3.org/TR/xml/#syntax | ||
7887 | if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') | ||
7888 | os << ">"; | ||
7889 | else | ||
7890 | os << c; | ||
7891 | break; | ||
7892 | |||
7893 | case '\"': | ||
7894 | if (m_forWhat == ForAttributes) | ||
7895 | os << """; | ||
7896 | else | ||
7897 | os << c; | ||
7898 | break; | ||
7899 | |||
7900 | default: | ||
7901 | // Check for control characters and invalid utf-8 | ||
7902 | |||
7903 | // Escape control characters in standard ascii | ||
7904 | // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 | ||
7905 | if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { | ||
7906 | hexEscapeChar(os, c); | ||
7907 | break; | ||
7908 | } | ||
7909 | |||
7910 | // Plain ASCII: Write it to stream | ||
7911 | if (c < 0x7F) { | ||
7912 | os << c; | ||
7913 | break; | ||
7914 | } | ||
7915 | |||
7916 | // UTF-8 territory | ||
7917 | // Check if the encoding is valid and if it is not, hex escape bytes. | ||
7918 | // Important: We do not check the exact decoded values for validity, only the encoding format | ||
7919 | // First check that this bytes is a valid lead byte: | ||
7920 | // This means that it is not encoded as 1111 1XXX | ||
7921 | // Or as 10XX XXXX | ||
7922 | if (c < 0xC0 || | ||
7923 | c >= 0xF8) { | ||
7924 | hexEscapeChar(os, c); | ||
7925 | break; | ||
7926 | } | ||
7927 | |||
7928 | auto encBytes = trailingBytes(c); | ||
7929 | // Are there enough bytes left to avoid accessing out-of-bounds memory? | ||
7930 | if (idx + encBytes - 1 >= m_str.size()) { | ||
7931 | hexEscapeChar(os, c); | ||
7932 | break; | ||
7933 | } | ||
7934 | // The header is valid, check data | ||
7935 | // The next encBytes bytes must together be a valid utf-8 | ||
7936 | // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) | ||
7937 | bool valid = true; | ||
7938 | uint32_t value = headerValue(c); | ||
7939 | for (std::size_t n = 1; n < encBytes; ++n) { | ||
7940 | unsigned char nc = static_cast<unsigned char>(m_str[idx + n]); | ||
7941 | valid &= ((nc & 0xC0) == 0x80); | ||
7942 | value = (value << 6) | (nc & 0x3F); | ||
7943 | } | ||
7944 | |||
7945 | if ( | ||
7946 | // Wrong bit pattern of following bytes | ||
7947 | (!valid) || | ||
7948 | // Overlong encodings | ||
7949 | (value < 0x80) || | ||
7950 | (0x80 <= value && value < 0x800 && encBytes > 2) || | ||
7951 | (0x800 < value && value < 0x10000 && encBytes > 3) || | ||
7952 | // Encoded value out of range | ||
7953 | (value >= 0x110000) | ||
7954 | ) { | ||
7955 | hexEscapeChar(os, c); | ||
7956 | break; | ||
7957 | } | ||
7958 | |||
7959 | // If we got here, this is in fact a valid(ish) utf-8 sequence | ||
7960 | for (std::size_t n = 0; n < encBytes; ++n) { | ||
7961 | os << m_str[idx + n]; | ||
7962 | } | ||
7963 | idx += encBytes - 1; | ||
7964 | break; | ||
7965 | } | ||
7966 | } | ||
7967 | } | ||
7968 | |||
7969 | std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { | ||
7970 | xmlEncode.encodeTo( os ); | ||
7971 | return os; | ||
7972 | } | ||
7973 | |||
7974 | XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt ) | ||
7975 | : m_writer( writer ), | ||
7976 | m_fmt(fmt) | ||
7977 | {} | ||
7978 | |||
7979 | XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept | ||
7980 | : m_writer( other.m_writer ), | ||
7981 | m_fmt(other.m_fmt) | ||
7982 | { | ||
7983 | other.m_writer = nullptr; | ||
7984 | other.m_fmt = XmlFormatting::None; | ||
7985 | } | ||
7986 | XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept { | ||
7987 | if ( m_writer ) { | ||
7988 | m_writer->endElement(); | ||
7989 | } | ||
7990 | m_writer = other.m_writer; | ||
7991 | other.m_writer = nullptr; | ||
7992 | m_fmt = other.m_fmt; | ||
7993 | other.m_fmt = XmlFormatting::None; | ||
7994 | return *this; | ||
7995 | } | ||
7996 | |||
7997 | |||
7998 | XmlWriter::ScopedElement::~ScopedElement() { | ||
7999 | if (m_writer) { | ||
8000 | m_writer->endElement(m_fmt); | ||
8001 | } | ||
8002 | } | ||
8003 | |||
8004 | XmlWriter::ScopedElement& | ||
8005 | XmlWriter::ScopedElement::writeText( StringRef text, XmlFormatting fmt ) { | ||
8006 | m_writer->writeText( text, fmt ); | ||
8007 | return *this; | ||
8008 | } | ||
8009 | |||
8010 | XmlWriter::ScopedElement& | ||
8011 | XmlWriter::ScopedElement::writeAttribute( StringRef name, | ||
8012 | StringRef attribute ) { | ||
8013 | m_writer->writeAttribute( name, attribute ); | ||
8014 | return *this; | ||
8015 | } | ||
8016 | |||
8017 | |||
8018 | XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) | ||
8019 | { | ||
8020 | writeDeclaration(); | ||
8021 | } | ||
8022 | |||
8023 | XmlWriter::~XmlWriter() { | ||
8024 | while (!m_tags.empty()) { | ||
8025 | endElement(); | ||
8026 | } | ||
8027 | newlineIfNecessary(); | ||
8028 | } | ||
8029 | |||
8030 | XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) { | ||
8031 | ensureTagClosed(); | ||
8032 | newlineIfNecessary(); | ||
8033 | if (shouldIndent(fmt)) { | ||
8034 | m_os << m_indent; | ||
8035 | m_indent += " "; | ||
8036 | } | ||
8037 | m_os << '<' << name; | ||
8038 | m_tags.push_back( name ); | ||
8039 | m_tagIsOpen = true; | ||
8040 | applyFormatting(fmt); | ||
8041 | return *this; | ||
8042 | } | ||
8043 | |||
8044 | XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) { | ||
8045 | ScopedElement scoped( this, fmt ); | ||
8046 | startElement( name, fmt ); | ||
8047 | return scoped; | ||
8048 | } | ||
8049 | |||
8050 | XmlWriter& XmlWriter::endElement(XmlFormatting fmt) { | ||
8051 | m_indent = m_indent.substr(0, m_indent.size() - 2); | ||
8052 | |||
8053 | if( m_tagIsOpen ) { | ||
8054 | m_os << "/>"; | ||
8055 | m_tagIsOpen = false; | ||
8056 | } else { | ||
8057 | newlineIfNecessary(); | ||
8058 | if (shouldIndent(fmt)) { | ||
8059 | m_os << m_indent; | ||
8060 | } | ||
8061 | m_os << "</" << m_tags.back() << '>'; | ||
8062 | } | ||
8063 | m_os << std::flush; | ||
8064 | applyFormatting(fmt); | ||
8065 | m_tags.pop_back(); | ||
8066 | return *this; | ||
8067 | } | ||
8068 | |||
8069 | XmlWriter& XmlWriter::writeAttribute( StringRef name, | ||
8070 | StringRef attribute ) { | ||
8071 | if( !name.empty() && !attribute.empty() ) | ||
8072 | m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; | ||
8073 | return *this; | ||
8074 | } | ||
8075 | |||
8076 | XmlWriter& XmlWriter::writeAttribute( StringRef name, bool attribute ) { | ||
8077 | writeAttribute(name, (attribute ? "true"_sr : "false"_sr)); | ||
8078 | return *this; | ||
8079 | } | ||
8080 | |||
8081 | XmlWriter& XmlWriter::writeAttribute( StringRef name, | ||
8082 | char const* attribute ) { | ||
8083 | writeAttribute( name, StringRef( attribute ) ); | ||
8084 | return *this; | ||
8085 | } | ||
8086 | |||
8087 | XmlWriter& XmlWriter::writeText( StringRef text, XmlFormatting fmt ) { | ||
8088 | CATCH_ENFORCE(!m_tags.empty(), "Cannot write text as top level element"); | ||
8089 | if( !text.empty() ){ | ||
8090 | bool tagWasOpen = m_tagIsOpen; | ||
8091 | ensureTagClosed(); | ||
8092 | if (tagWasOpen && shouldIndent(fmt)) { | ||
8093 | m_os << m_indent; | ||
8094 | } | ||
8095 | m_os << XmlEncode( text, XmlEncode::ForTextNodes ); | ||
8096 | applyFormatting(fmt); | ||
8097 | } | ||
8098 | return *this; | ||
8099 | } | ||
8100 | |||
8101 | XmlWriter& XmlWriter::writeComment( StringRef text, XmlFormatting fmt ) { | ||
8102 | ensureTagClosed(); | ||
8103 | if (shouldIndent(fmt)) { | ||
8104 | m_os << m_indent; | ||
8105 | } | ||
8106 | m_os << "<!-- " << text << " -->"; | ||
8107 | applyFormatting(fmt); | ||
8108 | return *this; | ||
8109 | } | ||
8110 | |||
8111 | void XmlWriter::writeStylesheetRef( StringRef url ) { | ||
8112 | m_os << R"(<?xml-stylesheet type="text/xsl" href=")" << url << R"("?>)" << '\n'; | ||
8113 | } | ||
8114 | |||
8115 | void XmlWriter::ensureTagClosed() { | ||
8116 | if( m_tagIsOpen ) { | ||
8117 | m_os << '>' << std::flush; | ||
8118 | newlineIfNecessary(); | ||
8119 | m_tagIsOpen = false; | ||
8120 | } | ||
8121 | } | ||
8122 | |||
8123 | void XmlWriter::applyFormatting(XmlFormatting fmt) { | ||
8124 | m_needsNewline = shouldNewline(fmt); | ||
8125 | } | ||
8126 | |||
8127 | void XmlWriter::writeDeclaration() { | ||
8128 | m_os << R"(<?xml version="1.0" encoding="UTF-8"?>)" << '\n'; | ||
8129 | } | ||
8130 | |||
8131 | void XmlWriter::newlineIfNecessary() { | ||
8132 | if( m_needsNewline ) { | ||
8133 | m_os << '\n' << std::flush; | ||
8134 | m_needsNewline = false; | ||
8135 | } | ||
8136 | } | ||
8137 | } | ||
8138 | |||
8139 | |||
8140 | |||
8141 | |||
8142 | |||
8143 | namespace Catch { | ||
8144 | namespace Matchers { | ||
8145 | |||
8146 | std::string MatcherUntypedBase::toString() const { | ||
8147 | if (m_cachedToString.empty()) { | ||
8148 | m_cachedToString = describe(); | ||
8149 | } | ||
8150 | return m_cachedToString; | ||
8151 | } | ||
8152 | |||
8153 | MatcherUntypedBase::~MatcherUntypedBase() = default; | ||
8154 | |||
8155 | } // namespace Matchers | ||
8156 | } // namespace Catch | ||
8157 | |||
8158 | |||
8159 | |||
8160 | |||
8161 | namespace Catch { | ||
8162 | namespace Matchers { | ||
8163 | |||
8164 | std::string IsEmptyMatcher::describe() const { | ||
8165 | return "is empty"; | ||
8166 | } | ||
8167 | |||
8168 | std::string HasSizeMatcher::describe() const { | ||
8169 | ReusableStringStream sstr; | ||
8170 | sstr << "has size == " << m_target_size; | ||
8171 | return sstr.str(); | ||
8172 | } | ||
8173 | |||
8174 | IsEmptyMatcher IsEmpty() { | ||
8175 | return {}; | ||
8176 | } | ||
8177 | |||
8178 | HasSizeMatcher SizeIs(std::size_t sz) { | ||
8179 | return HasSizeMatcher{ sz }; | ||
8180 | } | ||
8181 | |||
8182 | } // end namespace Matchers | ||
8183 | } // end namespace Catch | ||
8184 | |||
8185 | |||
8186 | |||
8187 | namespace Catch { | ||
8188 | namespace Matchers { | ||
8189 | |||
8190 | bool ExceptionMessageMatcher::match(std::exception const& ex) const { | ||
8191 | return ex.what() == m_message; | ||
8192 | } | ||
8193 | |||
8194 | std::string ExceptionMessageMatcher::describe() const { | ||
8195 | return "exception message matches \"" + m_message + '"'; | ||
8196 | } | ||
8197 | |||
8198 | ExceptionMessageMatcher Message(std::string const& message) { | ||
8199 | return ExceptionMessageMatcher(message); | ||
8200 | } | ||
8201 | |||
8202 | } // namespace Matchers | ||
8203 | } // namespace Catch | ||
8204 | |||
8205 | |||
8206 | |||
8207 | #include <algorithm> | ||
8208 | #include <cmath> | ||
8209 | #include <cstdlib> | ||
8210 | #include <cstdint> | ||
8211 | #include <sstream> | ||
8212 | #include <iomanip> | ||
8213 | #include <limits> | ||
8214 | |||
8215 | |||
8216 | namespace Catch { | ||
8217 | namespace { | ||
8218 | |||
8219 | template <typename FP> | ||
8220 | bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) { | ||
8221 | // Comparison with NaN should always be false. | ||
8222 | // This way we can rule it out before getting into the ugly details | ||
8223 | if (Catch::isnan(lhs) || Catch::isnan(rhs)) { | ||
8224 | return false; | ||
8225 | } | ||
8226 | |||
8227 | // This should also handle positive and negative zeros, infinities | ||
8228 | const auto ulpDist = ulpDistance(lhs, rhs); | ||
8229 | |||
8230 | return ulpDist <= maxUlpDiff; | ||
8231 | } | ||
8232 | |||
8233 | |||
8234 | template <typename FP> | ||
8235 | FP step(FP start, FP direction, uint64_t steps) { | ||
8236 | for (uint64_t i = 0; i < steps; ++i) { | ||
8237 | start = Catch::nextafter(start, direction); | ||
8238 | } | ||
8239 | return start; | ||
8240 | } | ||
8241 | |||
8242 | // Performs equivalent check of std::fabs(lhs - rhs) <= margin | ||
8243 | // But without the subtraction to allow for INFINITY in comparison | ||
8244 | bool marginComparison(double lhs, double rhs, double margin) { | ||
8245 | return (lhs + margin >= rhs) && (rhs + margin >= lhs); | ||
8246 | } | ||
8247 | |||
8248 | template <typename FloatingPoint> | ||
8249 | void write(std::ostream& out, FloatingPoint num) { | ||
8250 | out << std::scientific | ||
8251 | << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1) | ||
8252 | << num; | ||
8253 | } | ||
8254 | |||
8255 | } // end anonymous namespace | ||
8256 | |||
8257 | namespace Matchers { | ||
8258 | namespace Detail { | ||
8259 | |||
8260 | enum class FloatingPointKind : uint8_t { | ||
8261 | Float, | ||
8262 | Double | ||
8263 | }; | ||
8264 | |||
8265 | } // end namespace Detail | ||
8266 | |||
8267 | |||
8268 | WithinAbsMatcher::WithinAbsMatcher(double target, double margin) | ||
8269 | :m_target{ target }, m_margin{ margin } { | ||
8270 | CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.' | ||
8271 | << " Margin has to be non-negative."); | ||
8272 | } | ||
8273 | |||
8274 | // Performs equivalent check of std::fabs(lhs - rhs) <= margin | ||
8275 | // But without the subtraction to allow for INFINITY in comparison | ||
8276 | bool WithinAbsMatcher::match(double const& matchee) const { | ||
8277 | return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee); | ||
8278 | } | ||
8279 | |||
8280 | std::string WithinAbsMatcher::describe() const { | ||
8281 | return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target); | ||
8282 | } | ||
8283 | |||
8284 | |||
8285 | WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, Detail::FloatingPointKind baseType) | ||
8286 | :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } { | ||
8287 | CATCH_ENFORCE(m_type == Detail::FloatingPointKind::Double | ||
8288 | || m_ulps < (std::numeric_limits<uint32_t>::max)(), | ||
8289 | "Provided ULP is impossibly large for a float comparison."); | ||
8290 | CATCH_ENFORCE( std::numeric_limits<double>::is_iec559, | ||
8291 | "WithinUlp matcher only supports platforms with " | ||
8292 | "IEEE-754 compatible floating point representation" ); | ||
8293 | } | ||
8294 | |||
8295 | #if defined(__clang__) | ||
8296 | #pragma clang diagnostic push | ||
8297 | // Clang <3.5 reports on the default branch in the switch below | ||
8298 | #pragma clang diagnostic ignored "-Wunreachable-code" | ||
8299 | #endif | ||
8300 | |||
8301 | bool WithinUlpsMatcher::match(double const& matchee) const { | ||
8302 | switch (m_type) { | ||
8303 | case Detail::FloatingPointKind::Float: | ||
8304 | return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps); | ||
8305 | case Detail::FloatingPointKind::Double: | ||
8306 | return almostEqualUlps<double>(matchee, m_target, m_ulps); | ||
8307 | default: | ||
8308 | CATCH_INTERNAL_ERROR( "Unknown Detail::FloatingPointKind value" ); | ||
8309 | } | ||
8310 | } | ||
8311 | |||
8312 | #if defined(__clang__) | ||
8313 | #pragma clang diagnostic pop | ||
8314 | #endif | ||
8315 | |||
8316 | std::string WithinUlpsMatcher::describe() const { | ||
8317 | std::stringstream ret; | ||
8318 | |||
8319 | ret << "is within " << m_ulps << " ULPs of "; | ||
8320 | |||
8321 | if (m_type == Detail::FloatingPointKind::Float) { | ||
8322 | write(ret, static_cast<float>(m_target)); | ||
8323 | ret << 'f'; | ||
8324 | } else { | ||
8325 | write(ret, m_target); | ||
8326 | } | ||
8327 | |||
8328 | ret << " (["; | ||
8329 | if (m_type == Detail::FloatingPointKind::Double) { | ||
8330 | write( ret, | ||
8331 | step( m_target, | ||
8332 | -std::numeric_limits<double>::infinity(), | ||
8333 | m_ulps ) ); | ||
8334 | ret << ", "; | ||
8335 | write( ret, | ||
8336 | step( m_target, | ||
8337 | std::numeric_limits<double>::infinity(), | ||
8338 | m_ulps ) ); | ||
8339 | } else { | ||
8340 | // We have to cast INFINITY to float because of MinGW, see #1782 | ||
8341 | write( ret, | ||
8342 | step( static_cast<float>( m_target ), | ||
8343 | -std::numeric_limits<float>::infinity(), | ||
8344 | m_ulps ) ); | ||
8345 | ret << ", "; | ||
8346 | write( ret, | ||
8347 | step( static_cast<float>( m_target ), | ||
8348 | std::numeric_limits<float>::infinity(), | ||
8349 | m_ulps ) ); | ||
8350 | } | ||
8351 | ret << "])"; | ||
8352 | |||
8353 | return ret.str(); | ||
8354 | } | ||
8355 | |||
8356 | WithinRelMatcher::WithinRelMatcher(double target, double epsilon): | ||
8357 | m_target(target), | ||
8358 | m_epsilon(epsilon){ | ||
8359 | CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense."); | ||
8360 | CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense."); | ||
8361 | } | ||
8362 | |||
8363 | bool WithinRelMatcher::match(double const& matchee) const { | ||
8364 | const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target)); | ||
8365 | return marginComparison(matchee, m_target, | ||
8366 | std::isinf(relMargin)? 0 : relMargin); | ||
8367 | } | ||
8368 | |||
8369 | std::string WithinRelMatcher::describe() const { | ||
8370 | Catch::ReusableStringStream sstr; | ||
8371 | sstr << "and " << ::Catch::Detail::stringify(m_target) << " are within " << m_epsilon * 100. << "% of each other"; | ||
8372 | return sstr.str(); | ||
8373 | } | ||
8374 | |||
8375 | |||
8376 | WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) { | ||
8377 | return WithinUlpsMatcher(target, maxUlpDiff, Detail::FloatingPointKind::Double); | ||
8378 | } | ||
8379 | |||
8380 | WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) { | ||
8381 | return WithinUlpsMatcher(target, maxUlpDiff, Detail::FloatingPointKind::Float); | ||
8382 | } | ||
8383 | |||
8384 | WithinAbsMatcher WithinAbs(double target, double margin) { | ||
8385 | return WithinAbsMatcher(target, margin); | ||
8386 | } | ||
8387 | |||
8388 | WithinRelMatcher WithinRel(double target, double eps) { | ||
8389 | return WithinRelMatcher(target, eps); | ||
8390 | } | ||
8391 | |||
8392 | WithinRelMatcher WithinRel(double target) { | ||
8393 | return WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100); | ||
8394 | } | ||
8395 | |||
8396 | WithinRelMatcher WithinRel(float target, float eps) { | ||
8397 | return WithinRelMatcher(target, eps); | ||
8398 | } | ||
8399 | |||
8400 | WithinRelMatcher WithinRel(float target) { | ||
8401 | return WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100); | ||
8402 | } | ||
8403 | |||
8404 | |||
8405 | |||
8406 | bool IsNaNMatcher::match( double const& matchee ) const { | ||
8407 | return std::isnan( matchee ); | ||
8408 | } | ||
8409 | |||
8410 | std::string IsNaNMatcher::describe() const { | ||
8411 | using namespace std::string_literals; | ||
8412 | return "is NaN"s; | ||
8413 | } | ||
8414 | |||
8415 | IsNaNMatcher IsNaN() { return IsNaNMatcher(); } | ||
8416 | |||
8417 | } // namespace Matchers | ||
8418 | } // namespace Catch | ||
8419 | |||
8420 | |||
8421 | |||
8422 | |||
8423 | std::string Catch::Matchers::Detail::finalizeDescription(const std::string& desc) { | ||
8424 | if (desc.empty()) { | ||
8425 | return "matches undescribed predicate"; | ||
8426 | } else { | ||
8427 | return "matches predicate: \"" + desc + '"'; | ||
8428 | } | ||
8429 | } | ||
8430 | |||
8431 | |||
8432 | |||
8433 | namespace Catch { | ||
8434 | namespace Matchers { | ||
8435 | std::string AllTrueMatcher::describe() const { return "contains only true"; } | ||
8436 | |||
8437 | AllTrueMatcher AllTrue() { return AllTrueMatcher{}; } | ||
8438 | |||
8439 | std::string NoneTrueMatcher::describe() const { return "contains no true"; } | ||
8440 | |||
8441 | NoneTrueMatcher NoneTrue() { return NoneTrueMatcher{}; } | ||
8442 | |||
8443 | std::string AnyTrueMatcher::describe() const { return "contains at least one true"; } | ||
8444 | |||
8445 | AnyTrueMatcher AnyTrue() { return AnyTrueMatcher{}; } | ||
8446 | } // namespace Matchers | ||
8447 | } // namespace Catch | ||
8448 | |||
8449 | |||
8450 | |||
8451 | #include <regex> | ||
8452 | |||
8453 | namespace Catch { | ||
8454 | namespace Matchers { | ||
8455 | |||
8456 | CasedString::CasedString( std::string const& str, CaseSensitive caseSensitivity ) | ||
8457 | : m_caseSensitivity( caseSensitivity ), | ||
8458 | m_str( adjustString( str ) ) | ||
8459 | {} | ||
8460 | std::string CasedString::adjustString( std::string const& str ) const { | ||
8461 | return m_caseSensitivity == CaseSensitive::No | ||
8462 | ? toLower( str ) | ||
8463 | : str; | ||
8464 | } | ||
8465 | StringRef CasedString::caseSensitivitySuffix() const { | ||
8466 | return m_caseSensitivity == CaseSensitive::Yes | ||
8467 | ? StringRef() | ||
8468 | : " (case insensitive)"_sr; | ||
8469 | } | ||
8470 | |||
8471 | |||
8472 | StringMatcherBase::StringMatcherBase( StringRef operation, CasedString const& comparator ) | ||
8473 | : m_comparator( comparator ), | ||
8474 | m_operation( operation ) { | ||
8475 | } | ||
8476 | |||
8477 | std::string StringMatcherBase::describe() const { | ||
8478 | std::string description; | ||
8479 | description.reserve(5 + m_operation.size() + m_comparator.m_str.size() + | ||
8480 | m_comparator.caseSensitivitySuffix().size()); | ||
8481 | description += m_operation; | ||
8482 | description += ": \""; | ||
8483 | description += m_comparator.m_str; | ||
8484 | description += '"'; | ||
8485 | description += m_comparator.caseSensitivitySuffix(); | ||
8486 | return description; | ||
8487 | } | ||
8488 | |||
8489 | StringEqualsMatcher::StringEqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals"_sr, comparator ) {} | ||
8490 | |||
8491 | bool StringEqualsMatcher::match( std::string const& source ) const { | ||
8492 | return m_comparator.adjustString( source ) == m_comparator.m_str; | ||
8493 | } | ||
8494 | |||
8495 | |||
8496 | StringContainsMatcher::StringContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains"_sr, comparator ) {} | ||
8497 | |||
8498 | bool StringContainsMatcher::match( std::string const& source ) const { | ||
8499 | return contains( m_comparator.adjustString( source ), m_comparator.m_str ); | ||
8500 | } | ||
8501 | |||
8502 | |||
8503 | StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with"_sr, comparator ) {} | ||
8504 | |||
8505 | bool StartsWithMatcher::match( std::string const& source ) const { | ||
8506 | return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); | ||
8507 | } | ||
8508 | |||
8509 | |||
8510 | EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with"_sr, comparator ) {} | ||
8511 | |||
8512 | bool EndsWithMatcher::match( std::string const& source ) const { | ||
8513 | return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); | ||
8514 | } | ||
8515 | |||
8516 | |||
8517 | |||
8518 | RegexMatcher::RegexMatcher(std::string regex, CaseSensitive caseSensitivity): m_regex(CATCH_MOVE(regex)), m_caseSensitivity(caseSensitivity) {} | ||
8519 | |||
8520 | bool RegexMatcher::match(std::string const& matchee) const { | ||
8521 | auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway | ||
8522 | if (m_caseSensitivity == CaseSensitive::No) { | ||
8523 | flags |= std::regex::icase; | ||
8524 | } | ||
8525 | auto reg = std::regex(m_regex, flags); | ||
8526 | return std::regex_match(matchee, reg); | ||
8527 | } | ||
8528 | |||
8529 | std::string RegexMatcher::describe() const { | ||
8530 | return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Yes)? " case sensitively" : " case insensitively"); | ||
8531 | } | ||
8532 | |||
8533 | |||
8534 | StringEqualsMatcher Equals( std::string const& str, CaseSensitive caseSensitivity ) { | ||
8535 | return StringEqualsMatcher( CasedString( str, caseSensitivity) ); | ||
8536 | } | ||
8537 | StringContainsMatcher ContainsSubstring( std::string const& str, CaseSensitive caseSensitivity ) { | ||
8538 | return StringContainsMatcher( CasedString( str, caseSensitivity) ); | ||
8539 | } | ||
8540 | EndsWithMatcher EndsWith( std::string const& str, CaseSensitive caseSensitivity ) { | ||
8541 | return EndsWithMatcher( CasedString( str, caseSensitivity) ); | ||
8542 | } | ||
8543 | StartsWithMatcher StartsWith( std::string const& str, CaseSensitive caseSensitivity ) { | ||
8544 | return StartsWithMatcher( CasedString( str, caseSensitivity) ); | ||
8545 | } | ||
8546 | |||
8547 | RegexMatcher Matches(std::string const& regex, CaseSensitive caseSensitivity) { | ||
8548 | return RegexMatcher(regex, caseSensitivity); | ||
8549 | } | ||
8550 | |||
8551 | } // namespace Matchers | ||
8552 | } // namespace Catch | ||
8553 | |||
8554 | |||
8555 | |||
8556 | namespace Catch { | ||
8557 | namespace Matchers { | ||
8558 | MatcherGenericBase::~MatcherGenericBase() = default; | ||
8559 | |||
8560 | namespace Detail { | ||
8561 | |||
8562 | std::string describe_multi_matcher(StringRef combine, std::string const* descriptions_begin, std::string const* descriptions_end) { | ||
8563 | std::string description; | ||
8564 | std::size_t combined_size = 4; | ||
8565 | for ( auto desc = descriptions_begin; desc != descriptions_end; ++desc ) { | ||
8566 | combined_size += desc->size(); | ||
8567 | } | ||
8568 | combined_size += static_cast<size_t>(descriptions_end - descriptions_begin - 1) * combine.size(); | ||
8569 | |||
8570 | description.reserve(combined_size); | ||
8571 | |||
8572 | description += "( "; | ||
8573 | bool first = true; | ||
8574 | for( auto desc = descriptions_begin; desc != descriptions_end; ++desc ) { | ||
8575 | if( first ) | ||
8576 | first = false; | ||
8577 | else | ||
8578 | description += combine; | ||
8579 | description += *desc; | ||
8580 | } | ||
8581 | description += " )"; | ||
8582 | return description; | ||
8583 | } | ||
8584 | |||
8585 | } // namespace Detail | ||
8586 | } // namespace Matchers | ||
8587 | } // namespace Catch | ||
8588 | |||
8589 | |||
8590 | |||
8591 | |||
8592 | namespace Catch { | ||
8593 | |||
8594 | // This is the general overload that takes a any string matcher | ||
8595 | // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers | ||
8596 | // the Equals matcher (so the header does not mention matchers) | ||
8597 | void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher ) { | ||
8598 | std::string exceptionMessage = Catch::translateActiveException(); | ||
8599 | MatchExpr<std::string, StringMatcher const&> expr( CATCH_MOVE(exceptionMessage), matcher ); | ||
8600 | handler.handleExpr( expr ); | ||
8601 | } | ||
8602 | |||
8603 | } // namespace Catch | ||
8604 | |||
8605 | |||
8606 | |||
8607 | #include <ostream> | ||
8608 | |||
8609 | namespace Catch { | ||
8610 | |||
8611 | AutomakeReporter::~AutomakeReporter() = default; | ||
8612 | |||
8613 | void AutomakeReporter::testCaseEnded(TestCaseStats const& _testCaseStats) { | ||
8614 | // Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR. | ||
8615 | m_stream << ":test-result: "; | ||
8616 | if ( _testCaseStats.totals.testCases.skipped > 0 ) { | ||
8617 | m_stream << "SKIP"; | ||
8618 | } else if (_testCaseStats.totals.assertions.allPassed()) { | ||
8619 | m_stream << "PASS"; | ||
8620 | } else if (_testCaseStats.totals.assertions.allOk()) { | ||
8621 | m_stream << "XFAIL"; | ||
8622 | } else { | ||
8623 | m_stream << "FAIL"; | ||
8624 | } | ||
8625 | m_stream << ' ' << _testCaseStats.testInfo->name << '\n'; | ||
8626 | StreamingReporterBase::testCaseEnded(_testCaseStats); | ||
8627 | } | ||
8628 | |||
8629 | void AutomakeReporter::skipTest(TestCaseInfo const& testInfo) { | ||
8630 | m_stream << ":test-result: SKIP " << testInfo.name << '\n'; | ||
8631 | } | ||
8632 | |||
8633 | } // end namespace Catch | ||
8634 | |||
8635 | |||
8636 | |||
8637 | |||
8638 | |||
8639 | |||
8640 | namespace Catch { | ||
8641 | ReporterBase::ReporterBase( ReporterConfig&& config ): | ||
8642 | IEventListener( config.fullConfig() ), | ||
8643 | m_wrapped_stream( CATCH_MOVE(config).takeStream() ), | ||
8644 | m_stream( m_wrapped_stream->stream() ), | ||
8645 | m_colour( makeColourImpl( config.colourMode(), m_wrapped_stream.get() ) ), | ||
8646 | m_customOptions( config.customOptions() ) | ||
8647 | {} | ||
8648 | |||
8649 | ReporterBase::~ReporterBase() = default; | ||
8650 | |||
8651 | void ReporterBase::listReporters( | ||
8652 | std::vector<ReporterDescription> const& descriptions ) { | ||
8653 | defaultListReporters(m_stream, descriptions, m_config->verbosity()); | ||
8654 | } | ||
8655 | |||
8656 | void ReporterBase::listListeners( | ||
8657 | std::vector<ListenerDescription> const& descriptions ) { | ||
8658 | defaultListListeners( m_stream, descriptions ); | ||
8659 | } | ||
8660 | |||
8661 | void ReporterBase::listTests(std::vector<TestCaseHandle> const& tests) { | ||
8662 | defaultListTests(m_stream, | ||
8663 | m_colour.get(), | ||
8664 | tests, | ||
8665 | m_config->hasTestFilters(), | ||
8666 | m_config->verbosity()); | ||
8667 | } | ||
8668 | |||
8669 | void ReporterBase::listTags(std::vector<TagInfo> const& tags) { | ||
8670 | defaultListTags( m_stream, tags, m_config->hasTestFilters() ); | ||
8671 | } | ||
8672 | |||
8673 | } // namespace Catch | ||
8674 | |||
8675 | |||
8676 | |||
8677 | |||
8678 | #include <ostream> | ||
8679 | |||
8680 | namespace Catch { | ||
8681 | namespace { | ||
8682 | |||
8683 | // Colour::LightGrey | ||
8684 | static constexpr Colour::Code compactDimColour = Colour::FileName; | ||
8685 | |||
8686 | #ifdef CATCH_PLATFORM_MAC | ||
8687 | static constexpr Catch::StringRef compactFailedString = "FAILED"_sr; | ||
8688 | static constexpr Catch::StringRef compactPassedString = "PASSED"_sr; | ||
8689 | #else | ||
8690 | static constexpr Catch::StringRef compactFailedString = "failed"_sr; | ||
8691 | static constexpr Catch::StringRef compactPassedString = "passed"_sr; | ||
8692 | #endif | ||
8693 | |||
8694 | // Implementation of CompactReporter formatting | ||
8695 | class AssertionPrinter { | ||
8696 | public: | ||
8697 | AssertionPrinter& operator= (AssertionPrinter const&) = delete; | ||
8698 | AssertionPrinter(AssertionPrinter const&) = delete; | ||
8699 | AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages, ColourImpl* colourImpl_) | ||
8700 | : stream(_stream) | ||
8701 | , result(_stats.assertionResult) | ||
8702 | , messages(_stats.infoMessages) | ||
8703 | , itMessage(_stats.infoMessages.begin()) | ||
8704 | , printInfoMessages(_printInfoMessages) | ||
8705 | , colourImpl(colourImpl_) | ||
8706 | {} | ||
8707 | |||
8708 | void print() { | ||
8709 | printSourceInfo(); | ||
8710 | |||
8711 | itMessage = messages.begin(); | ||
8712 | |||
8713 | switch (result.getResultType()) { | ||
8714 | case ResultWas::Ok: | ||
8715 | printResultType(Colour::ResultSuccess, compactPassedString); | ||
8716 | printOriginalExpression(); | ||
8717 | printReconstructedExpression(); | ||
8718 | if (!result.hasExpression()) | ||
8719 | printRemainingMessages(Colour::None); | ||
8720 | else | ||
8721 | printRemainingMessages(); | ||
8722 | break; | ||
8723 | case ResultWas::ExpressionFailed: | ||
8724 | if (result.isOk()) | ||
8725 | printResultType(Colour::ResultSuccess, compactFailedString + " - but was ok"_sr); | ||
8726 | else | ||
8727 | printResultType(Colour::Error, compactFailedString); | ||
8728 | printOriginalExpression(); | ||
8729 | printReconstructedExpression(); | ||
8730 | printRemainingMessages(); | ||
8731 | break; | ||
8732 | case ResultWas::ThrewException: | ||
8733 | printResultType(Colour::Error, compactFailedString); | ||
8734 | printIssue("unexpected exception with message:"); | ||
8735 | printMessage(); | ||
8736 | printExpressionWas(); | ||
8737 | printRemainingMessages(); | ||
8738 | break; | ||
8739 | case ResultWas::FatalErrorCondition: | ||
8740 | printResultType(Colour::Error, compactFailedString); | ||
8741 | printIssue("fatal error condition with message:"); | ||
8742 | printMessage(); | ||
8743 | printExpressionWas(); | ||
8744 | printRemainingMessages(); | ||
8745 | break; | ||
8746 | case ResultWas::DidntThrowException: | ||
8747 | printResultType(Colour::Error, compactFailedString); | ||
8748 | printIssue("expected exception, got none"); | ||
8749 | printExpressionWas(); | ||
8750 | printRemainingMessages(); | ||
8751 | break; | ||
8752 | case ResultWas::Info: | ||
8753 | printResultType(Colour::None, "info"_sr); | ||
8754 | printMessage(); | ||
8755 | printRemainingMessages(); | ||
8756 | break; | ||
8757 | case ResultWas::Warning: | ||
8758 | printResultType(Colour::None, "warning"_sr); | ||
8759 | printMessage(); | ||
8760 | printRemainingMessages(); | ||
8761 | break; | ||
8762 | case ResultWas::ExplicitFailure: | ||
8763 | printResultType(Colour::Error, compactFailedString); | ||
8764 | printIssue("explicitly"); | ||
8765 | printRemainingMessages(Colour::None); | ||
8766 | break; | ||
8767 | case ResultWas::ExplicitSkip: | ||
8768 | printResultType(Colour::Skip, "skipped"_sr); | ||
8769 | printMessage(); | ||
8770 | printRemainingMessages(); | ||
8771 | break; | ||
8772 | // These cases are here to prevent compiler warnings | ||
8773 | case ResultWas::Unknown: | ||
8774 | case ResultWas::FailureBit: | ||
8775 | case ResultWas::Exception: | ||
8776 | printResultType(Colour::Error, "** internal error **"); | ||
8777 | break; | ||
8778 | } | ||
8779 | } | ||
8780 | |||
8781 | private: | ||
8782 | void printSourceInfo() const { | ||
8783 | stream << colourImpl->guardColour( Colour::FileName ) | ||
8784 | << result.getSourceInfo() << ':'; | ||
8785 | } | ||
8786 | |||
8787 | void printResultType(Colour::Code colour, StringRef passOrFail) const { | ||
8788 | if (!passOrFail.empty()) { | ||
8789 | stream << colourImpl->guardColour(colour) << ' ' << passOrFail; | ||
8790 | stream << ':'; | ||
8791 | } | ||
8792 | } | ||
8793 | |||
8794 | void printIssue(char const* issue) const { | ||
8795 | stream << ' ' << issue; | ||
8796 | } | ||
8797 | |||
8798 | void printExpressionWas() { | ||
8799 | if (result.hasExpression()) { | ||
8800 | stream << ';'; | ||
8801 | { | ||
8802 | stream << colourImpl->guardColour(compactDimColour) << " expression was:"; | ||
8803 | } | ||
8804 | printOriginalExpression(); | ||
8805 | } | ||
8806 | } | ||
8807 | |||
8808 | void printOriginalExpression() const { | ||
8809 | if (result.hasExpression()) { | ||
8810 | stream << ' ' << result.getExpression(); | ||
8811 | } | ||
8812 | } | ||
8813 | |||
8814 | void printReconstructedExpression() const { | ||
8815 | if (result.hasExpandedExpression()) { | ||
8816 | stream << colourImpl->guardColour(compactDimColour) << " for: "; | ||
8817 | stream << result.getExpandedExpression(); | ||
8818 | } | ||
8819 | } | ||
8820 | |||
8821 | void printMessage() { | ||
8822 | if (itMessage != messages.end()) { | ||
8823 | stream << " '" << itMessage->message << '\''; | ||
8824 | ++itMessage; | ||
8825 | } | ||
8826 | } | ||
8827 | |||
8828 | void printRemainingMessages(Colour::Code colour = compactDimColour) { | ||
8829 | if (itMessage == messages.end()) | ||
8830 | return; | ||
8831 | |||
8832 | const auto itEnd = messages.cend(); | ||
8833 | const auto N = static_cast<std::size_t>(itEnd - itMessage); | ||
8834 | |||
8835 | stream << colourImpl->guardColour( colour ) << " with " | ||
8836 | << pluralise( N, "message"_sr ) << ':'; | ||
8837 | |||
8838 | while (itMessage != itEnd) { | ||
8839 | // If this assertion is a warning ignore any INFO messages | ||
8840 | if (printInfoMessages || itMessage->type != ResultWas::Info) { | ||
8841 | printMessage(); | ||
8842 | if (itMessage != itEnd) { | ||
8843 | stream << colourImpl->guardColour(compactDimColour) << " and"; | ||
8844 | } | ||
8845 | continue; | ||
8846 | } | ||
8847 | ++itMessage; | ||
8848 | } | ||
8849 | } | ||
8850 | |||
8851 | private: | ||
8852 | std::ostream& stream; | ||
8853 | AssertionResult const& result; | ||
8854 | std::vector<MessageInfo> const& messages; | ||
8855 | std::vector<MessageInfo>::const_iterator itMessage; | ||
8856 | bool printInfoMessages; | ||
8857 | ColourImpl* colourImpl; | ||
8858 | }; | ||
8859 | |||
8860 | } // anon namespace | ||
8861 | |||
8862 | std::string CompactReporter::getDescription() { | ||
8863 | return "Reports test results on a single line, suitable for IDEs"; | ||
8864 | } | ||
8865 | |||
8866 | void CompactReporter::noMatchingTestCases( StringRef unmatchedSpec ) { | ||
8867 | m_stream << "No test cases matched '" << unmatchedSpec << "'\n"; | ||
8868 | } | ||
8869 | |||
8870 | void CompactReporter::testRunStarting( TestRunInfo const& ) { | ||
8871 | if ( m_config->testSpec().hasFilters() ) { | ||
8872 | m_stream << m_colour->guardColour( Colour::BrightYellow ) | ||
8873 | << "Filters: " | ||
8874 | << m_config->testSpec() | ||
8875 | << '\n'; | ||
8876 | } | ||
8877 | m_stream << "RNG seed: " << getSeed() << '\n'; | ||
8878 | } | ||
8879 | |||
8880 | void CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) { | ||
8881 | AssertionResult const& result = _assertionStats.assertionResult; | ||
8882 | |||
8883 | bool printInfoMessages = true; | ||
8884 | |||
8885 | // Drop out if result was successful and we're not printing those | ||
8886 | if( !m_config->includeSuccessfulResults() && result.isOk() ) { | ||
8887 | if( result.getResultType() != ResultWas::Warning && result.getResultType() != ResultWas::ExplicitSkip ) | ||
8888 | return; | ||
8889 | printInfoMessages = false; | ||
8890 | } | ||
8891 | |||
8892 | AssertionPrinter printer( m_stream, _assertionStats, printInfoMessages, m_colour.get() ); | ||
8893 | printer.print(); | ||
8894 | |||
8895 | m_stream << '\n' << std::flush; | ||
8896 | } | ||
8897 | |||
8898 | void CompactReporter::sectionEnded(SectionStats const& _sectionStats) { | ||
8899 | double dur = _sectionStats.durationInSeconds; | ||
8900 | if ( shouldShowDuration( *m_config, dur ) ) { | ||
8901 | m_stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << '\n' << std::flush; | ||
8902 | } | ||
8903 | } | ||
8904 | |||
8905 | void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) { | ||
8906 | printTestRunTotals( m_stream, *m_colour, _testRunStats.totals ); | ||
8907 | m_stream << "\n\n" << std::flush; | ||
8908 | StreamingReporterBase::testRunEnded( _testRunStats ); | ||
8909 | } | ||
8910 | |||
8911 | CompactReporter::~CompactReporter() = default; | ||
8912 | |||
8913 | } // end namespace Catch | ||
8914 | |||
8915 | |||
8916 | |||
8917 | |||
8918 | #include <cstdio> | ||
8919 | |||
8920 | #if defined(_MSC_VER) | ||
8921 | #pragma warning(push) | ||
8922 | #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch | ||
8923 | // Note that 4062 (not all labels are handled and default is missing) is enabled | ||
8924 | #endif | ||
8925 | |||
8926 | #if defined(__clang__) | ||
8927 | # pragma clang diagnostic push | ||
8928 | // For simplicity, benchmarking-only helpers are always enabled | ||
8929 | # pragma clang diagnostic ignored "-Wunused-function" | ||
8930 | #endif | ||
8931 | |||
8932 | |||
8933 | |||
8934 | namespace Catch { | ||
8935 | |||
8936 | namespace { | ||
8937 | |||
8938 | // Formatter impl for ConsoleReporter | ||
8939 | class ConsoleAssertionPrinter { | ||
8940 | public: | ||
8941 | ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete; | ||
8942 | ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete; | ||
8943 | ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, ColourImpl* colourImpl_, bool _printInfoMessages) | ||
8944 | : stream(_stream), | ||
8945 | stats(_stats), | ||
8946 | result(_stats.assertionResult), | ||
8947 | colour(Colour::None), | ||
8948 | messages(_stats.infoMessages), | ||
8949 | colourImpl(colourImpl_), | ||
8950 | printInfoMessages(_printInfoMessages) { | ||
8951 | switch (result.getResultType()) { | ||
8952 | case ResultWas::Ok: | ||
8953 | colour = Colour::Success; | ||
8954 | passOrFail = "PASSED"_sr; | ||
8955 | //if( result.hasMessage() ) | ||
8956 | if (messages.size() == 1) | ||
8957 | messageLabel = "with message"_sr; | ||
8958 | if (messages.size() > 1) | ||
8959 | messageLabel = "with messages"_sr; | ||
8960 | break; | ||
8961 | case ResultWas::ExpressionFailed: | ||
8962 | if (result.isOk()) { | ||
8963 | colour = Colour::Success; | ||
8964 | passOrFail = "FAILED - but was ok"_sr; | ||
8965 | } else { | ||
8966 | colour = Colour::Error; | ||
8967 | passOrFail = "FAILED"_sr; | ||
8968 | } | ||
8969 | if (messages.size() == 1) | ||
8970 | messageLabel = "with message"_sr; | ||
8971 | if (messages.size() > 1) | ||
8972 | messageLabel = "with messages"_sr; | ||
8973 | break; | ||
8974 | case ResultWas::ThrewException: | ||
8975 | colour = Colour::Error; | ||
8976 | passOrFail = "FAILED"_sr; | ||
8977 | // todo switch | ||
8978 | switch (messages.size()) { case 0: | ||
8979 | messageLabel = "due to unexpected exception with "_sr; | ||
8980 | break; | ||
8981 | case 1: | ||
8982 | messageLabel = "due to unexpected exception with message"_sr; | ||
8983 | break; | ||
8984 | default: | ||
8985 | messageLabel = "due to unexpected exception with messages"_sr; | ||
8986 | break; | ||
8987 | } | ||
8988 | break; | ||
8989 | case ResultWas::FatalErrorCondition: | ||
8990 | colour = Colour::Error; | ||
8991 | passOrFail = "FAILED"_sr; | ||
8992 | messageLabel = "due to a fatal error condition"_sr; | ||
8993 | break; | ||
8994 | case ResultWas::DidntThrowException: | ||
8995 | colour = Colour::Error; | ||
8996 | passOrFail = "FAILED"_sr; | ||
8997 | messageLabel = "because no exception was thrown where one was expected"_sr; | ||
8998 | break; | ||
8999 | case ResultWas::Info: | ||
9000 | messageLabel = "info"_sr; | ||
9001 | break; | ||
9002 | case ResultWas::Warning: | ||
9003 | messageLabel = "warning"_sr; | ||
9004 | break; | ||
9005 | case ResultWas::ExplicitFailure: | ||
9006 | passOrFail = "FAILED"_sr; | ||
9007 | colour = Colour::Error; | ||
9008 | if (messages.size() == 1) | ||
9009 | messageLabel = "explicitly with message"_sr; | ||
9010 | if (messages.size() > 1) | ||
9011 | messageLabel = "explicitly with messages"_sr; | ||
9012 | break; | ||
9013 | case ResultWas::ExplicitSkip: | ||
9014 | colour = Colour::Skip; | ||
9015 | passOrFail = "SKIPPED"_sr; | ||
9016 | if (messages.size() == 1) | ||
9017 | messageLabel = "explicitly with message"_sr; | ||
9018 | if (messages.size() > 1) | ||
9019 | messageLabel = "explicitly with messages"_sr; | ||
9020 | break; | ||
9021 | // These cases are here to prevent compiler warnings | ||
9022 | case ResultWas::Unknown: | ||
9023 | case ResultWas::FailureBit: | ||
9024 | case ResultWas::Exception: | ||
9025 | passOrFail = "** internal error **"_sr; | ||
9026 | colour = Colour::Error; | ||
9027 | break; | ||
9028 | } | ||
9029 | } | ||
9030 | |||
9031 | void print() const { | ||
9032 | printSourceInfo(); | ||
9033 | if (stats.totals.assertions.total() > 0) { | ||
9034 | printResultType(); | ||
9035 | printOriginalExpression(); | ||
9036 | printReconstructedExpression(); | ||
9037 | } else { | ||
9038 | stream << '\n'; | ||
9039 | } | ||
9040 | printMessage(); | ||
9041 | } | ||
9042 | |||
9043 | private: | ||
9044 | void printResultType() const { | ||
9045 | if (!passOrFail.empty()) { | ||
9046 | stream << colourImpl->guardColour(colour) << passOrFail << ":\n"; | ||
9047 | } | ||
9048 | } | ||
9049 | void printOriginalExpression() const { | ||
9050 | if (result.hasExpression()) { | ||
9051 | stream << colourImpl->guardColour( Colour::OriginalExpression ) | ||
9052 | << " " << result.getExpressionInMacro() << '\n'; | ||
9053 | } | ||
9054 | } | ||
9055 | void printReconstructedExpression() const { | ||
9056 | if (result.hasExpandedExpression()) { | ||
9057 | stream << "with expansion:\n"; | ||
9058 | stream << colourImpl->guardColour( Colour::ReconstructedExpression ) | ||
9059 | << TextFlow::Column( result.getExpandedExpression() ) | ||
9060 | .indent( 2 ) | ||
9061 | << '\n'; | ||
9062 | } | ||
9063 | } | ||
9064 | void printMessage() const { | ||
9065 | if (!messageLabel.empty()) | ||
9066 | stream << messageLabel << ':' << '\n'; | ||
9067 | for (auto const& msg : messages) { | ||
9068 | // If this assertion is a warning ignore any INFO messages | ||
9069 | if (printInfoMessages || msg.type != ResultWas::Info) | ||
9070 | stream << TextFlow::Column(msg.message).indent(2) << '\n'; | ||
9071 | } | ||
9072 | } | ||
9073 | void printSourceInfo() const { | ||
9074 | stream << colourImpl->guardColour( Colour::FileName ) | ||
9075 | << result.getSourceInfo() << ": "; | ||
9076 | } | ||
9077 | |||
9078 | std::ostream& stream; | ||
9079 | AssertionStats const& stats; | ||
9080 | AssertionResult const& result; | ||
9081 | Colour::Code colour; | ||
9082 | StringRef passOrFail; | ||
9083 | StringRef messageLabel; | ||
9084 | std::vector<MessageInfo> const& messages; | ||
9085 | ColourImpl* colourImpl; | ||
9086 | bool printInfoMessages; | ||
9087 | }; | ||
9088 | |||
9089 | std::size_t makeRatio( std::uint64_t number, std::uint64_t total ) { | ||
9090 | const auto ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0; | ||
9091 | return (ratio == 0 && number > 0) ? 1 : static_cast<std::size_t>(ratio); | ||
9092 | } | ||
9093 | |||
9094 | std::size_t& | ||
9095 | findMax( std::size_t& i, std::size_t& j, std::size_t& k, std::size_t& l ) { | ||
9096 | if (i > j && i > k && i > l) | ||
9097 | return i; | ||
9098 | else if (j > k && j > l) | ||
9099 | return j; | ||
9100 | else if (k > l) | ||
9101 | return k; | ||
9102 | else | ||
9103 | return l; | ||
9104 | } | ||
9105 | |||
9106 | struct ColumnBreak {}; | ||
9107 | struct RowBreak {}; | ||
9108 | struct OutputFlush {}; | ||
9109 | |||
9110 | class Duration { | ||
9111 | enum class Unit { | ||
9112 | Auto, | ||
9113 | Nanoseconds, | ||
9114 | Microseconds, | ||
9115 | Milliseconds, | ||
9116 | Seconds, | ||
9117 | Minutes | ||
9118 | }; | ||
9119 | static const uint64_t s_nanosecondsInAMicrosecond = 1000; | ||
9120 | static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond; | ||
9121 | static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond; | ||
9122 | static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond; | ||
9123 | |||
9124 | double m_inNanoseconds; | ||
9125 | Unit m_units; | ||
9126 | |||
9127 | public: | ||
9128 | explicit Duration(double inNanoseconds, Unit units = Unit::Auto) | ||
9129 | : m_inNanoseconds(inNanoseconds), | ||
9130 | m_units(units) { | ||
9131 | if (m_units == Unit::Auto) { | ||
9132 | if (m_inNanoseconds < s_nanosecondsInAMicrosecond) | ||
9133 | m_units = Unit::Nanoseconds; | ||
9134 | else if (m_inNanoseconds < s_nanosecondsInAMillisecond) | ||
9135 | m_units = Unit::Microseconds; | ||
9136 | else if (m_inNanoseconds < s_nanosecondsInASecond) | ||
9137 | m_units = Unit::Milliseconds; | ||
9138 | else if (m_inNanoseconds < s_nanosecondsInAMinute) | ||
9139 | m_units = Unit::Seconds; | ||
9140 | else | ||
9141 | m_units = Unit::Minutes; | ||
9142 | } | ||
9143 | |||
9144 | } | ||
9145 | |||
9146 | auto value() const -> double { | ||
9147 | switch (m_units) { | ||
9148 | case Unit::Microseconds: | ||
9149 | return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond); | ||
9150 | case Unit::Milliseconds: | ||
9151 | return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond); | ||
9152 | case Unit::Seconds: | ||
9153 | return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond); | ||
9154 | case Unit::Minutes: | ||
9155 | return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute); | ||
9156 | default: | ||
9157 | return m_inNanoseconds; | ||
9158 | } | ||
9159 | } | ||
9160 | StringRef unitsAsString() const { | ||
9161 | switch (m_units) { | ||
9162 | case Unit::Nanoseconds: | ||
9163 | return "ns"_sr; | ||
9164 | case Unit::Microseconds: | ||
9165 | return "us"_sr; | ||
9166 | case Unit::Milliseconds: | ||
9167 | return "ms"_sr; | ||
9168 | case Unit::Seconds: | ||
9169 | return "s"_sr; | ||
9170 | case Unit::Minutes: | ||
9171 | return "m"_sr; | ||
9172 | default: | ||
9173 | return "** internal error **"_sr; | ||
9174 | } | ||
9175 | |||
9176 | } | ||
9177 | friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& { | ||
9178 | return os << duration.value() << ' ' << duration.unitsAsString(); | ||
9179 | } | ||
9180 | }; | ||
9181 | } // end anon namespace | ||
9182 | |||
9183 | enum class Justification { Left, Right }; | ||
9184 | |||
9185 | struct ColumnInfo { | ||
9186 | std::string name; | ||
9187 | std::size_t width; | ||
9188 | Justification justification; | ||
9189 | }; | ||
9190 | |||
9191 | class TablePrinter { | ||
9192 | std::ostream& m_os; | ||
9193 | std::vector<ColumnInfo> m_columnInfos; | ||
9194 | ReusableStringStream m_oss; | ||
9195 | int m_currentColumn = -1; | ||
9196 | bool m_isOpen = false; | ||
9197 | |||
9198 | public: | ||
9199 | TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos ) | ||
9200 | : m_os( os ), | ||
9201 | m_columnInfos( CATCH_MOVE( columnInfos ) ) {} | ||
9202 | |||
9203 | auto columnInfos() const -> std::vector<ColumnInfo> const& { | ||
9204 | return m_columnInfos; | ||
9205 | } | ||
9206 | |||
9207 | void open() { | ||
9208 | if (!m_isOpen) { | ||
9209 | m_isOpen = true; | ||
9210 | *this << RowBreak(); | ||
9211 | |||
9212 | TextFlow::Columns headerCols; | ||
9213 | for (auto const& info : m_columnInfos) { | ||
9214 | assert(info.width > 2); | ||
9215 | headerCols += TextFlow::Column(info.name).width(info.width - 2); | ||
9216 | headerCols += TextFlow::Spacer( 2 ); | ||
9217 | } | ||
9218 | m_os << headerCols << '\n'; | ||
9219 | |||
9220 | m_os << lineOfChars('-') << '\n'; | ||
9221 | } | ||
9222 | } | ||
9223 | void close() { | ||
9224 | if (m_isOpen) { | ||
9225 | *this << RowBreak(); | ||
9226 | m_os << '\n' << std::flush; | ||
9227 | m_isOpen = false; | ||
9228 | } | ||
9229 | } | ||
9230 | |||
9231 | template<typename T> | ||
9232 | friend TablePrinter& operator<< (TablePrinter& tp, T const& value) { | ||
9233 | tp.m_oss << value; | ||
9234 | return tp; | ||
9235 | } | ||
9236 | |||
9237 | friend TablePrinter& operator<< (TablePrinter& tp, ColumnBreak) { | ||
9238 | auto colStr = tp.m_oss.str(); | ||
9239 | const auto strSize = colStr.size(); | ||
9240 | tp.m_oss.str(""); | ||
9241 | tp.open(); | ||
9242 | if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) { | ||
9243 | tp.m_currentColumn = -1; | ||
9244 | tp.m_os << '\n'; | ||
9245 | } | ||
9246 | tp.m_currentColumn++; | ||
9247 | |||
9248 | auto colInfo = tp.m_columnInfos[tp.m_currentColumn]; | ||
9249 | auto padding = (strSize + 1 < colInfo.width) | ||
9250 | ? std::string(colInfo.width - (strSize + 1), ' ') | ||
9251 | : std::string(); | ||
9252 | if (colInfo.justification == Justification::Left) | ||
9253 | tp.m_os << colStr << padding << ' '; | ||
9254 | else | ||
9255 | tp.m_os << padding << colStr << ' '; | ||
9256 | return tp; | ||
9257 | } | ||
9258 | |||
9259 | friend TablePrinter& operator<< (TablePrinter& tp, RowBreak) { | ||
9260 | if (tp.m_currentColumn > 0) { | ||
9261 | tp.m_os << '\n'; | ||
9262 | tp.m_currentColumn = -1; | ||
9263 | } | ||
9264 | return tp; | ||
9265 | } | ||
9266 | |||
9267 | friend TablePrinter& operator<<(TablePrinter& tp, OutputFlush) { | ||
9268 | tp.m_os << std::flush; | ||
9269 | return tp; | ||
9270 | } | ||
9271 | }; | ||
9272 | |||
9273 | ConsoleReporter::ConsoleReporter(ReporterConfig&& config): | ||
9274 | StreamingReporterBase( CATCH_MOVE( config ) ), | ||
9275 | m_tablePrinter(Detail::make_unique<TablePrinter>(m_stream, | ||
9276 | [&config]() -> std::vector<ColumnInfo> { | ||
9277 | if (config.fullConfig()->benchmarkNoAnalysis()) | ||
9278 | { | ||
9279 | return{ | ||
9280 | { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, Justification::Left }, | ||
9281 | { " samples", 14, Justification::Right }, | ||
9282 | { " iterations", 14, Justification::Right }, | ||
9283 | { " mean", 14, Justification::Right } | ||
9284 | }; | ||
9285 | } | ||
9286 | else | ||
9287 | { | ||
9288 | return{ | ||
9289 | { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, Justification::Left }, | ||
9290 | { "samples mean std dev", 14, Justification::Right }, | ||
9291 | { "iterations low mean low std dev", 14, Justification::Right }, | ||
9292 | { "est run time high mean high std dev", 14, Justification::Right } | ||
9293 | }; | ||
9294 | } | ||
9295 | }())) {} | ||
9296 | ConsoleReporter::~ConsoleReporter() = default; | ||
9297 | |||
9298 | std::string ConsoleReporter::getDescription() { | ||
9299 | return "Reports test results as plain lines of text"; | ||
9300 | } | ||
9301 | |||
9302 | void ConsoleReporter::noMatchingTestCases( StringRef unmatchedSpec ) { | ||
9303 | m_stream << "No test cases matched '" << unmatchedSpec << "'\n"; | ||
9304 | } | ||
9305 | |||
9306 | void ConsoleReporter::reportInvalidTestSpec( StringRef arg ) { | ||
9307 | m_stream << "Invalid Filter: " << arg << '\n'; | ||
9308 | } | ||
9309 | |||
9310 | void ConsoleReporter::assertionStarting(AssertionInfo const&) {} | ||
9311 | |||
9312 | void ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) { | ||
9313 | AssertionResult const& result = _assertionStats.assertionResult; | ||
9314 | |||
9315 | bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); | ||
9316 | |||
9317 | // Drop out if result was successful but we're not printing them. | ||
9318 | // TODO: Make configurable whether skips should be printed | ||
9319 | if (!includeResults && result.getResultType() != ResultWas::Warning && result.getResultType() != ResultWas::ExplicitSkip) | ||
9320 | return; | ||
9321 | |||
9322 | lazyPrint(); | ||
9323 | |||
9324 | ConsoleAssertionPrinter printer(m_stream, _assertionStats, m_colour.get(), includeResults); | ||
9325 | printer.print(); | ||
9326 | m_stream << '\n' << std::flush; | ||
9327 | } | ||
9328 | |||
9329 | void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) { | ||
9330 | m_tablePrinter->close(); | ||
9331 | m_headerPrinted = false; | ||
9332 | StreamingReporterBase::sectionStarting(_sectionInfo); | ||
9333 | } | ||
9334 | void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) { | ||
9335 | m_tablePrinter->close(); | ||
9336 | if (_sectionStats.missingAssertions) { | ||
9337 | lazyPrint(); | ||
9338 | auto guard = | ||
9339 | m_colour->guardColour( Colour::ResultError ).engage( m_stream ); | ||
9340 | if (m_sectionStack.size() > 1) | ||
9341 | m_stream << "\nNo assertions in section"; | ||
9342 | else | ||
9343 | m_stream << "\nNo assertions in test case"; | ||
9344 | m_stream << " '" << _sectionStats.sectionInfo.name << "'\n\n" << std::flush; | ||
9345 | } | ||
9346 | double dur = _sectionStats.durationInSeconds; | ||
9347 | if (shouldShowDuration(*m_config, dur)) { | ||
9348 | m_stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << '\n' << std::flush; | ||
9349 | } | ||
9350 | if (m_headerPrinted) { | ||
9351 | m_headerPrinted = false; | ||
9352 | } | ||
9353 | StreamingReporterBase::sectionEnded(_sectionStats); | ||
9354 | } | ||
9355 | |||
9356 | void ConsoleReporter::benchmarkPreparing( StringRef name ) { | ||
9357 | lazyPrintWithoutClosingBenchmarkTable(); | ||
9358 | |||
9359 | auto nameCol = TextFlow::Column( static_cast<std::string>( name ) ) | ||
9360 | .width( m_tablePrinter->columnInfos()[0].width - 2 ); | ||
9361 | |||
9362 | bool firstLine = true; | ||
9363 | for (auto line : nameCol) { | ||
9364 | if (!firstLine) | ||
9365 | (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak(); | ||
9366 | else | ||
9367 | firstLine = false; | ||
9368 | |||
9369 | (*m_tablePrinter) << line << ColumnBreak(); | ||
9370 | } | ||
9371 | } | ||
9372 | |||
9373 | void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) { | ||
9374 | (*m_tablePrinter) << info.samples << ColumnBreak() | ||
9375 | << info.iterations << ColumnBreak(); | ||
9376 | if ( !m_config->benchmarkNoAnalysis() ) { | ||
9377 | ( *m_tablePrinter ) | ||
9378 | << Duration( info.estimatedDuration ) << ColumnBreak(); | ||
9379 | } | ||
9380 | ( *m_tablePrinter ) << OutputFlush{}; | ||
9381 | } | ||
9382 | void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) { | ||
9383 | if (m_config->benchmarkNoAnalysis()) | ||
9384 | { | ||
9385 | (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak(); | ||
9386 | } | ||
9387 | else | ||
9388 | { | ||
9389 | (*m_tablePrinter) << ColumnBreak() | ||
9390 | << Duration(stats.mean.point.count()) << ColumnBreak() | ||
9391 | << Duration(stats.mean.lower_bound.count()) << ColumnBreak() | ||
9392 | << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak() | ||
9393 | << Duration(stats.standardDeviation.point.count()) << ColumnBreak() | ||
9394 | << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak() | ||
9395 | << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak(); | ||
9396 | } | ||
9397 | } | ||
9398 | |||
9399 | void ConsoleReporter::benchmarkFailed( StringRef error ) { | ||
9400 | auto guard = m_colour->guardColour( Colour::Red ).engage( m_stream ); | ||
9401 | (*m_tablePrinter) | ||
9402 | << "Benchmark failed (" << error << ')' | ||
9403 | << ColumnBreak() << RowBreak(); | ||
9404 | } | ||
9405 | |||
9406 | void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) { | ||
9407 | m_tablePrinter->close(); | ||
9408 | StreamingReporterBase::testCaseEnded(_testCaseStats); | ||
9409 | m_headerPrinted = false; | ||
9410 | } | ||
9411 | void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) { | ||
9412 | printTotalsDivider(_testRunStats.totals); | ||
9413 | printTestRunTotals( m_stream, *m_colour, _testRunStats.totals ); | ||
9414 | m_stream << '\n' << std::flush; | ||
9415 | StreamingReporterBase::testRunEnded(_testRunStats); | ||
9416 | } | ||
9417 | void ConsoleReporter::testRunStarting(TestRunInfo const& _testRunInfo) { | ||
9418 | StreamingReporterBase::testRunStarting(_testRunInfo); | ||
9419 | if ( m_config->testSpec().hasFilters() ) { | ||
9420 | m_stream << m_colour->guardColour( Colour::BrightYellow ) << "Filters: " | ||
9421 | << m_config->testSpec() << '\n'; | ||
9422 | } | ||
9423 | m_stream << "Randomness seeded to: " << getSeed() << '\n'; | ||
9424 | } | ||
9425 | |||
9426 | void ConsoleReporter::lazyPrint() { | ||
9427 | |||
9428 | m_tablePrinter->close(); | ||
9429 | lazyPrintWithoutClosingBenchmarkTable(); | ||
9430 | } | ||
9431 | |||
9432 | void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() { | ||
9433 | |||
9434 | if ( !m_testRunInfoPrinted ) { | ||
9435 | lazyPrintRunInfo(); | ||
9436 | } | ||
9437 | if (!m_headerPrinted) { | ||
9438 | printTestCaseAndSectionHeader(); | ||
9439 | m_headerPrinted = true; | ||
9440 | } | ||
9441 | } | ||
9442 | void ConsoleReporter::lazyPrintRunInfo() { | ||
9443 | m_stream << '\n' | ||
9444 | << lineOfChars( '~' ) << '\n' | ||
9445 | << m_colour->guardColour( Colour::SecondaryText ) | ||
9446 | << currentTestRunInfo.name << " is a Catch2 v" << libraryVersion() | ||
9447 | << " host application.\n" | ||
9448 | << "Run with -? for options\n\n"; | ||
9449 | |||
9450 | m_testRunInfoPrinted = true; | ||
9451 | } | ||
9452 | void ConsoleReporter::printTestCaseAndSectionHeader() { | ||
9453 | assert(!m_sectionStack.empty()); | ||
9454 | printOpenHeader(currentTestCaseInfo->name); | ||
9455 | |||
9456 | if (m_sectionStack.size() > 1) { | ||
9457 | auto guard = m_colour->guardColour( Colour::Headers ).engage( m_stream ); | ||
9458 | |||
9459 | auto | ||
9460 | it = m_sectionStack.begin() + 1, // Skip first section (test case) | ||
9461 | itEnd = m_sectionStack.end(); | ||
9462 | for (; it != itEnd; ++it) | ||
9463 | printHeaderString(it->name, 2); | ||
9464 | } | ||
9465 | |||
9466 | SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; | ||
9467 | |||
9468 | |||
9469 | m_stream << lineOfChars( '-' ) << '\n' | ||
9470 | << m_colour->guardColour( Colour::FileName ) << lineInfo << '\n' | ||
9471 | << lineOfChars( '.' ) << "\n\n" | ||
9472 | << std::flush; | ||
9473 | } | ||
9474 | |||
9475 | void ConsoleReporter::printClosedHeader(std::string const& _name) { | ||
9476 | printOpenHeader(_name); | ||
9477 | m_stream << lineOfChars('.') << '\n'; | ||
9478 | } | ||
9479 | void ConsoleReporter::printOpenHeader(std::string const& _name) { | ||
9480 | m_stream << lineOfChars('-') << '\n'; | ||
9481 | { | ||
9482 | auto guard = m_colour->guardColour( Colour::Headers ).engage( m_stream ); | ||
9483 | printHeaderString(_name); | ||
9484 | } | ||
9485 | } | ||
9486 | |||
9487 | void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) { | ||
9488 | // We want to get a bit fancy with line breaking here, so that subsequent | ||
9489 | // lines start after ":" if one is present, e.g. | ||
9490 | // ``` | ||
9491 | // blablabla: Fancy | ||
9492 | // linebreaking | ||
9493 | // ``` | ||
9494 | // but we also want to avoid problems with overly long indentation causing | ||
9495 | // the text to take up too many lines, e.g. | ||
9496 | // ``` | ||
9497 | // blablabla: F | ||
9498 | // a | ||
9499 | // n | ||
9500 | // c | ||
9501 | // y | ||
9502 | // . | ||
9503 | // . | ||
9504 | // . | ||
9505 | // ``` | ||
9506 | // So we limit the prefix indentation check to first quarter of the possible | ||
9507 | // width | ||
9508 | std::size_t idx = _string.find( ": " ); | ||
9509 | if ( idx != std::string::npos && idx < CATCH_CONFIG_CONSOLE_WIDTH / 4 ) { | ||
9510 | idx += 2; | ||
9511 | } else { | ||
9512 | idx = 0; | ||
9513 | } | ||
9514 | m_stream << TextFlow::Column( _string ) | ||
9515 | .indent( indent + idx ) | ||
9516 | .initialIndent( indent ) | ||
9517 | << '\n'; | ||
9518 | } | ||
9519 | |||
9520 | void ConsoleReporter::printTotalsDivider(Totals const& totals) { | ||
9521 | if (totals.testCases.total() > 0) { | ||
9522 | std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total()); | ||
9523 | std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total()); | ||
9524 | std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total()); | ||
9525 | std::size_t skippedRatio = makeRatio(totals.testCases.skipped, totals.testCases.total()); | ||
9526 | while (failedRatio + failedButOkRatio + passedRatio + skippedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1) | ||
9527 | findMax(failedRatio, failedButOkRatio, passedRatio, skippedRatio)++; | ||
9528 | while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1) | ||
9529 | findMax(failedRatio, failedButOkRatio, passedRatio, skippedRatio)--; | ||
9530 | |||
9531 | m_stream << m_colour->guardColour( Colour::Error ) | ||
9532 | << std::string( failedRatio, '=' ) | ||
9533 | << m_colour->guardColour( Colour::ResultExpectedFailure ) | ||
9534 | << std::string( failedButOkRatio, '=' ); | ||
9535 | if ( totals.testCases.allPassed() ) { | ||
9536 | m_stream << m_colour->guardColour( Colour::ResultSuccess ) | ||
9537 | << std::string( passedRatio, '=' ); | ||
9538 | } else { | ||
9539 | m_stream << m_colour->guardColour( Colour::Success ) | ||
9540 | << std::string( passedRatio, '=' ); | ||
9541 | } | ||
9542 | m_stream << m_colour->guardColour( Colour::Skip ) | ||
9543 | << std::string( skippedRatio, '=' ); | ||
9544 | } else { | ||
9545 | m_stream << m_colour->guardColour( Colour::Warning ) | ||
9546 | << std::string( CATCH_CONFIG_CONSOLE_WIDTH - 1, '=' ); | ||
9547 | } | ||
9548 | m_stream << '\n'; | ||
9549 | } | ||
9550 | |||
9551 | } // end namespace Catch | ||
9552 | |||
9553 | #if defined(_MSC_VER) | ||
9554 | #pragma warning(pop) | ||
9555 | #endif | ||
9556 | |||
9557 | #if defined(__clang__) | ||
9558 | # pragma clang diagnostic pop | ||
9559 | #endif | ||
9560 | |||
9561 | |||
9562 | |||
9563 | |||
9564 | #include <algorithm> | ||
9565 | #include <cassert> | ||
9566 | |||
9567 | namespace Catch { | ||
9568 | namespace { | ||
9569 | struct BySectionInfo { | ||
9570 | BySectionInfo( SectionInfo const& other ): m_other( other ) {} | ||
9571 | BySectionInfo( BySectionInfo const& other ) = default; | ||
9572 | bool operator()( | ||
9573 | Detail::unique_ptr<CumulativeReporterBase::SectionNode> const& | ||
9574 | node ) const { | ||
9575 | return ( | ||
9576 | ( node->stats.sectionInfo.name == m_other.name ) && | ||
9577 | ( node->stats.sectionInfo.lineInfo == m_other.lineInfo ) ); | ||
9578 | } | ||
9579 | void operator=( BySectionInfo const& ) = delete; | ||
9580 | |||
9581 | private: | ||
9582 | SectionInfo const& m_other; | ||
9583 | }; | ||
9584 | |||
9585 | } // namespace | ||
9586 | |||
9587 | namespace Detail { | ||
9588 | AssertionOrBenchmarkResult::AssertionOrBenchmarkResult( | ||
9589 | AssertionStats const& assertion ): | ||
9590 | m_assertion( assertion ) {} | ||
9591 | |||
9592 | AssertionOrBenchmarkResult::AssertionOrBenchmarkResult( | ||
9593 | BenchmarkStats<> const& benchmark ): | ||
9594 | m_benchmark( benchmark ) {} | ||
9595 | |||
9596 | bool AssertionOrBenchmarkResult::isAssertion() const { | ||
9597 | return m_assertion.some(); | ||
9598 | } | ||
9599 | bool AssertionOrBenchmarkResult::isBenchmark() const { | ||
9600 | return m_benchmark.some(); | ||
9601 | } | ||
9602 | |||
9603 | AssertionStats const& AssertionOrBenchmarkResult::asAssertion() const { | ||
9604 | assert(m_assertion.some()); | ||
9605 | |||
9606 | return *m_assertion; | ||
9607 | } | ||
9608 | BenchmarkStats<> const& AssertionOrBenchmarkResult::asBenchmark() const { | ||
9609 | assert(m_benchmark.some()); | ||
9610 | |||
9611 | return *m_benchmark; | ||
9612 | } | ||
9613 | |||
9614 | } | ||
9615 | |||
9616 | CumulativeReporterBase::~CumulativeReporterBase() = default; | ||
9617 | |||
9618 | void CumulativeReporterBase::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) { | ||
9619 | m_sectionStack.back()->assertionsAndBenchmarks.emplace_back(benchmarkStats); | ||
9620 | } | ||
9621 | |||
9622 | void | ||
9623 | CumulativeReporterBase::sectionStarting( SectionInfo const& sectionInfo ) { | ||
9624 | // We need a copy, because SectionStats expect to take ownership | ||
9625 | SectionStats incompleteStats( SectionInfo(sectionInfo), Counts(), 0, false ); | ||
9626 | SectionNode* node; | ||
9627 | if ( m_sectionStack.empty() ) { | ||
9628 | if ( !m_rootSection ) { | ||
9629 | m_rootSection = | ||
9630 | Detail::make_unique<SectionNode>( incompleteStats ); | ||
9631 | } | ||
9632 | node = m_rootSection.get(); | ||
9633 | } else { | ||
9634 | SectionNode& parentNode = *m_sectionStack.back(); | ||
9635 | auto it = std::find_if( parentNode.childSections.begin(), | ||
9636 | parentNode.childSections.end(), | ||
9637 | BySectionInfo( sectionInfo ) ); | ||
9638 | if ( it == parentNode.childSections.end() ) { | ||
9639 | auto newNode = | ||
9640 | Detail::make_unique<SectionNode>( incompleteStats ); | ||
9641 | node = newNode.get(); | ||
9642 | parentNode.childSections.push_back( CATCH_MOVE( newNode ) ); | ||
9643 | } else { | ||
9644 | node = it->get(); | ||
9645 | } | ||
9646 | } | ||
9647 | |||
9648 | m_deepestSection = node; | ||
9649 | m_sectionStack.push_back( node ); | ||
9650 | } | ||
9651 | |||
9652 | void CumulativeReporterBase::assertionEnded( | ||
9653 | AssertionStats const& assertionStats ) { | ||
9654 | assert( !m_sectionStack.empty() ); | ||
9655 | // AssertionResult holds a pointer to a temporary DecomposedExpression, | ||
9656 | // which getExpandedExpression() calls to build the expression string. | ||
9657 | // Our section stack copy of the assertionResult will likely outlive the | ||
9658 | // temporary, so it must be expanded or discarded now to avoid calling | ||
9659 | // a destroyed object later. | ||
9660 | if ( m_shouldStoreFailedAssertions && | ||
9661 | !assertionStats.assertionResult.isOk() ) { | ||
9662 | static_cast<void>( | ||
9663 | assertionStats.assertionResult.getExpandedExpression() ); | ||
9664 | } | ||
9665 | if ( m_shouldStoreSuccesfulAssertions && | ||
9666 | assertionStats.assertionResult.isOk() ) { | ||
9667 | static_cast<void>( | ||
9668 | assertionStats.assertionResult.getExpandedExpression() ); | ||
9669 | } | ||
9670 | SectionNode& sectionNode = *m_sectionStack.back(); | ||
9671 | sectionNode.assertionsAndBenchmarks.emplace_back( assertionStats ); | ||
9672 | } | ||
9673 | |||
9674 | void CumulativeReporterBase::sectionEnded( SectionStats const& sectionStats ) { | ||
9675 | assert( !m_sectionStack.empty() ); | ||
9676 | SectionNode& node = *m_sectionStack.back(); | ||
9677 | node.stats = sectionStats; | ||
9678 | m_sectionStack.pop_back(); | ||
9679 | } | ||
9680 | |||
9681 | void CumulativeReporterBase::testCaseEnded( | ||
9682 | TestCaseStats const& testCaseStats ) { | ||
9683 | auto node = Detail::make_unique<TestCaseNode>( testCaseStats ); | ||
9684 | assert( m_sectionStack.size() == 0 ); | ||
9685 | node->children.push_back( CATCH_MOVE(m_rootSection) ); | ||
9686 | m_testCases.push_back( CATCH_MOVE(node) ); | ||
9687 | |||
9688 | assert( m_deepestSection ); | ||
9689 | m_deepestSection->stdOut = testCaseStats.stdOut; | ||
9690 | m_deepestSection->stdErr = testCaseStats.stdErr; | ||
9691 | } | ||
9692 | |||
9693 | |||
9694 | void CumulativeReporterBase::testRunEnded( TestRunStats const& testRunStats ) { | ||
9695 | assert(!m_testRun && "CumulativeReporterBase assumes there can only be one test run"); | ||
9696 | m_testRun = Detail::make_unique<TestRunNode>( testRunStats ); | ||
9697 | m_testRun->children.swap( m_testCases ); | ||
9698 | testRunEndedCumulative(); | ||
9699 | } | ||
9700 | |||
9701 | bool CumulativeReporterBase::SectionNode::hasAnyAssertions() const { | ||
9702 | return std::any_of( | ||
9703 | assertionsAndBenchmarks.begin(), | ||
9704 | assertionsAndBenchmarks.end(), | ||
9705 | []( Detail::AssertionOrBenchmarkResult const& res ) { | ||
9706 | return res.isAssertion(); | ||
9707 | } ); | ||
9708 | } | ||
9709 | |||
9710 | } // end namespace Catch | ||
9711 | |||
9712 | |||
9713 | |||
9714 | |||
9715 | namespace Catch { | ||
9716 | |||
9717 | void EventListenerBase::fatalErrorEncountered( StringRef ) {} | ||
9718 | |||
9719 | void EventListenerBase::benchmarkPreparing( StringRef ) {} | ||
9720 | void EventListenerBase::benchmarkStarting( BenchmarkInfo const& ) {} | ||
9721 | void EventListenerBase::benchmarkEnded( BenchmarkStats<> const& ) {} | ||
9722 | void EventListenerBase::benchmarkFailed( StringRef ) {} | ||
9723 | |||
9724 | void EventListenerBase::assertionStarting( AssertionInfo const& ) {} | ||
9725 | |||
9726 | void EventListenerBase::assertionEnded( AssertionStats const& ) {} | ||
9727 | void EventListenerBase::listReporters( | ||
9728 | std::vector<ReporterDescription> const& ) {} | ||
9729 | void EventListenerBase::listListeners( | ||
9730 | std::vector<ListenerDescription> const& ) {} | ||
9731 | void EventListenerBase::listTests( std::vector<TestCaseHandle> const& ) {} | ||
9732 | void EventListenerBase::listTags( std::vector<TagInfo> const& ) {} | ||
9733 | void EventListenerBase::noMatchingTestCases( StringRef ) {} | ||
9734 | void EventListenerBase::reportInvalidTestSpec( StringRef ) {} | ||
9735 | void EventListenerBase::testRunStarting( TestRunInfo const& ) {} | ||
9736 | void EventListenerBase::testCaseStarting( TestCaseInfo const& ) {} | ||
9737 | void EventListenerBase::testCasePartialStarting(TestCaseInfo const&, uint64_t) {} | ||
9738 | void EventListenerBase::sectionStarting( SectionInfo const& ) {} | ||
9739 | void EventListenerBase::sectionEnded( SectionStats const& ) {} | ||
9740 | void EventListenerBase::testCasePartialEnded(TestCaseStats const&, uint64_t) {} | ||
9741 | void EventListenerBase::testCaseEnded( TestCaseStats const& ) {} | ||
9742 | void EventListenerBase::testRunEnded( TestRunStats const& ) {} | ||
9743 | void EventListenerBase::skipTest( TestCaseInfo const& ) {} | ||
9744 | } // namespace Catch | ||
9745 | |||
9746 | |||
9747 | |||
9748 | |||
9749 | #include <algorithm> | ||
9750 | #include <cfloat> | ||
9751 | #include <cstdio> | ||
9752 | #include <ostream> | ||
9753 | #include <iomanip> | ||
9754 | |||
9755 | namespace Catch { | ||
9756 | |||
9757 | namespace { | ||
9758 | void listTestNamesOnly(std::ostream& out, | ||
9759 | std::vector<TestCaseHandle> const& tests) { | ||
9760 | for (auto const& test : tests) { | ||
9761 | auto const& testCaseInfo = test.getTestCaseInfo(); | ||
9762 | |||
9763 | if (startsWith(testCaseInfo.name, '#')) { | ||
9764 | out << '"' << testCaseInfo.name << '"'; | ||
9765 | } else { | ||
9766 | out << testCaseInfo.name; | ||
9767 | } | ||
9768 | |||
9769 | out << '\n'; | ||
9770 | } | ||
9771 | out << std::flush; | ||
9772 | } | ||
9773 | } // end unnamed namespace | ||
9774 | |||
9775 | |||
9776 | // Because formatting using c++ streams is stateful, drop down to C is | ||
9777 | // required Alternatively we could use stringstream, but its performance | ||
9778 | // is... not good. | ||
9779 | std::string getFormattedDuration( double duration ) { | ||
9780 | // Max exponent + 1 is required to represent the whole part | ||
9781 | // + 1 for decimal point | ||
9782 | // + 3 for the 3 decimal places | ||
9783 | // + 1 for null terminator | ||
9784 | const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; | ||
9785 | char buffer[maxDoubleSize]; | ||
9786 | |||
9787 | // Save previous errno, to prevent sprintf from overwriting it | ||
9788 | ErrnoGuard guard; | ||
9789 | #ifdef _MSC_VER | ||
9790 | size_t printedLength = static_cast<size_t>( | ||
9791 | sprintf_s( buffer, "%.3f", duration ) ); | ||
9792 | #else | ||
9793 | size_t printedLength = static_cast<size_t>( | ||
9794 | std::snprintf( buffer, maxDoubleSize, "%.3f", duration ) ); | ||
9795 | #endif | ||
9796 | return std::string( buffer, printedLength ); | ||
9797 | } | ||
9798 | |||
9799 | bool shouldShowDuration( IConfig const& config, double duration ) { | ||
9800 | if ( config.showDurations() == ShowDurations::Always ) { | ||
9801 | return true; | ||
9802 | } | ||
9803 | if ( config.showDurations() == ShowDurations::Never ) { | ||
9804 | return false; | ||
9805 | } | ||
9806 | const double min = config.minDuration(); | ||
9807 | return min >= 0 && duration >= min; | ||
9808 | } | ||
9809 | |||
9810 | std::string serializeFilters( std::vector<std::string> const& filters ) { | ||
9811 | // We add a ' ' separator between each filter | ||
9812 | size_t serialized_size = filters.size() - 1; | ||
9813 | for (auto const& filter : filters) { | ||
9814 | serialized_size += filter.size(); | ||
9815 | } | ||
9816 | |||
9817 | std::string serialized; | ||
9818 | serialized.reserve(serialized_size); | ||
9819 | bool first = true; | ||
9820 | |||
9821 | for (auto const& filter : filters) { | ||
9822 | if (!first) { | ||
9823 | serialized.push_back(' '); | ||
9824 | } | ||
9825 | first = false; | ||
9826 | serialized.append(filter); | ||
9827 | } | ||
9828 | |||
9829 | return serialized; | ||
9830 | } | ||
9831 | |||
9832 | std::ostream& operator<<( std::ostream& out, lineOfChars value ) { | ||
9833 | for ( size_t idx = 0; idx < CATCH_CONFIG_CONSOLE_WIDTH - 1; ++idx ) { | ||
9834 | out.put( value.c ); | ||
9835 | } | ||
9836 | return out; | ||
9837 | } | ||
9838 | |||
9839 | void | ||
9840 | defaultListReporters( std::ostream& out, | ||
9841 | std::vector<ReporterDescription> const& descriptions, | ||
9842 | Verbosity verbosity ) { | ||
9843 | out << "Available reporters:\n"; | ||
9844 | const auto maxNameLen = | ||
9845 | std::max_element( descriptions.begin(), | ||
9846 | descriptions.end(), | ||
9847 | []( ReporterDescription const& lhs, | ||
9848 | ReporterDescription const& rhs ) { | ||
9849 | return lhs.name.size() < rhs.name.size(); | ||
9850 | } ) | ||
9851 | ->name.size(); | ||
9852 | |||
9853 | for ( auto const& desc : descriptions ) { | ||
9854 | if ( verbosity == Verbosity::Quiet ) { | ||
9855 | out << TextFlow::Column( desc.name ) | ||
9856 | .indent( 2 ) | ||
9857 | .width( 5 + maxNameLen ) | ||
9858 | << '\n'; | ||
9859 | } else { | ||
9860 | out << TextFlow::Column( desc.name + ':' ) | ||
9861 | .indent( 2 ) | ||
9862 | .width( 5 + maxNameLen ) + | ||
9863 | TextFlow::Column( desc.description ) | ||
9864 | .initialIndent( 0 ) | ||
9865 | .indent( 2 ) | ||
9866 | .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 ) | ||
9867 | << '\n'; | ||
9868 | } | ||
9869 | } | ||
9870 | out << '\n' << std::flush; | ||
9871 | } | ||
9872 | |||
9873 | void defaultListListeners( std::ostream& out, | ||
9874 | std::vector<ListenerDescription> const& descriptions ) { | ||
9875 | out << "Registered listeners:\n"; | ||
9876 | |||
9877 | if(descriptions.empty()) { | ||
9878 | return; | ||
9879 | } | ||
9880 | |||
9881 | const auto maxNameLen = | ||
9882 | std::max_element( descriptions.begin(), | ||
9883 | descriptions.end(), | ||
9884 | []( ListenerDescription const& lhs, | ||
9885 | ListenerDescription const& rhs ) { | ||
9886 | return lhs.name.size() < rhs.name.size(); | ||
9887 | } ) | ||
9888 | ->name.size(); | ||
9889 | |||
9890 | for ( auto const& desc : descriptions ) { | ||
9891 | out << TextFlow::Column( static_cast<std::string>( desc.name ) + | ||
9892 | ':' ) | ||
9893 | .indent( 2 ) | ||
9894 | .width( maxNameLen + 5 ) + | ||
9895 | TextFlow::Column( desc.description ) | ||
9896 | .initialIndent( 0 ) | ||
9897 | .indent( 2 ) | ||
9898 | .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 ) | ||
9899 | << '\n'; | ||
9900 | } | ||
9901 | |||
9902 | out << '\n' << std::flush; | ||
9903 | } | ||
9904 | |||
9905 | void defaultListTags( std::ostream& out, | ||
9906 | std::vector<TagInfo> const& tags, | ||
9907 | bool isFiltered ) { | ||
9908 | if ( isFiltered ) { | ||
9909 | out << "Tags for matching test cases:\n"; | ||
9910 | } else { | ||
9911 | out << "All available tags:\n"; | ||
9912 | } | ||
9913 | |||
9914 | for ( auto const& tagCount : tags ) { | ||
9915 | ReusableStringStream rss; | ||
9916 | rss << " " << std::setw( 2 ) << tagCount.count << " "; | ||
9917 | auto str = rss.str(); | ||
9918 | auto wrapper = TextFlow::Column( tagCount.all() ) | ||
9919 | .initialIndent( 0 ) | ||
9920 | .indent( str.size() ) | ||
9921 | .width( CATCH_CONFIG_CONSOLE_WIDTH - 10 ); | ||
9922 | out << str << wrapper << '\n'; | ||
9923 | } | ||
9924 | out << pluralise(tags.size(), "tag"_sr) << "\n\n" << std::flush; | ||
9925 | } | ||
9926 | |||
9927 | void defaultListTests(std::ostream& out, ColourImpl* streamColour, std::vector<TestCaseHandle> const& tests, bool isFiltered, Verbosity verbosity) { | ||
9928 | // We special case this to provide the equivalent of old | ||
9929 | // `--list-test-names-only`, which could then be used by the | ||
9930 | // `--input-file` option. | ||
9931 | if (verbosity == Verbosity::Quiet) { | ||
9932 | listTestNamesOnly(out, tests); | ||
9933 | return; | ||
9934 | } | ||
9935 | |||
9936 | if (isFiltered) { | ||
9937 | out << "Matching test cases:\n"; | ||
9938 | } else { | ||
9939 | out << "All available test cases:\n"; | ||
9940 | } | ||
9941 | |||
9942 | for (auto const& test : tests) { | ||
9943 | auto const& testCaseInfo = test.getTestCaseInfo(); | ||
9944 | Colour::Code colour = testCaseInfo.isHidden() | ||
9945 | ? Colour::SecondaryText | ||
9946 | : Colour::None; | ||
9947 | auto colourGuard = streamColour->guardColour( colour ).engage( out ); | ||
9948 | |||
9949 | out << TextFlow::Column(testCaseInfo.name).indent(2) << '\n'; | ||
9950 | if (verbosity >= Verbosity::High) { | ||
9951 | out << TextFlow::Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4) << '\n'; | ||
9952 | } | ||
9953 | if (!testCaseInfo.tags.empty() && | ||
9954 | verbosity > Verbosity::Quiet) { | ||
9955 | out << TextFlow::Column(testCaseInfo.tagsAsString()).indent(6) << '\n'; | ||
9956 | } | ||
9957 | } | ||
9958 | |||
9959 | if (isFiltered) { | ||
9960 | out << pluralise(tests.size(), "matching test case"_sr); | ||
9961 | } else { | ||
9962 | out << pluralise(tests.size(), "test case"_sr); | ||
9963 | } | ||
9964 | out << "\n\n" << std::flush; | ||
9965 | } | ||
9966 | |||
9967 | namespace { | ||
9968 | class SummaryColumn { | ||
9969 | public: | ||
9970 | SummaryColumn( std::string suffix, Colour::Code colour ): | ||
9971 | m_suffix( CATCH_MOVE( suffix ) ), m_colour( colour ) {} | ||
9972 | |||
9973 | SummaryColumn&& addRow( std::uint64_t count ) && { | ||
9974 | std::string row = std::to_string(count); | ||
9975 | auto const new_width = std::max( m_width, row.size() ); | ||
9976 | if ( new_width > m_width ) { | ||
9977 | for ( auto& oldRow : m_rows ) { | ||
9978 | oldRow.insert( 0, new_width - m_width, ' ' ); | ||
9979 | } | ||
9980 | } else { | ||
9981 | row.insert( 0, m_width - row.size(), ' ' ); | ||
9982 | } | ||
9983 | m_width = new_width; | ||
9984 | m_rows.push_back( row ); | ||
9985 | return std::move( *this ); | ||
9986 | } | ||
9987 | |||
9988 | std::string const& getSuffix() const { return m_suffix; } | ||
9989 | Colour::Code getColour() const { return m_colour; } | ||
9990 | std::string const& getRow( std::size_t index ) const { | ||
9991 | return m_rows[index]; | ||
9992 | } | ||
9993 | |||
9994 | private: | ||
9995 | std::string m_suffix; | ||
9996 | Colour::Code m_colour; | ||
9997 | std::size_t m_width = 0; | ||
9998 | std::vector<std::string> m_rows; | ||
9999 | }; | ||
10000 | |||
10001 | void printSummaryRow( std::ostream& stream, | ||
10002 | ColourImpl& colour, | ||
10003 | StringRef label, | ||
10004 | std::vector<SummaryColumn> const& cols, | ||
10005 | std::size_t row ) { | ||
10006 | for ( auto const& col : cols ) { | ||
10007 | auto const& value = col.getRow( row ); | ||
10008 | auto const& suffix = col.getSuffix(); | ||
10009 | if ( suffix.empty() ) { | ||
10010 | stream << label << ": "; | ||
10011 | if ( value != "0" ) { | ||
10012 | stream << value; | ||
10013 | } else { | ||
10014 | stream << colour.guardColour( Colour::Warning ) | ||
10015 | << "- none -"; | ||
10016 | } | ||
10017 | } else if ( value != "0" ) { | ||
10018 | stream << colour.guardColour( Colour::LightGrey ) << " | " | ||
10019 | << colour.guardColour( col.getColour() ) << value | ||
10020 | << ' ' << suffix; | ||
10021 | } | ||
10022 | } | ||
10023 | stream << '\n'; | ||
10024 | } | ||
10025 | } // namespace | ||
10026 | |||
10027 | void printTestRunTotals( std::ostream& stream, | ||
10028 | ColourImpl& streamColour, | ||
10029 | Totals const& totals ) { | ||
10030 | if ( totals.testCases.total() == 0 ) { | ||
10031 | stream << streamColour.guardColour( Colour::Warning ) | ||
10032 | << "No tests ran\n"; | ||
10033 | return; | ||
10034 | } | ||
10035 | |||
10036 | if ( totals.assertions.total() > 0 && totals.testCases.allPassed() ) { | ||
10037 | stream << streamColour.guardColour( Colour::ResultSuccess ) | ||
10038 | << "All tests passed"; | ||
10039 | stream << " (" | ||
10040 | << pluralise( totals.assertions.passed, "assertion"_sr ) | ||
10041 | << " in " | ||
10042 | << pluralise( totals.testCases.passed, "test case"_sr ) | ||
10043 | << ')' << '\n'; | ||
10044 | return; | ||
10045 | } | ||
10046 | |||
10047 | std::vector<SummaryColumn> columns; | ||
10048 | // Don't include "skipped assertions" in total count | ||
10049 | const auto totalAssertionCount = | ||
10050 | totals.assertions.total() - totals.assertions.skipped; | ||
10051 | columns.push_back( SummaryColumn( "", Colour::None ) | ||
10052 | .addRow( totals.testCases.total() ) | ||
10053 | .addRow( totalAssertionCount ) ); | ||
10054 | columns.push_back( SummaryColumn( "passed", Colour::Success ) | ||
10055 | .addRow( totals.testCases.passed ) | ||
10056 | .addRow( totals.assertions.passed ) ); | ||
10057 | columns.push_back( SummaryColumn( "failed", Colour::ResultError ) | ||
10058 | .addRow( totals.testCases.failed ) | ||
10059 | .addRow( totals.assertions.failed ) ); | ||
10060 | columns.push_back( SummaryColumn( "skipped", Colour::Skip ) | ||
10061 | .addRow( totals.testCases.skipped ) | ||
10062 | // Don't print "skipped assertions" | ||
10063 | .addRow( 0 ) ); | ||
10064 | columns.push_back( | ||
10065 | SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) | ||
10066 | .addRow( totals.testCases.failedButOk ) | ||
10067 | .addRow( totals.assertions.failedButOk ) ); | ||
10068 | printSummaryRow( stream, streamColour, "test cases"_sr, columns, 0 ); | ||
10069 | printSummaryRow( stream, streamColour, "assertions"_sr, columns, 1 ); | ||
10070 | } | ||
10071 | |||
10072 | } // namespace Catch | ||
10073 | |||
10074 | |||
10075 | // | ||
10076 | |||
10077 | namespace Catch { | ||
10078 | namespace { | ||
10079 | void writeSourceInfo( JsonObjectWriter& writer, | ||
10080 | SourceLineInfo const& sourceInfo ) { | ||
10081 | auto source_location_writer = | ||
10082 | writer.write( "source-location"_sr ).writeObject(); | ||
10083 | source_location_writer.write( "filename"_sr ) | ||
10084 | .write( sourceInfo.file ); | ||
10085 | source_location_writer.write( "line"_sr ).write( sourceInfo.line ); | ||
10086 | } | ||
10087 | |||
10088 | void writeTags( JsonArrayWriter writer, std::vector<Tag> const& tags ) { | ||
10089 | for ( auto const& tag : tags ) { | ||
10090 | writer.write( tag.original ); | ||
10091 | } | ||
10092 | } | ||
10093 | |||
10094 | void writeProperties( JsonArrayWriter writer, | ||
10095 | TestCaseInfo const& info ) { | ||
10096 | if ( info.isHidden() ) { writer.write( "is-hidden"_sr ); } | ||
10097 | if ( info.okToFail() ) { writer.write( "ok-to-fail"_sr ); } | ||
10098 | if ( info.expectedToFail() ) { | ||
10099 | writer.write( "expected-to-fail"_sr ); | ||
10100 | } | ||
10101 | if ( info.throws() ) { writer.write( "throws"_sr ); } | ||
10102 | } | ||
10103 | |||
10104 | } // namespace | ||
10105 | |||
10106 | JsonReporter::JsonReporter( ReporterConfig&& config ): | ||
10107 | StreamingReporterBase{ CATCH_MOVE( config ) } { | ||
10108 | |||
10109 | m_preferences.shouldRedirectStdOut = true; | ||
10110 | // TBD: Do we want to report all assertions? XML reporter does | ||
10111 | // not, but for machine-parseable reporters I think the answer | ||
10112 | // should be yes. | ||
10113 | m_preferences.shouldReportAllAssertions = true; | ||
10114 | |||
10115 | m_objectWriters.emplace( m_stream ); | ||
10116 | m_writers.emplace( Writer::Object ); | ||
10117 | auto& writer = m_objectWriters.top(); | ||
10118 | |||
10119 | writer.write( "version"_sr ).write( 1 ); | ||
10120 | |||
10121 | { | ||
10122 | auto metadata_writer = writer.write( "metadata"_sr ).writeObject(); | ||
10123 | metadata_writer.write( "name"_sr ).write( m_config->name() ); | ||
10124 | metadata_writer.write( "rng-seed"_sr ).write( m_config->rngSeed() ); | ||
10125 | metadata_writer.write( "catch2-version"_sr ) | ||
10126 | .write( libraryVersion() ); | ||
10127 | if ( m_config->testSpec().hasFilters() ) { | ||
10128 | metadata_writer.write( "filters"_sr ) | ||
10129 | .write( m_config->testSpec() ); | ||
10130 | } | ||
10131 | } | ||
10132 | } | ||
10133 | |||
10134 | JsonReporter::~JsonReporter() { | ||
10135 | endListing(); | ||
10136 | // TODO: Ensure this closes the top level object, add asserts | ||
10137 | assert( m_writers.size() == 1 && "Only the top level object should be open" ); | ||
10138 | assert( m_writers.top() == Writer::Object ); | ||
10139 | endObject(); | ||
10140 | m_stream << '\n' << std::flush; | ||
10141 | assert( m_writers.empty() ); | ||
10142 | } | ||
10143 | |||
10144 | JsonArrayWriter& JsonReporter::startArray() { | ||
10145 | m_arrayWriters.emplace( m_arrayWriters.top().writeArray() ); | ||
10146 | m_writers.emplace( Writer::Array ); | ||
10147 | return m_arrayWriters.top(); | ||
10148 | } | ||
10149 | JsonArrayWriter& JsonReporter::startArray( StringRef key ) { | ||
10150 | m_arrayWriters.emplace( | ||
10151 | m_objectWriters.top().write( key ).writeArray() ); | ||
10152 | m_writers.emplace( Writer::Array ); | ||
10153 | return m_arrayWriters.top(); | ||
10154 | } | ||
10155 | |||
10156 | JsonObjectWriter& JsonReporter::startObject() { | ||
10157 | m_objectWriters.emplace( m_arrayWriters.top().writeObject() ); | ||
10158 | m_writers.emplace( Writer::Object ); | ||
10159 | return m_objectWriters.top(); | ||
10160 | } | ||
10161 | JsonObjectWriter& JsonReporter::startObject( StringRef key ) { | ||
10162 | m_objectWriters.emplace( | ||
10163 | m_objectWriters.top().write( key ).writeObject() ); | ||
10164 | m_writers.emplace( Writer::Object ); | ||
10165 | return m_objectWriters.top(); | ||
10166 | } | ||
10167 | |||
10168 | void JsonReporter::endObject() { | ||
10169 | assert( isInside( Writer::Object ) ); | ||
10170 | m_objectWriters.pop(); | ||
10171 | m_writers.pop(); | ||
10172 | } | ||
10173 | void JsonReporter::endArray() { | ||
10174 | assert( isInside( Writer::Array ) ); | ||
10175 | m_arrayWriters.pop(); | ||
10176 | m_writers.pop(); | ||
10177 | } | ||
10178 | |||
10179 | bool JsonReporter::isInside( Writer writer ) { | ||
10180 | return !m_writers.empty() && m_writers.top() == writer; | ||
10181 | } | ||
10182 | |||
10183 | void JsonReporter::startListing() { | ||
10184 | if ( !m_startedListing ) { startObject( "listings"_sr ); } | ||
10185 | m_startedListing = true; | ||
10186 | } | ||
10187 | void JsonReporter::endListing() { | ||
10188 | if ( m_startedListing ) { endObject(); } | ||
10189 | m_startedListing = false; | ||
10190 | } | ||
10191 | |||
10192 | std::string JsonReporter::getDescription() { | ||
10193 | return "Outputs listings as JSON. Test listing is Work-in-Progress!"; | ||
10194 | } | ||
10195 | |||
10196 | void JsonReporter::testRunStarting( TestRunInfo const& runInfo ) { | ||
10197 | StreamingReporterBase::testRunStarting( runInfo ); | ||
10198 | endListing(); | ||
10199 | |||
10200 | assert( isInside( Writer::Object ) ); | ||
10201 | startObject( "test-run"_sr ); | ||
10202 | startArray( "test-cases"_sr ); | ||
10203 | } | ||
10204 | |||
10205 | static void writeCounts( JsonObjectWriter&& writer, Counts const& counts ) { | ||
10206 | writer.write( "passed"_sr ).write( counts.passed ); | ||
10207 | writer.write( "failed"_sr ).write( counts.failed ); | ||
10208 | writer.write( "fail-but-ok"_sr ).write( counts.failedButOk ); | ||
10209 | writer.write( "skipped"_sr ).write( counts.skipped ); | ||
10210 | } | ||
10211 | |||
10212 | void JsonReporter::testRunEnded(TestRunStats const& runStats) { | ||
10213 | assert( isInside( Writer::Array ) ); | ||
10214 | // End "test-cases" | ||
10215 | endArray(); | ||
10216 | |||
10217 | { | ||
10218 | auto totals = | ||
10219 | m_objectWriters.top().write( "totals"_sr ).writeObject(); | ||
10220 | writeCounts( totals.write( "assertions"_sr ).writeObject(), | ||
10221 | runStats.totals.assertions ); | ||
10222 | writeCounts( totals.write( "test-cases"_sr ).writeObject(), | ||
10223 | runStats.totals.testCases ); | ||
10224 | } | ||
10225 | |||
10226 | // End the "test-run" object | ||
10227 | endObject(); | ||
10228 | } | ||
10229 | |||
10230 | void JsonReporter::testCaseStarting( TestCaseInfo const& tcInfo ) { | ||
10231 | StreamingReporterBase::testCaseStarting( tcInfo ); | ||
10232 | |||
10233 | assert( isInside( Writer::Array ) && | ||
10234 | "We should be in the 'test-cases' array" ); | ||
10235 | startObject(); | ||
10236 | // "test-info" prelude | ||
10237 | { | ||
10238 | auto testInfo = | ||
10239 | m_objectWriters.top().write( "test-info"_sr ).writeObject(); | ||
10240 | // TODO: handle testName vs className!! | ||
10241 | testInfo.write( "name"_sr ).write( tcInfo.name ); | ||
10242 | writeSourceInfo(testInfo, tcInfo.lineInfo); | ||
10243 | writeTags( testInfo.write( "tags"_sr ).writeArray(), tcInfo.tags ); | ||
10244 | writeProperties( testInfo.write( "properties"_sr ).writeArray(), | ||
10245 | tcInfo ); | ||
10246 | } | ||
10247 | |||
10248 | |||
10249 | // Start the array for individual test runs (testCasePartial pairs) | ||
10250 | startArray( "runs"_sr ); | ||
10251 | } | ||
10252 | |||
10253 | void JsonReporter::testCaseEnded( TestCaseStats const& tcStats ) { | ||
10254 | StreamingReporterBase::testCaseEnded( tcStats ); | ||
10255 | |||
10256 | // We need to close the 'runs' array before finishing the test case | ||
10257 | assert( isInside( Writer::Array ) ); | ||
10258 | endArray(); | ||
10259 | |||
10260 | { | ||
10261 | auto totals = | ||
10262 | m_objectWriters.top().write( "totals"_sr ).writeObject(); | ||
10263 | writeCounts( totals.write( "assertions"_sr ).writeObject(), | ||
10264 | tcStats.totals.assertions ); | ||
10265 | // We do not write the test case totals, because there will always be just one test case here. | ||
10266 | // TODO: overall "result" -> success, skip, fail here? Or in partial result? | ||
10267 | } | ||
10268 | // We do not write out stderr/stdout, because we instead wrote those out in partial runs | ||
10269 | |||
10270 | // TODO: aborting? | ||
10271 | |||
10272 | // And we also close this test case's object | ||
10273 | assert( isInside( Writer::Object ) ); | ||
10274 | endObject(); | ||
10275 | } | ||
10276 | |||
10277 | void JsonReporter::testCasePartialStarting( TestCaseInfo const& /*tcInfo*/, | ||
10278 | uint64_t index ) { | ||
10279 | startObject(); | ||
10280 | m_objectWriters.top().write( "run-idx"_sr ).write( index ); | ||
10281 | startArray( "path"_sr ); | ||
10282 | // TODO: we want to delay most of the printing to the 'root' section | ||
10283 | // TODO: childSection key name? | ||
10284 | } | ||
10285 | |||
10286 | void JsonReporter::testCasePartialEnded( TestCaseStats const& tcStats, | ||
10287 | uint64_t /*index*/ ) { | ||
10288 | // Fixme: the top level section handles this. | ||
10289 | //// path object | ||
10290 | endArray(); | ||
10291 | if ( !tcStats.stdOut.empty() ) { | ||
10292 | m_objectWriters.top() | ||
10293 | .write( "captured-stdout"_sr ) | ||
10294 | .write( tcStats.stdOut ); | ||
10295 | } | ||
10296 | if ( !tcStats.stdErr.empty() ) { | ||
10297 | m_objectWriters.top() | ||
10298 | .write( "captured-stderr"_sr ) | ||
10299 | .write( tcStats.stdErr ); | ||
10300 | } | ||
10301 | { | ||
10302 | auto totals = | ||
10303 | m_objectWriters.top().write( "totals"_sr ).writeObject(); | ||
10304 | writeCounts( totals.write( "assertions"_sr ).writeObject(), | ||
10305 | tcStats.totals.assertions ); | ||
10306 | // We do not write the test case totals, because there will | ||
10307 | // always be just one test case here. | ||
10308 | // TODO: overall "result" -> success, skip, fail here? Or in | ||
10309 | // partial result? | ||
10310 | } | ||
10311 | // TODO: aborting? | ||
10312 | // run object | ||
10313 | endObject(); | ||
10314 | } | ||
10315 | |||
10316 | void JsonReporter::sectionStarting( SectionInfo const& sectionInfo ) { | ||
10317 | assert( isInside( Writer::Array ) && | ||
10318 | "Section should always start inside an object" ); | ||
10319 | // We want to nest top level sections, even though it shares name | ||
10320 | // and source loc with the TEST_CASE | ||
10321 | auto& sectionObject = startObject(); | ||
10322 | sectionObject.write( "kind"_sr ).write( "section"_sr ); | ||
10323 | sectionObject.write( "name"_sr ).write( sectionInfo.name ); | ||
10324 | writeSourceInfo( m_objectWriters.top(), sectionInfo.lineInfo ); | ||
10325 | |||
10326 | |||
10327 | // TBD: Do we want to create this event lazily? It would become | ||
10328 | // rather complex, but we could do it, and it would look | ||
10329 | // better for empty sections. OTOH, empty sections should | ||
10330 | // be rare. | ||
10331 | startArray( "path"_sr ); | ||
10332 | } | ||
10333 | void JsonReporter::sectionEnded( SectionStats const& /*sectionStats */) { | ||
10334 | // End the subpath array | ||
10335 | endArray(); | ||
10336 | // TODO: metadata | ||
10337 | // TODO: what info do we have here? | ||
10338 | |||
10339 | // End the section object | ||
10340 | endObject(); | ||
10341 | } | ||
10342 | |||
10343 | void JsonReporter::assertionStarting( AssertionInfo const& /*assertionInfo*/ ) {} | ||
10344 | void JsonReporter::assertionEnded( AssertionStats const& assertionStats ) { | ||
10345 | // TODO: There is lot of different things to handle here, but | ||
10346 | // we can fill it in later, after we show that the basic | ||
10347 | // outline and streaming reporter impl works well enough. | ||
10348 | //if ( !m_config->includeSuccessfulResults() | ||
10349 | // && assertionStats.assertionResult.isOk() ) { | ||
10350 | // return; | ||
10351 | //} | ||
10352 | assert( isInside( Writer::Array ) ); | ||
10353 | auto assertionObject = m_arrayWriters.top().writeObject(); | ||
10354 | |||
10355 | assertionObject.write( "kind"_sr ).write( "assertion"_sr ); | ||
10356 | writeSourceInfo( assertionObject, | ||
10357 | assertionStats.assertionResult.getSourceInfo() ); | ||
10358 | assertionObject.write( "status"_sr ) | ||
10359 | .write( assertionStats.assertionResult.isOk() ); | ||
10360 | // TODO: handling of result. | ||
10361 | // TODO: messages | ||
10362 | // TODO: totals? | ||
10363 | } | ||
10364 | |||
10365 | |||
10366 | void JsonReporter::benchmarkPreparing( StringRef name ) { (void)name; } | ||
10367 | void JsonReporter::benchmarkStarting( BenchmarkInfo const& ) {} | ||
10368 | void JsonReporter::benchmarkEnded( BenchmarkStats<> const& ) {} | ||
10369 | void JsonReporter::benchmarkFailed( StringRef error ) { (void)error; } | ||
10370 | |||
10371 | void JsonReporter::listReporters( | ||
10372 | std::vector<ReporterDescription> const& descriptions ) { | ||
10373 | startListing(); | ||
10374 | |||
10375 | auto writer = | ||
10376 | m_objectWriters.top().write( "reporters"_sr ).writeArray(); | ||
10377 | for ( auto const& desc : descriptions ) { | ||
10378 | auto desc_writer = writer.writeObject(); | ||
10379 | desc_writer.write( "name"_sr ).write( desc.name ); | ||
10380 | desc_writer.write( "description"_sr ).write( desc.description ); | ||
10381 | } | ||
10382 | } | ||
10383 | void JsonReporter::listListeners( | ||
10384 | std::vector<ListenerDescription> const& descriptions ) { | ||
10385 | startListing(); | ||
10386 | |||
10387 | auto writer = | ||
10388 | m_objectWriters.top().write( "listeners"_sr ).writeArray(); | ||
10389 | |||
10390 | for ( auto const& desc : descriptions ) { | ||
10391 | auto desc_writer = writer.writeObject(); | ||
10392 | desc_writer.write( "name"_sr ).write( desc.name ); | ||
10393 | desc_writer.write( "description"_sr ).write( desc.description ); | ||
10394 | } | ||
10395 | } | ||
10396 | void JsonReporter::listTests( std::vector<TestCaseHandle> const& tests ) { | ||
10397 | startListing(); | ||
10398 | |||
10399 | auto writer = m_objectWriters.top().write( "tests"_sr ).writeArray(); | ||
10400 | |||
10401 | for ( auto const& test : tests ) { | ||
10402 | auto desc_writer = writer.writeObject(); | ||
10403 | auto const& info = test.getTestCaseInfo(); | ||
10404 | |||
10405 | desc_writer.write( "name"_sr ).write( info.name ); | ||
10406 | desc_writer.write( "class-name"_sr ).write( info.className ); | ||
10407 | { | ||
10408 | auto tag_writer = desc_writer.write( "tags"_sr ).writeArray(); | ||
10409 | for ( auto const& tag : info.tags ) { | ||
10410 | tag_writer.write( tag.original ); | ||
10411 | } | ||
10412 | } | ||
10413 | writeSourceInfo( desc_writer, info.lineInfo ); | ||
10414 | } | ||
10415 | } | ||
10416 | void JsonReporter::listTags( std::vector<TagInfo> const& tags ) { | ||
10417 | startListing(); | ||
10418 | |||
10419 | auto writer = m_objectWriters.top().write( "tags"_sr ).writeArray(); | ||
10420 | for ( auto const& tag : tags ) { | ||
10421 | auto tag_writer = writer.writeObject(); | ||
10422 | { | ||
10423 | auto aliases_writer = | ||
10424 | tag_writer.write( "aliases"_sr ).writeArray(); | ||
10425 | for ( auto alias : tag.spellings ) { | ||
10426 | aliases_writer.write( alias ); | ||
10427 | } | ||
10428 | } | ||
10429 | tag_writer.write( "count"_sr ).write( tag.count ); | ||
10430 | } | ||
10431 | } | ||
10432 | } // namespace Catch | ||
10433 | |||
10434 | |||
10435 | |||
10436 | |||
10437 | #include <cassert> | ||
10438 | #include <ctime> | ||
10439 | #include <algorithm> | ||
10440 | #include <iomanip> | ||
10441 | |||
10442 | namespace Catch { | ||
10443 | |||
10444 | namespace { | ||
10445 | std::string getCurrentTimestamp() { | ||
10446 | time_t rawtime; | ||
10447 | std::time(&rawtime); | ||
10448 | |||
10449 | std::tm timeInfo = {}; | ||
10450 | #if defined (_MSC_VER) || defined (__MINGW32__) | ||
10451 | gmtime_s(&timeInfo, &rawtime); | ||
10452 | #elif defined (CATCH_PLATFORM_PLAYSTATION) | ||
10453 | gmtime_s(&rawtime, &timeInfo); | ||
10454 | #elif defined (__IAR_SYSTEMS_ICC__) | ||
10455 | timeInfo = *std::gmtime(&rawtime); | ||
10456 | #else | ||
10457 | gmtime_r(&rawtime, &timeInfo); | ||
10458 | #endif | ||
10459 | |||
10460 | auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); | ||
10461 | char timeStamp[timeStampSize]; | ||
10462 | const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; | ||
10463 | |||
10464 | std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); | ||
10465 | |||
10466 | return std::string(timeStamp, timeStampSize - 1); | ||
10467 | } | ||
10468 | |||
10469 | std::string fileNameTag(std::vector<Tag> const& tags) { | ||
10470 | auto it = std::find_if(begin(tags), | ||
10471 | end(tags), | ||
10472 | [] (Tag const& tag) { | ||
10473 | return tag.original.size() > 0 | ||
10474 | && tag.original[0] == '#'; }); | ||
10475 | if (it != tags.end()) { | ||
10476 | return static_cast<std::string>( | ||
10477 | it->original.substr(1, it->original.size() - 1) | ||
10478 | ); | ||
10479 | } | ||
10480 | return std::string(); | ||
10481 | } | ||
10482 | |||
10483 | // Formats the duration in seconds to 3 decimal places. | ||
10484 | // This is done because some genius defined Maven Surefire schema | ||
10485 | // in a way that only accepts 3 decimal places, and tools like | ||
10486 | // Jenkins use that schema for validation JUnit reporter output. | ||
10487 | std::string formatDuration( double seconds ) { | ||
10488 | ReusableStringStream rss; | ||
10489 | rss << std::fixed << std::setprecision( 3 ) << seconds; | ||
10490 | return rss.str(); | ||
10491 | } | ||
10492 | |||
10493 | static void normalizeNamespaceMarkers(std::string& str) { | ||
10494 | std::size_t pos = str.find( "::" ); | ||
10495 | while ( pos != std::string::npos ) { | ||
10496 | str.replace( pos, 2, "." ); | ||
10497 | pos += 1; | ||
10498 | pos = str.find( "::", pos ); | ||
10499 | } | ||
10500 | } | ||
10501 | |||
10502 | } // anonymous namespace | ||
10503 | |||
10504 | JunitReporter::JunitReporter( ReporterConfig&& _config ) | ||
10505 | : CumulativeReporterBase( CATCH_MOVE(_config) ), | ||
10506 | xml( m_stream ) | ||
10507 | { | ||
10508 | m_preferences.shouldRedirectStdOut = true; | ||
10509 | m_preferences.shouldReportAllAssertions = false; | ||
10510 | m_shouldStoreSuccesfulAssertions = false; | ||
10511 | } | ||
10512 | |||
10513 | std::string JunitReporter::getDescription() { | ||
10514 | return "Reports test results in an XML format that looks like Ant's junitreport target"; | ||
10515 | } | ||
10516 | |||
10517 | void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) { | ||
10518 | CumulativeReporterBase::testRunStarting( runInfo ); | ||
10519 | xml.startElement( "testsuites" ); | ||
10520 | suiteTimer.start(); | ||
10521 | stdOutForSuite.clear(); | ||
10522 | stdErrForSuite.clear(); | ||
10523 | unexpectedExceptions = 0; | ||
10524 | } | ||
10525 | |||
10526 | void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) { | ||
10527 | m_okToFail = testCaseInfo.okToFail(); | ||
10528 | } | ||
10529 | |||
10530 | void JunitReporter::assertionEnded( AssertionStats const& assertionStats ) { | ||
10531 | if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) | ||
10532 | unexpectedExceptions++; | ||
10533 | CumulativeReporterBase::assertionEnded( assertionStats ); | ||
10534 | } | ||
10535 | |||
10536 | void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { | ||
10537 | stdOutForSuite += testCaseStats.stdOut; | ||
10538 | stdErrForSuite += testCaseStats.stdErr; | ||
10539 | CumulativeReporterBase::testCaseEnded( testCaseStats ); | ||
10540 | } | ||
10541 | |||
10542 | void JunitReporter::testRunEndedCumulative() { | ||
10543 | const auto suiteTime = suiteTimer.getElapsedSeconds(); | ||
10544 | writeRun( *m_testRun, suiteTime ); | ||
10545 | xml.endElement(); | ||
10546 | } | ||
10547 | |||
10548 | void JunitReporter::writeRun( TestRunNode const& testRunNode, double suiteTime ) { | ||
10549 | XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); | ||
10550 | |||
10551 | TestRunStats const& stats = testRunNode.value; | ||
10552 | xml.writeAttribute( "name"_sr, stats.runInfo.name ); | ||
10553 | xml.writeAttribute( "errors"_sr, unexpectedExceptions ); | ||
10554 | xml.writeAttribute( "failures"_sr, stats.totals.assertions.failed-unexpectedExceptions ); | ||
10555 | xml.writeAttribute( "skipped"_sr, stats.totals.assertions.skipped ); | ||
10556 | xml.writeAttribute( "tests"_sr, stats.totals.assertions.total() ); | ||
10557 | xml.writeAttribute( "hostname"_sr, "tbd"_sr ); // !TBD | ||
10558 | if( m_config->showDurations() == ShowDurations::Never ) | ||
10559 | xml.writeAttribute( "time"_sr, ""_sr ); | ||
10560 | else | ||
10561 | xml.writeAttribute( "time"_sr, formatDuration( suiteTime ) ); | ||
10562 | xml.writeAttribute( "timestamp"_sr, getCurrentTimestamp() ); | ||
10563 | |||
10564 | // Write properties | ||
10565 | { | ||
10566 | auto properties = xml.scopedElement("properties"); | ||
10567 | xml.scopedElement("property") | ||
10568 | .writeAttribute("name"_sr, "random-seed"_sr) | ||
10569 | .writeAttribute("value"_sr, m_config->rngSeed()); | ||
10570 | if (m_config->testSpec().hasFilters()) { | ||
10571 | xml.scopedElement("property") | ||
10572 | .writeAttribute("name"_sr, "filters"_sr) | ||
10573 | .writeAttribute("value"_sr, m_config->testSpec()); | ||
10574 | } | ||
10575 | } | ||
10576 | |||
10577 | // Write test cases | ||
10578 | for( auto const& child : testRunNode.children ) | ||
10579 | writeTestCase( *child ); | ||
10580 | |||
10581 | xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline ); | ||
10582 | xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline ); | ||
10583 | } | ||
10584 | |||
10585 | void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) { | ||
10586 | TestCaseStats const& stats = testCaseNode.value; | ||
10587 | |||
10588 | // All test cases have exactly one section - which represents the | ||
10589 | // test case itself. That section may have 0-n nested sections | ||
10590 | assert( testCaseNode.children.size() == 1 ); | ||
10591 | SectionNode const& rootSection = *testCaseNode.children.front(); | ||
10592 | |||
10593 | std::string className = | ||
10594 | static_cast<std::string>( stats.testInfo->className ); | ||
10595 | |||
10596 | if( className.empty() ) { | ||
10597 | className = fileNameTag(stats.testInfo->tags); | ||
10598 | if ( className.empty() ) { | ||
10599 | className = "global"; | ||
10600 | } | ||
10601 | } | ||
10602 | |||
10603 | if ( !m_config->name().empty() ) | ||
10604 | className = static_cast<std::string>(m_config->name()) + '.' + className; | ||
10605 | |||
10606 | normalizeNamespaceMarkers(className); | ||
10607 | |||
10608 | writeSection( className, "", rootSection, stats.testInfo->okToFail() ); | ||
10609 | } | ||
10610 | |||
10611 | void JunitReporter::writeSection( std::string const& className, | ||
10612 | std::string const& rootName, | ||
10613 | SectionNode const& sectionNode, | ||
10614 | bool testOkToFail) { | ||
10615 | std::string name = trim( sectionNode.stats.sectionInfo.name ); | ||
10616 | if( !rootName.empty() ) | ||
10617 | name = rootName + '/' + name; | ||
10618 | |||
10619 | if ( sectionNode.stats.assertions.total() > 0 | ||
10620 | || !sectionNode.stdOut.empty() | ||
10621 | || !sectionNode.stdErr.empty() ) { | ||
10622 | XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); | ||
10623 | if( className.empty() ) { | ||
10624 | xml.writeAttribute( "classname"_sr, name ); | ||
10625 | xml.writeAttribute( "name"_sr, "root"_sr ); | ||
10626 | } | ||
10627 | else { | ||
10628 | xml.writeAttribute( "classname"_sr, className ); | ||
10629 | xml.writeAttribute( "name"_sr, name ); | ||
10630 | } | ||
10631 | xml.writeAttribute( "time"_sr, formatDuration( sectionNode.stats.durationInSeconds ) ); | ||
10632 | // This is not ideal, but it should be enough to mimic gtest's | ||
10633 | // junit output. | ||
10634 | // Ideally the JUnit reporter would also handle `skipTest` | ||
10635 | // events and write those out appropriately. | ||
10636 | xml.writeAttribute( "status"_sr, "run"_sr ); | ||
10637 | |||
10638 | if (sectionNode.stats.assertions.failedButOk) { | ||
10639 | xml.scopedElement("skipped") | ||
10640 | .writeAttribute("message", "TEST_CASE tagged with !mayfail"); | ||
10641 | } | ||
10642 | |||
10643 | writeAssertions( sectionNode ); | ||
10644 | |||
10645 | |||
10646 | if( !sectionNode.stdOut.empty() ) | ||
10647 | xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline ); | ||
10648 | if( !sectionNode.stdErr.empty() ) | ||
10649 | xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline ); | ||
10650 | } | ||
10651 | for( auto const& childNode : sectionNode.childSections ) | ||
10652 | if( className.empty() ) | ||
10653 | writeSection( name, "", *childNode, testOkToFail ); | ||
10654 | else | ||
10655 | writeSection( className, name, *childNode, testOkToFail ); | ||
10656 | } | ||
10657 | |||
10658 | void JunitReporter::writeAssertions( SectionNode const& sectionNode ) { | ||
10659 | for (auto const& assertionOrBenchmark : sectionNode.assertionsAndBenchmarks) { | ||
10660 | if (assertionOrBenchmark.isAssertion()) { | ||
10661 | writeAssertion(assertionOrBenchmark.asAssertion()); | ||
10662 | } | ||
10663 | } | ||
10664 | } | ||
10665 | |||
10666 | void JunitReporter::writeAssertion( AssertionStats const& stats ) { | ||
10667 | AssertionResult const& result = stats.assertionResult; | ||
10668 | if ( !result.isOk() || | ||
10669 | result.getResultType() == ResultWas::ExplicitSkip ) { | ||
10670 | std::string elementName; | ||
10671 | switch( result.getResultType() ) { | ||
10672 | case ResultWas::ThrewException: | ||
10673 | case ResultWas::FatalErrorCondition: | ||
10674 | elementName = "error"; | ||
10675 | break; | ||
10676 | case ResultWas::ExplicitFailure: | ||
10677 | case ResultWas::ExpressionFailed: | ||
10678 | case ResultWas::DidntThrowException: | ||
10679 | elementName = "failure"; | ||
10680 | break; | ||
10681 | case ResultWas::ExplicitSkip: | ||
10682 | elementName = "skipped"; | ||
10683 | break; | ||
10684 | // We should never see these here: | ||
10685 | case ResultWas::Info: | ||
10686 | case ResultWas::Warning: | ||
10687 | case ResultWas::Ok: | ||
10688 | case ResultWas::Unknown: | ||
10689 | case ResultWas::FailureBit: | ||
10690 | case ResultWas::Exception: | ||
10691 | elementName = "internalError"; | ||
10692 | break; | ||
10693 | } | ||
10694 | |||
10695 | XmlWriter::ScopedElement e = xml.scopedElement( elementName ); | ||
10696 | |||
10697 | xml.writeAttribute( "message"_sr, result.getExpression() ); | ||
10698 | xml.writeAttribute( "type"_sr, result.getTestMacroName() ); | ||
10699 | |||
10700 | ReusableStringStream rss; | ||
10701 | if ( result.getResultType() == ResultWas::ExplicitSkip ) { | ||
10702 | rss << "SKIPPED\n"; | ||
10703 | } else { | ||
10704 | rss << "FAILED" << ":\n"; | ||
10705 | if (result.hasExpression()) { | ||
10706 | rss << " "; | ||
10707 | rss << result.getExpressionInMacro(); | ||
10708 | rss << '\n'; | ||
10709 | } | ||
10710 | if (result.hasExpandedExpression()) { | ||
10711 | rss << "with expansion:\n"; | ||
10712 | rss << TextFlow::Column(result.getExpandedExpression()).indent(2) << '\n'; | ||
10713 | } | ||
10714 | } | ||
10715 | |||
10716 | if( result.hasMessage() ) | ||
10717 | rss << result.getMessage() << '\n'; | ||
10718 | for( auto const& msg : stats.infoMessages ) | ||
10719 | if( msg.type == ResultWas::Info ) | ||
10720 | rss << msg.message << '\n'; | ||
10721 | |||
10722 | rss << "at " << result.getSourceInfo(); | ||
10723 | xml.writeText( rss.str(), XmlFormatting::Newline ); | ||
10724 | } | ||
10725 | } | ||
10726 | |||
10727 | } // end namespace Catch | ||
10728 | |||
10729 | |||
10730 | |||
10731 | |||
10732 | #include <ostream> | ||
10733 | |||
10734 | namespace Catch { | ||
10735 | void MultiReporter::updatePreferences(IEventListener const& reporterish) { | ||
10736 | m_preferences.shouldRedirectStdOut |= | ||
10737 | reporterish.getPreferences().shouldRedirectStdOut; | ||
10738 | m_preferences.shouldReportAllAssertions |= | ||
10739 | reporterish.getPreferences().shouldReportAllAssertions; | ||
10740 | } | ||
10741 | |||
10742 | void MultiReporter::addListener( IEventListenerPtr&& listener ) { | ||
10743 | updatePreferences(*listener); | ||
10744 | m_reporterLikes.insert(m_reporterLikes.begin() + m_insertedListeners, CATCH_MOVE(listener) ); | ||
10745 | ++m_insertedListeners; | ||
10746 | } | ||
10747 | |||
10748 | void MultiReporter::addReporter( IEventListenerPtr&& reporter ) { | ||
10749 | updatePreferences(*reporter); | ||
10750 | |||
10751 | // We will need to output the captured stdout if there are reporters | ||
10752 | // that do not want it captured. | ||
10753 | // We do not consider listeners, because it is generally assumed that | ||
10754 | // listeners are output-transparent, even though they can ask for stdout | ||
10755 | // capture to do something with it. | ||
10756 | m_haveNoncapturingReporters |= !reporter->getPreferences().shouldRedirectStdOut; | ||
10757 | |||
10758 | // Reporters can always be placed to the back without breaking the | ||
10759 | // reporting order | ||
10760 | m_reporterLikes.push_back( CATCH_MOVE( reporter ) ); | ||
10761 | } | ||
10762 | |||
10763 | void MultiReporter::noMatchingTestCases( StringRef unmatchedSpec ) { | ||
10764 | for ( auto& reporterish : m_reporterLikes ) { | ||
10765 | reporterish->noMatchingTestCases( unmatchedSpec ); | ||
10766 | } | ||
10767 | } | ||
10768 | |||
10769 | void MultiReporter::fatalErrorEncountered( StringRef error ) { | ||
10770 | for ( auto& reporterish : m_reporterLikes ) { | ||
10771 | reporterish->fatalErrorEncountered( error ); | ||
10772 | } | ||
10773 | } | ||
10774 | |||
10775 | void MultiReporter::reportInvalidTestSpec( StringRef arg ) { | ||
10776 | for ( auto& reporterish : m_reporterLikes ) { | ||
10777 | reporterish->reportInvalidTestSpec( arg ); | ||
10778 | } | ||
10779 | } | ||
10780 | |||
10781 | void MultiReporter::benchmarkPreparing( StringRef name ) { | ||
10782 | for (auto& reporterish : m_reporterLikes) { | ||
10783 | reporterish->benchmarkPreparing(name); | ||
10784 | } | ||
10785 | } | ||
10786 | void MultiReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) { | ||
10787 | for ( auto& reporterish : m_reporterLikes ) { | ||
10788 | reporterish->benchmarkStarting( benchmarkInfo ); | ||
10789 | } | ||
10790 | } | ||
10791 | void MultiReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) { | ||
10792 | for ( auto& reporterish : m_reporterLikes ) { | ||
10793 | reporterish->benchmarkEnded( benchmarkStats ); | ||
10794 | } | ||
10795 | } | ||
10796 | |||
10797 | void MultiReporter::benchmarkFailed( StringRef error ) { | ||
10798 | for (auto& reporterish : m_reporterLikes) { | ||
10799 | reporterish->benchmarkFailed(error); | ||
10800 | } | ||
10801 | } | ||
10802 | |||
10803 | void MultiReporter::testRunStarting( TestRunInfo const& testRunInfo ) { | ||
10804 | for ( auto& reporterish : m_reporterLikes ) { | ||
10805 | reporterish->testRunStarting( testRunInfo ); | ||
10806 | } | ||
10807 | } | ||
10808 | |||
10809 | void MultiReporter::testCaseStarting( TestCaseInfo const& testInfo ) { | ||
10810 | for ( auto& reporterish : m_reporterLikes ) { | ||
10811 | reporterish->testCaseStarting( testInfo ); | ||
10812 | } | ||
10813 | } | ||
10814 | |||
10815 | void | ||
10816 | MultiReporter::testCasePartialStarting( TestCaseInfo const& testInfo, | ||
10817 | uint64_t partNumber ) { | ||
10818 | for ( auto& reporterish : m_reporterLikes ) { | ||
10819 | reporterish->testCasePartialStarting( testInfo, partNumber ); | ||
10820 | } | ||
10821 | } | ||
10822 | |||
10823 | void MultiReporter::sectionStarting( SectionInfo const& sectionInfo ) { | ||
10824 | for ( auto& reporterish : m_reporterLikes ) { | ||
10825 | reporterish->sectionStarting( sectionInfo ); | ||
10826 | } | ||
10827 | } | ||
10828 | |||
10829 | void MultiReporter::assertionStarting( AssertionInfo const& assertionInfo ) { | ||
10830 | for ( auto& reporterish : m_reporterLikes ) { | ||
10831 | reporterish->assertionStarting( assertionInfo ); | ||
10832 | } | ||
10833 | } | ||
10834 | |||
10835 | void MultiReporter::assertionEnded( AssertionStats const& assertionStats ) { | ||
10836 | const bool reportByDefault = | ||
10837 | assertionStats.assertionResult.getResultType() != ResultWas::Ok || | ||
10838 | m_config->includeSuccessfulResults(); | ||
10839 | |||
10840 | for ( auto & reporterish : m_reporterLikes ) { | ||
10841 | if ( reportByDefault || | ||
10842 | reporterish->getPreferences().shouldReportAllAssertions ) { | ||
10843 | reporterish->assertionEnded( assertionStats ); | ||
10844 | } | ||
10845 | } | ||
10846 | } | ||
10847 | |||
10848 | void MultiReporter::sectionEnded( SectionStats const& sectionStats ) { | ||
10849 | for ( auto& reporterish : m_reporterLikes ) { | ||
10850 | reporterish->sectionEnded( sectionStats ); | ||
10851 | } | ||
10852 | } | ||
10853 | |||
10854 | void MultiReporter::testCasePartialEnded( TestCaseStats const& testStats, | ||
10855 | uint64_t partNumber ) { | ||
10856 | if ( m_preferences.shouldRedirectStdOut && | ||
10857 | m_haveNoncapturingReporters ) { | ||
10858 | if ( !testStats.stdOut.empty() ) { | ||
10859 | Catch::cout() << testStats.stdOut << std::flush; | ||
10860 | } | ||
10861 | if ( !testStats.stdErr.empty() ) { | ||
10862 | Catch::cerr() << testStats.stdErr << std::flush; | ||
10863 | } | ||
10864 | } | ||
10865 | |||
10866 | for ( auto& reporterish : m_reporterLikes ) { | ||
10867 | reporterish->testCasePartialEnded( testStats, partNumber ); | ||
10868 | } | ||
10869 | } | ||
10870 | |||
10871 | void MultiReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { | ||
10872 | for ( auto& reporterish : m_reporterLikes ) { | ||
10873 | reporterish->testCaseEnded( testCaseStats ); | ||
10874 | } | ||
10875 | } | ||
10876 | |||
10877 | void MultiReporter::testRunEnded( TestRunStats const& testRunStats ) { | ||
10878 | for ( auto& reporterish : m_reporterLikes ) { | ||
10879 | reporterish->testRunEnded( testRunStats ); | ||
10880 | } | ||
10881 | } | ||
10882 | |||
10883 | |||
10884 | void MultiReporter::skipTest( TestCaseInfo const& testInfo ) { | ||
10885 | for ( auto& reporterish : m_reporterLikes ) { | ||
10886 | reporterish->skipTest( testInfo ); | ||
10887 | } | ||
10888 | } | ||
10889 | |||
10890 | void MultiReporter::listReporters(std::vector<ReporterDescription> const& descriptions) { | ||
10891 | for (auto& reporterish : m_reporterLikes) { | ||
10892 | reporterish->listReporters(descriptions); | ||
10893 | } | ||
10894 | } | ||
10895 | |||
10896 | void MultiReporter::listListeners( | ||
10897 | std::vector<ListenerDescription> const& descriptions ) { | ||
10898 | for ( auto& reporterish : m_reporterLikes ) { | ||
10899 | reporterish->listListeners( descriptions ); | ||
10900 | } | ||
10901 | } | ||
10902 | |||
10903 | void MultiReporter::listTests(std::vector<TestCaseHandle> const& tests) { | ||
10904 | for (auto& reporterish : m_reporterLikes) { | ||
10905 | reporterish->listTests(tests); | ||
10906 | } | ||
10907 | } | ||
10908 | |||
10909 | void MultiReporter::listTags(std::vector<TagInfo> const& tags) { | ||
10910 | for (auto& reporterish : m_reporterLikes) { | ||
10911 | reporterish->listTags(tags); | ||
10912 | } | ||
10913 | } | ||
10914 | |||
10915 | } // end namespace Catch | ||
10916 | |||
10917 | |||
10918 | |||
10919 | |||
10920 | |||
10921 | namespace Catch { | ||
10922 | namespace Detail { | ||
10923 | |||
10924 | void registerReporterImpl( std::string const& name, | ||
10925 | IReporterFactoryPtr reporterPtr ) { | ||
10926 | CATCH_TRY { | ||
10927 | getMutableRegistryHub().registerReporter( | ||
10928 | name, CATCH_MOVE( reporterPtr ) ); | ||
10929 | } | ||
10930 | CATCH_CATCH_ALL { | ||
10931 | // Do not throw when constructing global objects, instead | ||
10932 | // register the exception to be processed later | ||
10933 | getMutableRegistryHub().registerStartupException(); | ||
10934 | } | ||
10935 | } | ||
10936 | |||
10937 | void registerListenerImpl( Detail::unique_ptr<EventListenerFactory> listenerFactory ) { | ||
10938 | getMutableRegistryHub().registerListener( CATCH_MOVE(listenerFactory) ); | ||
10939 | } | ||
10940 | |||
10941 | |||
10942 | } // namespace Detail | ||
10943 | } // namespace Catch | ||
10944 | |||
10945 | |||
10946 | |||
10947 | |||
10948 | #include <map> | ||
10949 | |||
10950 | namespace Catch { | ||
10951 | |||
10952 | namespace { | ||
10953 | std::string createMetadataString(IConfig const& config) { | ||
10954 | ReusableStringStream sstr; | ||
10955 | if ( config.testSpec().hasFilters() ) { | ||
10956 | sstr << "filters='" | ||
10957 | << config.testSpec() | ||
10958 | << "' "; | ||
10959 | } | ||
10960 | sstr << "rng-seed=" << config.rngSeed(); | ||
10961 | return sstr.str(); | ||
10962 | } | ||
10963 | } | ||
10964 | |||
10965 | void SonarQubeReporter::testRunStarting(TestRunInfo const& testRunInfo) { | ||
10966 | CumulativeReporterBase::testRunStarting(testRunInfo); | ||
10967 | |||
10968 | xml.writeComment( createMetadataString( *m_config ) ); | ||
10969 | xml.startElement("testExecutions"); | ||
10970 | xml.writeAttribute("version"_sr, '1'); | ||
10971 | } | ||
10972 | |||
10973 | void SonarQubeReporter::writeRun( TestRunNode const& runNode ) { | ||
10974 | std::map<StringRef, std::vector<TestCaseNode const*>> testsPerFile; | ||
10975 | |||
10976 | for ( auto const& child : runNode.children ) { | ||
10977 | testsPerFile[child->value.testInfo->lineInfo.file].push_back( | ||
10978 | child.get() ); | ||
10979 | } | ||
10980 | |||
10981 | for ( auto const& kv : testsPerFile ) { | ||
10982 | writeTestFile( kv.first, kv.second ); | ||
10983 | } | ||
10984 | } | ||
10985 | |||
10986 | void SonarQubeReporter::writeTestFile(StringRef filename, std::vector<TestCaseNode const*> const& testCaseNodes) { | ||
10987 | XmlWriter::ScopedElement e = xml.scopedElement("file"); | ||
10988 | xml.writeAttribute("path"_sr, filename); | ||
10989 | |||
10990 | for (auto const& child : testCaseNodes) | ||
10991 | writeTestCase(*child); | ||
10992 | } | ||
10993 | |||
10994 | void SonarQubeReporter::writeTestCase(TestCaseNode const& testCaseNode) { | ||
10995 | // All test cases have exactly one section - which represents the | ||
10996 | // test case itself. That section may have 0-n nested sections | ||
10997 | assert(testCaseNode.children.size() == 1); | ||
10998 | SectionNode const& rootSection = *testCaseNode.children.front(); | ||
10999 | writeSection("", rootSection, testCaseNode.value.testInfo->okToFail()); | ||
11000 | } | ||
11001 | |||
11002 | void SonarQubeReporter::writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail) { | ||
11003 | std::string name = trim(sectionNode.stats.sectionInfo.name); | ||
11004 | if (!rootName.empty()) | ||
11005 | name = rootName + '/' + name; | ||
11006 | |||
11007 | if ( sectionNode.stats.assertions.total() > 0 | ||
11008 | || !sectionNode.stdOut.empty() | ||
11009 | || !sectionNode.stdErr.empty() ) { | ||
11010 | XmlWriter::ScopedElement e = xml.scopedElement("testCase"); | ||
11011 | xml.writeAttribute("name"_sr, name); | ||
11012 | xml.writeAttribute("duration"_sr, static_cast<long>(sectionNode.stats.durationInSeconds * 1000)); | ||
11013 | |||
11014 | writeAssertions(sectionNode, okToFail); | ||
11015 | } | ||
11016 | |||
11017 | for (auto const& childNode : sectionNode.childSections) | ||
11018 | writeSection(name, *childNode, okToFail); | ||
11019 | } | ||
11020 | |||
11021 | void SonarQubeReporter::writeAssertions(SectionNode const& sectionNode, bool okToFail) { | ||
11022 | for (auto const& assertionOrBenchmark : sectionNode.assertionsAndBenchmarks) { | ||
11023 | if (assertionOrBenchmark.isAssertion()) { | ||
11024 | writeAssertion(assertionOrBenchmark.asAssertion(), okToFail); | ||
11025 | } | ||
11026 | } | ||
11027 | } | ||
11028 | |||
11029 | void SonarQubeReporter::writeAssertion(AssertionStats const& stats, bool okToFail) { | ||
11030 | AssertionResult const& result = stats.assertionResult; | ||
11031 | if ( !result.isOk() || | ||
11032 | result.getResultType() == ResultWas::ExplicitSkip ) { | ||
11033 | std::string elementName; | ||
11034 | if (okToFail) { | ||
11035 | elementName = "skipped"; | ||
11036 | } else { | ||
11037 | switch (result.getResultType()) { | ||
11038 | case ResultWas::ThrewException: | ||
11039 | case ResultWas::FatalErrorCondition: | ||
11040 | elementName = "error"; | ||
11041 | break; | ||
11042 | case ResultWas::ExplicitFailure: | ||
11043 | case ResultWas::ExpressionFailed: | ||
11044 | case ResultWas::DidntThrowException: | ||
11045 | elementName = "failure"; | ||
11046 | break; | ||
11047 | case ResultWas::ExplicitSkip: | ||
11048 | elementName = "skipped"; | ||
11049 | break; | ||
11050 | // We should never see these here: | ||
11051 | case ResultWas::Info: | ||
11052 | case ResultWas::Warning: | ||
11053 | case ResultWas::Ok: | ||
11054 | case ResultWas::Unknown: | ||
11055 | case ResultWas::FailureBit: | ||
11056 | case ResultWas::Exception: | ||
11057 | elementName = "internalError"; | ||
11058 | break; | ||
11059 | } | ||
11060 | } | ||
11061 | |||
11062 | XmlWriter::ScopedElement e = xml.scopedElement(elementName); | ||
11063 | |||
11064 | ReusableStringStream messageRss; | ||
11065 | messageRss << result.getTestMacroName() << '(' << result.getExpression() << ')'; | ||
11066 | xml.writeAttribute("message"_sr, messageRss.str()); | ||
11067 | |||
11068 | ReusableStringStream textRss; | ||
11069 | if ( result.getResultType() == ResultWas::ExplicitSkip ) { | ||
11070 | textRss << "SKIPPED\n"; | ||
11071 | } else { | ||
11072 | textRss << "FAILED:\n"; | ||
11073 | if (result.hasExpression()) { | ||
11074 | textRss << '\t' << result.getExpressionInMacro() << '\n'; | ||
11075 | } | ||
11076 | if (result.hasExpandedExpression()) { | ||
11077 | textRss << "with expansion:\n\t" << result.getExpandedExpression() << '\n'; | ||
11078 | } | ||
11079 | } | ||
11080 | |||
11081 | if (result.hasMessage()) | ||
11082 | textRss << result.getMessage() << '\n'; | ||
11083 | |||
11084 | for (auto const& msg : stats.infoMessages) | ||
11085 | if (msg.type == ResultWas::Info) | ||
11086 | textRss << msg.message << '\n'; | ||
11087 | |||
11088 | textRss << "at " << result.getSourceInfo(); | ||
11089 | xml.writeText(textRss.str(), XmlFormatting::Newline); | ||
11090 | } | ||
11091 | } | ||
11092 | |||
11093 | } // end namespace Catch | ||
11094 | |||
11095 | |||
11096 | |||
11097 | namespace Catch { | ||
11098 | |||
11099 | StreamingReporterBase::~StreamingReporterBase() = default; | ||
11100 | |||
11101 | void | ||
11102 | StreamingReporterBase::testRunStarting( TestRunInfo const& _testRunInfo ) { | ||
11103 | currentTestRunInfo = _testRunInfo; | ||
11104 | } | ||
11105 | |||
11106 | void StreamingReporterBase::testRunEnded( TestRunStats const& ) { | ||
11107 | currentTestCaseInfo = nullptr; | ||
11108 | } | ||
11109 | |||
11110 | } // end namespace Catch | ||
11111 | |||
11112 | |||
11113 | |||
11114 | #include <algorithm> | ||
11115 | #include <ostream> | ||
11116 | |||
11117 | namespace Catch { | ||
11118 | |||
11119 | namespace { | ||
11120 | // Yes, this has to be outside the class and namespaced by naming. | ||
11121 | // Making older compiler happy is hard. | ||
11122 | static constexpr StringRef tapFailedString = "not ok"_sr; | ||
11123 | static constexpr StringRef tapPassedString = "ok"_sr; | ||
11124 | static constexpr Colour::Code tapDimColour = Colour::FileName; | ||
11125 | |||
11126 | class TapAssertionPrinter { | ||
11127 | public: | ||
11128 | TapAssertionPrinter& operator= (TapAssertionPrinter const&) = delete; | ||
11129 | TapAssertionPrinter(TapAssertionPrinter const&) = delete; | ||
11130 | TapAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter, ColourImpl* colour_) | ||
11131 | : stream(_stream) | ||
11132 | , result(_stats.assertionResult) | ||
11133 | , messages(_stats.infoMessages) | ||
11134 | , itMessage(_stats.infoMessages.begin()) | ||
11135 | , printInfoMessages(true) | ||
11136 | , counter(_counter) | ||
11137 | , colourImpl( colour_ ) {} | ||
11138 | |||
11139 | void print() { | ||
11140 | itMessage = messages.begin(); | ||
11141 | |||
11142 | switch (result.getResultType()) { | ||
11143 | case ResultWas::Ok: | ||
11144 | printResultType(tapPassedString); | ||
11145 | printOriginalExpression(); | ||
11146 | printReconstructedExpression(); | ||
11147 | if (!result.hasExpression()) | ||
11148 | printRemainingMessages(Colour::None); | ||
11149 | else | ||
11150 | printRemainingMessages(); | ||
11151 | break; | ||
11152 | case ResultWas::ExpressionFailed: | ||
11153 | if (result.isOk()) { | ||
11154 | printResultType(tapPassedString); | ||
11155 | } else { | ||
11156 | printResultType(tapFailedString); | ||
11157 | } | ||
11158 | printOriginalExpression(); | ||
11159 | printReconstructedExpression(); | ||
11160 | if (result.isOk()) { | ||
11161 | printIssue(" # TODO"); | ||
11162 | } | ||
11163 | printRemainingMessages(); | ||
11164 | break; | ||
11165 | case ResultWas::ThrewException: | ||
11166 | printResultType(tapFailedString); | ||
11167 | printIssue("unexpected exception with message:"_sr); | ||
11168 | printMessage(); | ||
11169 | printExpressionWas(); | ||
11170 | printRemainingMessages(); | ||
11171 | break; | ||
11172 | case ResultWas::FatalErrorCondition: | ||
11173 | printResultType(tapFailedString); | ||
11174 | printIssue("fatal error condition with message:"_sr); | ||
11175 | printMessage(); | ||
11176 | printExpressionWas(); | ||
11177 | printRemainingMessages(); | ||
11178 | break; | ||
11179 | case ResultWas::DidntThrowException: | ||
11180 | printResultType(tapFailedString); | ||
11181 | printIssue("expected exception, got none"_sr); | ||
11182 | printExpressionWas(); | ||
11183 | printRemainingMessages(); | ||
11184 | break; | ||
11185 | case ResultWas::Info: | ||
11186 | printResultType("info"_sr); | ||
11187 | printMessage(); | ||
11188 | printRemainingMessages(); | ||
11189 | break; | ||
11190 | case ResultWas::Warning: | ||
11191 | printResultType("warning"_sr); | ||
11192 | printMessage(); | ||
11193 | printRemainingMessages(); | ||
11194 | break; | ||
11195 | case ResultWas::ExplicitFailure: | ||
11196 | printResultType(tapFailedString); | ||
11197 | printIssue("explicitly"_sr); | ||
11198 | printRemainingMessages(Colour::None); | ||
11199 | break; | ||
11200 | case ResultWas::ExplicitSkip: | ||
11201 | printResultType(tapPassedString); | ||
11202 | printIssue(" # SKIP"_sr); | ||
11203 | printMessage(); | ||
11204 | printRemainingMessages(); | ||
11205 | break; | ||
11206 | // These cases are here to prevent compiler warnings | ||
11207 | case ResultWas::Unknown: | ||
11208 | case ResultWas::FailureBit: | ||
11209 | case ResultWas::Exception: | ||
11210 | printResultType("** internal error **"_sr); | ||
11211 | break; | ||
11212 | } | ||
11213 | } | ||
11214 | |||
11215 | private: | ||
11216 | void printResultType(StringRef passOrFail) const { | ||
11217 | if (!passOrFail.empty()) { | ||
11218 | stream << passOrFail << ' ' << counter << " -"; | ||
11219 | } | ||
11220 | } | ||
11221 | |||
11222 | void printIssue(StringRef issue) const { | ||
11223 | stream << ' ' << issue; | ||
11224 | } | ||
11225 | |||
11226 | void printExpressionWas() { | ||
11227 | if (result.hasExpression()) { | ||
11228 | stream << ';'; | ||
11229 | stream << colourImpl->guardColour( tapDimColour ) | ||
11230 | << " expression was:"; | ||
11231 | printOriginalExpression(); | ||
11232 | } | ||
11233 | } | ||
11234 | |||
11235 | void printOriginalExpression() const { | ||
11236 | if (result.hasExpression()) { | ||
11237 | stream << ' ' << result.getExpression(); | ||
11238 | } | ||
11239 | } | ||
11240 | |||
11241 | void printReconstructedExpression() const { | ||
11242 | if (result.hasExpandedExpression()) { | ||
11243 | stream << colourImpl->guardColour( tapDimColour ) << " for: "; | ||
11244 | |||
11245 | std::string expr = result.getExpandedExpression(); | ||
11246 | std::replace(expr.begin(), expr.end(), '\n', ' '); | ||
11247 | stream << expr; | ||
11248 | } | ||
11249 | } | ||
11250 | |||
11251 | void printMessage() { | ||
11252 | if (itMessage != messages.end()) { | ||
11253 | stream << " '" << itMessage->message << '\''; | ||
11254 | ++itMessage; | ||
11255 | } | ||
11256 | } | ||
11257 | |||
11258 | void printRemainingMessages(Colour::Code colour = tapDimColour) { | ||
11259 | if (itMessage == messages.end()) { | ||
11260 | return; | ||
11261 | } | ||
11262 | |||
11263 | // using messages.end() directly (or auto) yields compilation error: | ||
11264 | std::vector<MessageInfo>::const_iterator itEnd = messages.end(); | ||
11265 | const std::size_t N = static_cast<std::size_t>(itEnd - itMessage); | ||
11266 | |||
11267 | stream << colourImpl->guardColour( colour ) << " with " | ||
11268 | << pluralise( N, "message"_sr ) << ':'; | ||
11269 | |||
11270 | for (; itMessage != itEnd; ) { | ||
11271 | // If this assertion is a warning ignore any INFO messages | ||
11272 | if (printInfoMessages || itMessage->type != ResultWas::Info) { | ||
11273 | stream << " '" << itMessage->message << '\''; | ||
11274 | if (++itMessage != itEnd) { | ||
11275 | stream << colourImpl->guardColour(tapDimColour) << " and"; | ||
11276 | } | ||
11277 | } | ||
11278 | } | ||
11279 | } | ||
11280 | |||
11281 | private: | ||
11282 | std::ostream& stream; | ||
11283 | AssertionResult const& result; | ||
11284 | std::vector<MessageInfo> const& messages; | ||
11285 | std::vector<MessageInfo>::const_iterator itMessage; | ||
11286 | bool printInfoMessages; | ||
11287 | std::size_t counter; | ||
11288 | ColourImpl* colourImpl; | ||
11289 | }; | ||
11290 | |||
11291 | } // End anonymous namespace | ||
11292 | |||
11293 | void TAPReporter::testRunStarting( TestRunInfo const& ) { | ||
11294 | if ( m_config->testSpec().hasFilters() ) { | ||
11295 | m_stream << "# filters: " << m_config->testSpec() << '\n'; | ||
11296 | } | ||
11297 | m_stream << "# rng-seed: " << m_config->rngSeed() << '\n'; | ||
11298 | } | ||
11299 | |||
11300 | void TAPReporter::noMatchingTestCases( StringRef unmatchedSpec ) { | ||
11301 | m_stream << "# No test cases matched '" << unmatchedSpec << "'\n"; | ||
11302 | } | ||
11303 | |||
11304 | void TAPReporter::assertionEnded(AssertionStats const& _assertionStats) { | ||
11305 | ++counter; | ||
11306 | |||
11307 | m_stream << "# " << currentTestCaseInfo->name << '\n'; | ||
11308 | TapAssertionPrinter printer(m_stream, _assertionStats, counter, m_colour.get()); | ||
11309 | printer.print(); | ||
11310 | |||
11311 | m_stream << '\n' << std::flush; | ||
11312 | } | ||
11313 | |||
11314 | void TAPReporter::testRunEnded(TestRunStats const& _testRunStats) { | ||
11315 | m_stream << "1.." << _testRunStats.totals.assertions.total(); | ||
11316 | if (_testRunStats.totals.testCases.total() == 0) { | ||
11317 | m_stream << " # Skipped: No tests ran."; | ||
11318 | } | ||
11319 | m_stream << "\n\n" << std::flush; | ||
11320 | StreamingReporterBase::testRunEnded(_testRunStats); | ||
11321 | } | ||
11322 | |||
11323 | |||
11324 | |||
11325 | |||
11326 | } // end namespace Catch | ||
11327 | |||
11328 | |||
11329 | |||
11330 | |||
11331 | #include <cassert> | ||
11332 | #include <ostream> | ||
11333 | |||
11334 | namespace Catch { | ||
11335 | |||
11336 | namespace { | ||
11337 | // if string has a : in first line will set indent to follow it on | ||
11338 | // subsequent lines | ||
11339 | void printHeaderString(std::ostream& os, std::string const& _string, std::size_t indent = 0) { | ||
11340 | std::size_t i = _string.find(": "); | ||
11341 | if (i != std::string::npos) | ||
11342 | i += 2; | ||
11343 | else | ||
11344 | i = 0; | ||
11345 | os << TextFlow::Column(_string) | ||
11346 | .indent(indent + i) | ||
11347 | .initialIndent(indent) << '\n'; | ||
11348 | } | ||
11349 | |||
11350 | std::string escape(StringRef str) { | ||
11351 | std::string escaped = static_cast<std::string>(str); | ||
11352 | replaceInPlace(escaped, "|", "||"); | ||
11353 | replaceInPlace(escaped, "'", "|'"); | ||
11354 | replaceInPlace(escaped, "\n", "|n"); | ||
11355 | replaceInPlace(escaped, "\r", "|r"); | ||
11356 | replaceInPlace(escaped, "[", "|["); | ||
11357 | replaceInPlace(escaped, "]", "|]"); | ||
11358 | return escaped; | ||
11359 | } | ||
11360 | } // end anonymous namespace | ||
11361 | |||
11362 | |||
11363 | TeamCityReporter::~TeamCityReporter() = default; | ||
11364 | |||
11365 | void TeamCityReporter::testRunStarting( TestRunInfo const& runInfo ) { | ||
11366 | m_stream << "##teamcity[testSuiteStarted name='" << escape( runInfo.name ) | ||
11367 | << "']\n"; | ||
11368 | } | ||
11369 | |||
11370 | void TeamCityReporter::testRunEnded( TestRunStats const& runStats ) { | ||
11371 | m_stream << "##teamcity[testSuiteFinished name='" | ||
11372 | << escape( runStats.runInfo.name ) << "']\n"; | ||
11373 | } | ||
11374 | |||
11375 | void TeamCityReporter::assertionEnded(AssertionStats const& assertionStats) { | ||
11376 | AssertionResult const& result = assertionStats.assertionResult; | ||
11377 | if ( !result.isOk() || | ||
11378 | result.getResultType() == ResultWas::ExplicitSkip ) { | ||
11379 | |||
11380 | ReusableStringStream msg; | ||
11381 | if (!m_headerPrintedForThisSection) | ||
11382 | printSectionHeader(msg.get()); | ||
11383 | m_headerPrintedForThisSection = true; | ||
11384 | |||
11385 | msg << result.getSourceInfo() << '\n'; | ||
11386 | |||
11387 | switch (result.getResultType()) { | ||
11388 | case ResultWas::ExpressionFailed: | ||
11389 | msg << "expression failed"; | ||
11390 | break; | ||
11391 | case ResultWas::ThrewException: | ||
11392 | msg << "unexpected exception"; | ||
11393 | break; | ||
11394 | case ResultWas::FatalErrorCondition: | ||
11395 | msg << "fatal error condition"; | ||
11396 | break; | ||
11397 | case ResultWas::DidntThrowException: | ||
11398 | msg << "no exception was thrown where one was expected"; | ||
11399 | break; | ||
11400 | case ResultWas::ExplicitFailure: | ||
11401 | msg << "explicit failure"; | ||
11402 | break; | ||
11403 | case ResultWas::ExplicitSkip: | ||
11404 | msg << "explicit skip"; | ||
11405 | break; | ||
11406 | |||
11407 | // We shouldn't get here because of the isOk() test | ||
11408 | case ResultWas::Ok: | ||
11409 | case ResultWas::Info: | ||
11410 | case ResultWas::Warning: | ||
11411 | CATCH_ERROR("Internal error in TeamCity reporter"); | ||
11412 | // These cases are here to prevent compiler warnings | ||
11413 | case ResultWas::Unknown: | ||
11414 | case ResultWas::FailureBit: | ||
11415 | case ResultWas::Exception: | ||
11416 | CATCH_ERROR("Not implemented"); | ||
11417 | } | ||
11418 | if (assertionStats.infoMessages.size() == 1) | ||
11419 | msg << " with message:"; | ||
11420 | if (assertionStats.infoMessages.size() > 1) | ||
11421 | msg << " with messages:"; | ||
11422 | for (auto const& messageInfo : assertionStats.infoMessages) | ||
11423 | msg << "\n \"" << messageInfo.message << '"'; | ||
11424 | |||
11425 | |||
11426 | if (result.hasExpression()) { | ||
11427 | msg << | ||
11428 | "\n " << result.getExpressionInMacro() << "\n" | ||
11429 | "with expansion:\n" | ||
11430 | " " << result.getExpandedExpression() << '\n'; | ||
11431 | } | ||
11432 | |||
11433 | if ( result.getResultType() == ResultWas::ExplicitSkip ) { | ||
11434 | m_stream << "##teamcity[testIgnored"; | ||
11435 | } else if ( currentTestCaseInfo->okToFail() ) { | ||
11436 | msg << "- failure ignore as test marked as 'ok to fail'\n"; | ||
11437 | m_stream << "##teamcity[testIgnored"; | ||
11438 | } else { | ||
11439 | m_stream << "##teamcity[testFailed"; | ||
11440 | } | ||
11441 | m_stream << " name='" << escape( currentTestCaseInfo->name ) << '\'' | ||
11442 | << " message='" << escape( msg.str() ) << '\'' << "]\n"; | ||
11443 | } | ||
11444 | m_stream.flush(); | ||
11445 | } | ||
11446 | |||
11447 | void TeamCityReporter::testCaseStarting(TestCaseInfo const& testInfo) { | ||
11448 | m_testTimer.start(); | ||
11449 | StreamingReporterBase::testCaseStarting(testInfo); | ||
11450 | m_stream << "##teamcity[testStarted name='" | ||
11451 | << escape(testInfo.name) << "']\n"; | ||
11452 | m_stream.flush(); | ||
11453 | } | ||
11454 | |||
11455 | void TeamCityReporter::testCaseEnded(TestCaseStats const& testCaseStats) { | ||
11456 | StreamingReporterBase::testCaseEnded(testCaseStats); | ||
11457 | auto const& testCaseInfo = *testCaseStats.testInfo; | ||
11458 | if (!testCaseStats.stdOut.empty()) | ||
11459 | m_stream << "##teamcity[testStdOut name='" | ||
11460 | << escape(testCaseInfo.name) | ||
11461 | << "' out='" << escape(testCaseStats.stdOut) << "']\n"; | ||
11462 | if (!testCaseStats.stdErr.empty()) | ||
11463 | m_stream << "##teamcity[testStdErr name='" | ||
11464 | << escape(testCaseInfo.name) | ||
11465 | << "' out='" << escape(testCaseStats.stdErr) << "']\n"; | ||
11466 | m_stream << "##teamcity[testFinished name='" | ||
11467 | << escape(testCaseInfo.name) << "' duration='" | ||
11468 | << m_testTimer.getElapsedMilliseconds() << "']\n"; | ||
11469 | m_stream.flush(); | ||
11470 | } | ||
11471 | |||
11472 | void TeamCityReporter::printSectionHeader(std::ostream& os) { | ||
11473 | assert(!m_sectionStack.empty()); | ||
11474 | |||
11475 | if (m_sectionStack.size() > 1) { | ||
11476 | os << lineOfChars('-') << '\n'; | ||
11477 | |||
11478 | std::vector<SectionInfo>::const_iterator | ||
11479 | it = m_sectionStack.begin() + 1, // Skip first section (test case) | ||
11480 | itEnd = m_sectionStack.end(); | ||
11481 | for (; it != itEnd; ++it) | ||
11482 | printHeaderString(os, it->name); | ||
11483 | os << lineOfChars('-') << '\n'; | ||
11484 | } | ||
11485 | |||
11486 | SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; | ||
11487 | |||
11488 | os << lineInfo << '\n'; | ||
11489 | os << lineOfChars('.') << "\n\n"; | ||
11490 | } | ||
11491 | |||
11492 | } // end namespace Catch | ||
11493 | |||
11494 | |||
11495 | |||
11496 | |||
11497 | #if defined(_MSC_VER) | ||
11498 | #pragma warning(push) | ||
11499 | #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch | ||
11500 | // Note that 4062 (not all labels are handled | ||
11501 | // and default is missing) is enabled | ||
11502 | #endif | ||
11503 | |||
11504 | namespace Catch { | ||
11505 | XmlReporter::XmlReporter( ReporterConfig&& _config ) | ||
11506 | : StreamingReporterBase( CATCH_MOVE(_config) ), | ||
11507 | m_xml(m_stream) | ||
11508 | { | ||
11509 | m_preferences.shouldRedirectStdOut = true; | ||
11510 | m_preferences.shouldReportAllAssertions = true; | ||
11511 | } | ||
11512 | |||
11513 | XmlReporter::~XmlReporter() = default; | ||
11514 | |||
11515 | std::string XmlReporter::getDescription() { | ||
11516 | return "Reports test results as an XML document"; | ||
11517 | } | ||
11518 | |||
11519 | std::string XmlReporter::getStylesheetRef() const { | ||
11520 | return std::string(); | ||
11521 | } | ||
11522 | |||
11523 | void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) { | ||
11524 | m_xml | ||
11525 | .writeAttribute( "filename"_sr, sourceInfo.file ) | ||
11526 | .writeAttribute( "line"_sr, sourceInfo.line ); | ||
11527 | } | ||
11528 | |||
11529 | void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) { | ||
11530 | StreamingReporterBase::testRunStarting( testInfo ); | ||
11531 | std::string stylesheetRef = getStylesheetRef(); | ||
11532 | if( !stylesheetRef.empty() ) | ||
11533 | m_xml.writeStylesheetRef( stylesheetRef ); | ||
11534 | m_xml.startElement("Catch2TestRun") | ||
11535 | .writeAttribute("name"_sr, m_config->name()) | ||
11536 | .writeAttribute("rng-seed"_sr, m_config->rngSeed()) | ||
11537 | .writeAttribute("xml-format-version"_sr, 3) | ||
11538 | .writeAttribute("catch2-version"_sr, libraryVersion()); | ||
11539 | if ( m_config->testSpec().hasFilters() ) { | ||
11540 | m_xml.writeAttribute( "filters"_sr, m_config->testSpec() ); | ||
11541 | } | ||
11542 | } | ||
11543 | |||
11544 | void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) { | ||
11545 | StreamingReporterBase::testCaseStarting(testInfo); | ||
11546 | m_xml.startElement( "TestCase" ) | ||
11547 | .writeAttribute( "name"_sr, trim( StringRef(testInfo.name) ) ) | ||
11548 | .writeAttribute( "tags"_sr, testInfo.tagsAsString() ); | ||
11549 | |||
11550 | writeSourceInfo( testInfo.lineInfo ); | ||
11551 | |||
11552 | if ( m_config->showDurations() == ShowDurations::Always ) | ||
11553 | m_testCaseTimer.start(); | ||
11554 | m_xml.ensureTagClosed(); | ||
11555 | } | ||
11556 | |||
11557 | void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) { | ||
11558 | StreamingReporterBase::sectionStarting( sectionInfo ); | ||
11559 | if( m_sectionDepth++ > 0 ) { | ||
11560 | m_xml.startElement( "Section" ) | ||
11561 | .writeAttribute( "name"_sr, trim( StringRef(sectionInfo.name) ) ); | ||
11562 | writeSourceInfo( sectionInfo.lineInfo ); | ||
11563 | m_xml.ensureTagClosed(); | ||
11564 | } | ||
11565 | } | ||
11566 | |||
11567 | void XmlReporter::assertionStarting( AssertionInfo const& ) { } | ||
11568 | |||
11569 | void XmlReporter::assertionEnded( AssertionStats const& assertionStats ) { | ||
11570 | |||
11571 | AssertionResult const& result = assertionStats.assertionResult; | ||
11572 | |||
11573 | bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); | ||
11574 | |||
11575 | if( includeResults || result.getResultType() == ResultWas::Warning ) { | ||
11576 | // Print any info messages in <Info> tags. | ||
11577 | for( auto const& msg : assertionStats.infoMessages ) { | ||
11578 | if( msg.type == ResultWas::Info && includeResults ) { | ||
11579 | auto t = m_xml.scopedElement( "Info" ); | ||
11580 | writeSourceInfo( msg.lineInfo ); | ||
11581 | t.writeText( msg.message ); | ||
11582 | } else if ( msg.type == ResultWas::Warning ) { | ||
11583 | auto t = m_xml.scopedElement( "Warning" ); | ||
11584 | writeSourceInfo( msg.lineInfo ); | ||
11585 | t.writeText( msg.message ); | ||
11586 | } | ||
11587 | } | ||
11588 | } | ||
11589 | |||
11590 | // Drop out if result was successful but we're not printing them. | ||
11591 | if ( !includeResults && result.getResultType() != ResultWas::Warning && | ||
11592 | result.getResultType() != ResultWas::ExplicitSkip ) { | ||
11593 | return; | ||
11594 | } | ||
11595 | |||
11596 | // Print the expression if there is one. | ||
11597 | if( result.hasExpression() ) { | ||
11598 | m_xml.startElement( "Expression" ) | ||
11599 | .writeAttribute( "success"_sr, result.succeeded() ) | ||
11600 | .writeAttribute( "type"_sr, result.getTestMacroName() ); | ||
11601 | |||
11602 | writeSourceInfo( result.getSourceInfo() ); | ||
11603 | |||
11604 | m_xml.scopedElement( "Original" ) | ||
11605 | .writeText( result.getExpression() ); | ||
11606 | m_xml.scopedElement( "Expanded" ) | ||
11607 | .writeText( result.getExpandedExpression() ); | ||
11608 | } | ||
11609 | |||
11610 | // And... Print a result applicable to each result type. | ||
11611 | switch( result.getResultType() ) { | ||
11612 | case ResultWas::ThrewException: | ||
11613 | m_xml.startElement( "Exception" ); | ||
11614 | writeSourceInfo( result.getSourceInfo() ); | ||
11615 | m_xml.writeText( result.getMessage() ); | ||
11616 | m_xml.endElement(); | ||
11617 | break; | ||
11618 | case ResultWas::FatalErrorCondition: | ||
11619 | m_xml.startElement( "FatalErrorCondition" ); | ||
11620 | writeSourceInfo( result.getSourceInfo() ); | ||
11621 | m_xml.writeText( result.getMessage() ); | ||
11622 | m_xml.endElement(); | ||
11623 | break; | ||
11624 | case ResultWas::Info: | ||
11625 | m_xml.scopedElement( "Info" ) | ||
11626 | .writeText( result.getMessage() ); | ||
11627 | break; | ||
11628 | case ResultWas::Warning: | ||
11629 | // Warning will already have been written | ||
11630 | break; | ||
11631 | case ResultWas::ExplicitFailure: | ||
11632 | m_xml.startElement( "Failure" ); | ||
11633 | writeSourceInfo( result.getSourceInfo() ); | ||
11634 | m_xml.writeText( result.getMessage() ); | ||
11635 | m_xml.endElement(); | ||
11636 | break; | ||
11637 | case ResultWas::ExplicitSkip: | ||
11638 | m_xml.startElement( "Skip" ); | ||
11639 | writeSourceInfo( result.getSourceInfo() ); | ||
11640 | m_xml.writeText( result.getMessage() ); | ||
11641 | m_xml.endElement(); | ||
11642 | break; | ||
11643 | default: | ||
11644 | break; | ||
11645 | } | ||
11646 | |||
11647 | if( result.hasExpression() ) | ||
11648 | m_xml.endElement(); | ||
11649 | } | ||
11650 | |||
11651 | void XmlReporter::sectionEnded( SectionStats const& sectionStats ) { | ||
11652 | StreamingReporterBase::sectionEnded( sectionStats ); | ||
11653 | if ( --m_sectionDepth > 0 ) { | ||
11654 | { | ||
11655 | XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); | ||
11656 | e.writeAttribute( "successes"_sr, sectionStats.assertions.passed ); | ||
11657 | e.writeAttribute( "failures"_sr, sectionStats.assertions.failed ); | ||
11658 | e.writeAttribute( "expectedFailures"_sr, sectionStats.assertions.failedButOk ); | ||
11659 | e.writeAttribute( "skipped"_sr, sectionStats.assertions.skipped > 0 ); | ||
11660 | |||
11661 | if ( m_config->showDurations() == ShowDurations::Always ) | ||
11662 | e.writeAttribute( "durationInSeconds"_sr, sectionStats.durationInSeconds ); | ||
11663 | } | ||
11664 | // Ends assertion tag | ||
11665 | m_xml.endElement(); | ||
11666 | } | ||
11667 | } | ||
11668 | |||
11669 | void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { | ||
11670 | StreamingReporterBase::testCaseEnded( testCaseStats ); | ||
11671 | XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); | ||
11672 | e.writeAttribute( "success"_sr, testCaseStats.totals.assertions.allOk() ); | ||
11673 | e.writeAttribute( "skips"_sr, testCaseStats.totals.assertions.skipped ); | ||
11674 | |||
11675 | if ( m_config->showDurations() == ShowDurations::Always ) | ||
11676 | e.writeAttribute( "durationInSeconds"_sr, m_testCaseTimer.getElapsedSeconds() ); | ||
11677 | if( !testCaseStats.stdOut.empty() ) | ||
11678 | m_xml.scopedElement( "StdOut" ).writeText( trim( StringRef(testCaseStats.stdOut) ), XmlFormatting::Newline ); | ||
11679 | if( !testCaseStats.stdErr.empty() ) | ||
11680 | m_xml.scopedElement( "StdErr" ).writeText( trim( StringRef(testCaseStats.stdErr) ), XmlFormatting::Newline ); | ||
11681 | |||
11682 | m_xml.endElement(); | ||
11683 | } | ||
11684 | |||
11685 | void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) { | ||
11686 | StreamingReporterBase::testRunEnded( testRunStats ); | ||
11687 | m_xml.scopedElement( "OverallResults" ) | ||
11688 | .writeAttribute( "successes"_sr, testRunStats.totals.assertions.passed ) | ||
11689 | .writeAttribute( "failures"_sr, testRunStats.totals.assertions.failed ) | ||
11690 | .writeAttribute( "expectedFailures"_sr, testRunStats.totals.assertions.failedButOk ) | ||
11691 | .writeAttribute( "skips"_sr, testRunStats.totals.assertions.skipped ); | ||
11692 | m_xml.scopedElement( "OverallResultsCases") | ||
11693 | .writeAttribute( "successes"_sr, testRunStats.totals.testCases.passed ) | ||
11694 | .writeAttribute( "failures"_sr, testRunStats.totals.testCases.failed ) | ||
11695 | .writeAttribute( "expectedFailures"_sr, testRunStats.totals.testCases.failedButOk ) | ||
11696 | .writeAttribute( "skips"_sr, testRunStats.totals.testCases.skipped ); | ||
11697 | m_xml.endElement(); | ||
11698 | } | ||
11699 | |||
11700 | void XmlReporter::benchmarkPreparing( StringRef name ) { | ||
11701 | m_xml.startElement("BenchmarkResults") | ||
11702 | .writeAttribute("name"_sr, name); | ||
11703 | } | ||
11704 | |||
11705 | void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) { | ||
11706 | m_xml.writeAttribute("samples"_sr, info.samples) | ||
11707 | .writeAttribute("resamples"_sr, info.resamples) | ||
11708 | .writeAttribute("iterations"_sr, info.iterations) | ||
11709 | .writeAttribute("clockResolution"_sr, info.clockResolution) | ||
11710 | .writeAttribute("estimatedDuration"_sr, info.estimatedDuration) | ||
11711 | .writeComment("All values in nano seconds"_sr); | ||
11712 | } | ||
11713 | |||
11714 | void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) { | ||
11715 | m_xml.scopedElement("mean") | ||
11716 | .writeAttribute("value"_sr, benchmarkStats.mean.point.count()) | ||
11717 | .writeAttribute("lowerBound"_sr, benchmarkStats.mean.lower_bound.count()) | ||
11718 | .writeAttribute("upperBound"_sr, benchmarkStats.mean.upper_bound.count()) | ||
11719 | .writeAttribute("ci"_sr, benchmarkStats.mean.confidence_interval); | ||
11720 | m_xml.scopedElement("standardDeviation") | ||
11721 | .writeAttribute("value"_sr, benchmarkStats.standardDeviation.point.count()) | ||
11722 | .writeAttribute("lowerBound"_sr, benchmarkStats.standardDeviation.lower_bound.count()) | ||
11723 | .writeAttribute("upperBound"_sr, benchmarkStats.standardDeviation.upper_bound.count()) | ||
11724 | .writeAttribute("ci"_sr, benchmarkStats.standardDeviation.confidence_interval); | ||
11725 | m_xml.scopedElement("outliers") | ||
11726 | .writeAttribute("variance"_sr, benchmarkStats.outlierVariance) | ||
11727 | .writeAttribute("lowMild"_sr, benchmarkStats.outliers.low_mild) | ||
11728 | .writeAttribute("lowSevere"_sr, benchmarkStats.outliers.low_severe) | ||
11729 | .writeAttribute("highMild"_sr, benchmarkStats.outliers.high_mild) | ||
11730 | .writeAttribute("highSevere"_sr, benchmarkStats.outliers.high_severe); | ||
11731 | m_xml.endElement(); | ||
11732 | } | ||
11733 | |||
11734 | void XmlReporter::benchmarkFailed(StringRef error) { | ||
11735 | m_xml.scopedElement("failed"). | ||
11736 | writeAttribute("message"_sr, error); | ||
11737 | m_xml.endElement(); | ||
11738 | } | ||
11739 | |||
11740 | void XmlReporter::listReporters(std::vector<ReporterDescription> const& descriptions) { | ||
11741 | auto outerTag = m_xml.scopedElement("AvailableReporters"); | ||
11742 | for (auto const& reporter : descriptions) { | ||
11743 | auto inner = m_xml.scopedElement("Reporter"); | ||
11744 | m_xml.startElement("Name", XmlFormatting::Indent) | ||
11745 | .writeText(reporter.name, XmlFormatting::None) | ||
11746 | .endElement(XmlFormatting::Newline); | ||
11747 | m_xml.startElement("Description", XmlFormatting::Indent) | ||
11748 | .writeText(reporter.description, XmlFormatting::None) | ||
11749 | .endElement(XmlFormatting::Newline); | ||
11750 | } | ||
11751 | } | ||
11752 | |||
11753 | void XmlReporter::listListeners(std::vector<ListenerDescription> const& descriptions) { | ||
11754 | auto outerTag = m_xml.scopedElement( "RegisteredListeners" ); | ||
11755 | for ( auto const& listener : descriptions ) { | ||
11756 | auto inner = m_xml.scopedElement( "Listener" ); | ||
11757 | m_xml.startElement( "Name", XmlFormatting::Indent ) | ||
11758 | .writeText( listener.name, XmlFormatting::None ) | ||
11759 | .endElement( XmlFormatting::Newline ); | ||
11760 | m_xml.startElement( "Description", XmlFormatting::Indent ) | ||
11761 | .writeText( listener.description, XmlFormatting::None ) | ||
11762 | .endElement( XmlFormatting::Newline ); | ||
11763 | } | ||
11764 | } | ||
11765 | |||
11766 | void XmlReporter::listTests(std::vector<TestCaseHandle> const& tests) { | ||
11767 | auto outerTag = m_xml.scopedElement("MatchingTests"); | ||
11768 | for (auto const& test : tests) { | ||
11769 | auto innerTag = m_xml.scopedElement("TestCase"); | ||
11770 | auto const& testInfo = test.getTestCaseInfo(); | ||
11771 | m_xml.startElement("Name", XmlFormatting::Indent) | ||
11772 | .writeText(testInfo.name, XmlFormatting::None) | ||
11773 | .endElement(XmlFormatting::Newline); | ||
11774 | m_xml.startElement("ClassName", XmlFormatting::Indent) | ||
11775 | .writeText(testInfo.className, XmlFormatting::None) | ||
11776 | .endElement(XmlFormatting::Newline); | ||
11777 | m_xml.startElement("Tags", XmlFormatting::Indent) | ||
11778 | .writeText(testInfo.tagsAsString(), XmlFormatting::None) | ||
11779 | .endElement(XmlFormatting::Newline); | ||
11780 | |||
11781 | auto sourceTag = m_xml.scopedElement("SourceInfo"); | ||
11782 | m_xml.startElement("File", XmlFormatting::Indent) | ||
11783 | .writeText(testInfo.lineInfo.file, XmlFormatting::None) | ||
11784 | .endElement(XmlFormatting::Newline); | ||
11785 | m_xml.startElement("Line", XmlFormatting::Indent) | ||
11786 | .writeText(std::to_string(testInfo.lineInfo.line), XmlFormatting::None) | ||
11787 | .endElement(XmlFormatting::Newline); | ||
11788 | } | ||
11789 | } | ||
11790 | |||
11791 | void XmlReporter::listTags(std::vector<TagInfo> const& tags) { | ||
11792 | auto outerTag = m_xml.scopedElement("TagsFromMatchingTests"); | ||
11793 | for (auto const& tag : tags) { | ||
11794 | auto innerTag = m_xml.scopedElement("Tag"); | ||
11795 | m_xml.startElement("Count", XmlFormatting::Indent) | ||
11796 | .writeText(std::to_string(tag.count), XmlFormatting::None) | ||
11797 | .endElement(XmlFormatting::Newline); | ||
11798 | auto aliasTag = m_xml.scopedElement("Aliases"); | ||
11799 | for (auto const& alias : tag.spellings) { | ||
11800 | m_xml.startElement("Alias", XmlFormatting::Indent) | ||
11801 | .writeText(alias, XmlFormatting::None) | ||
11802 | .endElement(XmlFormatting::Newline); | ||
11803 | } | ||
11804 | } | ||
11805 | } | ||
11806 | |||
11807 | } // end namespace Catch | ||
11808 | |||
11809 | #if defined(_MSC_VER) | ||
11810 | #pragma warning(pop) | ||
11811 | #endif | ||