Debian Codegraph @

Tests/Contrib/catch2/catch_amalgamated.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright Catch2 Authors
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file LICENSE_1_0.txt or copy at
4 // https://www.boost.org/LICENSE_1_0.txt)
5
6 // SPDX-License-Identifier: BSL-1.0
7
8 // Catch v3.1.1
9 // Generated: 2022-10-17 18:47:22.400176
10 // ----------------------------------------------------------
11 // This file is an amalgamation of multiple different files.
12 // You probably shouldn't edit it directly.
13 // ----------------------------------------------------------
14
15 #include "catch_all.hpp"
16
17
18 #ifndef CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
19 #define CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
20
21
22 #if defined(CATCH_PLATFORM_WINDOWS)
23
24 // We might end up with the define made globally through the compiler,
25 // and we don't want to trigger warnings for this
26 #if !defined(NOMINMAX)
27 # define NOMINMAX
28 #endif
29 #if !defined(WIN32_LEAN_AND_MEAN)
30 # define WIN32_LEAN_AND_MEAN
31 #endif
32
33 #include <windows.h>
34
35 #endif // defined(CATCH_PLATFORM_WINDOWS)
36
37 #endif // CATCH_WINDOWS_H_PROXY_HPP_INCLUDED
38
39
40
41
42 namespace Catch {
43 namespace Benchmark {
44 namespace Detail {
45 ChronometerConcept::~ChronometerConcept() = default;
46 } // namespace Detail
47 } // namespace Benchmark
48 } // namespace Catch
49
50
51
52
53 namespace Catch {
54 namespace Benchmark {
55 namespace Detail {
56 BenchmarkFunction::callable::~callable() = default;
57 } // namespace Detail
58 } // namespace Benchmark
59 } // namespace Catch
60
61
62
63 #include <exception>
64
65 namespace Catch {
66 namespace Benchmark {
67 namespace Detail {
68 struct optimized_away_error : std::exception {
69 const char* what() const noexcept override;
70 };
71
72 const char* optimized_away_error::what() const noexcept {
73 return "could not measure benchmark, maybe it was optimized away";
74 }
75
76 void throw_optimized_away_error() {
77 Catch::throw_exception(optimized_away_error{});
78 }
79
80 } // namespace Detail
81 } // namespace Benchmark
82 } // namespace Catch
83
84
85 // Adapted from donated nonius code.
86
87
88
89 #include <cassert>
90 #include <cstddef>
91 #include <iterator>
92 #include <random>
93
94
95 #if defined(CATCH_CONFIG_USE_ASYNC)
96 #include <future>
97 #endif
98
99 namespace {
100
101 using Catch::Benchmark::Detail::sample;
102
103 template <typename URng, typename Estimator>
104 sample resample(URng& rng, unsigned int resamples, std::vector<double>::iterator first, std::vector<double>::iterator last, Estimator& estimator) {
105 auto n = static_cast<size_t>(last - first);
106 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
107
108 sample out;
109 out.reserve(resamples);
110 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
111 std::vector<double> resampled;
112 resampled.reserve(n);
113 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[static_cast<std::ptrdiff_t>(dist(rng))]; });
114 return estimator(resampled.begin(), resampled.end());
115 });
116 std::sort(out.begin(), out.end());
117 return out;
118 }
119
120
121 double erf_inv(double x) {
122 // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
123 double w, p;
124
125 w = -log((1.0 - x) * (1.0 + x));
126
127 if (w < 6.250000) {
128 w = w - 3.125000;
129 p = -3.6444120640178196996e-21;
130 p = -1.685059138182016589e-19 + p * w;
131 p = 1.2858480715256400167e-18 + p * w;
132 p = 1.115787767802518096e-17 + p * w;
133 p = -1.333171662854620906e-16 + p * w;
134 p = 2.0972767875968561637e-17 + p * w;
135 p = 6.6376381343583238325e-15 + p * w;
136 p = -4.0545662729752068639e-14 + p * w;
137 p = -8.1519341976054721522e-14 + p * w;
138 p = 2.6335093153082322977e-12 + p * w;
139 p = -1.2975133253453532498e-11 + p * w;
140 p = -5.4154120542946279317e-11 + p * w;
141 p = 1.051212273321532285e-09 + p * w;
142 p = -4.1126339803469836976e-09 + p * w;
143 p = -2.9070369957882005086e-08 + p * w;
144 p = 4.2347877827932403518e-07 + p * w;
145 p = -1.3654692000834678645e-06 + p * w;
146 p = -1.3882523362786468719e-05 + p * w;
147 p = 0.0001867342080340571352 + p * w;
148 p = -0.00074070253416626697512 + p * w;
149 p = -0.0060336708714301490533 + p * w;
150 p = 0.24015818242558961693 + p * w;
151 p = 1.6536545626831027356 + p * w;
152 } else if (w < 16.000000) {
153 w = sqrt(w) - 3.250000;
154 p = 2.2137376921775787049e-09;
155 p = 9.0756561938885390979e-08 + p * w;
156 p = -2.7517406297064545428e-07 + p * w;
157 p = 1.8239629214389227755e-08 + p * w;
158 p = 1.5027403968909827627e-06 + p * w;
159 p = -4.013867526981545969e-06 + p * w;
160 p = 2.9234449089955446044e-06 + p * w;
161 p = 1.2475304481671778723e-05 + p * w;
162 p = -4.7318229009055733981e-05 + p * w;
163 p = 6.8284851459573175448e-05 + p * w;
164 p = 2.4031110387097893999e-05 + p * w;
165 p = -0.0003550375203628474796 + p * w;
166 p = 0.00095328937973738049703 + p * w;
167 p = -0.0016882755560235047313 + p * w;
168 p = 0.0024914420961078508066 + p * w;
169 p = -0.0037512085075692412107 + p * w;
170 p = 0.005370914553590063617 + p * w;
171 p = 1.0052589676941592334 + p * w;
172 p = 3.0838856104922207635 + p * w;
173 } else {
174 w = sqrt(w) - 5.000000;
175 p = -2.7109920616438573243e-11;
176 p = -2.5556418169965252055e-10 + p * w;
177 p = 1.5076572693500548083e-09 + p * w;
178 p = -3.7894654401267369937e-09 + p * w;
179 p = 7.6157012080783393804e-09 + p * w;
180 p = -1.4960026627149240478e-08 + p * w;
181 p = 2.9147953450901080826e-08 + p * w;
182 p = -6.7711997758452339498e-08 + p * w;
183 p = 2.2900482228026654717e-07 + p * w;
184 p = -9.9298272942317002539e-07 + p * w;
185 p = 4.5260625972231537039e-06 + p * w;
186 p = -1.9681778105531670567e-05 + p * w;
187 p = 7.5995277030017761139e-05 + p * w;
188 p = -0.00021503011930044477347 + p * w;
189 p = -0.00013871931833623122026 + p * w;
190 p = 1.0103004648645343977 + p * w;
191 p = 4.8499064014085844221 + p * w;
192 }
193 return p * x;
194 }
195
196 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
197 auto m = Catch::Benchmark::Detail::mean(first, last);
198 double variance = std::accumulate( first,
199 last,
200 0.,
201 [m]( double a, double b ) {
202 double diff = b - m;
203 return a + diff * diff;
204 } ) /
205 ( last - first );
206 return std::sqrt( variance );
207 }
208
209 }
210
211 namespace Catch {
212 namespace Benchmark {
213 namespace Detail {
214
215 #if defined( __GNUC__ ) || defined( __clang__ )
216 # pragma GCC diagnostic push
217 # pragma GCC diagnostic ignored "-Wfloat-equal"
218 #endif
219 bool directCompare( double lhs, double rhs ) { return lhs == rhs; }
220 #if defined( __GNUC__ ) || defined( __clang__ )
221 # pragma GCC diagnostic pop
222 #endif
223
224 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
225 auto count = last - first;
226 double idx = (count - 1) * k / static_cast<double>(q);
227 int j = static_cast<int>(idx);
228 double g = idx - j;
229 std::nth_element(first, first + j, last);
230 auto xj = first[j];
231 if ( directCompare( g, 0 ) ) {
232 return xj;
233 }
234
235 auto xj1 = *std::min_element(first + (j + 1), last);
236 return xj + g * (xj1 - xj);
237 }
238
239
240 double erfc_inv(double x) {
241 return erf_inv(1.0 - x);
242 }
243
244 double normal_quantile(double p) {
245 static const double ROOT_TWO = std::sqrt(2.0);
246
247 double result = 0.0;
248 assert(p >= 0 && p <= 1);
249 if (p < 0 || p > 1) {
250 return result;
251 }
252
253 result = -erfc_inv(2.0 * p);
254 // result *= normal distribution standard deviation (1.0) * sqrt(2)
255 result *= /*sd * */ ROOT_TWO;
256 // result += normal disttribution mean (0)
257 return result;
258 }
259
260
261 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
262 double sb = stddev.point;
263 double mn = mean.point / n;
264 double mg_min = mn / 2.;
265 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
266 double sg2 = sg * sg;
267 double sb2 = sb * sb;
268
269 auto c_max = [n, mn, sb2, sg2](double x) -> double {
270 double k = mn - x;
271 double d = k * k;
272 double nd = n * d;
273 double k0 = -n * nd;
274 double k1 = sb2 - n * sg2 + nd;
275 double det = k1 * k1 - 4 * sg2 * k0;
276 return static_cast<int>(-2. * k0 / (k1 + std::sqrt(det)));
277 };
278
279 auto var_out = [n, sb2, sg2](double c) {
280 double nc = n - c;
281 return (nc / n) * (sb2 - nc * sg2);
282 };
283
284 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
285 }
286
287
288 bootstrap_analysis analyse_samples(double confidence_level, unsigned int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
289 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
290 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
291 static std::random_device entropy;
292 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
293
294 auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
295
296 auto mean = &Detail::mean<std::vector<double>::iterator>;
297 auto stddev = &standard_deviation;
298
299 #if defined(CATCH_CONFIG_USE_ASYNC)
300 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
301 auto seed = entropy();
302 return std::async(std::launch::async, [=] {
303 std::mt19937 rng(seed);
304 auto resampled = resample(rng, n_resamples, first, last, f);
305 return bootstrap(confidence_level, first, last, resampled, f);
306 });
307 };
308
309 auto mean_future = Estimate(mean);
310 auto stddev_future = Estimate(stddev);
311
312 auto mean_estimate = mean_future.get();
313 auto stddev_estimate = stddev_future.get();
314 #else
315 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
316 auto seed = entropy();
317 std::mt19937 rng(seed);
318 auto resampled = resample(rng, n_resamples, first, last, f);
319 return bootstrap(confidence_level, first, last, resampled, f);
320 };
321
322 auto mean_estimate = Estimate(mean);
323 auto stddev_estimate = Estimate(stddev);
324 #endif // CATCH_USE_ASYNC
325
326 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
327
328 return { mean_estimate, stddev_estimate, outlier_variance };
329 }
330 } // namespace Detail
331 } // namespace Benchmark
332 } // namespace Catch
333
334
335
336 #include <cmath>
337 #include <limits>
338
339 namespace {
340
341 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
342 // But without the subtraction to allow for INFINITY in comparison
343 bool marginComparison(double lhs, double rhs, double margin) {
344 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
345 }
346
347 }
348
349 namespace Catch {
350
351 Approx::Approx ( double value )
352 : m_epsilon( std::numeric_limits<float>::epsilon()*100. ),
353 m_margin( 0.0 ),
354 m_scale( 0.0 ),
355 m_value( value )
356 {}
357
358 Approx Approx::custom() {
359 return Approx( 0 );
360 }
361
362 Approx Approx::operator-() const {
363 auto temp(*this);
364 temp.m_value = -temp.m_value;
365 return temp;
366 }
367
368
369 std::string Approx::toString() const {
370 ReusableStringStream rss;
371 rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
372 return rss.str();
373 }
374
375 bool Approx::equalityComparisonImpl(const double other) const {
376 // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
377 // Thanks to Richard Harris for his help refining the scaled margin value
378 return marginComparison(m_value, other, m_margin)
379 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
380 }
381
382 void Approx::setMargin(double newMargin) {
383 CATCH_ENFORCE(newMargin >= 0,
384 "Invalid Approx::margin: " << newMargin << '.'
385 << " Approx::Margin has to be non-negative.");
386 m_margin = newMargin;
387 }
388
389 void Approx::setEpsilon(double newEpsilon) {
390 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
391 "Invalid Approx::epsilon: " << newEpsilon << '.'
392 << " Approx::epsilon has to be in [0, 1]");
393 m_epsilon = newEpsilon;
394 }
395
396 namespace literals {
397 Approx operator "" _a(long double val) {
398 return Approx(val);
399 }
400 Approx operator "" _a(unsigned long long val) {
401 return Approx(val);
402 }
403 } // end namespace literals
404
405 std::string StringMaker<Catch::Approx>::convert(Catch::Approx const& value) {
406 return value.toString();
407 }
408
409 } // end namespace Catch
410
411
412
413 namespace Catch {
414
415 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
416 lazyExpression(_lazyExpression),
417 resultType(_resultType) {}
418
419 std::string AssertionResultData::reconstructExpression() const {
420
421 if( reconstructedExpression.empty() ) {
422 if( lazyExpression ) {
423 ReusableStringStream rss;
424 rss << lazyExpression;
425 reconstructedExpression = rss.str();
426 }
427 }
428 return reconstructedExpression;
429 }
430
431 AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
432 : m_info( info ),
433 m_resultData( data )
434 {}
435
436 // Result was a success
437 bool AssertionResult::succeeded() const {
438 return Catch::isOk( m_resultData.resultType );
439 }
440
441 // Result was a success, or failure is suppressed
442 bool AssertionResult::isOk() const {
443 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
444 }
445
446 ResultWas::OfType AssertionResult::getResultType() const {
447 return m_resultData.resultType;
448 }
449
450 bool AssertionResult::hasExpression() const {
451 return !m_info.capturedExpression.empty();
452 }
453
454 bool AssertionResult::hasMessage() const {
455 return !m_resultData.message.empty();
456 }
457
458 std::string AssertionResult::getExpression() const {
459 // Possibly overallocating by 3 characters should be basically free
460 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
461 if (isFalseTest(m_info.resultDisposition)) {
462 expr += "!(";
463 }
464 expr += m_info.capturedExpression;
465 if (isFalseTest(m_info.resultDisposition)) {
466 expr += ')';
467 }
468 return expr;
469 }
470
471 std::string AssertionResult::getExpressionInMacro() const {
472 std::string expr;
473 if( m_info.macroName.empty() )
474 expr = static_cast<std::string>(m_info.capturedExpression);
475 else {
476 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
477 expr += m_info.macroName;
478 expr += "( ";
479 expr += m_info.capturedExpression;
480 expr += " )";
481 }
482 return expr;
483 }
484
485 bool AssertionResult::hasExpandedExpression() const {
486 return hasExpression() && getExpandedExpression() != getExpression();
487 }
488
489 std::string AssertionResult::getExpandedExpression() const {
490 std::string expr = m_resultData.reconstructExpression();
491 return expr.empty()
492 ? getExpression()
493 : expr;
494 }
495
496 StringRef AssertionResult::getMessage() const {
497 return m_resultData.message;
498 }
499 SourceLineInfo AssertionResult::getSourceInfo() const {
500 return m_info.lineInfo;
501 }
502
503 StringRef AssertionResult::getTestMacroName() const {
504 return m_info.macroName;
505 }
506
507 } // end namespace Catch
508
509
510
511 namespace {
512 bool provideBazelReporterOutput() {
513 #if defined(CATCH_CONFIG_BAZEL_SUPPORT)
514 return true;
515 #elif defined(CATCH_PLATFORM_WINDOWS_UWP)
516 // UWP does not support environment variables
517 return false;
518 #else
519
520 # if defined( _MSC_VER )
521 // On Windows getenv throws a warning as there is no input validation,
522 // since the switch is hardcoded, this should not be an issue.
523 # pragma warning( push )
524 # pragma warning( disable : 4996 )
525 # endif
526
527 return std::getenv( "BAZEL_TEST" ) != nullptr;
528
529 # if defined( _MSC_VER )
530 # pragma warning( pop )
531 # endif
532 #endif
533 }
534 }
535
536 namespace Catch {
537
538 bool operator==( ProcessedReporterSpec const& lhs,
539 ProcessedReporterSpec const& rhs ) {
540 return lhs.name == rhs.name &&
541 lhs.outputFilename == rhs.outputFilename &&
542 lhs.colourMode == rhs.colourMode &&
543 lhs.customOptions == rhs.customOptions;
544 }
545
546 Config::Config( ConfigData const& data ):
547 m_data( data ) {
548 // We need to trim filter specs to avoid trouble with superfluous
549 // whitespace (esp. important for bdd macros, as those are manually
550 // aligned with whitespace).
551
552 for (auto& elem : m_data.testsOrTags) {
553 elem = trim(elem);
554 }
555 for (auto& elem : m_data.sectionsToRun) {
556 elem = trim(elem);
557 }
558
559
560 TestSpecParser parser(ITagAliasRegistry::get());
561 if (!m_data.testsOrTags.empty()) {
562 m_hasTestFilters = true;
563 for (auto const& testOrTags : m_data.testsOrTags) {
564 parser.parse(testOrTags);
565 }
566 }
567 m_testSpec = parser.testSpec();
568
569
570 // Insert the default reporter if user hasn't asked for a specfic one
571 if ( m_data.reporterSpecifications.empty() ) {
572 m_data.reporterSpecifications.push_back( {
573 #if defined( CATCH_CONFIG_DEFAULT_REPORTER )
574 CATCH_CONFIG_DEFAULT_REPORTER,
575 #else
576 "console",
577 #endif
578 {}, {}, {}
579 } );
580 }
581
582 #if !defined(CATCH_PLATFORM_WINDOWS_UWP)
583 if(provideBazelReporterOutput()){
584 // Register a JUnit reporter for Bazel. Bazel sets an environment
585 // variable with the path to XML output. If this file is written to
586 // during test, Bazel will not generate a default XML output.
587 // This allows the XML output file to contain higher level of detail
588 // than what is possible otherwise.
589 # if defined( _MSC_VER )
590 // On Windows getenv throws a warning as there is no input validation,
591 // since the key is hardcoded, this should not be an issue.
592 # pragma warning( push )
593 # pragma warning( disable : 4996 )
594 # endif
595 const auto bazelOutputFilePtr = std::getenv( "XML_OUTPUT_FILE" );
596 # if defined( _MSC_VER )
597 # pragma warning( pop )
598 # endif
599 if ( bazelOutputFilePtr != nullptr ) {
600 m_data.reporterSpecifications.push_back(
601 { "junit", std::string( bazelOutputFilePtr ), {}, {} } );
602 }
603 }
604 #endif
605
606 // We now fixup the reporter specs to handle default output spec,
607 // default colour spec, etc
608 bool defaultOutputUsed = false;
609 for ( auto const& reporterSpec : m_data.reporterSpecifications ) {
610 // We do the default-output check separately, while always
611 // using the default output below to make the code simpler
612 // and avoid superfluous copies.
613 if ( reporterSpec.outputFile().none() ) {
614 CATCH_ENFORCE( !defaultOutputUsed,
615 "Internal error: cannot use default output for "
616 "multiple reporters" );
617 defaultOutputUsed = true;
618 }
619
620 m_processedReporterSpecs.push_back( ProcessedReporterSpec{
621 reporterSpec.name(),
622 reporterSpec.outputFile() ? *reporterSpec.outputFile()
623 : data.defaultOutputFilename,
624 reporterSpec.colourMode().valueOr( data.defaultColourMode ),
625 reporterSpec.customOptions() } );
626 }
627 }
628
629 Config::~Config() = default;
630
631
632 bool Config::listTests() const { return m_data.listTests; }
633 bool Config::listTags() const { return m_data.listTags; }
634 bool Config::listReporters() const { return m_data.listReporters; }
635 bool Config::listListeners() const { return m_data.listListeners; }
636
637 std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
638 std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
639
640 std::vector<ReporterSpec> const& Config::getReporterSpecs() const {
641 return m_data.reporterSpecifications;
642 }
643
644 std::vector<ProcessedReporterSpec> const&
645 Config::getProcessedReporterSpecs() const {
646 return m_processedReporterSpecs;
647 }
648
649 TestSpec const& Config::testSpec() const { return m_testSpec; }
650 bool Config::hasTestFilters() const { return m_hasTestFilters; }
651
652 bool Config::showHelp() const { return m_data.showHelp; }
653
654 // IConfig interface
655 bool Config::allowThrows() const { return !m_data.noThrow; }
656 StringRef Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
657 bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
658 bool Config::warnAboutMissingAssertions() const {
659 return !!( m_data.warnings & WarnAbout::NoAssertions );
660 }
661 bool Config::warnAboutUnmatchedTestSpecs() const {
662 return !!( m_data.warnings & WarnAbout::UnmatchedTestSpec );
663 }
664 bool Config::zeroTestsCountAsSuccess() const { return m_data.allowZeroTests; }
665 ShowDurations Config::showDurations() const { return m_data.showDurations; }
666 double Config::minDuration() const { return m_data.minDuration; }
667 TestRunOrder Config::runOrder() const { return m_data.runOrder; }
668 uint32_t Config::rngSeed() const { return m_data.rngSeed; }
669 unsigned int Config::shardCount() const { return m_data.shardCount; }
670 unsigned int Config::shardIndex() const { return m_data.shardIndex; }
671 ColourMode Config::defaultColourMode() const { return m_data.defaultColourMode; }
672 bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
673 int Config::abortAfter() const { return m_data.abortAfter; }
674 bool Config::showInvisibles() const { return m_data.showInvisibles; }
675 Verbosity Config::verbosity() const { return m_data.verbosity; }
676
677 bool Config::skipBenchmarks() const { return m_data.skipBenchmarks; }
678 bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
679 unsigned int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
680 double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
681 unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
682 std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
683
684 } // end namespace Catch
685
686
687
688
689
690 namespace Catch {
691 std::uint32_t getSeed() {
692 return getCurrentContext().getConfig()->rngSeed();
693 }
694 }
695
696
697
698 #include <cassert>
699 #include <stack>
700
701 namespace Catch {
702
703 ////////////////////////////////////////////////////////////////////////////
704
705
706 ScopedMessage::ScopedMessage( MessageBuilder const& builder ):
707 m_info( builder.m_info ) {
708 m_info.message = builder.m_stream.str();
709 getResultCapture().pushScopedMessage( m_info );
710 }
711
712 ScopedMessage::ScopedMessage( ScopedMessage&& old ) noexcept:
713 m_info( CATCH_MOVE( old.m_info ) ) {
714 old.m_moved = true;
715 }
716
717 ScopedMessage::~ScopedMessage() {
718 if ( !uncaught_exceptions() && !m_moved ){
719 getResultCapture().popScopedMessage(m_info);
720 }
721 }
722
723
724 Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
725 auto trimmed = [&] (size_t start, size_t end) {
726 while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
727 ++start;
728 }
729 while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
730 --end;
731 }
732 return names.substr(start, end - start + 1);
733 };
734 auto skipq = [&] (size_t start, char quote) {
735 for (auto i = start + 1; i < names.size() ; ++i) {
736 if (names[i] == quote)
737 return i;
738 if (names[i] == '\\')
739 ++i;
740 }
741 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
742 };
743
744 size_t start = 0;
745 std::stack<char> openings;
746 for (size_t pos = 0; pos < names.size(); ++pos) {
747 char c = names[pos];
748 switch (c) {
749 case '[':
750 case '{':
751 case '(':
752 // It is basically impossible to disambiguate between
753 // comparison and start of template args in this context
754 // case '<':
755 openings.push(c);
756 break;
757 case ']':
758 case '}':
759 case ')':
760 // case '>':
761 openings.pop();
762 break;
763 case '"':
764 case '\'':
765 pos = skipq(pos, c);
766 break;
767 case ',':
768 if (start != pos && openings.empty()) {
769 m_messages.emplace_back(macroName, lineInfo, resultType);
770 m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
771 m_messages.back().message += " := ";
772 start = pos;
773 }
774 }
775 }
776 assert(openings.empty() && "Mismatched openings");
777 m_messages.emplace_back(macroName, lineInfo, resultType);
778 m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
779 m_messages.back().message += " := ";
780 }
781 Capturer::~Capturer() {
782 if ( !uncaught_exceptions() ){
783 assert( m_captured == m_messages.size() );
784 for( size_t i = 0; i < m_captured; ++i )
785 m_resultCapture.popScopedMessage( m_messages[i] );
786 }
787 }
788
789 void Capturer::captureValue( size_t index, std::string const& value ) {
790 assert( index < m_messages.size() );
791 m_messages[index].message += value;
792 m_resultCapture.pushScopedMessage( m_messages[index] );
793 m_captured++;
794 }
795
796 } // end namespace Catch
797
798
799
800
801 namespace Catch {
802
803 namespace {
804
805 class RegistryHub : public IRegistryHub,
806 public IMutableRegistryHub,
807 private Detail::NonCopyable {
808
809 public: // IRegistryHub
810 RegistryHub() = default;
811 IReporterRegistry const& getReporterRegistry() const override {
812 return m_reporterRegistry;
813 }
814 ITestCaseRegistry const& getTestCaseRegistry() const override {
815 return m_testCaseRegistry;
816 }
817 IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
818 return m_exceptionTranslatorRegistry;
819 }
820 ITagAliasRegistry const& getTagAliasRegistry() const override {
821 return m_tagAliasRegistry;
822 }
823 StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
824 return m_exceptionRegistry;
825 }
826
827 public: // IMutableRegistryHub
828 void registerReporter( std::string const& name, IReporterFactoryPtr factory ) override {
829 m_reporterRegistry.registerReporter( name, CATCH_MOVE(factory) );
830 }
831 void registerListener( Detail::unique_ptr<EventListenerFactory> factory ) override {
832 m_reporterRegistry.registerListener( CATCH_MOVE(factory) );
833 }
834 void registerTest( Detail::unique_ptr<TestCaseInfo>&& testInfo, Detail::unique_ptr<ITestInvoker>&& invoker ) override {
835 m_testCaseRegistry.registerTest( CATCH_MOVE(testInfo), CATCH_MOVE(invoker) );
836 }
837 void registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator ) override {
838 m_exceptionTranslatorRegistry.registerTranslator( CATCH_MOVE(translator) );
839 }
840 void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
841 m_tagAliasRegistry.add( alias, tag, lineInfo );
842 }
843 void registerStartupException() noexcept override {
844 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
845 m_exceptionRegistry.add(std::current_exception());
846 #else
847 CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
848 #endif
849 }
850 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
851 return m_enumValuesRegistry;
852 }
853
854 private:
855 TestRegistry m_testCaseRegistry;
856 ReporterRegistry m_reporterRegistry;
857 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
858 TagAliasRegistry m_tagAliasRegistry;
859 StartupExceptionRegistry m_exceptionRegistry;
860 Detail::EnumValuesRegistry m_enumValuesRegistry;
861 };
862 }
863
864 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
865
866 IRegistryHub const& getRegistryHub() {
867 return RegistryHubSingleton::get();
868 }
869 IMutableRegistryHub& getMutableRegistryHub() {
870 return RegistryHubSingleton::getMutable();
871 }
872 void cleanUp() {
873 cleanupSingletons();
874 cleanUpContext();
875 }
876 std::string translateActiveException() {
877 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
878 }
879
880
881 } // end namespace Catch
882
883
884
885 #include <algorithm>
886 #include <cassert>
887 #include <iomanip>
888 #include <set>
889
890 namespace Catch {
891
892 namespace {
893 const int MaxExitCode = 255;
894
895 IEventListenerPtr createReporter(std::string const& reporterName, ReporterConfig&& config) {
896 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, CATCH_MOVE(config));
897 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << '\'');
898
899 return reporter;
900 }
901
902 IEventListenerPtr prepareReporters(Config const* config) {
903 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()
904 && config->getProcessedReporterSpecs().size() == 1) {
905 auto const& spec = config->getProcessedReporterSpecs()[0];
906 return createReporter(
907 spec.name,
908 ReporterConfig( config,
909 makeStream( spec.outputFilename ),
910 spec.colourMode,
911 spec.customOptions ) );
912 }
913
914 auto multi = Detail::make_unique<MultiReporter>(config);
915
916 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
917 for (auto const& listener : listeners) {
918 multi->addListener(listener->create(config));
919 }
920
921 for ( auto const& reporterSpec : config->getProcessedReporterSpecs() ) {
922 multi->addReporter( createReporter(
923 reporterSpec.name,
924 ReporterConfig( config,
925 makeStream( reporterSpec.outputFilename ),
926 reporterSpec.colourMode,
927 reporterSpec.customOptions ) ) );
928 }
929
930 return multi;
931 }
932
933 class TestGroup {
934 public:
935 explicit TestGroup(IEventListenerPtr&& reporter, Config const* config):
936 m_reporter(reporter.get()),
937 m_config{config},
938 m_context{config, CATCH_MOVE(reporter)} {
939
940 assert( m_config->testSpec().getInvalidSpecs().empty() &&
941 "Invalid test specs should be handled before running tests" );
942
943 auto const& allTestCases = getAllTestCasesSorted(*m_config);
944 auto const& testSpec = m_config->testSpec();
945 if ( !testSpec.hasFilters() ) {
946 for ( auto const& test : allTestCases ) {
947 if ( !test.getTestCaseInfo().isHidden() ) {
948 m_tests.emplace( &test );
949 }
950 }
951 } else {
952 m_matches =
953 testSpec.matchesByFilter( allTestCases, *m_config );
954 for ( auto const& match : m_matches ) {
955 m_tests.insert( match.tests.begin(),
956 match.tests.end() );
957 }
958 }
959
960 m_tests = createShard(m_tests, m_config->shardCount(), m_config->shardIndex());
961 }
962
963 Totals execute() {
964 Totals totals;
965 for (auto const& testCase : m_tests) {
966 if (!m_context.aborting())
967 totals += m_context.runTest(*testCase);
968 else
969 m_reporter->skipTest(testCase->getTestCaseInfo());
970 }
971
972 for (auto const& match : m_matches) {
973 if (match.tests.empty()) {
974 m_unmatchedTestSpecs = true;
975 m_reporter->noMatchingTestCases( match.name );
976 }
977 }
978
979 return totals;
980 }
981
982 bool hadUnmatchedTestSpecs() const {
983 return m_unmatchedTestSpecs;
984 }
985
986
987 private:
988 IEventListener* m_reporter;
989 Config const* m_config;
990 RunContext m_context;
991 std::set<TestCaseHandle const*> m_tests;
992 TestSpec::Matches m_matches;
993 bool m_unmatchedTestSpecs = false;
994 };
995
996 void applyFilenamesAsTags() {
997 for (auto const& testInfo : getRegistryHub().getTestCaseRegistry().getAllInfos()) {
998 testInfo->addFilenameTag();
999 }
1000 }
1001
1002 } // anon namespace
1003
1004 Session::Session() {
1005 static bool alreadyInstantiated = false;
1006 if( alreadyInstantiated ) {
1007 CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
1008 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
1009 }
1010
1011 // There cannot be exceptions at startup in no-exception mode.
1012 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
1013 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
1014 if ( !exceptions.empty() ) {
1015 config();
1016 getCurrentMutableContext().setConfig(m_config.get());
1017
1018 m_startupExceptions = true;
1019 auto errStream = makeStream( "%stderr" );
1020 auto colourImpl = makeColourImpl(
1021 ColourMode::PlatformDefault, errStream.get() );
1022 auto guard = colourImpl->guardColour( Colour::Red );
1023 errStream->stream() << "Errors occurred during startup!" << '\n';
1024 // iterate over all exceptions and notify user
1025 for ( const auto& ex_ptr : exceptions ) {
1026 try {
1027 std::rethrow_exception(ex_ptr);
1028 } catch ( std::exception const& ex ) {
1029 errStream->stream() << TextFlow::Column( ex.what() ).indent(2) << '\n';
1030 }
1031 }
1032 }
1033 #endif
1034
1035 alreadyInstantiated = true;
1036 m_cli = makeCommandLineParser( m_configData );
1037 }
1038 Session::~Session() {
1039 Catch::cleanUp();
1040 }
1041
1042 void Session::showHelp() const {
1043 Catch::cout()
1044 << "\nCatch2 v" << libraryVersion() << '\n'
1045 << m_cli << '\n'
1046 << "For more detailed usage please see the project docs\n\n" << std::flush;
1047 }
1048 void Session::libIdentify() {
1049 Catch::cout()
1050 << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
1051 << std::left << std::setw(16) << "category: " << "testframework\n"
1052 << std::left << std::setw(16) << "framework: " << "Catch2\n"
1053 << std::left << std::setw(16) << "version: " << libraryVersion() << '\n' << std::flush;
1054 }
1055
1056 int Session::applyCommandLine( int argc, char const * const * argv ) {
1057 if( m_startupExceptions )
1058 return 1;
1059
1060 auto result = m_cli.parse( Clara::Args( argc, argv ) );
1061
1062 if( !result ) {
1063 config();
1064 getCurrentMutableContext().setConfig(m_config.get());
1065 auto errStream = makeStream( "%stderr" );
1066 auto colour = makeColourImpl( ColourMode::PlatformDefault, errStream.get() );
1067
1068 errStream->stream()
1069 << colour->guardColour( Colour::Red )
1070 << "\nError(s) in input:\n"
1071 << TextFlow::Column( result.errorMessage() ).indent( 2 )
1072 << "\n\n";
1073 errStream->stream() << "Run with -? for usage\n\n" << std::flush;
1074 return MaxExitCode;
1075 }
1076
1077 if( m_configData.showHelp )
1078 showHelp();
1079 if( m_configData.libIdentify )
1080 libIdentify();
1081
1082 m_config.reset();
1083 return 0;
1084 }
1085
1086 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
1087 int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
1088
1089 char **utf8Argv = new char *[ argc ];
1090
1091 for ( int i = 0; i < argc; ++i ) {
1092 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
1093
1094 utf8Argv[ i ] = new char[ bufSize ];
1095
1096 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
1097 }
1098
1099 int returnCode = applyCommandLine( argc, utf8Argv );
1100
1101 for ( int i = 0; i < argc; ++i )
1102 delete [] utf8Argv[ i ];
1103
1104 delete [] utf8Argv;
1105
1106 return returnCode;
1107 }
1108 #endif
1109
1110 void Session::useConfigData( ConfigData const& configData ) {
1111 m_configData = configData;
1112 m_config.reset();
1113 }
1114
1115 int Session::run() {
1116 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
1117 Catch::cout() << "...waiting for enter/ return before starting\n" << std::flush;
1118 static_cast<void>(std::getchar());
1119 }
1120 int exitCode = runInternal();
1121 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
1122 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << '\n' << std::flush;
1123 static_cast<void>(std::getchar());
1124 }
1125 return exitCode;
1126 }
1127
1128 Clara::Parser const& Session::cli() const {
1129 return m_cli;
1130 }
1131 void Session::cli( Clara::Parser const& newParser ) {
1132 m_cli = newParser;
1133 }
1134 ConfigData& Session::configData() {
1135 return m_configData;
1136 }
1137 Config& Session::config() {
1138 if( !m_config )
1139 m_config = Detail::make_unique<Config>( m_configData );
1140 return *m_config;
1141 }
1142
1143 int Session::runInternal() {
1144 if( m_startupExceptions )
1145 return 1;
1146
1147 if (m_configData.showHelp || m_configData.libIdentify) {
1148 return 0;
1149 }
1150
1151 if ( m_configData.shardIndex >= m_configData.shardCount ) {
1152 Catch::cerr() << "The shard count (" << m_configData.shardCount
1153 << ") must be greater than the shard index ("
1154 << m_configData.shardIndex << ")\n"
1155 << std::flush;
1156 return 1;
1157 }
1158
1159 CATCH_TRY {
1160 config(); // Force config to be constructed
1161
1162 seedRng( *m_config );
1163
1164 if (m_configData.filenamesAsTags) {
1165 applyFilenamesAsTags();
1166 }
1167
1168 // Set up global config instance before we start calling into other functions
1169 getCurrentMutableContext().setConfig(m_config.get());
1170
1171 // Create reporter(s) so we can route listings through them
1172 auto reporter = prepareReporters(m_config.get());
1173
1174 auto const& invalidSpecs = m_config->testSpec().getInvalidSpecs();
1175 if ( !invalidSpecs.empty() ) {
1176 for ( auto const& spec : invalidSpecs ) {
1177 reporter->reportInvalidTestSpec( spec );
1178 }
1179 return 1;
1180 }
1181
1182
1183 // Handle list request
1184 if (list(*reporter, *m_config)) {
1185 return 0;
1186 }
1187
1188 TestGroup tests { CATCH_MOVE(reporter), m_config.get() };
1189 auto const totals = tests.execute();
1190
1191 if ( tests.hadUnmatchedTestSpecs()
1192 && m_config->warnAboutUnmatchedTestSpecs() ) {
1193 return 3;
1194 }
1195
1196 if ( totals.testCases.total() == 0
1197 && !m_config->zeroTestsCountAsSuccess() ) {
1198 return 2;
1199 }
1200
1201 // Note that on unices only the lower 8 bits are usually used, clamping
1202 // the return value to 255 prevents false negative when some multiple
1203 // of 256 tests has failed
1204 return (std::min) (MaxExitCode, static_cast<int>(totals.assertions.failed));
1205 }
1206 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
1207 catch( std::exception& ex ) {
1208 Catch::cerr() << ex.what() << '\n' << std::flush;
1209 return MaxExitCode;
1210 }
1211 #endif
1212 }
1213
1214 } // end namespace Catch
1215
1216
1217
1218
1219 namespace Catch {
1220
1221 RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
1222 CATCH_TRY {
1223 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
1224 } CATCH_CATCH_ALL {
1225 // Do not throw when constructing global objects, instead register the exception to be processed later
1226 getMutableRegistryHub().registerStartupException();
1227 }
1228 }
1229
1230 }
1231
1232
1233
1234 #include <cassert>
1235 #include <cctype>
1236 #include <algorithm>
1237
1238 namespace Catch {
1239
1240 namespace {
1241 using TCP_underlying_type = uint8_t;
1242 static_assert(sizeof(TestCaseProperties) == sizeof(TCP_underlying_type),
1243 "The size of the TestCaseProperties is different from the assumed size");
1244
1245 TestCaseProperties operator|(TestCaseProperties lhs, TestCaseProperties rhs) {
1246 return static_cast<TestCaseProperties>(
1247 static_cast<TCP_underlying_type>(lhs) | static_cast<TCP_underlying_type>(rhs)
1248 );
1249 }
1250
1251 TestCaseProperties& operator|=(TestCaseProperties& lhs, TestCaseProperties rhs) {
1252 lhs = static_cast<TestCaseProperties>(
1253 static_cast<TCP_underlying_type>(lhs) | static_cast<TCP_underlying_type>(rhs)
1254 );
1255 return lhs;
1256 }
1257
1258 TestCaseProperties operator&(TestCaseProperties lhs, TestCaseProperties rhs) {
1259 return static_cast<TestCaseProperties>(
1260 static_cast<TCP_underlying_type>(lhs) & static_cast<TCP_underlying_type>(rhs)
1261 );
1262 }
1263
1264 bool applies(TestCaseProperties tcp) {
1265 static_assert(static_cast<TCP_underlying_type>(TestCaseProperties::None) == 0,
1266 "TestCaseProperties::None must be equal to 0");
1267 return tcp != TestCaseProperties::None;
1268 }
1269
1270 TestCaseProperties parseSpecialTag( StringRef tag ) {
1271 if( !tag.empty() && tag[0] == '.' )
1272 return TestCaseProperties::IsHidden;
1273 else if( tag == "!throws"_sr )
1274 return TestCaseProperties::Throws;
1275 else if( tag == "!shouldfail"_sr )
1276 return TestCaseProperties::ShouldFail;
1277 else if( tag == "!mayfail"_sr )
1278 return TestCaseProperties::MayFail;
1279 else if( tag == "!nonportable"_sr )
1280 return TestCaseProperties::NonPortable;
1281 else if( tag == "!benchmark"_sr )
1282 return TestCaseProperties::Benchmark | TestCaseProperties::IsHidden;
1283 else
1284 return TestCaseProperties::None;
1285 }
1286 bool isReservedTag( StringRef tag ) {
1287 return parseSpecialTag( tag ) == TestCaseProperties::None
1288 && tag.size() > 0
1289 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
1290 }
1291 void enforceNotReservedTag( StringRef tag, SourceLineInfo const& _lineInfo ) {
1292 CATCH_ENFORCE( !isReservedTag(tag),
1293 "Tag name: [" << tag << "] is not allowed.\n"
1294 << "Tag names starting with non alphanumeric characters are reserved\n"
1295 << _lineInfo );
1296 }
1297
1298 std::string makeDefaultName() {
1299 static size_t counter = 0;
1300 return "Anonymous test case " + std::to_string(++counter);
1301 }
1302
1303 StringRef extractFilenamePart(StringRef filename) {
1304 size_t lastDot = filename.size();
1305 while (lastDot > 0 && filename[lastDot - 1] != '.') {
1306 --lastDot;
1307 }
1308 --lastDot;
1309
1310 size_t nameStart = lastDot;
1311 while (nameStart > 0 && filename[nameStart - 1] != '/' && filename[nameStart - 1] != '\\') {
1312 --nameStart;
1313 }
1314
1315 return filename.substr(nameStart, lastDot - nameStart);
1316 }
1317
1318 // Returns the upper bound on size of extra tags ([#file]+[.])
1319 size_t sizeOfExtraTags(StringRef filepath) {
1320 // [.] is 3, [#] is another 3
1321 const size_t extras = 3 + 3;
1322 return extractFilenamePart(filepath).size() + extras;
1323 }
1324 } // end unnamed namespace
1325
1326 bool operator<( Tag const& lhs, Tag const& rhs ) {
1327 Detail::CaseInsensitiveLess cmp;
1328 return cmp( lhs.original, rhs.original );
1329 }
1330 bool operator==( Tag const& lhs, Tag const& rhs ) {
1331 Detail::CaseInsensitiveEqualTo cmp;
1332 return cmp( lhs.original, rhs.original );
1333 }
1334
1335 Detail::unique_ptr<TestCaseInfo>
1336 makeTestCaseInfo(StringRef _className,
1337 NameAndTags const& nameAndTags,
1338 SourceLineInfo const& _lineInfo ) {
1339 return Detail::make_unique<TestCaseInfo>(_className, nameAndTags, _lineInfo);
1340 }
1341
1342 TestCaseInfo::TestCaseInfo(StringRef _className,
1343 NameAndTags const& _nameAndTags,
1344 SourceLineInfo const& _lineInfo):
1345 name( _nameAndTags.name.empty() ? makeDefaultName() : _nameAndTags.name ),
1346 className( _className ),
1347 lineInfo( _lineInfo )
1348 {
1349 StringRef originalTags = _nameAndTags.tags;
1350 // We need to reserve enough space to store all of the tags
1351 // (including optional hidden tag and filename tag)
1352 auto requiredSize = originalTags.size() + sizeOfExtraTags(_lineInfo.file);
1353 backingTags.reserve(requiredSize);
1354
1355 // We cannot copy the tags directly, as we need to normalize
1356 // some tags, so that [.foo] is copied as [.][foo].
1357 size_t tagStart = 0;
1358 size_t tagEnd = 0;
1359 bool inTag = false;
1360 for (size_t idx = 0; idx < originalTags.size(); ++idx) {
1361 auto c = originalTags[idx];
1362 if (c == '[') {
1363 assert(!inTag);
1364 inTag = true;
1365 tagStart = idx;
1366 }
1367 if (c == ']') {
1368 assert(inTag);
1369 inTag = false;
1370 tagEnd = idx;
1371 assert(tagStart < tagEnd);
1372
1373 // We need to check the tag for special meanings, copy
1374 // it over to backing storage and actually reference the
1375 // backing storage in the saved tags
1376 StringRef tagStr = originalTags.substr(tagStart+1, tagEnd - tagStart - 1);
1377 CATCH_ENFORCE(!tagStr.empty(), "Empty tags are not allowed");
1378 enforceNotReservedTag(tagStr, lineInfo);
1379 properties |= parseSpecialTag(tagStr);
1380 // When copying a tag to the backing storage, we need to
1381 // check if it is a merged hide tag, such as [.foo], and
1382 // if it is, we need to handle it as if it was [foo].
1383 if (tagStr.size() > 1 && tagStr[0] == '.') {
1384 tagStr = tagStr.substr(1, tagStr.size() - 1);
1385 }
1386 // We skip over dealing with the [.] tag, as we will add
1387 // it later unconditionally and then sort and unique all
1388 // the tags.
1389 internalAppendTag(tagStr);
1390 }
1391 (void)inTag; // Silence "set-but-unused" warning in release mode.
1392 }
1393 // Add [.] if relevant
1394 if (isHidden()) {
1395 internalAppendTag("."_sr);
1396 }
1397
1398 // Sort and prepare tags
1399 std::sort(begin(tags), end(tags));
1400 tags.erase(std::unique(begin(tags), end(tags)),
1401 end(tags));
1402 }
1403
1404 bool TestCaseInfo::isHidden() const {
1405 return applies( properties & TestCaseProperties::IsHidden );
1406 }
1407 bool TestCaseInfo::throws() const {
1408 return applies( properties & TestCaseProperties::Throws );
1409 }
1410 bool TestCaseInfo::okToFail() const {
1411 return applies( properties & (TestCaseProperties::ShouldFail | TestCaseProperties::MayFail ) );
1412 }
1413 bool TestCaseInfo::expectedToFail() const {
1414 return applies( properties & (TestCaseProperties::ShouldFail) );
1415 }
1416
1417 void TestCaseInfo::addFilenameTag() {
1418 std::string combined("#");
1419 combined += extractFilenamePart(lineInfo.file);
1420 internalAppendTag(combined);
1421 }
1422
1423 std::string TestCaseInfo::tagsAsString() const {
1424 std::string ret;
1425 // '[' and ']' per tag
1426 std::size_t full_size = 2 * tags.size();
1427 for (const auto& tag : tags) {
1428 full_size += tag.original.size();
1429 }
1430 ret.reserve(full_size);
1431 for (const auto& tag : tags) {
1432 ret.push_back('[');
1433 ret += tag.original;
1434 ret.push_back(']');
1435 }
1436
1437 return ret;
1438 }
1439
1440 void TestCaseInfo::internalAppendTag(StringRef tagStr) {
1441 backingTags += '[';
1442 const auto backingStart = backingTags.size();
1443 backingTags += tagStr;
1444 const auto backingEnd = backingTags.size();
1445 backingTags += ']';
1446 tags.emplace_back(StringRef(backingTags.c_str() + backingStart, backingEnd - backingStart));
1447 }
1448
1449 bool operator<( TestCaseInfo const& lhs, TestCaseInfo const& rhs ) {
1450 // We want to avoid redoing the string comparisons multiple times,
1451 // so we store the result of a three-way comparison before using
1452 // it in the actual comparison logic.
1453 const auto cmpName = lhs.name.compare( rhs.name );
1454 if ( cmpName != 0 ) {
1455 return cmpName < 0;
1456 }
1457 const auto cmpClassName = lhs.className.compare( rhs.className );
1458 if ( cmpClassName != 0 ) {
1459 return cmpClassName < 0;
1460 }
1461 return lhs.tags < rhs.tags;
1462 }
1463
1464 TestCaseInfo const& TestCaseHandle::getTestCaseInfo() const {
1465 return *m_info;
1466 }
1467
1468 } // end namespace Catch
1469
1470
1471
1472 #include <algorithm>
1473 #include <string>
1474 #include <vector>
1475
1476 namespace Catch {
1477
1478 TestSpec::Pattern::Pattern( std::string const& name )
1479 : m_name( name )
1480 {}
1481
1482 TestSpec::Pattern::~Pattern() = default;
1483
1484 std::string const& TestSpec::Pattern::name() const {
1485 return m_name;
1486 }
1487
1488
1489 TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
1490 : Pattern( filterString )
1491 , m_wildcardPattern( toLower( name ), CaseSensitive::No )
1492 {}
1493
1494 bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
1495 return m_wildcardPattern.matches( testCase.name );
1496 }
1497
1498
1499 TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
1500 : Pattern( filterString )
1501 , m_tag( tag )
1502 {}
1503
1504 bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
1505 return std::find( begin( testCase.tags ),
1506 end( testCase.tags ),
1507 Tag( m_tag ) ) != end( testCase.tags );
1508 }
1509
1510 bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
1511 bool should_use = !testCase.isHidden();
1512 for (auto const& pattern : m_required) {
1513 should_use = true;
1514 if (!pattern->matches(testCase)) {
1515 return false;
1516 }
1517 }
1518 for (auto const& pattern : m_forbidden) {
1519 if (pattern->matches(testCase)) {
1520 return false;
1521 }
1522 }
1523 return should_use;
1524 }
1525
1526 std::string TestSpec::Filter::name() const {
1527 std::string name;
1528 for (auto const& p : m_required) {
1529 name += p->name();
1530 }
1531 for (auto const& p : m_forbidden) {
1532 name += p->name();
1533 }
1534 return name;
1535 }
1536
1537
1538 bool TestSpec::hasFilters() const {
1539 return !m_filters.empty();
1540 }
1541
1542 bool TestSpec::matches( TestCaseInfo const& testCase ) const {
1543 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
1544 }
1545
1546 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCaseHandle> const& testCases, IConfig const& config ) const
1547 {
1548 Matches matches( m_filters.size() );
1549 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
1550 std::vector<TestCaseHandle const*> currentMatches;
1551 for( auto const& test : testCases )
1552 if( isThrowSafe( test, config ) && filter.matches( test.getTestCaseInfo() ) )
1553 currentMatches.emplace_back( &test );
1554 return FilterMatch{ filter.name(), currentMatches };
1555 } );
1556 return matches;
1557 }
1558
1559 const TestSpec::vectorStrings& TestSpec::getInvalidSpecs() const {
1560 return m_invalidSpecs;
1561 }
1562
1563 }
1564
1565
1566
1567 #include <chrono>
1568
1569 namespace Catch {
1570
1571 namespace {
1572 static auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
1573 return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
1574 }
1575 } // end unnamed namespace
1576
1577 void Timer::start() {
1578 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
1579 }
1580 auto Timer::getElapsedNanoseconds() const -> uint64_t {
1581 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
1582 }
1583 auto Timer::getElapsedMicroseconds() const -> uint64_t {
1584 return getElapsedNanoseconds()/1000;
1585 }
1586 auto Timer::getElapsedMilliseconds() const -> unsigned int {
1587 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
1588 }
1589 auto Timer::getElapsedSeconds() const -> double {
1590 return getElapsedMicroseconds()/1000000.0;
1591 }
1592
1593
1594 } // namespace Catch
1595
1596
1597
1598
1599 #include <cmath>
1600 #include <iomanip>
1601
1602 namespace Catch {
1603
1604 namespace Detail {
1605
1606 namespace {
1607 const int hexThreshold = 255;
1608
1609 struct Endianness {
1610 enum Arch { Big, Little };
1611
1612 static Arch which() {
1613 int one = 1;
1614 // If the lowest byte we read is non-zero, we can assume
1615 // that little endian format is used.
1616 auto value = *reinterpret_cast<char*>(&one);
1617 return value ? Little : Big;
1618 }
1619 };
1620
1621 template<typename T>
1622 std::string fpToString(T value, int precision) {
1623 if (Catch::isnan(value)) {
1624 return "nan";
1625 }
1626
1627 ReusableStringStream rss;
1628 rss << std::setprecision(precision)
1629 << std::fixed
1630 << value;
1631 std::string d = rss.str();
1632 std::size_t i = d.find_last_not_of('0');
1633 if (i != std::string::npos && i != d.size() - 1) {
1634 if (d[i] == '.')
1635 i++;
1636 d = d.substr(0, i + 1);
1637 }
1638 return d;
1639 }
1640 } // end unnamed namespace
1641
1642 std::string convertIntoString(StringRef string, bool escape_invisibles) {
1643 std::string ret;
1644 // This is enough for the "don't escape invisibles" case, and a good
1645 // lower bound on the "escape invisibles" case.
1646 ret.reserve(string.size() + 2);
1647
1648 if (!escape_invisibles) {
1649 ret += '"';
1650 ret += string;
1651 ret += '"';
1652 return ret;
1653 }
1654
1655 ret += '"';
1656 for (char c : string) {
1657 switch (c) {
1658 case '\r':
1659 ret.append("\\r");
1660 break;
1661 case '\n':
1662 ret.append("\\n");
1663 break;
1664 case '\t':
1665 ret.append("\\t");
1666 break;
1667 case '\f':
1668 ret.append("\\f");
1669 break;
1670 default:
1671 ret.push_back(c);
1672 break;
1673 }
1674 }
1675 ret += '"';
1676
1677 return ret;
1678 }
1679
1680 std::string convertIntoString(StringRef string) {
1681 return convertIntoString(string, getCurrentContext().getConfig()->showInvisibles());
1682 }
1683
1684 std::string rawMemoryToString( const void *object, std::size_t size ) {
1685 // Reverse order for little endian architectures
1686 int i = 0, end = static_cast<int>( size ), inc = 1;
1687 if( Endianness::which() == Endianness::Little ) {
1688 i = end-1;
1689 end = inc = -1;
1690 }
1691
1692 unsigned char const *bytes = static_cast<unsigned char const *>(object);
1693 ReusableStringStream rss;
1694 rss << "0x" << std::setfill('0') << std::hex;
1695 for( ; i != end; i += inc )
1696 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
1697 return rss.str();
1698 }
1699 } // end Detail namespace
1700
1701
1702
1703 //// ======================================================= ////
1704 //
1705 // Out-of-line defs for full specialization of StringMaker
1706 //
1707 //// ======================================================= ////
1708
1709 std::string StringMaker<std::string>::convert(const std::string& str) {
1710 return Detail::convertIntoString( str );
1711 }
1712
1713 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1714 std::string StringMaker<std::string_view>::convert(std::string_view str) {
1715 return Detail::convertIntoString( StringRef( str.data(), str.size() ) );
1716 }
1717 #endif
1718
1719 std::string StringMaker<char const*>::convert(char const* str) {
1720 if (str) {
1721 return Detail::convertIntoString( str );
1722 } else {
1723 return{ "{null string}" };
1724 }
1725 }
1726 std::string StringMaker<char*>::convert(char* str) {
1727 if (str) {
1728 return Detail::convertIntoString( str );
1729 } else {
1730 return{ "{null string}" };
1731 }
1732 }
1733
1734 #ifdef CATCH_CONFIG_WCHAR
1735 std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
1736 std::string s;
1737 s.reserve(wstr.size());
1738 for (auto c : wstr) {
1739 s += (c <= 0xff) ? static_cast<char>(c) : '?';
1740 }
1741 return ::Catch::Detail::stringify(s);
1742 }
1743
1744 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1745 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
1746 return StringMaker<std::wstring>::convert(std::wstring(str));
1747 }
1748 # endif
1749
1750 std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
1751 if (str) {
1752 return ::Catch::Detail::stringify(std::wstring{ str });
1753 } else {
1754 return{ "{null string}" };
1755 }
1756 }
1757 std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
1758 if (str) {
1759 return ::Catch::Detail::stringify(std::wstring{ str });
1760 } else {
1761 return{ "{null string}" };
1762 }
1763 }
1764 #endif
1765
1766 #if defined(CATCH_CONFIG_CPP17_BYTE)
1767 #include <cstddef>
1768 std::string StringMaker<std::byte>::convert(std::byte value) {
1769 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
1770 }
1771 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
1772
1773 std::string StringMaker<int>::convert(int value) {
1774 return ::Catch::Detail::stringify(static_cast<long long>(value));
1775 }
1776 std::string StringMaker<long>::convert(long value) {
1777 return ::Catch::Detail::stringify(static_cast<long long>(value));
1778 }
1779 std::string StringMaker<long long>::convert(long long value) {
1780 ReusableStringStream rss;
1781 rss << value;
1782 if (value > Detail::hexThreshold) {
1783 rss << " (0x" << std::hex << value << ')';
1784 }
1785 return rss.str();
1786 }
1787
1788 std::string StringMaker<unsigned int>::convert(unsigned int value) {
1789 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
1790 }
1791 std::string StringMaker<unsigned long>::convert(unsigned long value) {
1792 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
1793 }
1794 std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
1795 ReusableStringStream rss;
1796 rss << value;
1797 if (value > Detail::hexThreshold) {
1798 rss << " (0x" << std::hex << value << ')';
1799 }
1800 return rss.str();
1801 }
1802
1803 std::string StringMaker<signed char>::convert(signed char value) {
1804 if (value == '\r') {
1805 return "'\\r'";
1806 } else if (value == '\f') {
1807 return "'\\f'";
1808 } else if (value == '\n') {
1809 return "'\\n'";
1810 } else if (value == '\t') {
1811 return "'\\t'";
1812 } else if ('\0' <= value && value < ' ') {
1813 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
1814 } else {
1815 char chstr[] = "' '";
1816 chstr[1] = value;
1817 return chstr;
1818 }
1819 }
1820 std::string StringMaker<char>::convert(char c) {
1821 return ::Catch::Detail::stringify(static_cast<signed char>(c));
1822 }
1823 std::string StringMaker<unsigned char>::convert(unsigned char c) {
1824 return ::Catch::Detail::stringify(static_cast<char>(c));
1825 }
1826
1827 int StringMaker<float>::precision = 5;
1828
1829 std::string StringMaker<float>::convert(float value) {
1830 return Detail::fpToString(value, precision) + 'f';
1831 }
1832
1833 int StringMaker<double>::precision = 10;
1834
1835 std::string StringMaker<double>::convert(double value) {
1836 return Detail::fpToString(value, precision);
1837 }
1838
1839 } // end namespace Catch
1840
1841
1842
1843 namespace Catch {
1844
1845 Counts Counts::operator - ( Counts const& other ) const {
1846 Counts diff;
1847 diff.passed = passed - other.passed;
1848 diff.failed = failed - other.failed;
1849 diff.failedButOk = failedButOk - other.failedButOk;
1850 return diff;
1851 }
1852
1853 Counts& Counts::operator += ( Counts const& other ) {
1854 passed += other.passed;
1855 failed += other.failed;
1856 failedButOk += other.failedButOk;
1857 return *this;
1858 }
1859
1860 std::uint64_t Counts::total() const {
1861 return passed + failed + failedButOk;
1862 }
1863 bool Counts::allPassed() const {
1864 return failed == 0 && failedButOk == 0;
1865 }
1866 bool Counts::allOk() const {
1867 return failed == 0;
1868 }
1869
1870 Totals Totals::operator - ( Totals const& other ) const {
1871 Totals diff;
1872 diff.assertions = assertions - other.assertions;
1873 diff.testCases = testCases - other.testCases;
1874 return diff;
1875 }
1876
1877 Totals& Totals::operator += ( Totals const& other ) {
1878 assertions += other.assertions;
1879 testCases += other.testCases;
1880 return *this;
1881 }
1882
1883 Totals Totals::delta( Totals const& prevTotals ) const {
1884 Totals diff = *this - prevTotals;
1885 if( diff.assertions.failed > 0 )
1886 ++diff.testCases.failed;
1887 else if( diff.assertions.failedButOk > 0 )
1888 ++diff.testCases.failedButOk;
1889 else
1890 ++diff.testCases.passed;
1891 return diff;
1892 }
1893
1894 }
1895
1896
1897 #include <ostream>
1898
1899 namespace Catch {
1900
1901 Version::Version
1902 ( unsigned int _majorVersion,
1903 unsigned int _minorVersion,
1904 unsigned int _patchNumber,
1905 char const * const _branchName,
1906 unsigned int _buildNumber )
1907 : majorVersion( _majorVersion ),
1908 minorVersion( _minorVersion ),
1909 patchNumber( _patchNumber ),
1910 branchName( _branchName ),
1911 buildNumber( _buildNumber )
1912 {}
1913
1914 std::ostream& operator << ( std::ostream& os, Version const& version ) {
1915 os << version.majorVersion << '.'
1916 << version.minorVersion << '.'
1917 << version.patchNumber;
1918 // branchName is never null -> 0th char is \0 if it is empty
1919 if (version.branchName[0]) {
1920 os << '-' << version.branchName
1921 << '.' << version.buildNumber;
1922 }
1923 return os;
1924 }
1925
1926 Version const& libraryVersion() {
1927 static Version version( 3, 1, 1, "", 0 );
1928 return version;
1929 }
1930
1931 }
1932
1933
1934
1935
1936 namespace Catch {
1937
1938 const char* GeneratorException::what() const noexcept {
1939 return m_msg;
1940 }
1941
1942 } // end namespace Catch
1943
1944
1945
1946
1947 namespace Catch {
1948
1949 IGeneratorTracker::~IGeneratorTracker() = default;
1950
1951 namespace Generators {
1952
1953 namespace Detail {
1954
1955 [[noreturn]]
1956 void throw_generator_exception(char const* msg) {
1957 Catch::throw_exception(GeneratorException{ msg });
1958 }
1959 } // end namespace Detail
1960
1961 GeneratorUntypedBase::~GeneratorUntypedBase() = default;
1962
1963 auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
1964 return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
1965 }
1966
1967 } // namespace Generators
1968 } // namespace Catch
1969
1970
1971
1972
1973
1974 std::uint32_t Catch::Generators::Detail::getSeed() { return sharedRng()(); }
1975
1976
1977
1978
1979 namespace Catch {
1980 IResultCapture::~IResultCapture() = default;
1981 }
1982
1983
1984
1985
1986 namespace Catch {
1987 IConfig::~IConfig() = default;
1988 }
1989
1990
1991
1992
1993 namespace Catch {
1994 IExceptionTranslator::~IExceptionTranslator() = default;
1995 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
1996 }
1997
1998
1999
2000 #include <string>
2001
2002 namespace Catch {
2003 namespace Generators {
2004
2005 bool GeneratorUntypedBase::countedNext() {
2006 auto ret = next();
2007 if ( ret ) {
2008 m_stringReprCache.clear();
2009 ++m_currentElementIndex;
2010 }
2011 return ret;
2012 }
2013
2014 StringRef GeneratorUntypedBase::currentElementAsString() const {
2015 if ( m_stringReprCache.empty() ) {
2016 m_stringReprCache = stringifyImpl();
2017 }
2018 return m_stringReprCache;
2019 }
2020
2021 } // namespace Generators
2022 } // namespace Catch
2023
2024
2025
2026
2027 namespace Catch {
2028 IRegistryHub::~IRegistryHub() = default;
2029 IMutableRegistryHub::~IMutableRegistryHub() = default;
2030 }
2031
2032
2033
2034 #include <algorithm>
2035 #include <cassert>
2036 #include <iomanip>
2037
2038 namespace Catch {
2039
2040 ReporterConfig::ReporterConfig(
2041 IConfig const* _fullConfig,
2042 Detail::unique_ptr<IStream> _stream,
2043 ColourMode colourMode,
2044 std::map<std::string, std::string> customOptions ):
2045 m_stream( CATCH_MOVE(_stream) ),
2046 m_fullConfig( _fullConfig ),
2047 m_colourMode( colourMode ),
2048 m_customOptions( CATCH_MOVE( customOptions ) ) {}
2049
2050 Detail::unique_ptr<IStream> ReporterConfig::takeStream() && {
2051 assert( m_stream );
2052 return CATCH_MOVE( m_stream );
2053 }
2054 IConfig const * ReporterConfig::fullConfig() const { return m_fullConfig; }
2055 ColourMode ReporterConfig::colourMode() const { return m_colourMode; }
2056
2057 std::map<std::string, std::string> const&
2058 ReporterConfig::customOptions() const {
2059 return m_customOptions;
2060 }
2061
2062 ReporterConfig::~ReporterConfig() = default;
2063
2064 AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
2065 std::vector<MessageInfo> const& _infoMessages,
2066 Totals const& _totals )
2067 : assertionResult( _assertionResult ),
2068 infoMessages( _infoMessages ),
2069 totals( _totals )
2070 {
2071 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
2072
2073 if( assertionResult.hasMessage() ) {
2074 // Copy message into messages list.
2075 // !TBD This should have been done earlier, somewhere
2076 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
2077 builder << assertionResult.getMessage();
2078 builder.m_info.message = builder.m_stream.str();
2079
2080 infoMessages.push_back( builder.m_info );
2081 }
2082 }
2083
2084 SectionStats::SectionStats( SectionInfo const& _sectionInfo,
2085 Counts const& _assertions,
2086 double _durationInSeconds,
2087 bool _missingAssertions )
2088 : sectionInfo( _sectionInfo ),
2089 assertions( _assertions ),
2090 durationInSeconds( _durationInSeconds ),
2091 missingAssertions( _missingAssertions )
2092 {}
2093
2094
2095 TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
2096 Totals const& _totals,
2097 std::string const& _stdOut,
2098 std::string const& _stdErr,
2099 bool _aborting )
2100 : testInfo( &_testInfo ),
2101 totals( _totals ),
2102 stdOut( _stdOut ),
2103 stdErr( _stdErr ),
2104 aborting( _aborting )
2105 {}
2106
2107
2108 TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
2109 Totals const& _totals,
2110 bool _aborting )
2111 : runInfo( _runInfo ),
2112 totals( _totals ),
2113 aborting( _aborting )
2114 {}
2115
2116 IEventListener::~IEventListener() = default;
2117
2118 } // end namespace Catch
2119
2120
2121
2122
2123 namespace Catch {
2124 IReporterFactory::~IReporterFactory() = default;
2125 EventListenerFactory::~EventListenerFactory() = default;
2126 }
2127
2128
2129
2130
2131 namespace Catch {
2132 IReporterRegistry::~IReporterRegistry() = default;
2133 }
2134
2135
2136
2137
2138 namespace Catch {
2139 ITestInvoker::~ITestInvoker() = default;
2140 ITestCaseRegistry::~ITestCaseRegistry() = default;
2141 }
2142
2143
2144
2145 namespace Catch {
2146
2147 AssertionHandler::AssertionHandler
2148 ( StringRef macroName,
2149 SourceLineInfo const& lineInfo,
2150 StringRef capturedExpression,
2151 ResultDisposition::Flags resultDisposition )
2152 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
2153 m_resultCapture( getResultCapture() )
2154 {}
2155
2156 void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
2157 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
2158 }
2159 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef message) {
2160 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
2161 }
2162
2163 auto AssertionHandler::allowThrows() const -> bool {
2164 return getCurrentContext().getConfig()->allowThrows();
2165 }
2166
2167 void AssertionHandler::complete() {
2168 setCompleted();
2169 if( m_reaction.shouldDebugBreak ) {
2170
2171 // If you find your debugger stopping you here then go one level up on the
2172 // call-stack for the code that caused it (typically a failed assertion)
2173
2174 // (To go back to the test and change execution, jump over the throw, next)
2175 CATCH_BREAK_INTO_DEBUGGER();
2176 }
2177 if (m_reaction.shouldThrow) {
2178 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2179 throw Catch::TestFailureException();
2180 #else
2181 CATCH_ERROR( "Test failure requires aborting test!" );
2182 #endif
2183 }
2184 }
2185 void AssertionHandler::setCompleted() {
2186 m_completed = true;
2187 }
2188
2189 void AssertionHandler::handleUnexpectedInflightException() {
2190 m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
2191 }
2192
2193 void AssertionHandler::handleExceptionThrownAsExpected() {
2194 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
2195 }
2196 void AssertionHandler::handleExceptionNotThrownAsExpected() {
2197 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
2198 }
2199
2200 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
2201 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
2202 }
2203
2204 void AssertionHandler::handleThrowingCallSkipped() {
2205 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
2206 }
2207
2208 // This is the overload that takes a string and infers the Equals matcher from it
2209 // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
2210 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
2211 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
2212 }
2213
2214 } // namespace Catch
2215
2216
2217
2218
2219 #include <algorithm>
2220
2221 namespace Catch {
2222 namespace Detail {
2223
2224 bool CaseInsensitiveLess::operator()( StringRef lhs,
2225 StringRef rhs ) const {
2226 return std::lexicographical_compare(
2227 lhs.begin(), lhs.end(),
2228 rhs.begin(), rhs.end(),
2229 []( char l, char r ) { return toLower( l ) < toLower( r ); } );
2230 }
2231
2232 bool
2233 CaseInsensitiveEqualTo::operator()( StringRef lhs,
2234 StringRef rhs ) const {
2235 return std::equal(
2236 lhs.begin(), lhs.end(),
2237 rhs.begin(), rhs.end(),
2238 []( char l, char r ) { return toLower( l ) == toLower( r ); } );
2239 }
2240
2241 } // namespace Detail
2242 } // namespace Catch
2243
2244
2245
2246
2247 #include <algorithm>
2248 #include <ostream>
2249
2250 namespace {
2251 bool isOptPrefix( char c ) {
2252 return c == '-'
2253 #ifdef CATCH_PLATFORM_WINDOWS
2254 || c == '/'
2255 #endif
2256 ;
2257 }
2258
2259 std::string normaliseOpt( std::string const& optName ) {
2260 #ifdef CATCH_PLATFORM_WINDOWS
2261 if ( optName[0] == '/' )
2262 return "-" + optName.substr( 1 );
2263 else
2264 #endif
2265 return optName;
2266 }
2267
2268 } // namespace
2269
2270 namespace Catch {
2271 namespace Clara {
2272 namespace Detail {
2273
2274 void TokenStream::loadBuffer() {
2275 m_tokenBuffer.clear();
2276
2277 // Skip any empty strings
2278 while ( it != itEnd && it->empty() ) {
2279 ++it;
2280 }
2281
2282 if ( it != itEnd ) {
2283 auto const& next = *it;
2284 if ( isOptPrefix( next[0] ) ) {
2285 auto delimiterPos = next.find_first_of( " :=" );
2286 if ( delimiterPos != std::string::npos ) {
2287 m_tokenBuffer.push_back(
2288 { TokenType::Option,
2289 next.substr( 0, delimiterPos ) } );
2290 m_tokenBuffer.push_back(
2291 { TokenType::Argument,
2292 next.substr( delimiterPos + 1 ) } );
2293 } else {
2294 if ( next[1] != '-' && next.size() > 2 ) {
2295 std::string opt = "- ";
2296 for ( size_t i = 1; i < next.size(); ++i ) {
2297 opt[1] = next[i];
2298 m_tokenBuffer.push_back(
2299 { TokenType::Option, opt } );
2300 }
2301 } else {
2302 m_tokenBuffer.push_back(
2303 { TokenType::Option, next } );
2304 }
2305 }
2306 } else {
2307 m_tokenBuffer.push_back(
2308 { TokenType::Argument, next } );
2309 }
2310 }
2311 }
2312
2313 TokenStream::TokenStream( Args const& args ):
2314 TokenStream( args.m_args.begin(), args.m_args.end() ) {}
2315
2316 TokenStream::TokenStream( Iterator it_, Iterator itEnd_ ):
2317 it( it_ ), itEnd( itEnd_ ) {
2318 loadBuffer();
2319 }
2320
2321 TokenStream& TokenStream::operator++() {
2322 if ( m_tokenBuffer.size() >= 2 ) {
2323 m_tokenBuffer.erase( m_tokenBuffer.begin() );
2324 } else {
2325 if ( it != itEnd )
2326 ++it;
2327 loadBuffer();
2328 }
2329 return *this;
2330 }
2331
2332 ParserResult convertInto( std::string const& source,
2333 std::string& target ) {
2334 target = source;
2335 return ParserResult::ok( ParseResultType::Matched );
2336 }
2337
2338 ParserResult convertInto( std::string const& source,
2339 bool& target ) {
2340 std::string srcLC = toLower( source );
2341
2342 if ( srcLC == "y" || srcLC == "1" || srcLC == "true" ||
2343 srcLC == "yes" || srcLC == "on" ) {
2344 target = true;
2345 } else if ( srcLC == "n" || srcLC == "0" || srcLC == "false" ||
2346 srcLC == "no" || srcLC == "off" ) {
2347 target = false;
2348 } else {
2349 return ParserResult::runtimeError(
2350 "Expected a boolean value but did not recognise: '" +
2351 source + '\'' );
2352 }
2353 return ParserResult::ok( ParseResultType::Matched );
2354 }
2355
2356 size_t ParserBase::cardinality() const { return 1; }
2357
2358 InternalParseResult ParserBase::parse( Args const& args ) const {
2359 return parse( args.exeName(), TokenStream( args ) );
2360 }
2361
2362 ParseState::ParseState( ParseResultType type,
2363 TokenStream const& remainingTokens ):
2364 m_type( type ), m_remainingTokens( remainingTokens ) {}
2365
2366 ParserResult BoundFlagRef::setFlag( bool flag ) {
2367 m_ref = flag;
2368 return ParserResult::ok( ParseResultType::Matched );
2369 }
2370
2371 ResultBase::~ResultBase() = default;
2372
2373 bool BoundRef::isContainer() const { return false; }
2374
2375 bool BoundRef::isFlag() const { return false; }
2376
2377 bool BoundFlagRefBase::isFlag() const { return true; }
2378
2379 } // namespace Detail
2380
2381 Detail::InternalParseResult Arg::parse(std::string const&,
2382 Detail::TokenStream const& tokens) const {
2383 auto validationResult = validate();
2384 if (!validationResult)
2385 return Detail::InternalParseResult(validationResult);
2386
2387 auto remainingTokens = tokens;
2388 auto const& token = *remainingTokens;
2389 if (token.type != Detail::TokenType::Argument)
2390 return Detail::InternalParseResult::ok(Detail::ParseState(
2391 ParseResultType::NoMatch, remainingTokens));
2392
2393 assert(!m_ref->isFlag());
2394 auto valueRef =
2395 static_cast<Detail::BoundValueRefBase*>(m_ref.get());
2396
2397 auto result = valueRef->setValue(remainingTokens->token);
2398 if (!result)
2399 return Detail::InternalParseResult(result);
2400 else
2401 return Detail::InternalParseResult::ok(Detail::ParseState(
2402 ParseResultType::Matched, ++remainingTokens));
2403 }
2404
2405 Opt::Opt(bool& ref) :
2406 ParserRefImpl(std::make_shared<Detail::BoundFlagRef>(ref)) {}
2407
2408 std::vector<Detail::HelpColumns> Opt::getHelpColumns() const {
2409 std::ostringstream oss;
2410 bool first = true;
2411 for (auto const& opt : m_optNames) {
2412 if (first)
2413 first = false;
2414 else
2415 oss << ", ";
2416 oss << opt;
2417 }
2418 if (!m_hint.empty())
2419 oss << " <" << m_hint << '>';
2420 return { { oss.str(), m_description } };
2421 }
2422
2423 bool Opt::isMatch(std::string const& optToken) const {
2424 auto normalisedToken = normaliseOpt(optToken);
2425 for (auto const& name : m_optNames) {
2426 if (normaliseOpt(name) == normalisedToken)
2427 return true;
2428 }
2429 return false;
2430 }
2431
2432 Detail::InternalParseResult Opt::parse(std::string const&,
2433 Detail::TokenStream const& tokens) const {
2434 auto validationResult = validate();
2435 if (!validationResult)
2436 return Detail::InternalParseResult(validationResult);
2437
2438 auto remainingTokens = tokens;
2439 if (remainingTokens &&
2440 remainingTokens->type == Detail::TokenType::Option) {
2441 auto const& token = *remainingTokens;
2442 if (isMatch(token.token)) {
2443 if (m_ref->isFlag()) {
2444 auto flagRef =
2445 static_cast<Detail::BoundFlagRefBase*>(
2446 m_ref.get());
2447 auto result = flagRef->setFlag(true);
2448 if (!result)
2449 return Detail::InternalParseResult(result);
2450 if (result.value() ==
2451 ParseResultType::ShortCircuitAll)
2452 return Detail::InternalParseResult::ok(Detail::ParseState(
2453 result.value(), remainingTokens));
2454 } else {
2455 auto valueRef =
2456 static_cast<Detail::BoundValueRefBase*>(
2457 m_ref.get());
2458 ++remainingTokens;
2459 if (!remainingTokens)
2460 return Detail::InternalParseResult::runtimeError(
2461 "Expected argument following " +
2462 token.token);
2463 auto const& argToken = *remainingTokens;
2464 if (argToken.type != Detail::TokenType::Argument)
2465 return Detail::InternalParseResult::runtimeError(
2466 "Expected argument following " +
2467 token.token);
2468 const auto result = valueRef->setValue(argToken.token);
2469 if (!result)
2470 return Detail::InternalParseResult(result);
2471 if (result.value() ==
2472 ParseResultType::ShortCircuitAll)
2473 return Detail::InternalParseResult::ok(Detail::ParseState(
2474 result.value(), remainingTokens));
2475 }
2476 return Detail::InternalParseResult::ok(Detail::ParseState(
2477 ParseResultType::Matched, ++remainingTokens));
2478 }
2479 }
2480 return Detail::InternalParseResult::ok(
2481 Detail::ParseState(ParseResultType::NoMatch, remainingTokens));
2482 }
2483
2484 Detail::Result Opt::validate() const {
2485 if (m_optNames.empty())
2486 return Detail::Result::logicError("No options supplied to Opt");
2487 for (auto const& name : m_optNames) {
2488 if (name.empty())
2489 return Detail::Result::logicError(
2490 "Option name cannot be empty");
2491 #ifdef CATCH_PLATFORM_WINDOWS
2492 if (name[0] != '-' && name[0] != '/')
2493 return Detail::Result::logicError(
2494 "Option name must begin with '-' or '/'");
2495 #else
2496 if (name[0] != '-')
2497 return Detail::Result::logicError(
2498 "Option name must begin with '-'");
2499 #endif
2500 }
2501 return ParserRefImpl::validate();
2502 }
2503
2504 ExeName::ExeName() :
2505 m_name(std::make_shared<std::string>("<executable>")) {}
2506
2507 ExeName::ExeName(std::string& ref) : ExeName() {
2508 m_ref = std::make_shared<Detail::BoundValueRef<std::string>>(ref);
2509 }
2510
2511 Detail::InternalParseResult
2512 ExeName::parse(std::string const&,
2513 Detail::TokenStream const& tokens) const {
2514 return Detail::InternalParseResult::ok(
2515 Detail::ParseState(ParseResultType::NoMatch, tokens));
2516 }
2517
2518 ParserResult ExeName::set(std::string const& newName) {
2519 auto lastSlash = newName.find_last_of("\\/");
2520 auto filename = (lastSlash == std::string::npos)
2521 ? newName
2522 : newName.substr(lastSlash + 1);
2523
2524 *m_name = filename;
2525 if (m_ref)
2526 return m_ref->setValue(filename);
2527 else
2528 return ParserResult::ok(ParseResultType::Matched);
2529 }
2530
2531
2532
2533
2534 Parser& Parser::operator|=( Parser const& other ) {
2535 m_options.insert( m_options.end(),
2536 other.m_options.begin(),
2537 other.m_options.end() );
2538 m_args.insert(
2539 m_args.end(), other.m_args.begin(), other.m_args.end() );
2540 return *this;
2541 }
2542
2543 std::vector<Detail::HelpColumns> Parser::getHelpColumns() const {
2544 std::vector<Detail::HelpColumns> cols;
2545 for ( auto const& o : m_options ) {
2546 auto childCols = o.getHelpColumns();
2547 cols.insert( cols.end(), childCols.begin(), childCols.end() );
2548 }
2549 return cols;
2550 }
2551
2552 void Parser::writeToStream( std::ostream& os ) const {
2553 if ( !m_exeName.name().empty() ) {
2554 os << "usage:\n"
2555 << " " << m_exeName.name() << ' ';
2556 bool required = true, first = true;
2557 for ( auto const& arg : m_args ) {
2558 if ( first )
2559 first = false;
2560 else
2561 os << ' ';
2562 if ( arg.isOptional() && required ) {
2563 os << '[';
2564 required = false;
2565 }
2566 os << '<' << arg.hint() << '>';
2567 if ( arg.cardinality() == 0 )
2568 os << " ... ";
2569 }
2570 if ( !required )
2571 os << ']';
2572 if ( !m_options.empty() )
2573 os << " options";
2574 os << "\n\nwhere options are:\n";
2575 }
2576
2577 auto rows = getHelpColumns();
2578 size_t consoleWidth = CATCH_CONFIG_CONSOLE_WIDTH;
2579 size_t optWidth = 0;
2580 for ( auto const& cols : rows )
2581 optWidth = ( std::max )( optWidth, cols.left.size() + 2 );
2582
2583 optWidth = ( std::min )( optWidth, consoleWidth / 2 );
2584
2585 for ( auto const& cols : rows ) {
2586 auto row = TextFlow::Column( cols.left )
2587 .width( optWidth )
2588 .indent( 2 ) +
2589 TextFlow::Spacer( 4 ) +
2590 TextFlow::Column( cols.right )
2591 .width( consoleWidth - 7 - optWidth );
2592 os << row << '\n';
2593 }
2594 }
2595
2596 Detail::Result Parser::validate() const {
2597 for ( auto const& opt : m_options ) {
2598 auto result = opt.validate();
2599 if ( !result )
2600 return result;
2601 }
2602 for ( auto const& arg : m_args ) {
2603 auto result = arg.validate();
2604 if ( !result )
2605 return result;
2606 }
2607 return Detail::Result::ok();
2608 }
2609
2610 Detail::InternalParseResult
2611 Parser::parse( std::string const& exeName,
2612 Detail::TokenStream const& tokens ) const {
2613
2614 struct ParserInfo {
2615 ParserBase const* parser = nullptr;
2616 size_t count = 0;
2617 };
2618 std::vector<ParserInfo> parseInfos;
2619 parseInfos.reserve( m_options.size() + m_args.size() );
2620 for ( auto const& opt : m_options ) {
2621 parseInfos.push_back( { &opt, 0 } );
2622 }
2623 for ( auto const& arg : m_args ) {
2624 parseInfos.push_back( { &arg, 0 } );
2625 }
2626
2627 m_exeName.set( exeName );
2628
2629 auto result = Detail::InternalParseResult::ok(
2630 Detail::ParseState( ParseResultType::NoMatch, tokens ) );
2631 while ( result.value().remainingTokens() ) {
2632 bool tokenParsed = false;
2633
2634 for ( auto& parseInfo : parseInfos ) {
2635 if ( parseInfo.parser->cardinality() == 0 ||
2636 parseInfo.count < parseInfo.parser->cardinality() ) {
2637 result = parseInfo.parser->parse(
2638 exeName, result.value().remainingTokens() );
2639 if ( !result )
2640 return result;
2641 if ( result.value().type() !=
2642 ParseResultType::NoMatch ) {
2643 tokenParsed = true;
2644 ++parseInfo.count;
2645 break;
2646 }
2647 }
2648 }
2649
2650 if ( result.value().type() == ParseResultType::ShortCircuitAll )
2651 return result;
2652 if ( !tokenParsed )
2653 return Detail::InternalParseResult::runtimeError(
2654 "Unrecognised token: " +
2655 result.value().remainingTokens()->token );
2656 }
2657 // !TBD Check missing required options
2658 return result;
2659 }
2660
2661 Args::Args(int argc, char const* const* argv) :
2662 m_exeName(argv[0]), m_args(argv + 1, argv + argc) {}
2663
2664 Args::Args(std::initializer_list<std::string> args) :
2665 m_exeName(*args.begin()),
2666 m_args(args.begin() + 1, args.end()) {}
2667
2668
2669 Help::Help( bool& showHelpFlag ):
2670 Opt( [&]( bool flag ) {
2671 showHelpFlag = flag;
2672 return ParserResult::ok( ParseResultType::ShortCircuitAll );
2673 } ) {
2674 static_cast<Opt&> ( *this )(
2675 "display usage information" )["-?"]["-h"]["--help"]
2676 .optional();
2677 }
2678
2679 } // namespace Clara
2680 } // namespace Catch
2681
2682
2683
2684
2685 #include <fstream>
2686 #include <string>
2687
2688 namespace Catch {
2689
2690 Clara::Parser makeCommandLineParser( ConfigData& config ) {
2691
2692 using namespace Clara;
2693
2694 auto const setWarning = [&]( std::string const& warning ) {
2695 if ( warning == "NoAssertions" ) {
2696 config.warnings = static_cast<WarnAbout::What>(config.warnings | WarnAbout::NoAssertions);
2697 return ParserResult::ok( ParseResultType::Matched );
2698 } else if ( warning == "UnmatchedTestSpec" ) {
2699 config.warnings = static_cast<WarnAbout::What>(config.warnings | WarnAbout::UnmatchedTestSpec);
2700 return ParserResult::ok( ParseResultType::Matched );
2701 }
2702
2703 return ParserResult ::runtimeError(
2704 "Unrecognised warning option: '" + warning + '\'' );
2705 };
2706 auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
2707 std::ifstream f( filename.c_str() );
2708 if( !f.is_open() )
2709 return ParserResult::runtimeError( "Unable to load input file: '" + filename + '\'' );
2710
2711 std::string line;
2712 while( std::getline( f, line ) ) {
2713 line = trim(line);
2714 if( !line.empty() && !startsWith( line, '#' ) ) {
2715 if( !startsWith( line, '"' ) )
2716 line = '"' + line + '"';
2717 config.testsOrTags.push_back( line );
2718 config.testsOrTags.emplace_back( "," );
2719 }
2720 }
2721 //Remove comma in the end
2722 if(!config.testsOrTags.empty())
2723 config.testsOrTags.erase( config.testsOrTags.end()-1 );
2724
2725 return ParserResult::ok( ParseResultType::Matched );
2726 };
2727 auto const setTestOrder = [&]( std::string const& order ) {
2728 if( startsWith( "declared", order ) )
2729 config.runOrder = TestRunOrder::Declared;
2730 else if( startsWith( "lexical", order ) )
2731 config.runOrder = TestRunOrder::LexicographicallySorted;
2732 else if( startsWith( "random", order ) )
2733 config.runOrder = TestRunOrder::Randomized;
2734 else
2735 return ParserResult::runtimeError( "Unrecognised ordering: '" + order + '\'' );
2736 return ParserResult::ok( ParseResultType::Matched );
2737 };
2738 auto const setRngSeed = [&]( std::string const& seed ) {
2739 if( seed == "time" ) {
2740 config.rngSeed = generateRandomSeed(GenerateFrom::Time);
2741 return ParserResult::ok(ParseResultType::Matched);
2742 } else if (seed == "random-device") {
2743 config.rngSeed = generateRandomSeed(GenerateFrom::RandomDevice);
2744 return ParserResult::ok(ParseResultType::Matched);
2745 }
2746
2747 CATCH_TRY {
2748 std::size_t parsedTo = 0;
2749 unsigned long parsedSeed = std::stoul(seed, &parsedTo, 0);
2750 if (parsedTo != seed.size()) {
2751 return ParserResult::runtimeError("Could not parse '" + seed + "' as seed");
2752 }
2753
2754 // TODO: Ideally we could parse unsigned int directly,
2755 // but the stdlib doesn't provide helper for that
2756 // type. After this is refactored to use fixed size
2757 // type, we should check the parsed value is in range
2758 // of the underlying type.
2759 config.rngSeed = static_cast<unsigned int>(parsedSeed);
2760 return ParserResult::ok(ParseResultType::Matched);
2761 } CATCH_CATCH_ANON(std::exception const&) {
2762 return ParserResult::runtimeError("Could not parse '" + seed + "' as seed");
2763 }
2764 };
2765 auto const setDefaultColourMode = [&]( std::string const& colourMode ) {
2766 Optional<ColourMode> maybeMode = Catch::Detail::stringToColourMode(toLower( colourMode ));
2767 if ( !maybeMode ) {
2768 return ParserResult::runtimeError(
2769 "colour mode must be one of: default, ansi, win32, "
2770 "or none. '" +
2771 colourMode + "' is not recognised" );
2772 }
2773 auto mode = *maybeMode;
2774 if ( !isColourImplAvailable( mode ) ) {
2775 return ParserResult::runtimeError(
2776 "colour mode '" + colourMode +
2777 "' is not supported in this binary" );
2778 }
2779 config.defaultColourMode = mode;
2780 return ParserResult::ok( ParseResultType::Matched );
2781 };
2782 auto const setWaitForKeypress = [&]( std::string const& keypress ) {
2783 auto keypressLc = toLower( keypress );
2784 if (keypressLc == "never")
2785 config.waitForKeypress = WaitForKeypress::Never;
2786 else if( keypressLc == "start" )
2787 config.waitForKeypress = WaitForKeypress::BeforeStart;
2788 else if( keypressLc == "exit" )
2789 config.waitForKeypress = WaitForKeypress::BeforeExit;
2790 else if( keypressLc == "both" )
2791 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
2792 else
2793 return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
2794 return ParserResult::ok( ParseResultType::Matched );
2795 };
2796 auto const setVerbosity = [&]( std::string const& verbosity ) {
2797 auto lcVerbosity = toLower( verbosity );
2798 if( lcVerbosity == "quiet" )
2799 config.verbosity = Verbosity::Quiet;
2800 else if( lcVerbosity == "normal" )
2801 config.verbosity = Verbosity::Normal;
2802 else if( lcVerbosity == "high" )
2803 config.verbosity = Verbosity::High;
2804 else
2805 return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + '\'' );
2806 return ParserResult::ok( ParseResultType::Matched );
2807 };
2808 auto const setReporter = [&]( std::string const& userReporterSpec ) {
2809 if ( userReporterSpec.empty() ) {
2810 return ParserResult::runtimeError( "Received empty reporter spec." );
2811 }
2812
2813 Optional<ReporterSpec> parsed =
2814 parseReporterSpec( userReporterSpec );
2815 if ( !parsed ) {
2816 return ParserResult::runtimeError(
2817 "Could not parse reporter spec '" + userReporterSpec +
2818 "'" );
2819 }
2820
2821 auto const& reporterSpec = *parsed;
2822
2823 IReporterRegistry::FactoryMap const& factories =
2824 getRegistryHub().getReporterRegistry().getFactories();
2825 auto result = factories.find( reporterSpec.name() );
2826
2827 if ( result == factories.end() ) {
2828 return ParserResult::runtimeError(
2829 "Unrecognized reporter, '" + reporterSpec.name() +
2830 "'. Check available with --list-reporters" );
2831 }
2832
2833
2834 const bool hadOutputFile = reporterSpec.outputFile().some();
2835 config.reporterSpecifications.push_back( CATCH_MOVE( *parsed ) );
2836 // It would be enough to check this only once at the very end, but
2837 // there is not a place where we could call this check, so do it
2838 // every time it could fail. For valid inputs, this is still called
2839 // at most once.
2840 if (!hadOutputFile) {
2841 int n_reporters_without_file = 0;
2842 for (auto const& spec : config.reporterSpecifications) {
2843 if (spec.outputFile().none()) {
2844 n_reporters_without_file++;
2845 }
2846 }
2847 if (n_reporters_without_file > 1) {
2848 return ParserResult::runtimeError( "Only one reporter may have unspecified output file." );
2849 }
2850 }
2851
2852 return ParserResult::ok( ParseResultType::Matched );
2853 };
2854 auto const setShardCount = [&]( std::string const& shardCount ) {
2855 CATCH_TRY{
2856 std::size_t parsedTo = 0;
2857 int64_t parsedCount = std::stoll(shardCount, &parsedTo, 0);
2858 if (parsedTo != shardCount.size()) {
2859 return ParserResult::runtimeError("Could not parse '" + shardCount + "' as shard count");
2860 }
2861 if (parsedCount <= 0) {
2862 return ParserResult::runtimeError("Shard count must be a positive number");
2863 }
2864
2865 config.shardCount = static_cast<unsigned int>(parsedCount);
2866 return ParserResult::ok(ParseResultType::Matched);
2867 } CATCH_CATCH_ANON(std::exception const&) {
2868 return ParserResult::runtimeError("Could not parse '" + shardCount + "' as shard count");
2869 }
2870 };
2871
2872 auto const setShardIndex = [&](std::string const& shardIndex) {
2873 CATCH_TRY{
2874 std::size_t parsedTo = 0;
2875 int64_t parsedIndex = std::stoll(shardIndex, &parsedTo, 0);
2876 if (parsedTo != shardIndex.size()) {
2877 return ParserResult::runtimeError("Could not parse '" + shardIndex + "' as shard index");
2878 }
2879 if (parsedIndex < 0) {
2880 return ParserResult::runtimeError("Shard index must be a non-negative number");
2881 }
2882
2883 config.shardIndex = static_cast<unsigned int>(parsedIndex);
2884 return ParserResult::ok(ParseResultType::Matched);
2885 } CATCH_CATCH_ANON(std::exception const&) {
2886 return ParserResult::runtimeError("Could not parse '" + shardIndex + "' as shard index");
2887 }
2888 };
2889
2890
2891 auto cli
2892 = ExeName( config.processName )
2893 | Help( config.showHelp )
2894 | Opt( config.showSuccessfulTests )
2895 ["-s"]["--success"]
2896 ( "include successful tests in output" )
2897 | Opt( config.shouldDebugBreak )
2898 ["-b"]["--break"]
2899 ( "break into debugger on failure" )
2900 | Opt( config.noThrow )
2901 ["-e"]["--nothrow"]
2902 ( "skip exception tests" )
2903 | Opt( config.showInvisibles )
2904 ["-i"]["--invisibles"]
2905 ( "show invisibles (tabs, newlines)" )
2906 | Opt( config.defaultOutputFilename, "filename" )
2907 ["-o"]["--out"]
2908 ( "default output filename" )
2909 | Opt( accept_many, setReporter, "name[::key=value]*" )
2910 ["-r"]["--reporter"]
2911 ( "reporter to use (defaults to console)" )
2912 | Opt( config.name, "name" )
2913 ["-n"]["--name"]
2914 ( "suite name" )
2915 | Opt( [&]( bool ){ config.abortAfter = 1; } )
2916 ["-a"]["--abort"]
2917 ( "abort at first failure" )
2918 | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
2919 ["-x"]["--abortx"]
2920 ( "abort after x failures" )
2921 | Opt( accept_many, setWarning, "warning name" )
2922 ["-w"]["--warn"]
2923 ( "enable warnings" )
2924 | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
2925 ["-d"]["--durations"]
2926 ( "show test durations" )
2927 | Opt( config.minDuration, "seconds" )
2928 ["-D"]["--min-duration"]
2929 ( "show test durations for tests taking at least the given number of seconds" )
2930 | Opt( loadTestNamesFromFile, "filename" )
2931 ["-f"]["--input-file"]
2932 ( "load test names to run from a file" )
2933 | Opt( config.filenamesAsTags )
2934 ["-#"]["--filenames-as-tags"]
2935 ( "adds a tag for the filename" )
2936 | Opt( config.sectionsToRun, "section name" )
2937 ["-c"]["--section"]
2938 ( "specify section to run" )
2939 | Opt( setVerbosity, "quiet|normal|high" )
2940 ["-v"]["--verbosity"]
2941 ( "set output verbosity" )
2942 | Opt( config.listTests )
2943 ["--list-tests"]
2944 ( "list all/matching test cases" )
2945 | Opt( config.listTags )
2946 ["--list-tags"]
2947 ( "list all/matching tags" )
2948 | Opt( config.listReporters )
2949 ["--list-reporters"]
2950 ( "list all available reporters" )
2951 | Opt( config.listListeners )
2952 ["--list-listeners"]
2953 ( "list all listeners" )
2954 | Opt( setTestOrder, "decl|lex|rand" )
2955 ["--order"]
2956 ( "test case order (defaults to decl)" )
2957 | Opt( setRngSeed, "'time'|'random-device'|number" )
2958 ["--rng-seed"]
2959 ( "set a specific seed for random numbers" )
2960 | Opt( setDefaultColourMode, "ansi|win32|none|default" )
2961 ["--colour-mode"]
2962 ( "what color mode should be used as default" )
2963 | Opt( config.libIdentify )
2964 ["--libidentify"]
2965 ( "report name and version according to libidentify standard" )
2966 | Opt( setWaitForKeypress, "never|start|exit|both" )
2967 ["--wait-for-keypress"]
2968 ( "waits for a keypress before exiting" )
2969 | Opt( config.skipBenchmarks)
2970 ["--skip-benchmarks"]
2971 ( "disable running benchmarks")
2972 | Opt( config.benchmarkSamples, "samples" )
2973 ["--benchmark-samples"]
2974 ( "number of samples to collect (default: 100)" )
2975 | Opt( config.benchmarkResamples, "resamples" )
2976 ["--benchmark-resamples"]
2977 ( "number of resamples for the bootstrap (default: 100000)" )
2978 | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
2979 ["--benchmark-confidence-interval"]
2980 ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
2981 | Opt( config.benchmarkNoAnalysis )
2982 ["--benchmark-no-analysis"]
2983 ( "perform only measurements; do not perform any analysis" )
2984 | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
2985 ["--benchmark-warmup-time"]
2986 ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
2987 | Opt( setShardCount, "shard count" )
2988 ["--shard-count"]
2989 ( "split the tests to execute into this many groups" )
2990 | Opt( setShardIndex, "shard index" )
2991 ["--shard-index"]
2992 ( "index of the group of tests to execute (see --shard-count)" ) |
2993 Opt( config.allowZeroTests )
2994 ["--allow-running-no-tests"]
2995 ( "Treat 'No tests run' as a success" )
2996 | Arg( config.testsOrTags, "test name|pattern|tags" )
2997 ( "which test or tests to use" );
2998
2999 return cli;
3000 }
3001
3002 } // end namespace Catch
3003
3004
3005 #if defined(__clang__)
3006 # pragma clang diagnostic push
3007 # pragma clang diagnostic ignored "-Wexit-time-destructors"
3008 #endif
3009
3010
3011
3012 #include <cassert>
3013 #include <ostream>
3014 #include <utility>
3015
3016 namespace Catch {
3017
3018 ColourImpl::~ColourImpl() = default;
3019
3020 ColourImpl::ColourGuard ColourImpl::guardColour( Colour::Code colourCode ) {
3021 return ColourGuard(colourCode, this );
3022 }
3023
3024 void ColourImpl::ColourGuard::engageImpl( std::ostream& stream ) {
3025 assert( &stream == &m_colourImpl->m_stream->stream() &&
3026 "Engaging colour guard for different stream than used by the "
3027 "parent colour implementation" );
3028 static_cast<void>( stream );
3029
3030 m_engaged = true;
3031 m_colourImpl->use( m_code );
3032 }
3033
3034 ColourImpl::ColourGuard::ColourGuard( Colour::Code code,
3035 ColourImpl const* colour ):
3036 m_colourImpl( colour ), m_code( code ) {
3037 }
3038 ColourImpl::ColourGuard::ColourGuard( ColourGuard&& rhs ) noexcept:
3039 m_colourImpl( rhs.m_colourImpl ),
3040 m_code( rhs.m_code ),
3041 m_engaged( rhs.m_engaged ) {
3042 rhs.m_engaged = false;
3043 }
3044 ColourImpl::ColourGuard&
3045 ColourImpl::ColourGuard::operator=( ColourGuard&& rhs ) noexcept {
3046 using std::swap;
3047 swap( m_colourImpl, rhs.m_colourImpl );
3048 swap( m_code, rhs.m_code );
3049 swap( m_engaged, rhs.m_engaged );
3050
3051 return *this;
3052 }
3053 ColourImpl::ColourGuard::~ColourGuard() {
3054 if ( m_engaged ) {
3055 m_colourImpl->use( Colour::None );
3056 }
3057 }
3058
3059 ColourImpl::ColourGuard&
3060 ColourImpl::ColourGuard::engage( std::ostream& stream ) & {
3061 engageImpl( stream );
3062 return *this;
3063 }
3064
3065 ColourImpl::ColourGuard&&
3066 ColourImpl::ColourGuard::engage( std::ostream& stream ) && {
3067 engageImpl( stream );
3068 return CATCH_MOVE(*this);
3069 }
3070
3071 namespace {
3072 //! A do-nothing implementation of colour, used as fallback for unknown
3073 //! platforms, and when the user asks to deactivate all colours.
3074 class NoColourImpl : public ColourImpl {
3075 public:
3076 NoColourImpl( IStream* stream ): ColourImpl( stream ) {}
3077
3078 private:
3079 void use( Colour::Code ) const override {}
3080 };
3081 } // namespace
3082
3083
3084 } // namespace Catch
3085
3086
3087 #if defined ( CATCH_CONFIG_COLOUR_WIN32 ) /////////////////////////////////////////
3088
3089 namespace Catch {
3090 namespace {
3091
3092 class Win32ColourImpl : public ColourImpl {
3093 public:
3094 Win32ColourImpl(IStream* stream):
3095 ColourImpl(stream) {
3096 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
3097 GetConsoleScreenBufferInfo( GetStdHandle( STD_OUTPUT_HANDLE ),
3098 &csbiInfo );
3099 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
3100 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
3101 }
3102
3103 static bool useImplementationForStream(IStream const& stream) {
3104 // Win32 text colour APIs can only be used on console streams
3105 // We cannot check that the output hasn't been redirected,
3106 // so we just check that the original stream is console stream.
3107 return stream.isConsole();
3108 }
3109
3110 private:
3111 void use( Colour::Code _colourCode ) const override {
3112 switch( _colourCode ) {
3113 case Colour::None: return setTextAttribute( originalForegroundAttributes );
3114 case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
3115 case Colour::Red: return setTextAttribute( FOREGROUND_RED );
3116 case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
3117 case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
3118 case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
3119 case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
3120 case Colour::Grey: return setTextAttribute( 0 );
3121
3122 case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
3123 case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
3124 case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
3125 case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
3126 case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
3127
3128 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
3129
3130 default:
3131 CATCH_ERROR( "Unknown colour requested" );
3132 }
3133 }
3134
3135 void setTextAttribute( WORD _textAttribute ) const {
3136 SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ),
3137 _textAttribute |
3138 originalBackgroundAttributes );
3139 }
3140 WORD originalForegroundAttributes;
3141 WORD originalBackgroundAttributes;
3142 };
3143
3144 } // end anon namespace
3145 } // end namespace Catch
3146
3147 #endif // Windows/ ANSI/ None
3148
3149
3150 #if defined( CATCH_PLATFORM_LINUX ) || defined( CATCH_PLATFORM_MAC )
3151 # define CATCH_INTERNAL_HAS_ISATTY
3152 # include <unistd.h>
3153 #endif
3154
3155 namespace Catch {
3156 namespace {
3157
3158 class ANSIColourImpl : public ColourImpl {
3159 public:
3160 ANSIColourImpl( IStream* stream ): ColourImpl( stream ) {}
3161
3162 static bool useImplementationForStream(IStream const& stream) {
3163 // This is kinda messy due to trying to support a bunch of
3164 // different platforms at once.
3165 // The basic idea is that if we are asked to do autodetection (as
3166 // opposed to being told to use posixy colours outright), then we
3167 // only want to use the colours if we are writing to console.
3168 // However, console might be redirected, so we make an attempt at
3169 // checking for that on platforms where we know how to do that.
3170 bool useColour = stream.isConsole();
3171 #if defined( CATCH_INTERNAL_HAS_ISATTY ) && \
3172 !( defined( __DJGPP__ ) && defined( __STRICT_ANSI__ ) )
3173 ErrnoGuard _; // for isatty
3174 useColour = useColour && isatty( STDOUT_FILENO );
3175 # endif
3176 # if defined( CATCH_PLATFORM_MAC ) || defined( CATCH_PLATFORM_IPHONE )
3177 useColour = useColour && !isDebuggerActive();
3178 # endif
3179
3180 return useColour;
3181 }
3182
3183 private:
3184 void use( Colour::Code _colourCode ) const override {
3185 auto setColour = [&out =
3186 m_stream->stream()]( char const* escapeCode ) {
3187 // The escape sequence must be flushed to console, otherwise
3188 // if stdin and stderr are intermixed, we'd get accidentally
3189 // coloured output.
3190 out << '\033' << escapeCode << std::flush;
3191 };
3192 switch( _colourCode ) {
3193 case Colour::None:
3194 case Colour::White: return setColour( "[0m" );
3195 case Colour::Red: return setColour( "[0;31m" );
3196 case Colour::Green: return setColour( "[0;32m" );
3197 case Colour::Blue: return setColour( "[0;34m" );
3198 case Colour::Cyan: return setColour( "[0;36m" );
3199 case Colour::Yellow: return setColour( "[0;33m" );
3200 case Colour::Grey: return setColour( "[1;30m" );
3201
3202 case Colour::LightGrey: return setColour( "[0;37m" );
3203 case Colour::BrightRed: return setColour( "[1;31m" );
3204 case Colour::BrightGreen: return setColour( "[1;32m" );
3205 case Colour::BrightWhite: return setColour( "[1;37m" );
3206 case Colour::BrightYellow: return setColour( "[1;33m" );
3207
3208 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
3209 default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
3210 }
3211 }
3212 };
3213
3214 } // end anon namespace
3215 } // end namespace Catch
3216
3217 namespace Catch {
3218
3219 Detail::unique_ptr<ColourImpl> makeColourImpl( ColourMode implSelection,
3220 IStream* stream ) {
3221 #if defined( CATCH_CONFIG_COLOUR_WIN32 )
3222 if ( implSelection == ColourMode::Win32 ) {
3223 return Detail::make_unique<Win32ColourImpl>( stream );
3224 }
3225 #endif
3226 if ( implSelection == ColourMode::ANSI ) {
3227 return Detail::make_unique<ANSIColourImpl>( stream );
3228 }
3229 if ( implSelection == ColourMode::None ) {
3230 return Detail::make_unique<NoColourImpl>( stream );
3231 }
3232
3233 if ( implSelection == ColourMode::PlatformDefault) {
3234 #if defined( CATCH_CONFIG_COLOUR_WIN32 )
3235 if ( Win32ColourImpl::useImplementationForStream( *stream ) ) {
3236 return Detail::make_unique<Win32ColourImpl>( stream );
3237 }
3238 #endif
3239 if ( ANSIColourImpl::useImplementationForStream( *stream ) ) {
3240 return Detail::make_unique<ANSIColourImpl>( stream );
3241 }
3242 return Detail::make_unique<NoColourImpl>( stream );
3243 }
3244
3245 CATCH_ERROR( "Could not create colour impl for selection " << static_cast<int>(implSelection) );
3246 }
3247
3248 bool isColourImplAvailable( ColourMode colourSelection ) {
3249 switch ( colourSelection ) {
3250 #if defined( CATCH_CONFIG_COLOUR_WIN32 )
3251 case ColourMode::Win32:
3252 #endif
3253 case ColourMode::ANSI:
3254 case ColourMode::None:
3255 case ColourMode::PlatformDefault:
3256 return true;
3257 default:
3258 return false;
3259 }
3260 }
3261
3262
3263 } // end namespace Catch
3264
3265 #if defined(__clang__)
3266 # pragma clang diagnostic pop
3267 #endif
3268
3269
3270
3271
3272 namespace Catch {
3273
3274 class Context : public IMutableContext, private Detail::NonCopyable {
3275
3276 public: // IContext
3277 IResultCapture* getResultCapture() override {
3278 return m_resultCapture;
3279 }
3280
3281 IConfig const* getConfig() const override {
3282 return m_config;
3283 }
3284
3285 ~Context() override;
3286
3287 public: // IMutableContext
3288 void setResultCapture( IResultCapture* resultCapture ) override {
3289 m_resultCapture = resultCapture;
3290 }
3291 void setConfig( IConfig const* config ) override {
3292 m_config = config;
3293 }
3294
3295 friend IMutableContext& getCurrentMutableContext();
3296
3297 private:
3298 IConfig const* m_config = nullptr;
3299 IResultCapture* m_resultCapture = nullptr;
3300 };
3301
3302 IMutableContext *IMutableContext::currentContext = nullptr;
3303
3304 void IMutableContext::createContext()
3305 {
3306 currentContext = new Context();
3307 }
3308
3309 void cleanUpContext() {
3310 delete IMutableContext::currentContext;
3311 IMutableContext::currentContext = nullptr;
3312 }
3313 IContext::~IContext() = default;
3314 IMutableContext::~IMutableContext() = default;
3315 Context::~Context() = default;
3316
3317
3318 SimplePcg32& sharedRng() {
3319 static SimplePcg32 s_rng;
3320 return s_rng;
3321 }
3322
3323 }
3324
3325
3326
3327
3328
3329 #include <ostream>
3330
3331 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
3332 #include <android/log.h>
3333
3334 namespace Catch {
3335 void writeToDebugConsole( std::string const& text ) {
3336 __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
3337 }
3338 }
3339
3340 #elif defined(CATCH_PLATFORM_WINDOWS)
3341
3342 namespace Catch {
3343 void writeToDebugConsole( std::string const& text ) {
3344 ::OutputDebugStringA( text.c_str() );
3345 }
3346 }
3347
3348 #else
3349
3350 namespace Catch {
3351 void writeToDebugConsole( std::string const& text ) {
3352 // !TBD: Need a version for Mac/ XCode and other IDEs
3353 Catch::cout() << text;
3354 }
3355 }
3356
3357 #endif // Platform
3358
3359
3360
3361 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
3362
3363 # include <cassert>
3364 # include <sys/types.h>
3365 # include <unistd.h>
3366 # include <cstddef>
3367 # include <ostream>
3368
3369 #ifdef __apple_build_version__
3370 // These headers will only compile with AppleClang (XCode)
3371 // For other compilers (Clang, GCC, ... ) we need to exclude them
3372 # include <sys/sysctl.h>
3373 #endif
3374
3375 namespace Catch {
3376 #ifdef __apple_build_version__
3377 // The following function is taken directly from the following technical note:
3378 // https://developer.apple.com/library/archive/qa/qa1361/_index.html
3379
3380 // Returns true if the current process is being debugged (either
3381 // running under the debugger or has a debugger attached post facto).
3382 bool isDebuggerActive(){
3383 int mib[4];
3384 struct kinfo_proc info;
3385 std::size_t size;
3386
3387 // Initialize the flags so that, if sysctl fails for some bizarre
3388 // reason, we get a predictable result.
3389
3390 info.kp_proc.p_flag = 0;
3391
3392 // Initialize mib, which tells sysctl the info we want, in this case
3393 // we're looking for information about a specific process ID.
3394
3395 mib[0] = CTL_KERN;
3396 mib[1] = KERN_PROC;
3397 mib[2] = KERN_PROC_PID;
3398 mib[3] = getpid();
3399
3400 // Call sysctl.
3401
3402 size = sizeof(info);
3403 if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
3404 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n\n" << std::flush;
3405 return false;
3406 }
3407
3408 // We're being debugged if the P_TRACED flag is set.
3409
3410 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
3411 }
3412 #else
3413 bool isDebuggerActive() {
3414 // We need to find another way to determine this for non-appleclang compilers on macOS
3415 return false;
3416 }
3417 #endif
3418 } // namespace Catch
3419
3420 #elif defined(CATCH_PLATFORM_LINUX)
3421 #include <fstream>
3422 #include <string>
3423
3424 namespace Catch{
3425 // The standard POSIX way of detecting a debugger is to attempt to
3426 // ptrace() the process, but this needs to be done from a child and not
3427 // this process itself to still allow attaching to this process later
3428 // if wanted, so is rather heavy. Under Linux we have the PID of the
3429 // "debugger" (which doesn't need to be gdb, of course, it could also
3430 // be strace, for example) in /proc/$PID/status, so just get it from
3431 // there instead.
3432 bool isDebuggerActive(){
3433 // Libstdc++ has a bug, where std::ifstream sets errno to 0
3434 // This way our users can properly assert over errno values
3435 ErrnoGuard guard;
3436 std::ifstream in("/proc/self/status");
3437 for( std::string line; std::getline(in, line); ) {
3438 static const int PREFIX_LEN = 11;
3439 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
3440 // We're traced if the PID is not 0 and no other PID starts
3441 // with 0 digit, so it's enough to check for just a single
3442 // character.
3443 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
3444 }
3445 }
3446
3447 return false;
3448 }
3449 } // namespace Catch
3450 #elif defined(_MSC_VER)
3451 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
3452 namespace Catch {
3453 bool isDebuggerActive() {
3454 return IsDebuggerPresent() != 0;
3455 }
3456 }
3457 #elif defined(__MINGW32__)
3458 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
3459 namespace Catch {
3460 bool isDebuggerActive() {
3461 return IsDebuggerPresent() != 0;
3462 }
3463 }
3464 #else
3465 namespace Catch {
3466 bool isDebuggerActive() { return false; }
3467 }
3468 #endif // Platform
3469
3470
3471
3472
3473 namespace Catch {
3474
3475 ITransientExpression::~ITransientExpression() = default;
3476
3477 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
3478 if( lhs.size() + rhs.size() < 40 &&
3479 lhs.find('\n') == std::string::npos &&
3480 rhs.find('\n') == std::string::npos )
3481 os << lhs << ' ' << op << ' ' << rhs;
3482 else
3483 os << lhs << '\n' << op << '\n' << rhs;
3484 }
3485 }
3486
3487
3488
3489 #include <stdexcept>
3490
3491
3492 namespace Catch {
3493 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
3494 [[noreturn]]
3495 void throw_exception(std::exception const& e) {
3496 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
3497 << "The message was: " << e.what() << '\n';
3498 std::terminate();
3499 }
3500 #endif
3501
3502 [[noreturn]]
3503 void throw_logic_error(std::string const& msg) {
3504 throw_exception(std::logic_error(msg));
3505 }
3506
3507 [[noreturn]]
3508 void throw_domain_error(std::string const& msg) {
3509 throw_exception(std::domain_error(msg));
3510 }
3511
3512 [[noreturn]]
3513 void throw_runtime_error(std::string const& msg) {
3514 throw_exception(std::runtime_error(msg));
3515 }
3516
3517
3518
3519 } // namespace Catch;
3520
3521
3522
3523 #include <cassert>
3524
3525 namespace Catch {
3526
3527 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() = default;
3528
3529 namespace Detail {
3530
3531 namespace {
3532 // Extracts the actual name part of an enum instance
3533 // In other words, it returns the Blue part of Bikeshed::Colour::Blue
3534 StringRef extractInstanceName(StringRef enumInstance) {
3535 // Find last occurrence of ":"
3536 size_t name_start = enumInstance.size();
3537 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
3538 --name_start;
3539 }
3540 return enumInstance.substr(name_start, enumInstance.size() - name_start);
3541 }
3542 }
3543
3544 std::vector<StringRef> parseEnums( StringRef enums ) {
3545 auto enumValues = splitStringRef( enums, ',' );
3546 std::vector<StringRef> parsed;
3547 parsed.reserve( enumValues.size() );
3548 for( auto const& enumValue : enumValues ) {
3549 parsed.push_back(trim(extractInstanceName(enumValue)));
3550 }
3551 return parsed;
3552 }
3553
3554 EnumInfo::~EnumInfo() {}
3555
3556 StringRef EnumInfo::lookup( int value ) const {
3557 for( auto const& valueToName : m_values ) {
3558 if( valueToName.first == value )
3559 return valueToName.second;
3560 }
3561 return "{** unexpected enum value **}"_sr;
3562 }
3563
3564 Catch::Detail::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
3565 auto enumInfo = Catch::Detail::make_unique<EnumInfo>();
3566 enumInfo->m_name = enumName;
3567 enumInfo->m_values.reserve( values.size() );
3568
3569 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
3570 assert( valueNames.size() == values.size() );
3571 std::size_t i = 0;
3572 for( auto value : values )
3573 enumInfo->m_values.emplace_back(value, valueNames[i++]);
3574
3575 return enumInfo;
3576 }
3577
3578 EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
3579 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
3580 return *m_enumInfos.back();
3581 }
3582
3583 } // Detail
3584 } // Catch
3585
3586
3587
3588
3589
3590 #include <cerrno>
3591
3592 namespace Catch {
3593 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
3594 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
3595 }
3596
3597
3598
3599 namespace Catch {
3600
3601 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
3602 }
3603
3604 void ExceptionTranslatorRegistry::registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator ) {
3605 m_translators.push_back( CATCH_MOVE( translator ) );
3606 }
3607
3608 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3609 std::string ExceptionTranslatorRegistry::translateActiveException() const {
3610 // Compiling a mixed mode project with MSVC means that CLR
3611 // exceptions will be caught in (...) as well. However, these do
3612 // do not fill-in std::current_exception and thus lead to crash
3613 // when attempting rethrow.
3614 // /EHa switch also causes structured exceptions to be caught
3615 // here, but they fill-in current_exception properly, so
3616 // at worst the output should be a little weird, instead of
3617 // causing a crash.
3618 if ( std::current_exception() == nullptr ) {
3619 return "Non C++ exception. Possibly a CLR exception.";
3620 }
3621
3622 // First we try user-registered translators. If none of them can
3623 // handle the exception, it will be rethrown handled by our defaults.
3624 try {
3625 return tryTranslators();
3626 }
3627 // To avoid having to handle TFE explicitly everywhere, we just
3628 // rethrow it so that it goes back up the caller.
3629 catch( TestFailureException& ) {
3630 std::rethrow_exception(std::current_exception());
3631 }
3632 catch( std::exception const& ex ) {
3633 return ex.what();
3634 }
3635 catch( std::string const& msg ) {
3636 return msg;
3637 }
3638 catch( const char* msg ) {
3639 return msg;
3640 }
3641 catch(...) {
3642 return "Unknown exception";
3643 }
3644 }
3645
3646 std::string ExceptionTranslatorRegistry::tryTranslators() const {
3647 if (m_translators.empty()) {
3648 std::rethrow_exception(std::current_exception());
3649 } else {
3650 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
3651 }
3652 }
3653
3654 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
3655 std::string ExceptionTranslatorRegistry::translateActiveException() const {
3656 CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
3657 }
3658
3659 std::string ExceptionTranslatorRegistry::tryTranslators() const {
3660 CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
3661 }
3662 #endif
3663
3664
3665 }
3666
3667
3668
3669 /** \file
3670 * This file provides platform specific implementations of FatalConditionHandler
3671 *
3672 * This means that there is a lot of conditional compilation, and platform
3673 * specific code. Currently, Catch2 supports a dummy handler (if no
3674 * handler is desired), and 2 platform specific handlers:
3675 * * Windows' SEH
3676 * * POSIX signals
3677 *
3678 * Consequently, various pieces of code below are compiled if either of
3679 * the platform specific handlers is enabled, or if none of them are
3680 * enabled. It is assumed that both cannot be enabled at the same time,
3681 * and doing so should cause a compilation error.
3682 *
3683 * If another platform specific handler is added, the compile guards
3684 * below will need to be updated taking these assumptions into account.
3685 */
3686
3687
3688
3689 #include <algorithm>
3690
3691 #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
3692
3693 namespace Catch {
3694
3695 // If neither SEH nor signal handling is required, the handler impls
3696 // do not have to do anything, and can be empty.
3697 void FatalConditionHandler::engage_platform() {}
3698 void FatalConditionHandler::disengage_platform() noexcept {}
3699 FatalConditionHandler::FatalConditionHandler() = default;
3700 FatalConditionHandler::~FatalConditionHandler() = default;
3701
3702 } // end namespace Catch
3703
3704 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
3705
3706 #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
3707 #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
3708 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
3709
3710 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
3711
3712 namespace {
3713 //! Signals fatal error message to the run context
3714 void reportFatal( char const * const message ) {
3715 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
3716 }
3717
3718 //! Minimal size Catch2 needs for its own fatal error handling.
3719 //! Picked empirically, so it might not be sufficient on all
3720 //! platforms, and for all configurations.
3721 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
3722 } // end unnamed namespace
3723
3724 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
3725
3726 #if defined( CATCH_CONFIG_WINDOWS_SEH )
3727
3728 namespace Catch {
3729
3730 struct SignalDefs { DWORD id; const char* name; };
3731
3732 // There is no 1-1 mapping between signals and windows exceptions.
3733 // Windows can easily distinguish between SO and SigSegV,
3734 // but SigInt, SigTerm, etc are handled differently.
3735 static SignalDefs signalDefs[] = {
3736 { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
3737 { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
3738 { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
3739 { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
3740 };
3741
3742 static LONG CALLBACK topLevelExceptionFilter(PEXCEPTION_POINTERS ExceptionInfo) {
3743 for (auto const& def : signalDefs) {
3744 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
3745 reportFatal(def.name);
3746 }
3747 }
3748 // If its not an exception we care about, pass it along.
3749 // This stops us from eating debugger breaks etc.
3750 return EXCEPTION_CONTINUE_SEARCH;
3751 }
3752
3753 // Since we do not support multiple instantiations, we put these
3754 // into global variables and rely on cleaning them up in outlined
3755 // constructors/destructors
3756 static LPTOP_LEVEL_EXCEPTION_FILTER previousTopLevelExceptionFilter = nullptr;
3757
3758
3759 // For MSVC, we reserve part of the stack memory for handling
3760 // memory overflow structured exception.
3761 FatalConditionHandler::FatalConditionHandler() {
3762 ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
3763 if (!SetThreadStackGuarantee(&guaranteeSize)) {
3764 // We do not want to fully error out, because needing
3765 // the stack reserve should be rare enough anyway.
3766 Catch::cerr()
3767 << "Failed to reserve piece of stack."
3768 << " Stack overflows will not be reported successfully.";
3769 }
3770 }
3771
3772 // We do not attempt to unset the stack guarantee, because
3773 // Windows does not support lowering the stack size guarantee.
3774 FatalConditionHandler::~FatalConditionHandler() = default;
3775
3776
3777 void FatalConditionHandler::engage_platform() {
3778 // Register as a the top level exception filter.
3779 previousTopLevelExceptionFilter = SetUnhandledExceptionFilter(topLevelExceptionFilter);
3780 }
3781
3782 void FatalConditionHandler::disengage_platform() noexcept {
3783 if (SetUnhandledExceptionFilter(previousTopLevelExceptionFilter) != topLevelExceptionFilter) {
3784 Catch::cerr()
3785 << "Unexpected SEH unhandled exception filter on disengage."
3786 << " The filter was restored, but might be rolled back unexpectedly.";
3787 }
3788 previousTopLevelExceptionFilter = nullptr;
3789 }
3790
3791 } // end namespace Catch
3792
3793 #endif // CATCH_CONFIG_WINDOWS_SEH
3794
3795 #if defined( CATCH_CONFIG_POSIX_SIGNALS )
3796
3797 #include <signal.h>
3798
3799 namespace Catch {
3800
3801 struct SignalDefs {
3802 int id;
3803 const char* name;
3804 };
3805
3806 static SignalDefs signalDefs[] = {
3807 { SIGINT, "SIGINT - Terminal interrupt signal" },
3808 { SIGILL, "SIGILL - Illegal instruction signal" },
3809 { SIGFPE, "SIGFPE - Floating point error signal" },
3810 { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
3811 { SIGTERM, "SIGTERM - Termination request signal" },
3812 { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
3813 };
3814
3815 // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
3816 // which is zero initialization, but not explicit. We want to avoid
3817 // that.
3818 #if defined(__GNUC__)
3819 # pragma GCC diagnostic push
3820 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
3821 #endif
3822
3823 static char* altStackMem = nullptr;
3824 static std::size_t altStackSize = 0;
3825 static stack_t oldSigStack{};
3826 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
3827
3828 static void restorePreviousSignalHandlers() noexcept {
3829 // We set signal handlers back to the previous ones. Hopefully
3830 // nobody overwrote them in the meantime, and doesn't expect
3831 // their signal handlers to live past ours given that they
3832 // installed them after ours..
3833 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
3834 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
3835 }
3836 // Return the old stack
3837 sigaltstack(&oldSigStack, nullptr);
3838 }
3839
3840 static void handleSignal( int sig ) {
3841 char const * name = "<unknown signal>";
3842 for (auto const& def : signalDefs) {
3843 if (sig == def.id) {
3844 name = def.name;
3845 break;
3846 }
3847 }
3848 // We need to restore previous signal handlers and let them do
3849 // their thing, so that the users can have the debugger break
3850 // when a signal is raised, and so on.
3851 restorePreviousSignalHandlers();
3852 reportFatal( name );
3853 raise( sig );
3854 }
3855
3856 FatalConditionHandler::FatalConditionHandler() {
3857 assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
3858 if (altStackSize == 0) {
3859 altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
3860 }
3861 altStackMem = new char[altStackSize]();
3862 }
3863
3864 FatalConditionHandler::~FatalConditionHandler() {
3865 delete[] altStackMem;
3866 // We signal that another instance can be constructed by zeroing
3867 // out the pointer.
3868 altStackMem = nullptr;
3869 }
3870
3871 void FatalConditionHandler::engage_platform() {
3872 stack_t sigStack;
3873 sigStack.ss_sp = altStackMem;
3874 sigStack.ss_size = altStackSize;
3875 sigStack.ss_flags = 0;
3876 sigaltstack(&sigStack, &oldSigStack);
3877 struct sigaction sa = { };
3878
3879 sa.sa_handler = handleSignal;
3880 sa.sa_flags = SA_ONSTACK;
3881 for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
3882 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
3883 }
3884 }
3885
3886 #if defined(__GNUC__)
3887 # pragma GCC diagnostic pop
3888 #endif
3889
3890
3891 void FatalConditionHandler::disengage_platform() noexcept {
3892 restorePreviousSignalHandlers();
3893 }
3894
3895 } // end namespace Catch
3896
3897 #endif // CATCH_CONFIG_POSIX_SIGNALS
3898
3899
3900
3901
3902 #include <cstring>
3903
3904 namespace Catch {
3905 namespace Detail {
3906
3907 uint32_t convertToBits(float f) {
3908 static_assert(sizeof(float) == sizeof(uint32_t), "Important ULP matcher assumption violated");
3909 uint32_t i;
3910 std::memcpy(&i, &f, sizeof(f));
3911 return i;
3912 }
3913
3914 uint64_t convertToBits(double d) {
3915 static_assert(sizeof(double) == sizeof(uint64_t), "Important ULP matcher assumption violated");
3916 uint64_t i;
3917 std::memcpy(&i, &d, sizeof(d));
3918 return i;
3919 }
3920
3921 } // end namespace Detail
3922 } // end namespace Catch
3923
3924
3925
3926
3927
3928 #include <cstdio>
3929 #include <fstream>
3930 #include <sstream>
3931 #include <vector>
3932
3933 namespace Catch {
3934
3935 Catch::IStream::~IStream() = default;
3936
3937 namespace Detail {
3938 namespace {
3939 template<typename WriterF, std::size_t bufferSize=256>
3940 class StreamBufImpl : public std::streambuf {
3941 char data[bufferSize];
3942 WriterF m_writer;
3943
3944 public:
3945 StreamBufImpl() {
3946 setp( data, data + sizeof(data) );
3947 }
3948
3949 ~StreamBufImpl() noexcept override {
3950 StreamBufImpl::sync();
3951 }
3952
3953 private:
3954 int overflow( int c ) override {
3955 sync();
3956
3957 if( c != EOF ) {
3958 if( pbase() == epptr() )
3959 m_writer( std::string( 1, static_cast<char>( c ) ) );
3960 else
3961 sputc( static_cast<char>( c ) );
3962 }
3963 return 0;
3964 }
3965
3966 int sync() override {
3967 if( pbase() != pptr() ) {
3968 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
3969 setp( pbase(), epptr() );
3970 }
3971 return 0;
3972 }
3973 };
3974
3975 ///////////////////////////////////////////////////////////////////////////
3976
3977 struct OutputDebugWriter {
3978
3979 void operator()( std::string const& str ) {
3980 if ( !str.empty() ) {
3981 writeToDebugConsole( str );
3982 }
3983 }
3984 };
3985
3986 ///////////////////////////////////////////////////////////////////////////
3987
3988 class FileStream : public IStream {
3989 std::ofstream m_ofs;
3990 public:
3991 FileStream( std::string const& filename ) {
3992 m_ofs.open( filename.c_str() );
3993 CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << '\'' );
3994 m_ofs << std::unitbuf;
3995 }
3996 ~FileStream() override = default;
3997 public: // IStream
3998 std::ostream& stream() override {
3999 return m_ofs;
4000 }
4001 };
4002
4003 ///////////////////////////////////////////////////////////////////////////
4004
4005 class CoutStream : public IStream {
4006 std::ostream m_os;
4007 public:
4008 // Store the streambuf from cout up-front because
4009 // cout may get redirected when running tests
4010 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
4011 ~CoutStream() override = default;
4012
4013 public: // IStream
4014 std::ostream& stream() override { return m_os; }
4015 bool isConsole() const override { return true; }
4016 };
4017
4018 class CerrStream : public IStream {
4019 std::ostream m_os;
4020
4021 public:
4022 // Store the streambuf from cerr up-front because
4023 // cout may get redirected when running tests
4024 CerrStream(): m_os( Catch::cerr().rdbuf() ) {}
4025 ~CerrStream() override = default;
4026
4027 public: // IStream
4028 std::ostream& stream() override { return m_os; }
4029 bool isConsole() const override { return true; }
4030 };
4031
4032 ///////////////////////////////////////////////////////////////////////////
4033
4034 class DebugOutStream : public IStream {
4035 Detail::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
4036 std::ostream m_os;
4037 public:
4038 DebugOutStream()
4039 : m_streamBuf( Detail::make_unique<StreamBufImpl<OutputDebugWriter>>() ),
4040 m_os( m_streamBuf.get() )
4041 {}
4042
4043 ~DebugOutStream() override = default;
4044
4045 public: // IStream
4046 std::ostream& stream() override { return m_os; }
4047 };
4048
4049 } // unnamed namespace
4050 } // namespace Detail
4051
4052 ///////////////////////////////////////////////////////////////////////////
4053
4054 auto makeStream( std::string const& filename ) -> Detail::unique_ptr<IStream> {
4055 if ( filename.empty() || filename == "-" ) {
4056 return Detail::make_unique<Detail::CoutStream>();
4057 }
4058 if( filename[0] == '%' ) {
4059 if ( filename == "%debug" ) {
4060 return Detail::make_unique<Detail::DebugOutStream>();
4061 } else if ( filename == "%stderr" ) {
4062 return Detail::make_unique<Detail::CerrStream>();
4063 } else if ( filename == "%stdout" ) {
4064 return Detail::make_unique<Detail::CoutStream>();
4065 } else {
4066 CATCH_ERROR( "Unrecognised stream: '" << filename << '\'' );
4067 }
4068 }
4069 return Detail::make_unique<Detail::FileStream>( filename );
4070 }
4071
4072 }
4073
4074
4075
4076
4077 namespace Catch {
4078
4079 auto operator << (std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream& {
4080 if (lazyExpr.m_isNegated)
4081 os << '!';
4082
4083 if (lazyExpr) {
4084 if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression())
4085 os << '(' << *lazyExpr.m_transientExpression << ')';
4086 else
4087 os << *lazyExpr.m_transientExpression;
4088 } else {
4089 os << "{** error - unchecked empty expression requested **}";
4090 }
4091 return os;
4092 }
4093
4094 } // namespace Catch
4095
4096
4097
4098
4099 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
4100 #include <crtdbg.h>
4101
4102 namespace Catch {
4103
4104 LeakDetector::LeakDetector() {
4105 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
4106 flag |= _CRTDBG_LEAK_CHECK_DF;
4107 flag |= _CRTDBG_ALLOC_MEM_DF;
4108 _CrtSetDbgFlag(flag);
4109 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
4110 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
4111 // Change this to leaking allocation's number to break there
4112 _CrtSetBreakAlloc(-1);
4113 }
4114 }
4115
4116 #else // ^^ Windows crt debug heap enabled // Windows crt debug heap disabled vv
4117
4118 Catch::LeakDetector::LeakDetector() {}
4119
4120 #endif // CATCH_CONFIG_WINDOWS_CRTDBG
4121
4122 Catch::LeakDetector::~LeakDetector() {
4123 Catch::cleanUp();
4124 }
4125
4126
4127
4128
4129
4130 namespace Catch {
4131 namespace {
4132
4133 void listTests(IEventListener& reporter, IConfig const& config) {
4134 auto const& testSpec = config.testSpec();
4135 auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
4136 reporter.listTests(matchedTestCases);
4137 }
4138
4139 void listTags(IEventListener& reporter, IConfig const& config) {
4140 auto const& testSpec = config.testSpec();
4141 std::vector<TestCaseHandle> matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
4142
4143 std::map<StringRef, TagInfo, Detail::CaseInsensitiveLess> tagCounts;
4144 for (auto const& testCase : matchedTestCases) {
4145 for (auto const& tagName : testCase.getTestCaseInfo().tags) {
4146 auto it = tagCounts.find(tagName.original);
4147 if (it == tagCounts.end())
4148 it = tagCounts.insert(std::make_pair(tagName.original, TagInfo())).first;
4149 it->second.add(tagName.original);
4150 }
4151 }
4152
4153 std::vector<TagInfo> infos; infos.reserve(tagCounts.size());
4154 for (auto& tagc : tagCounts) {
4155 infos.push_back(CATCH_MOVE(tagc.second));
4156 }
4157
4158 reporter.listTags(infos);
4159 }
4160
4161 void listReporters(IEventListener& reporter) {
4162 std::vector<ReporterDescription> descriptions;
4163
4164 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
4165 descriptions.reserve(factories.size());
4166 for (auto const& fac : factories) {
4167 descriptions.push_back({ fac.first, fac.second->getDescription() });
4168 }
4169
4170 reporter.listReporters(descriptions);
4171 }
4172
4173 void listListeners(IEventListener& reporter) {
4174 std::vector<ListenerDescription> descriptions;
4175
4176 auto const& factories =
4177 getRegistryHub().getReporterRegistry().getListeners();
4178 descriptions.reserve( factories.size() );
4179 for ( auto const& fac : factories ) {
4180 descriptions.push_back( { fac->getName(), fac->getDescription() } );
4181 }
4182
4183 reporter.listListeners( descriptions );
4184 }
4185
4186 } // end anonymous namespace
4187
4188 void TagInfo::add( StringRef spelling ) {
4189 ++count;
4190 spellings.insert( spelling );
4191 }
4192
4193 std::string TagInfo::all() const {
4194 // 2 per tag for brackets '[' and ']'
4195 size_t size = spellings.size() * 2;
4196 for (auto const& spelling : spellings) {
4197 size += spelling.size();
4198 }
4199
4200 std::string out; out.reserve(size);
4201 for (auto const& spelling : spellings) {
4202 out += '[';
4203 out += spelling;
4204 out += ']';
4205 }
4206 return out;
4207 }
4208
4209 bool list( IEventListener& reporter, Config const& config ) {
4210 bool listed = false;
4211 if (config.listTests()) {
4212 listed = true;
4213 listTests(reporter, config);
4214 }
4215 if (config.listTags()) {
4216 listed = true;
4217 listTags(reporter, config);
4218 }
4219 if (config.listReporters()) {
4220 listed = true;
4221 listReporters(reporter);
4222 }
4223 if ( config.listListeners() ) {
4224 listed = true;
4225 listListeners( reporter );
4226 }
4227 return listed;
4228 }
4229
4230 } // end namespace Catch
4231
4232
4233
4234 namespace Catch {
4235 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
4236 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
4237 static LeakDetector leakDetector;
4238 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
4239 }
4240
4241 // Allow users of amalgamated .cpp file to remove our main and provide their own.
4242 #if !defined(CATCH_AMALGAMATED_CUSTOM_MAIN)
4243
4244 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
4245 // Standard C/C++ Win32 Unicode wmain entry point
4246 extern "C" int __cdecl wmain (int argc, wchar_t * argv[], wchar_t * []) {
4247 #else
4248 // Standard C/C++ main entry point
4249 int main (int argc, char * argv[]) {
4250 #endif
4251
4252 // We want to force the linker not to discard the global variable
4253 // and its constructor, as it (optionally) registers leak detector
4254 (void)&Catch::leakDetector;
4255
4256 return Catch::Session().run( argc, argv );
4257 }
4258
4259 #endif // !defined(CATCH_AMALGAMATED_CUSTOM_MAIN
4260
4261
4262
4263
4264 namespace Catch {
4265
4266 MessageInfo::MessageInfo( StringRef _macroName,
4267 SourceLineInfo const& _lineInfo,
4268 ResultWas::OfType _type )
4269 : macroName( _macroName ),
4270 lineInfo( _lineInfo ),
4271 type( _type ),
4272 sequence( ++globalCount )
4273 {}
4274
4275 // This may need protecting if threading support is added
4276 unsigned int MessageInfo::globalCount = 0;
4277
4278 } // end namespace Catch
4279
4280
4281
4282 #include <cstdio>
4283 #include <cstring>
4284 #include <sstream>
4285
4286 #if defined(CATCH_CONFIG_NEW_CAPTURE)
4287 #if defined(_MSC_VER)
4288 #include <io.h> //_dup and _dup2
4289 #define dup _dup
4290 #define dup2 _dup2
4291 #define fileno _fileno
4292 #else
4293 #include <unistd.h> // dup and dup2
4294 #endif
4295 #endif
4296
4297
4298 namespace Catch {
4299
4300 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
4301 : m_originalStream( originalStream ),
4302 m_redirectionStream( redirectionStream ),
4303 m_prevBuf( m_originalStream.rdbuf() )
4304 {
4305 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
4306 }
4307
4308 RedirectedStream::~RedirectedStream() {
4309 m_originalStream.rdbuf( m_prevBuf );
4310 }
4311
4312 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
4313 auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
4314
4315 RedirectedStdErr::RedirectedStdErr()
4316 : m_cerr( Catch::cerr(), m_rss.get() ),
4317 m_clog( Catch::clog(), m_rss.get() )
4318 {}
4319 auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
4320
4321 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
4322 : m_redirectedCout(redirectedCout),
4323 m_redirectedCerr(redirectedCerr)
4324 {}
4325
4326 RedirectedStreams::~RedirectedStreams() {
4327 m_redirectedCout += m_redirectedStdOut.str();
4328 m_redirectedCerr += m_redirectedStdErr.str();
4329 }
4330
4331 #if defined(CATCH_CONFIG_NEW_CAPTURE)
4332
4333 #if defined(_MSC_VER)
4334 TempFile::TempFile() {
4335 if (tmpnam_s(m_buffer)) {
4336 CATCH_RUNTIME_ERROR("Could not get a temp filename");
4337 }
4338 if (fopen_s(&m_file, m_buffer, "w+")) {
4339 char buffer[100];
4340 if (strerror_s(buffer, errno)) {
4341 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
4342 }
4343 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
4344 }
4345 }
4346 #else
4347 TempFile::TempFile() {
4348 m_file = std::tmpfile();
4349 if (!m_file) {
4350 CATCH_RUNTIME_ERROR("Could not create a temp file.");
4351 }
4352 }
4353
4354 #endif
4355
4356 TempFile::~TempFile() {
4357 // TBD: What to do about errors here?
4358 std::fclose(m_file);
4359 // We manually create the file on Windows only, on Linux
4360 // it will be autodeleted
4361 #if defined(_MSC_VER)
4362 std::remove(m_buffer);
4363 #endif
4364 }
4365
4366
4367 FILE* TempFile::getFile() {
4368 return m_file;
4369 }
4370
4371 std::string TempFile::getContents() {
4372 std::stringstream sstr;
4373 char buffer[100] = {};
4374 std::rewind(m_file);
4375 while (std::fgets(buffer, sizeof(buffer), m_file)) {
4376 sstr << buffer;
4377 }
4378 return sstr.str();
4379 }
4380
4381 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
4382 m_originalStdout(dup(1)),
4383 m_originalStderr(dup(2)),
4384 m_stdoutDest(stdout_dest),
4385 m_stderrDest(stderr_dest) {
4386 dup2(fileno(m_stdoutFile.getFile()), 1);
4387 dup2(fileno(m_stderrFile.getFile()), 2);
4388 }
4389
4390 OutputRedirect::~OutputRedirect() {
4391 Catch::cout() << std::flush;
4392 fflush(stdout);
4393 // Since we support overriding these streams, we flush cerr
4394 // even though std::cerr is unbuffered
4395 Catch::cerr() << std::flush;
4396 Catch::clog() << std::flush;
4397 fflush(stderr);
4398
4399 dup2(m_originalStdout, 1);
4400 dup2(m_originalStderr, 2);
4401
4402 m_stdoutDest += m_stdoutFile.getContents();
4403 m_stderrDest += m_stderrFile.getContents();
4404 }
4405
4406 #endif // CATCH_CONFIG_NEW_CAPTURE
4407
4408 } // namespace Catch
4409
4410 #if defined(CATCH_CONFIG_NEW_CAPTURE)
4411 #if defined(_MSC_VER)
4412 #undef dup
4413 #undef dup2
4414 #undef fileno
4415 #endif
4416 #endif
4417
4418
4419
4420
4421 #include <cmath>
4422
4423 namespace Catch {
4424
4425 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
4426 bool isnan(float f) {
4427 return std::isnan(f);
4428 }
4429 bool isnan(double d) {
4430 return std::isnan(d);
4431 }
4432 #else
4433 // For now we only use this for embarcadero
4434 bool isnan(float f) {
4435 return std::_isnan(f);
4436 }
4437 bool isnan(double d) {
4438 return std::_isnan(d);
4439 }
4440 #endif
4441
4442 } // end namespace Catch
4443
4444
4445
4446 namespace Catch {
4447
4448 namespace {
4449
4450 #if defined(_MSC_VER)
4451 #pragma warning(push)
4452 #pragma warning(disable:4146) // we negate uint32 during the rotate
4453 #endif
4454 // Safe rotr implementation thanks to John Regehr
4455 uint32_t rotate_right(uint32_t val, uint32_t count) {
4456 const uint32_t mask = 31;
4457 count &= mask;
4458 return (val >> count) | (val << (-count & mask));
4459 }
4460
4461 #if defined(_MSC_VER)
4462 #pragma warning(pop)
4463 #endif
4464
4465 }
4466
4467
4468 SimplePcg32::SimplePcg32(result_type seed_) {
4469 seed(seed_);
4470 }
4471
4472
4473 void SimplePcg32::seed(result_type seed_) {
4474 m_state = 0;
4475 (*this)();
4476 m_state += seed_;
4477 (*this)();
4478 }
4479
4480 void SimplePcg32::discard(uint64_t skip) {
4481 // We could implement this to run in O(log n) steps, but this
4482 // should suffice for our use case.
4483 for (uint64_t s = 0; s < skip; ++s) {
4484 static_cast<void>((*this)());
4485 }
4486 }
4487
4488 SimplePcg32::result_type SimplePcg32::operator()() {
4489 // prepare the output value
4490 const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
4491 const auto output = rotate_right(xorshifted, m_state >> 59u);
4492
4493 // advance state
4494 m_state = m_state * 6364136223846793005ULL + s_inc;
4495
4496 return output;
4497 }
4498
4499 bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
4500 return lhs.m_state == rhs.m_state;
4501 }
4502
4503 bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
4504 return lhs.m_state != rhs.m_state;
4505 }
4506 }
4507
4508
4509
4510
4511
4512 #include <ctime>
4513 #include <random>
4514
4515 namespace Catch {
4516
4517 std::uint32_t generateRandomSeed( GenerateFrom from ) {
4518 switch ( from ) {
4519 case GenerateFrom::Time:
4520 return static_cast<std::uint32_t>( std::time( nullptr ) );
4521
4522 case GenerateFrom::Default:
4523 case GenerateFrom::RandomDevice:
4524 // In theory, a platform could have random_device that returns just
4525 // 16 bits. That is still some randomness, so we don't care too much
4526 return static_cast<std::uint32_t>( std::random_device{}() );
4527
4528 default:
4529 CATCH_ERROR("Unknown generation method");
4530 }
4531 }
4532
4533 } // end namespace Catch
4534
4535
4536
4537
4538 namespace Catch {
4539
4540 ReporterRegistry::ReporterRegistry() {
4541 // Because it is impossible to move out of initializer list,
4542 // we have to add the elements manually
4543 m_factories["Automake"] = Detail::make_unique<ReporterFactory<AutomakeReporter>>();
4544 m_factories["compact"] = Detail::make_unique<ReporterFactory<CompactReporter>>();
4545 m_factories["console"] = Detail::make_unique<ReporterFactory<ConsoleReporter>>();
4546 m_factories["JUnit"] = Detail::make_unique<ReporterFactory<JunitReporter>>();
4547 m_factories["SonarQube"] = Detail::make_unique<ReporterFactory<SonarQubeReporter>>();
4548 m_factories["TAP"] = Detail::make_unique<ReporterFactory<TAPReporter>>();
4549 m_factories["TeamCity"] = Detail::make_unique<ReporterFactory<TeamCityReporter>>();
4550 m_factories["XML"] = Detail::make_unique<ReporterFactory<XmlReporter>>();
4551 }
4552
4553 ReporterRegistry::~ReporterRegistry() = default;
4554
4555
4556 IEventListenerPtr ReporterRegistry::create( std::string const& name, ReporterConfig&& config ) const {
4557 auto it = m_factories.find( name );
4558 if( it == m_factories.end() )
4559 return nullptr;
4560 return it->second->create( CATCH_MOVE(config) );
4561 }
4562
4563 void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr factory ) {
4564 CATCH_ENFORCE( name.find( "::" ) == name.npos,
4565 "'::' is not allowed in reporter name: '" + name + '\'' );
4566 auto ret = m_factories.emplace(name, CATCH_MOVE(factory));
4567 CATCH_ENFORCE( ret.second, "reporter using '" + name + "' as name was already registered" );
4568 }
4569 void ReporterRegistry::registerListener(
4570 Detail::unique_ptr<EventListenerFactory> factory ) {
4571 m_listeners.push_back( CATCH_MOVE(factory) );
4572 }
4573
4574 IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
4575 return m_factories;
4576 }
4577 IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
4578 return m_listeners;
4579 }
4580
4581 }
4582
4583
4584
4585
4586
4587 #include <algorithm>
4588
4589 namespace Catch {
4590
4591 namespace {
4592 struct kvPair {
4593 StringRef key, value;
4594 };
4595
4596 kvPair splitKVPair(StringRef kvString) {
4597 auto splitPos = static_cast<size_t>( std::distance(
4598 kvString.begin(),
4599 std::find( kvString.begin(), kvString.end(), '=' ) ) );
4600
4601 return { kvString.substr( 0, splitPos ),
4602 kvString.substr( splitPos + 1, kvString.size() ) };
4603 }
4604 }
4605
4606 namespace Detail {
4607 std::vector<std::string> splitReporterSpec( StringRef reporterSpec ) {
4608 static constexpr auto separator = "::";
4609 static constexpr size_t separatorSize = 2;
4610
4611 size_t separatorPos = 0;
4612 auto findNextSeparator = [&reporterSpec]( size_t startPos ) {
4613 static_assert(
4614 separatorSize == 2,
4615 "The code below currently assumes 2 char separator" );
4616
4617 auto currentPos = startPos;
4618 do {
4619 while ( currentPos < reporterSpec.size() &&
4620 reporterSpec[currentPos] != separator[0] ) {
4621 ++currentPos;
4622 }
4623 if ( currentPos + 1 < reporterSpec.size() &&
4624 reporterSpec[currentPos + 1] == separator[1] ) {
4625 return currentPos;
4626 }
4627 ++currentPos;
4628 } while ( currentPos < reporterSpec.size() );
4629
4630 return static_cast<size_t>( -1 );
4631 };
4632
4633 std::vector<std::string> parts;
4634
4635 while ( separatorPos < reporterSpec.size() ) {
4636 const auto nextSeparator = findNextSeparator( separatorPos );
4637 parts.push_back( static_cast<std::string>( reporterSpec.substr(
4638 separatorPos, nextSeparator - separatorPos ) ) );
4639
4640 if ( nextSeparator == static_cast<size_t>( -1 ) ) {
4641 break;
4642 }
4643 separatorPos = nextSeparator + separatorSize;
4644 }
4645
4646 // Handle a separator at the end.
4647 // This is not a valid spec, but we want to do validation in a
4648 // centralized place
4649 if ( separatorPos == reporterSpec.size() ) {
4650 parts.emplace_back();
4651 }
4652
4653 return parts;
4654 }
4655
4656 Optional<ColourMode> stringToColourMode( StringRef colourMode ) {
4657 if ( colourMode == "default" ) {
4658 return ColourMode::PlatformDefault;
4659 } else if ( colourMode == "ansi" ) {
4660 return ColourMode::ANSI;
4661 } else if ( colourMode == "win32" ) {
4662 return ColourMode::Win32;
4663 } else if ( colourMode == "none" ) {
4664 return ColourMode::None;
4665 } else {
4666 return {};
4667 }
4668 }
4669 } // namespace Detail
4670
4671
4672 bool operator==( ReporterSpec const& lhs, ReporterSpec const& rhs ) {
4673 return lhs.m_name == rhs.m_name &&
4674 lhs.m_outputFileName == rhs.m_outputFileName &&
4675 lhs.m_colourMode == rhs.m_colourMode &&
4676 lhs.m_customOptions == rhs.m_customOptions;
4677 }
4678
4679 Optional<ReporterSpec> parseReporterSpec( StringRef reporterSpec ) {
4680 auto parts = Detail::splitReporterSpec( reporterSpec );
4681
4682 assert( parts.size() > 0 && "Split should never return empty vector" );
4683
4684 std::map<std::string, std::string> kvPairs;
4685 Optional<std::string> outputFileName;
4686 Optional<ColourMode> colourMode;
4687
4688 // First part is always reporter name, so we skip it
4689 for ( size_t i = 1; i < parts.size(); ++i ) {
4690 auto kv = splitKVPair( parts[i] );
4691 auto key = kv.key, value = kv.value;
4692
4693 if ( key.empty() || value.empty() ) {
4694 return {};
4695 } else if ( key[0] == 'X' ) {
4696 // This is a reporter-specific option, we don't check these
4697 // apart from basic sanity checks
4698 if ( key.size() == 1 ) {
4699 return {};
4700 }
4701
4702 auto ret = kvPairs.emplace( std::string(kv.key), std::string(kv.value) );
4703 if ( !ret.second ) {
4704 // Duplicated key. We might want to handle this differently,
4705 // e.g. by overwriting the existing value?
4706 return {};
4707 }
4708 } else if ( key == "out" ) {
4709 // Duplicated key
4710 if ( outputFileName ) {
4711 return {};
4712 }
4713 outputFileName = static_cast<std::string>( value );
4714 } else if ( key == "colour-mode" ) {
4715 // Duplicated key
4716 if ( colourMode ) {
4717 return {};
4718 }
4719 colourMode = Detail::stringToColourMode( value );
4720 // Parsing failed
4721 if ( !colourMode ) {
4722 return {};
4723 }
4724 } else {
4725 // Unrecognized option
4726 return {};
4727 }
4728 }
4729
4730 return ReporterSpec{ CATCH_MOVE( parts[0] ),
4731 CATCH_MOVE( outputFileName ),
4732 CATCH_MOVE( colourMode ),
4733 CATCH_MOVE( kvPairs ) };
4734 }
4735
4736 ReporterSpec::ReporterSpec(
4737 std::string name,
4738 Optional<std::string> outputFileName,
4739 Optional<ColourMode> colourMode,
4740 std::map<std::string, std::string> customOptions ):
4741 m_name( CATCH_MOVE( name ) ),
4742 m_outputFileName( CATCH_MOVE( outputFileName ) ),
4743 m_colourMode( CATCH_MOVE( colourMode ) ),
4744 m_customOptions( CATCH_MOVE( customOptions ) ) {}
4745
4746 } // namespace Catch
4747
4748
4749
4750 namespace Catch {
4751
4752 bool isOk( ResultWas::OfType resultType ) {
4753 return ( resultType & ResultWas::FailureBit ) == 0;
4754 }
4755 bool isJustInfo( int flags ) {
4756 return flags == ResultWas::Info;
4757 }
4758
4759 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
4760 return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
4761 }
4762
4763 bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
4764 bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
4765
4766 } // end namespace Catch
4767
4768
4769
4770 #include <cstdio>
4771 #include <sstream>
4772 #include <vector>
4773
4774 namespace Catch {
4775
4776 // This class encapsulates the idea of a pool of ostringstreams that can be reused.
4777 struct StringStreams {
4778 std::vector<Detail::unique_ptr<std::ostringstream>> m_streams;
4779 std::vector<std::size_t> m_unused;
4780 std::ostringstream m_referenceStream; // Used for copy state/ flags from
4781
4782 auto add() -> std::size_t {
4783 if( m_unused.empty() ) {
4784 m_streams.push_back( Detail::make_unique<std::ostringstream>() );
4785 return m_streams.size()-1;
4786 }
4787 else {
4788 auto index = m_unused.back();
4789 m_unused.pop_back();
4790 return index;
4791 }
4792 }
4793
4794 void release( std::size_t index ) {
4795 m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
4796 m_unused.push_back(index);
4797 }
4798 };
4799
4800 ReusableStringStream::ReusableStringStream()
4801 : m_index( Singleton<StringStreams>::getMutable().add() ),
4802 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
4803 {}
4804
4805 ReusableStringStream::~ReusableStringStream() {
4806 static_cast<std::ostringstream*>( m_oss )->str("");
4807 m_oss->clear();
4808 Singleton<StringStreams>::getMutable().release( m_index );
4809 }
4810
4811 std::string ReusableStringStream::str() const {
4812 return static_cast<std::ostringstream*>( m_oss )->str();
4813 }
4814
4815 void ReusableStringStream::str( std::string const& str ) {
4816 static_cast<std::ostringstream*>( m_oss )->str( str );
4817 }
4818
4819
4820 }
4821
4822
4823
4824
4825 #include <cassert>
4826 #include <algorithm>
4827
4828 namespace Catch {
4829
4830 namespace Generators {
4831 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
4832 GeneratorBasePtr m_generator;
4833
4834 GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
4835 : TrackerBase( nameAndLocation, ctx, parent )
4836 {}
4837 ~GeneratorTracker() override;
4838
4839 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
4840 GeneratorTracker* tracker;
4841
4842 ITracker& currentTracker = ctx.currentTracker();
4843 // Under specific circumstances, the generator we want
4844 // to acquire is also the current tracker. If this is
4845 // the case, we have to avoid looking through current
4846 // tracker's children, and instead return the current
4847 // tracker.
4848 // A case where this check is important is e.g.
4849 // for (int i = 0; i < 5; ++i) {
4850 // int n = GENERATE(1, 2);
4851 // }
4852 //
4853 // without it, the code above creates 5 nested generators.
4854 if ( currentTracker.nameAndLocation() == nameAndLocation ) {
4855 auto thisTracker =
4856 currentTracker.parent()->findChild( nameAndLocation );
4857 assert( thisTracker );
4858 assert( thisTracker->isGeneratorTracker() );
4859 tracker = static_cast<GeneratorTracker*>( thisTracker );
4860 } else if ( ITracker* childTracker =
4861 currentTracker.findChild( nameAndLocation ) ) {
4862 assert( childTracker );
4863 assert( childTracker->isGeneratorTracker() );
4864 tracker = static_cast<GeneratorTracker*>( childTracker );
4865 } else {
4866 auto newTracker =
4867 Catch::Detail::make_unique<GeneratorTracker>(
4868 nameAndLocation, ctx, &currentTracker );
4869 tracker = newTracker.get();
4870 currentTracker.addChild( CATCH_MOVE(newTracker) );
4871 }
4872
4873 if( !tracker->isComplete() ) {
4874 tracker->open();
4875 }
4876
4877 return *tracker;
4878 }
4879
4880 // TrackerBase interface
4881 bool isGeneratorTracker() const override { return true; }
4882 auto hasGenerator() const -> bool override {
4883 return !!m_generator;
4884 }
4885 void close() override {
4886 TrackerBase::close();
4887 // If a generator has a child (it is followed by a section)
4888 // and none of its children have started, then we must wait
4889 // until later to start consuming its values.
4890 // This catches cases where `GENERATE` is placed between two
4891 // `SECTION`s.
4892 // **The check for m_children.empty cannot be removed**.
4893 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
4894 const bool should_wait_for_child = [&]() {
4895 // No children -> nobody to wait for
4896 if ( m_children.empty() ) {
4897 return false;
4898 }
4899 // If at least one child started executing, don't wait
4900 if ( std::find_if(
4901 m_children.begin(),
4902 m_children.end(),
4903 []( TestCaseTracking::ITrackerPtr const& tracker ) {
4904 return tracker->hasStarted();
4905 } ) != m_children.end() ) {
4906 return false;
4907 }
4908
4909 // No children have started. We need to check if they _can_
4910 // start, and thus we should wait for them, or they cannot
4911 // start (due to filters), and we shouldn't wait for them
4912 ITracker* parent = m_parent;
4913 // This is safe: there is always at least one section
4914 // tracker in a test case tracking tree
4915 while ( !parent->isSectionTracker() ) {
4916 parent = parent->parent();
4917 }
4918 assert( parent &&
4919 "Missing root (test case) level section" );
4920
4921 auto const& parentSection =
4922 static_cast<SectionTracker const&>( *parent );
4923 auto const& filters = parentSection.getFilters();
4924 // No filters -> no restrictions on running sections
4925 if ( filters.empty() ) {
4926 return true;
4927 }
4928
4929 for ( auto const& child : m_children ) {
4930 if ( child->isSectionTracker() &&
4931 std::find(
4932 filters.begin(),
4933 filters.end(),
4934 static_cast<SectionTracker const&>( *child )
4935 .trimmedName() ) != filters.end() ) {
4936 return true;
4937 }
4938 }
4939 return false;
4940 }();
4941
4942 // This check is a bit tricky, because m_generator->next()
4943 // has a side-effect, where it consumes generator's current
4944 // value, but we do not want to invoke the side-effect if
4945 // this generator is still waiting for any child to start.
4946 if ( should_wait_for_child ||
4947 ( m_runState == CompletedSuccessfully &&
4948 m_generator->countedNext() ) ) {
4949 m_children.clear();
4950 m_runState = Executing;
4951 }
4952 }
4953
4954 // IGeneratorTracker interface
4955 auto getGenerator() const -> GeneratorBasePtr const& override {
4956 return m_generator;
4957 }
4958 void setGenerator( GeneratorBasePtr&& generator ) override {
4959 m_generator = CATCH_MOVE( generator );
4960 }
4961 };
4962 GeneratorTracker::~GeneratorTracker() = default;
4963 }
4964
4965 RunContext::RunContext(IConfig const* _config, IEventListenerPtr&& reporter)
4966 : m_runInfo(_config->name()),
4967 m_context(getCurrentMutableContext()),
4968 m_config(_config),
4969 m_reporter(CATCH_MOVE(reporter)),
4970 m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
4971 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
4972 {
4973 m_context.setResultCapture(this);
4974 m_reporter->testRunStarting(m_runInfo);
4975 }
4976
4977 RunContext::~RunContext() {
4978 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
4979 }
4980
4981 Totals RunContext::runTest(TestCaseHandle const& testCase) {
4982 const Totals prevTotals = m_totals;
4983
4984 std::string redirectedCout;
4985 std::string redirectedCerr;
4986
4987 auto const& testInfo = testCase.getTestCaseInfo();
4988
4989 m_reporter->testCaseStarting(testInfo);
4990
4991 m_activeTestCase = &testCase;
4992
4993
4994 ITracker& rootTracker = m_trackerContext.startRun();
4995 assert(rootTracker.isSectionTracker());
4996 static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
4997
4998 // We intentionally only seed the internal RNG once per test case,
4999 // before it is first invoked. The reason for that is a complex
5000 // interplay of generator/section implementation details and the
5001 // Random*Generator types.
5002 //
5003 // The issue boils down to us needing to seed the Random*Generators
5004 // with different seed each, so that they return different sequences
5005 // of random numbers. We do this by giving them a number from the
5006 // shared RNG instance as their seed.
5007 //
5008 // However, this runs into an issue if the reseeding happens each
5009 // time the test case is entered (as opposed to first time only),
5010 // because multiple generators could get the same seed, e.g. in
5011 // ```cpp
5012 // TEST_CASE() {
5013 // auto i = GENERATE(take(10, random(0, 100));
5014 // SECTION("A") {
5015 // auto j = GENERATE(take(10, random(0, 100));
5016 // }
5017 // SECTION("B") {
5018 // auto k = GENERATE(take(10, random(0, 100));
5019 // }
5020 // }
5021 // ```
5022 // `i` and `j` would properly return values from different sequences,
5023 // but `i` and `k` would return the same sequence, because their seed
5024 // would be the same.
5025 // (The reason their seeds would be the same is that the generator
5026 // for k would be initialized when the test case is entered the second
5027 // time, after the shared RNG instance was reset to the same value
5028 // it had when the generator for i was initialized.)
5029 seedRng( *m_config );
5030
5031 uint64_t testRuns = 0;
5032 do {
5033 m_trackerContext.startCycle();
5034 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
5035
5036 m_reporter->testCasePartialStarting(testInfo, testRuns);
5037
5038 const auto beforeRunTotals = m_totals;
5039 std::string oneRunCout, oneRunCerr;
5040 runCurrentTest(oneRunCout, oneRunCerr);
5041 redirectedCout += oneRunCout;
5042 redirectedCerr += oneRunCerr;
5043
5044 const auto singleRunTotals = m_totals.delta(beforeRunTotals);
5045 auto statsForOneRun = TestCaseStats(testInfo, singleRunTotals, oneRunCout, oneRunCerr, aborting());
5046
5047 m_reporter->testCasePartialEnded(statsForOneRun, testRuns);
5048 ++testRuns;
5049 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
5050
5051 Totals deltaTotals = m_totals.delta(prevTotals);
5052 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
5053 deltaTotals.assertions.failed++;
5054 deltaTotals.testCases.passed--;
5055 deltaTotals.testCases.failed++;
5056 }
5057 m_totals.testCases += deltaTotals.testCases;
5058 m_reporter->testCaseEnded(TestCaseStats(testInfo,
5059 deltaTotals,
5060 redirectedCout,
5061 redirectedCerr,
5062 aborting()));
5063
5064 m_activeTestCase = nullptr;
5065 m_testCaseTracker = nullptr;
5066
5067 return deltaTotals;
5068 }
5069
5070
5071 void RunContext::assertionEnded(AssertionResult const & result) {
5072 if (result.getResultType() == ResultWas::Ok) {
5073 m_totals.assertions.passed++;
5074 m_lastAssertionPassed = true;
5075 } else if (!result.succeeded()) {
5076 m_lastAssertionPassed = false;
5077 if (result.isOk()) {
5078 }
5079 else if( m_activeTestCase->getTestCaseInfo().okToFail() )
5080 m_totals.assertions.failedButOk++;
5081 else
5082 m_totals.assertions.failed++;
5083 }
5084 else {
5085 m_lastAssertionPassed = true;
5086 }
5087
5088 m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals));
5089
5090 if (result.getResultType() != ResultWas::Warning)
5091 m_messageScopes.clear();
5092
5093 // Reset working state
5094 resetAssertionInfo();
5095 m_lastResult = result;
5096 }
5097 void RunContext::resetAssertionInfo() {
5098 m_lastAssertionInfo.macroName = StringRef();
5099 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
5100 }
5101
5102 bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
5103 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
5104 if (!sectionTracker.isOpen())
5105 return false;
5106 m_activeSections.push_back(&sectionTracker);
5107
5108 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
5109
5110 m_reporter->sectionStarting(sectionInfo);
5111
5112 assertions = m_totals.assertions;
5113
5114 return true;
5115 }
5116 auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
5117 using namespace Generators;
5118 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
5119 TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
5120 m_lastAssertionInfo.lineInfo = lineInfo;
5121 return tracker;
5122 }
5123
5124 bool RunContext::testForMissingAssertions(Counts& assertions) {
5125 if (assertions.total() != 0)
5126 return false;
5127 if (!m_config->warnAboutMissingAssertions())
5128 return false;
5129 if (m_trackerContext.currentTracker().hasChildren())
5130 return false;
5131 m_totals.assertions.failed++;
5132 assertions.failed++;
5133 return true;
5134 }
5135
5136 void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
5137 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
5138 bool missingAssertions = testForMissingAssertions(assertions);
5139
5140 if (!m_activeSections.empty()) {
5141 m_activeSections.back()->close();
5142 m_activeSections.pop_back();
5143 }
5144
5145 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
5146 m_messages.clear();
5147 m_messageScopes.clear();
5148 }
5149
5150 void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
5151 if (m_unfinishedSections.empty())
5152 m_activeSections.back()->fail();
5153 else
5154 m_activeSections.back()->close();
5155 m_activeSections.pop_back();
5156
5157 m_unfinishedSections.push_back(endInfo);
5158 }
5159
5160 void RunContext::benchmarkPreparing( StringRef name ) {
5161 m_reporter->benchmarkPreparing(name);
5162 }
5163 void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
5164 m_reporter->benchmarkStarting( info );
5165 }
5166 void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
5167 m_reporter->benchmarkEnded( stats );
5168 }
5169 void RunContext::benchmarkFailed( StringRef error ) {
5170 m_reporter->benchmarkFailed( error );
5171 }
5172
5173 void RunContext::pushScopedMessage(MessageInfo const & message) {
5174 m_messages.push_back(message);
5175 }
5176
5177 void RunContext::popScopedMessage(MessageInfo const & message) {
5178 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
5179 }
5180
5181 void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
5182 m_messageScopes.emplace_back( builder );
5183 }
5184
5185 std::string RunContext::getCurrentTestName() const {
5186 return m_activeTestCase
5187 ? m_activeTestCase->getTestCaseInfo().name
5188 : std::string();
5189 }
5190
5191 const AssertionResult * RunContext::getLastResult() const {
5192 return &(*m_lastResult);
5193 }
5194
5195 void RunContext::exceptionEarlyReported() {
5196 m_shouldReportUnexpected = false;
5197 }
5198
5199 void RunContext::handleFatalErrorCondition( StringRef message ) {
5200 // First notify reporter that bad things happened
5201 m_reporter->fatalErrorEncountered(message);
5202
5203 // Don't rebuild the result -- the stringification itself can cause more fatal errors
5204 // Instead, fake a result data.
5205 AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
5206 tempResult.message = static_cast<std::string>(message);
5207 AssertionResult result(m_lastAssertionInfo, tempResult);
5208
5209 assertionEnded(result);
5210
5211 handleUnfinishedSections();
5212
5213 // Recreate section for test case (as we will lose the one that was in scope)
5214 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
5215 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
5216
5217 Counts assertions;
5218 assertions.failed = 1;
5219 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
5220 m_reporter->sectionEnded(testCaseSectionStats);
5221
5222 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
5223
5224 Totals deltaTotals;
5225 deltaTotals.testCases.failed = 1;
5226 deltaTotals.assertions.failed = 1;
5227 m_reporter->testCaseEnded(TestCaseStats(testInfo,
5228 deltaTotals,
5229 std::string(),
5230 std::string(),
5231 false));
5232 m_totals.testCases.failed++;
5233 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
5234 }
5235
5236 bool RunContext::lastAssertionPassed() {
5237 return m_lastAssertionPassed;
5238 }
5239
5240 void RunContext::assertionPassed() {
5241 m_lastAssertionPassed = true;
5242 ++m_totals.assertions.passed;
5243 resetAssertionInfo();
5244 m_messageScopes.clear();
5245 }
5246
5247 bool RunContext::aborting() const {
5248 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
5249 }
5250
5251 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
5252 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
5253 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
5254 m_reporter->sectionStarting(testCaseSection);
5255 Counts prevAssertions = m_totals.assertions;
5256 double duration = 0;
5257 m_shouldReportUnexpected = true;
5258 m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
5259
5260 Timer timer;
5261 CATCH_TRY {
5262 if (m_reporter->getPreferences().shouldRedirectStdOut) {
5263 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
5264 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
5265
5266 timer.start();
5267 invokeActiveTestCase();
5268 #else
5269 OutputRedirect r(redirectedCout, redirectedCerr);
5270 timer.start();
5271 invokeActiveTestCase();
5272 #endif
5273 } else {
5274 timer.start();
5275 invokeActiveTestCase();
5276 }
5277 duration = timer.getElapsedSeconds();
5278 } CATCH_CATCH_ANON (TestFailureException&) {
5279 // This just means the test was aborted due to failure
5280 } CATCH_CATCH_ALL {
5281 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
5282 // are reported without translation at the point of origin.
5283 if( m_shouldReportUnexpected ) {
5284 AssertionReaction dummyReaction;
5285 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
5286 }
5287 }
5288 Counts assertions = m_totals.assertions - prevAssertions;
5289 bool missingAssertions = testForMissingAssertions(assertions);
5290
5291 m_testCaseTracker->close();
5292 handleUnfinishedSections();
5293 m_messages.clear();
5294 m_messageScopes.clear();
5295
5296 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
5297 m_reporter->sectionEnded(testCaseSectionStats);
5298 }
5299
5300 void RunContext::invokeActiveTestCase() {
5301 // We need to engage a handler for signals/structured exceptions
5302 // before running the tests themselves, or the binary can crash
5303 // without failed test being reported.
5304 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
5305 // We keep having issue where some compilers warn about an unused
5306 // variable, even though the type has non-trivial constructor and
5307 // destructor. This is annoying and ugly, but it makes them stfu.
5308 (void)_;
5309
5310 m_activeTestCase->invoke();
5311 }
5312
5313 void RunContext::handleUnfinishedSections() {
5314 // If sections ended prematurely due to an exception we stored their
5315 // infos here so we can tear them down outside the unwind process.
5316 for (auto it = m_unfinishedSections.rbegin(),
5317 itEnd = m_unfinishedSections.rend();
5318 it != itEnd;
5319 ++it)
5320 sectionEnded(*it);
5321 m_unfinishedSections.clear();
5322 }
5323
5324 void RunContext::handleExpr(
5325 AssertionInfo const& info,
5326 ITransientExpression const& expr,
5327 AssertionReaction& reaction
5328 ) {
5329 m_reporter->assertionStarting( info );
5330
5331 bool negated = isFalseTest( info.resultDisposition );
5332 bool result = expr.getResult() != negated;
5333
5334 if( result ) {
5335 if (!m_includeSuccessfulResults) {
5336 assertionPassed();
5337 }
5338 else {
5339 reportExpr(info, ResultWas::Ok, &expr, negated);
5340 }
5341 }
5342 else {
5343 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
5344 populateReaction( reaction );
5345 }
5346 }
5347 void RunContext::reportExpr(
5348 AssertionInfo const &info,
5349 ResultWas::OfType resultType,
5350 ITransientExpression const *expr,
5351 bool negated ) {
5352
5353 m_lastAssertionInfo = info;
5354 AssertionResultData data( resultType, LazyExpression( negated ) );
5355
5356 AssertionResult assertionResult{ info, data };
5357 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
5358
5359 assertionEnded( assertionResult );
5360 }
5361
5362 void RunContext::handleMessage(
5363 AssertionInfo const& info,
5364 ResultWas::OfType resultType,
5365 StringRef message,
5366 AssertionReaction& reaction
5367 ) {
5368 m_reporter->assertionStarting( info );
5369
5370 m_lastAssertionInfo = info;
5371
5372 AssertionResultData data( resultType, LazyExpression( false ) );
5373 data.message = static_cast<std::string>(message);
5374 AssertionResult assertionResult{ m_lastAssertionInfo, data };
5375 assertionEnded( assertionResult );
5376 if( !assertionResult.isOk() )
5377 populateReaction( reaction );
5378 }
5379 void RunContext::handleUnexpectedExceptionNotThrown(
5380 AssertionInfo const& info,
5381 AssertionReaction& reaction
5382 ) {
5383 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
5384 }
5385
5386 void RunContext::handleUnexpectedInflightException(
5387 AssertionInfo const& info,
5388 std::string const& message,
5389 AssertionReaction& reaction
5390 ) {
5391 m_lastAssertionInfo = info;
5392
5393 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
5394 data.message = message;
5395 AssertionResult assertionResult{ info, data };
5396 assertionEnded( assertionResult );
5397 populateReaction( reaction );
5398 }
5399
5400 void RunContext::populateReaction( AssertionReaction& reaction ) {
5401 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
5402 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
5403 }
5404
5405 void RunContext::handleIncomplete(
5406 AssertionInfo const& info
5407 ) {
5408 m_lastAssertionInfo = info;
5409
5410 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
5411 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
5412 AssertionResult assertionResult{ info, data };
5413 assertionEnded( assertionResult );
5414 }
5415 void RunContext::handleNonExpr(
5416 AssertionInfo const &info,
5417 ResultWas::OfType resultType,
5418 AssertionReaction &reaction
5419 ) {
5420 m_lastAssertionInfo = info;
5421
5422 AssertionResultData data( resultType, LazyExpression( false ) );
5423 AssertionResult assertionResult{ info, data };
5424 assertionEnded( assertionResult );
5425
5426 if( !assertionResult.isOk() )
5427 populateReaction( reaction );
5428 }
5429
5430
5431 IResultCapture& getResultCapture() {
5432 if (auto* capture = getCurrentContext().getResultCapture())
5433 return *capture;
5434 else
5435 CATCH_INTERNAL_ERROR("No result capture instance");
5436 }
5437
5438 void seedRng(IConfig const& config) {
5439 sharedRng().seed(config.rngSeed());
5440 }
5441
5442 unsigned int rngSeed() {
5443 return getCurrentContext().getConfig()->rngSeed();
5444 }
5445
5446 }
5447
5448
5449
5450 namespace Catch {
5451
5452 Section::Section( SectionInfo&& info ):
5453 m_info( CATCH_MOVE( info ) ),
5454 m_sectionIncluded(
5455 getResultCapture().sectionStarted( m_info, m_assertions ) ) {
5456 // Non-"included" sections will not use the timing information
5457 // anyway, so don't bother with the potential syscall.
5458 if (m_sectionIncluded) {
5459 m_timer.start();
5460 }
5461 }
5462
5463 Section::~Section() {
5464 if( m_sectionIncluded ) {
5465 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
5466 if( uncaught_exceptions() )
5467 getResultCapture().sectionEndedEarly( endInfo );
5468 else
5469 getResultCapture().sectionEnded( endInfo );
5470 }
5471 }
5472
5473 // This indicates whether the section should be executed or not
5474 Section::operator bool() const {
5475 return m_sectionIncluded;
5476 }
5477
5478
5479 } // end namespace Catch
5480
5481
5482
5483 #include <vector>
5484
5485 namespace Catch {
5486
5487 namespace {
5488 static auto getSingletons() -> std::vector<ISingleton*>*& {
5489 static std::vector<ISingleton*>* g_singletons = nullptr;
5490 if( !g_singletons )
5491 g_singletons = new std::vector<ISingleton*>();
5492 return g_singletons;
5493 }
5494 }
5495
5496 ISingleton::~ISingleton() = default;
5497
5498 void addSingleton(ISingleton* singleton ) {
5499 getSingletons()->push_back( singleton );
5500 }
5501 void cleanupSingletons() {
5502 auto& singletons = getSingletons();
5503 for( auto singleton : *singletons )
5504 delete singleton;
5505 delete singletons;
5506 singletons = nullptr;
5507 }
5508
5509 } // namespace Catch
5510
5511
5512
5513 #include <cstring>
5514 #include <ostream>
5515
5516 namespace Catch {
5517
5518 bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
5519 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
5520 }
5521 bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
5522 // We can assume that the same file will usually have the same pointer.
5523 // Thus, if the pointers are the same, there is no point in calling the strcmp
5524 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
5525 }
5526
5527 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
5528 #ifndef __GNUG__
5529 os << info.file << '(' << info.line << ')';
5530 #else
5531 os << info.file << ':' << info.line;
5532 #endif
5533 return os;
5534 }
5535
5536 } // end namespace Catch
5537
5538
5539
5540
5541 namespace Catch {
5542 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
5543 void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
5544 CATCH_TRY {
5545 m_exceptions.push_back(exception);
5546 } CATCH_CATCH_ALL {
5547 // If we run out of memory during start-up there's really not a lot more we can do about it
5548 std::terminate();
5549 }
5550 }
5551
5552 std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
5553 return m_exceptions;
5554 }
5555 #endif
5556
5557 } // end namespace Catch
5558
5559
5560
5561
5562
5563 #include <iostream>
5564
5565 namespace Catch {
5566
5567 // If you #define this you must implement these functions
5568 #if !defined( CATCH_CONFIG_NOSTDOUT )
5569 std::ostream& cout() { return std::cout; }
5570 std::ostream& cerr() { return std::cerr; }
5571 std::ostream& clog() { return std::clog; }
5572 #endif
5573
5574 } // namespace Catch
5575
5576
5577
5578 #include <algorithm>
5579 #include <ostream>
5580 #include <cstring>
5581 #include <cctype>
5582 #include <vector>
5583
5584 namespace Catch {
5585
5586 bool startsWith( std::string const& s, std::string const& prefix ) {
5587 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
5588 }
5589 bool startsWith( StringRef s, char prefix ) {
5590 return !s.empty() && s[0] == prefix;
5591 }
5592 bool endsWith( std::string const& s, std::string const& suffix ) {
5593 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
5594 }
5595 bool endsWith( std::string const& s, char suffix ) {
5596 return !s.empty() && s[s.size()-1] == suffix;
5597 }
5598 bool contains( std::string const& s, std::string const& infix ) {
5599 return s.find( infix ) != std::string::npos;
5600 }
5601 void toLowerInPlace( std::string& s ) {
5602 std::transform( s.begin(), s.end(), s.begin(), []( char c ) {
5603 return toLower( c );
5604 } );
5605 }
5606 std::string toLower( std::string const& s ) {
5607 std::string lc = s;
5608 toLowerInPlace( lc );
5609 return lc;
5610 }
5611 char toLower(char c) {
5612 return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
5613 }
5614
5615 std::string trim( std::string const& str ) {
5616 static char const* whitespaceChars = "\n\r\t ";
5617 std::string::size_type start = str.find_first_not_of( whitespaceChars );
5618 std::string::size_type end = str.find_last_not_of( whitespaceChars );
5619
5620 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
5621 }
5622
5623 StringRef trim(StringRef ref) {
5624 const auto is_ws = [](char c) {
5625 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
5626 };
5627 size_t real_begin = 0;
5628 while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
5629 size_t real_end = ref.size();
5630 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
5631
5632 return ref.substr(real_begin, real_end - real_begin);
5633 }
5634
5635 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
5636 bool replaced = false;
5637 std::size_t i = str.find( replaceThis );
5638 while( i != std::string::npos ) {
5639 replaced = true;
5640 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
5641 if( i < str.size()-withThis.size() )
5642 i = str.find( replaceThis, i+withThis.size() );
5643 else
5644 i = std::string::npos;
5645 }
5646 return replaced;
5647 }
5648
5649 std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
5650 std::vector<StringRef> subStrings;
5651 std::size_t start = 0;
5652 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
5653 if( str[pos] == delimiter ) {
5654 if( pos - start > 1 )
5655 subStrings.push_back( str.substr( start, pos-start ) );
5656 start = pos+1;
5657 }
5658 }
5659 if( start < str.size() )
5660 subStrings.push_back( str.substr( start, str.size()-start ) );
5661 return subStrings;
5662 }
5663
5664 std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
5665 os << pluraliser.m_count << ' ' << pluraliser.m_label;
5666 if( pluraliser.m_count != 1 )
5667 os << 's';
5668 return os;
5669 }
5670
5671 }
5672
5673
5674
5675 #include <algorithm>
5676 #include <ostream>
5677 #include <cstring>
5678 #include <cstdint>
5679
5680 namespace Catch {
5681 StringRef::StringRef( char const* rawChars ) noexcept
5682 : StringRef( rawChars, std::strlen(rawChars) )
5683 {}
5684
5685 auto StringRef::operator == ( StringRef other ) const noexcept -> bool {
5686 return m_size == other.m_size
5687 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
5688 }
5689
5690 bool StringRef::operator<(StringRef rhs) const noexcept {
5691 if (m_size < rhs.m_size) {
5692 return strncmp(m_start, rhs.m_start, m_size) <= 0;
5693 }
5694 return strncmp(m_start, rhs.m_start, rhs.m_size) < 0;
5695 }
5696
5697 int StringRef::compare( StringRef rhs ) const {
5698 auto cmpResult =
5699 strncmp( m_start, rhs.m_start, std::min( m_size, rhs.m_size ) );
5700
5701 // This means that strncmp found a difference before the strings
5702 // ended, and we can return it directly
5703 if ( cmpResult != 0 ) {
5704 return cmpResult;
5705 }
5706
5707 // If strings are equal up to length, then their comparison results on
5708 // their size
5709 if ( m_size < rhs.m_size ) {
5710 return -1;
5711 } else if ( m_size > rhs.m_size ) {
5712 return 1;
5713 } else {
5714 return 0;
5715 }
5716 }
5717
5718 auto operator << ( std::ostream& os, StringRef str ) -> std::ostream& {
5719 return os.write(str.data(), static_cast<std::streamsize>(str.size()));
5720 }
5721
5722 std::string operator+(StringRef lhs, StringRef rhs) {
5723 std::string ret;
5724 ret.reserve(lhs.size() + rhs.size());
5725 ret += lhs;
5726 ret += rhs;
5727 return ret;
5728 }
5729
5730 auto operator+=( std::string& lhs, StringRef rhs ) -> std::string& {
5731 lhs.append(rhs.data(), rhs.size());
5732 return lhs;
5733 }
5734
5735 } // namespace Catch
5736
5737
5738
5739 namespace Catch {
5740
5741 TagAliasRegistry::~TagAliasRegistry() {}
5742
5743 TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
5744 auto it = m_registry.find( alias );
5745 if( it != m_registry.end() )
5746 return &(it->second);
5747 else
5748 return nullptr;
5749 }
5750
5751 std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
5752 std::string expandedTestSpec = unexpandedTestSpec;
5753 for( auto const& registryKvp : m_registry ) {
5754 std::size_t pos = expandedTestSpec.find( registryKvp.first );
5755 if( pos != std::string::npos ) {
5756 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
5757 registryKvp.second.tag +
5758 expandedTestSpec.substr( pos + registryKvp.first.size() );
5759 }
5760 }
5761 return expandedTestSpec;
5762 }
5763
5764 void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
5765 CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
5766 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
5767
5768 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
5769 "error: tag alias, '" << alias << "' already registered.\n"
5770 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
5771 << "\tRedefined at: " << lineInfo );
5772 }
5773
5774 ITagAliasRegistry::~ITagAliasRegistry() = default;
5775
5776 ITagAliasRegistry const& ITagAliasRegistry::get() {
5777 return getRegistryHub().getTagAliasRegistry();
5778 }
5779
5780 } // end namespace Catch
5781
5782
5783
5784
5785 namespace Catch {
5786 TestCaseInfoHasher::TestCaseInfoHasher( hash_t seed ): m_seed( seed ) {}
5787
5788 uint32_t TestCaseInfoHasher::operator()( TestCaseInfo const& t ) const {
5789 // FNV-1a hash algorithm that is designed for uniqueness:
5790 const hash_t prime = 1099511628211u;
5791 hash_t hash = 14695981039346656037u;
5792 for ( const char c : t.name ) {
5793 hash ^= c;
5794 hash *= prime;
5795 }
5796 for ( const char c : t.className ) {
5797 hash ^= c;
5798 hash *= prime;
5799 }
5800 for ( const Tag& tag : t.tags ) {
5801 for ( const char c : tag.original ) {
5802 hash ^= c;
5803 hash *= prime;
5804 }
5805 }
5806 hash ^= m_seed;
5807 hash *= prime;
5808 const uint32_t low{ static_cast<uint32_t>( hash ) };
5809 const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
5810 return low * high;
5811 }
5812 } // namespace Catch
5813
5814
5815
5816
5817 #include <algorithm>
5818 #include <set>
5819
5820 namespace Catch {
5821
5822 std::vector<TestCaseHandle> sortTests( IConfig const& config, std::vector<TestCaseHandle> const& unsortedTestCases ) {
5823 switch (config.runOrder()) {
5824 case TestRunOrder::Declared:
5825 return unsortedTestCases;
5826
5827 case TestRunOrder::LexicographicallySorted: {
5828 std::vector<TestCaseHandle> sorted = unsortedTestCases;
5829 std::sort(
5830 sorted.begin(),
5831 sorted.end(),
5832 []( TestCaseHandle const& lhs, TestCaseHandle const& rhs ) {
5833 return lhs.getTestCaseInfo() < rhs.getTestCaseInfo();
5834 }
5835 );
5836 return sorted;
5837 }
5838 case TestRunOrder::Randomized: {
5839 seedRng(config);
5840 using TestWithHash = std::pair<TestCaseInfoHasher::hash_t, TestCaseHandle>;
5841
5842 TestCaseInfoHasher h{ config.rngSeed() };
5843 std::vector<TestWithHash> indexed_tests;
5844 indexed_tests.reserve(unsortedTestCases.size());
5845
5846 for (auto const& handle : unsortedTestCases) {
5847 indexed_tests.emplace_back(h(handle.getTestCaseInfo()), handle);
5848 }
5849
5850 std::sort( indexed_tests.begin(),
5851 indexed_tests.end(),
5852 []( TestWithHash const& lhs, TestWithHash const& rhs ) {
5853 if ( lhs.first == rhs.first ) {
5854 return lhs.second.getTestCaseInfo() <
5855 rhs.second.getTestCaseInfo();
5856 }
5857 return lhs.first < rhs.first;
5858 } );
5859
5860 std::vector<TestCaseHandle> randomized;
5861 randomized.reserve(indexed_tests.size());
5862
5863 for (auto const& indexed : indexed_tests) {
5864 randomized.push_back(indexed.second);
5865 }
5866
5867 return randomized;
5868 }
5869 }
5870
5871 CATCH_INTERNAL_ERROR("Unknown test order value!");
5872 }
5873
5874 bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config ) {
5875 return !testCase.getTestCaseInfo().throws() || config.allowThrows();
5876 }
5877
5878 bool matchTest( TestCaseHandle const& testCase, TestSpec const& testSpec, IConfig const& config ) {
5879 return testSpec.matches( testCase.getTestCaseInfo() ) && isThrowSafe( testCase, config );
5880 }
5881
5882 void
5883 enforceNoDuplicateTestCases( std::vector<TestCaseHandle> const& tests ) {
5884 auto testInfoCmp = []( TestCaseInfo const* lhs,
5885 TestCaseInfo const* rhs ) {
5886 return *lhs < *rhs;
5887 };
5888 std::set<TestCaseInfo const*, decltype(testInfoCmp)> seenTests(testInfoCmp);
5889 for ( auto const& test : tests ) {
5890 const auto infoPtr = &test.getTestCaseInfo();
5891 const auto prev = seenTests.insert( infoPtr );
5892 CATCH_ENFORCE(
5893 prev.second,
5894 "error: test case \"" << infoPtr->name << "\", with tags \""
5895 << infoPtr->tagsAsString() << "\" already defined.\n"
5896 << "\tFirst seen at " << ( *prev.first )->lineInfo << "\n"
5897 << "\tRedefined at " << infoPtr->lineInfo );
5898 }
5899 }
5900
5901 std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
5902 std::vector<TestCaseHandle> filtered;
5903 filtered.reserve( testCases.size() );
5904 for (auto const& testCase : testCases) {
5905 if ((!testSpec.hasFilters() && !testCase.getTestCaseInfo().isHidden()) ||
5906 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
5907 filtered.push_back(testCase);
5908 }
5909 }
5910 return createShard(filtered, config.shardCount(), config.shardIndex());
5911 }
5912 std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config ) {
5913 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
5914 }
5915
5916 void TestRegistry::registerTest(Detail::unique_ptr<TestCaseInfo> testInfo, Detail::unique_ptr<ITestInvoker> testInvoker) {
5917 m_handles.emplace_back(testInfo.get(), testInvoker.get());
5918 m_viewed_test_infos.push_back(testInfo.get());
5919 m_owned_test_infos.push_back(CATCH_MOVE(testInfo));
5920 m_invokers.push_back(CATCH_MOVE(testInvoker));
5921 }
5922
5923 std::vector<TestCaseInfo*> const& TestRegistry::getAllInfos() const {
5924 return m_viewed_test_infos;
5925 }
5926
5927 std::vector<TestCaseHandle> const& TestRegistry::getAllTests() const {
5928 return m_handles;
5929 }
5930 std::vector<TestCaseHandle> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
5931 if( m_sortedFunctions.empty() )
5932 enforceNoDuplicateTestCases( m_handles );
5933
5934 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
5935 m_sortedFunctions = sortTests( config, m_handles );
5936 m_currentSortOrder = config.runOrder();
5937 }
5938 return m_sortedFunctions;
5939 }
5940
5941
5942
5943 ///////////////////////////////////////////////////////////////////////////
5944 void TestInvokerAsFunction::invoke() const {
5945 m_testAsFunction();
5946 }
5947
5948 } // end namespace Catch
5949
5950
5951
5952
5953 #include <algorithm>
5954 #include <cassert>
5955
5956 #if defined(__clang__)
5957 # pragma clang diagnostic push
5958 # pragma clang diagnostic ignored "-Wexit-time-destructors"
5959 #endif
5960
5961 namespace Catch {
5962 namespace TestCaseTracking {
5963
5964 NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
5965 : name( _name ),
5966 location( _location )
5967 {}
5968
5969
5970 ITracker::~ITracker() = default;
5971
5972 void ITracker::markAsNeedingAnotherRun() {
5973 m_runState = NeedsAnotherRun;
5974 }
5975
5976 void ITracker::addChild( ITrackerPtr&& child ) {
5977 m_children.push_back( CATCH_MOVE(child) );
5978 }
5979
5980 ITracker* ITracker::findChild( NameAndLocation const& nameAndLocation ) {
5981 auto it = std::find_if(
5982 m_children.begin(),
5983 m_children.end(),
5984 [&nameAndLocation]( ITrackerPtr const& tracker ) {
5985 return tracker->nameAndLocation().location ==
5986 nameAndLocation.location &&
5987 tracker->nameAndLocation().name == nameAndLocation.name;
5988 } );
5989 return ( it != m_children.end() ) ? it->get() : nullptr;
5990 }
5991
5992 bool ITracker::isSectionTracker() const { return false; }
5993 bool ITracker::isGeneratorTracker() const { return false; }
5994
5995 bool ITracker::isSuccessfullyCompleted() const {
5996 return m_runState == CompletedSuccessfully;
5997 }
5998
5999 bool ITracker::isOpen() const {
6000 return m_runState != NotStarted && !isComplete();
6001 }
6002
6003 bool ITracker::hasStarted() const { return m_runState != NotStarted; }
6004
6005 void ITracker::openChild() {
6006 if (m_runState != ExecutingChildren) {
6007 m_runState = ExecutingChildren;
6008 if (m_parent) {
6009 m_parent->openChild();
6010 }
6011 }
6012 }
6013
6014 ITracker& TrackerContext::startRun() {
6015 using namespace std::string_literals;
6016 m_rootTracker = Catch::Detail::make_unique<SectionTracker>(
6017 NameAndLocation( "{root}"s, CATCH_INTERNAL_LINEINFO ),
6018 *this,
6019 nullptr );
6020 m_currentTracker = nullptr;
6021 m_runState = Executing;
6022 return *m_rootTracker;
6023 }
6024
6025 void TrackerContext::endRun() {
6026 m_rootTracker.reset();
6027 m_currentTracker = nullptr;
6028 m_runState = NotStarted;
6029 }
6030
6031 void TrackerContext::startCycle() {
6032 m_currentTracker = m_rootTracker.get();
6033 m_runState = Executing;
6034 }
6035 void TrackerContext::completeCycle() {
6036 m_runState = CompletedCycle;
6037 }
6038
6039 bool TrackerContext::completedCycle() const {
6040 return m_runState == CompletedCycle;
6041 }
6042 ITracker& TrackerContext::currentTracker() {
6043 return *m_currentTracker;
6044 }
6045 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
6046 m_currentTracker = tracker;
6047 }
6048
6049
6050 TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
6051 ITracker(nameAndLocation, parent),
6052 m_ctx( ctx )
6053 {}
6054
6055 bool TrackerBase::isComplete() const {
6056 return m_runState == CompletedSuccessfully || m_runState == Failed;
6057 }
6058
6059 void TrackerBase::open() {
6060 m_runState = Executing;
6061 moveToThis();
6062 if( m_parent )
6063 m_parent->openChild();
6064 }
6065
6066 void TrackerBase::close() {
6067
6068 // Close any still open children (e.g. generators)
6069 while( &m_ctx.currentTracker() != this )
6070 m_ctx.currentTracker().close();
6071
6072 switch( m_runState ) {
6073 case NeedsAnotherRun:
6074 break;
6075
6076 case Executing:
6077 m_runState = CompletedSuccessfully;
6078 break;
6079 case ExecutingChildren:
6080 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
6081 m_runState = CompletedSuccessfully;
6082 break;
6083
6084 case NotStarted:
6085 case CompletedSuccessfully:
6086 case Failed:
6087 CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
6088
6089 default:
6090 CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
6091 }
6092 moveToParent();
6093 m_ctx.completeCycle();
6094 }
6095 void TrackerBase::fail() {
6096 m_runState = Failed;
6097 if( m_parent )
6098 m_parent->markAsNeedingAnotherRun();
6099 moveToParent();
6100 m_ctx.completeCycle();
6101 }
6102
6103 void TrackerBase::moveToParent() {
6104 assert( m_parent );
6105 m_ctx.setCurrentTracker( m_parent );
6106 }
6107 void TrackerBase::moveToThis() {
6108 m_ctx.setCurrentTracker( this );
6109 }
6110
6111 SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
6112 : TrackerBase( nameAndLocation, ctx, parent ),
6113 m_trimmed_name(trim(nameAndLocation.name))
6114 {
6115 if( parent ) {
6116 while( !parent->isSectionTracker() )
6117 parent = parent->parent();
6118
6119 SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
6120 addNextFilters( parentSection.m_filters );
6121 }
6122 }
6123
6124 bool SectionTracker::isComplete() const {
6125 bool complete = true;
6126
6127 if (m_filters.empty()
6128 || m_filters[0].empty()
6129 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
6130 complete = TrackerBase::isComplete();
6131 }
6132 return complete;
6133 }
6134
6135 bool SectionTracker::isSectionTracker() const { return true; }
6136
6137 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
6138 SectionTracker* section;
6139
6140 ITracker& currentTracker = ctx.currentTracker();
6141 if ( ITracker* childTracker =
6142 currentTracker.findChild( nameAndLocation ) ) {
6143 assert( childTracker );
6144 assert( childTracker->isSectionTracker() );
6145 section = static_cast<SectionTracker*>( childTracker );
6146 } else {
6147 auto newSection = Catch::Detail::make_unique<SectionTracker>(
6148 nameAndLocation, ctx, &currentTracker );
6149 section = newSection.get();
6150 currentTracker.addChild( CATCH_MOVE( newSection ) );
6151 }
6152 if( !ctx.completedCycle() )
6153 section->tryOpen();
6154 return *section;
6155 }
6156
6157 void SectionTracker::tryOpen() {
6158 if( !isComplete() )
6159 open();
6160 }
6161
6162 void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
6163 if( !filters.empty() ) {
6164 m_filters.reserve( m_filters.size() + filters.size() + 2 );
6165 m_filters.emplace_back(StringRef{}); // Root - should never be consulted
6166 m_filters.emplace_back(StringRef{}); // Test Case - not a section filter
6167 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
6168 }
6169 }
6170 void SectionTracker::addNextFilters( std::vector<StringRef> const& filters ) {
6171 if( filters.size() > 1 )
6172 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
6173 }
6174
6175 std::vector<StringRef> const& SectionTracker::getFilters() const {
6176 return m_filters;
6177 }
6178
6179 StringRef SectionTracker::trimmedName() const {
6180 return m_trimmed_name;
6181 }
6182
6183 } // namespace TestCaseTracking
6184
6185 } // namespace Catch
6186
6187 #if defined(__clang__)
6188 # pragma clang diagnostic pop
6189 #endif
6190
6191
6192
6193 #include <algorithm>
6194 #include <iterator>
6195
6196 namespace Catch {
6197
6198 namespace {
6199 StringRef extractClassName( StringRef classOrMethodName ) {
6200 if ( !startsWith( classOrMethodName, '&' ) ) {
6201 return classOrMethodName;
6202 }
6203
6204 // Remove the leading '&' to avoid having to special case it later
6205 const auto methodName =
6206 classOrMethodName.substr( 1, classOrMethodName.size() );
6207
6208 auto reverseStart = std::make_reverse_iterator( methodName.end() );
6209 auto reverseEnd = std::make_reverse_iterator( methodName.begin() );
6210
6211 // We make a simplifying assumption that ":" is only present
6212 // in the input as part of "::" from C++ typenames (this is
6213 // relatively safe assumption because the input is generated
6214 // as stringification of type through preprocessor).
6215 auto lastColons = std::find( reverseStart, reverseEnd, ':' ) + 1;
6216 auto secondLastColons =
6217 std::find( lastColons + 1, reverseEnd, ':' );
6218
6219 auto const startIdx = reverseEnd - secondLastColons;
6220 auto const classNameSize = secondLastColons - lastColons - 1;
6221
6222 return methodName.substr(
6223 static_cast<std::size_t>( startIdx ),
6224 static_cast<std::size_t>( classNameSize ) );
6225 }
6226 } // namespace
6227
6228 Detail::unique_ptr<ITestInvoker> makeTestInvoker( void(*testAsFunction)() ) {
6229 return Detail::make_unique<TestInvokerAsFunction>( testAsFunction );
6230 }
6231
6232 AutoReg::AutoReg( Detail::unique_ptr<ITestInvoker> invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept {
6233 CATCH_TRY {
6234 getMutableRegistryHub()
6235 .registerTest(
6236 makeTestCaseInfo(
6237 extractClassName( classOrMethod ),
6238 nameAndTags,
6239 lineInfo),
6240 CATCH_MOVE(invoker)
6241 );
6242 } CATCH_CATCH_ALL {
6243 // Do not throw when constructing global objects, instead register the exception to be processed later
6244 getMutableRegistryHub().registerStartupException();
6245 }
6246 }
6247 }
6248
6249
6250
6251
6252
6253 namespace Catch {
6254
6255 TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
6256
6257 TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
6258 m_mode = None;
6259 m_exclusion = false;
6260 m_arg = m_tagAliases->expandAliases( arg );
6261 m_escapeChars.clear();
6262 m_substring.reserve(m_arg.size());
6263 m_patternName.reserve(m_arg.size());
6264 m_realPatternPos = 0;
6265
6266 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
6267 //if visitChar fails
6268 if( !visitChar( m_arg[m_pos] ) ){
6269 m_testSpec.m_invalidSpecs.push_back(arg);
6270 break;
6271 }
6272 endMode();
6273 return *this;
6274 }
6275 TestSpec TestSpecParser::testSpec() {
6276 addFilter();
6277 return CATCH_MOVE(m_testSpec);
6278 }
6279 bool TestSpecParser::visitChar( char c ) {
6280 if( (m_mode != EscapedName) && (c == '\\') ) {
6281 escape();
6282 addCharToPattern(c);
6283 return true;
6284 }else if((m_mode != EscapedName) && (c == ',') ) {
6285 return separate();
6286 }
6287
6288 switch( m_mode ) {
6289 case None:
6290 if( processNoneChar( c ) )
6291 return true;
6292 break;
6293 case Name:
6294 processNameChar( c );
6295 break;
6296 case EscapedName:
6297 endMode();
6298 addCharToPattern(c);
6299 return true;
6300 default:
6301 case Tag:
6302 case QuotedName:
6303 if( processOtherChar( c ) )
6304 return true;
6305 break;
6306 }
6307
6308 m_substring += c;
6309 if( !isControlChar( c ) ) {
6310 m_patternName += c;
6311 m_realPatternPos++;
6312 }
6313 return true;
6314 }
6315 // Two of the processing methods return true to signal the caller to return
6316 // without adding the given character to the current pattern strings
6317 bool TestSpecParser::processNoneChar( char c ) {
6318 switch( c ) {
6319 case ' ':
6320 return true;
6321 case '~':
6322 m_exclusion = true;
6323 return false;
6324 case '[':
6325 startNewMode( Tag );
6326 return false;
6327 case '"':
6328 startNewMode( QuotedName );
6329 return false;
6330 default:
6331 startNewMode( Name );
6332 return false;
6333 }
6334 }
6335 void TestSpecParser::processNameChar( char c ) {
6336 if( c == '[' ) {
6337 if( m_substring == "exclude:" )
6338 m_exclusion = true;
6339 else
6340 endMode();
6341 startNewMode( Tag );
6342 }
6343 }
6344 bool TestSpecParser::processOtherChar( char c ) {
6345 if( !isControlChar( c ) )
6346 return false;
6347 m_substring += c;
6348 endMode();
6349 return true;
6350 }
6351 void TestSpecParser::startNewMode( Mode mode ) {
6352 m_mode = mode;
6353 }
6354 void TestSpecParser::endMode() {
6355 switch( m_mode ) {
6356 case Name:
6357 case QuotedName:
6358 return addNamePattern();
6359 case Tag:
6360 return addTagPattern();
6361 case EscapedName:
6362 revertBackToLastMode();
6363 return;
6364 case None:
6365 default:
6366 return startNewMode( None );
6367 }
6368 }
6369 void TestSpecParser::escape() {
6370 saveLastMode();
6371 m_mode = EscapedName;
6372 m_escapeChars.push_back(m_realPatternPos);
6373 }
6374 bool TestSpecParser::isControlChar( char c ) const {
6375 switch( m_mode ) {
6376 default:
6377 return false;
6378 case None:
6379 return c == '~';
6380 case Name:
6381 return c == '[';
6382 case EscapedName:
6383 return true;
6384 case QuotedName:
6385 return c == '"';
6386 case Tag:
6387 return c == '[' || c == ']';
6388 }
6389 }
6390
6391 void TestSpecParser::addFilter() {
6392 if( !m_currentFilter.m_required.empty() || !m_currentFilter.m_forbidden.empty() ) {
6393 m_testSpec.m_filters.push_back( CATCH_MOVE(m_currentFilter) );
6394 m_currentFilter = TestSpec::Filter();
6395 }
6396 }
6397
6398 void TestSpecParser::saveLastMode() {
6399 lastMode = m_mode;
6400 }
6401
6402 void TestSpecParser::revertBackToLastMode() {
6403 m_mode = lastMode;
6404 }
6405
6406 bool TestSpecParser::separate() {
6407 if( (m_mode==QuotedName) || (m_mode==Tag) ){
6408 //invalid argument, signal failure to previous scope.
6409 m_mode = None;
6410 m_pos = m_arg.size();
6411 m_substring.clear();
6412 m_patternName.clear();
6413 m_realPatternPos = 0;
6414 return false;
6415 }
6416 endMode();
6417 addFilter();
6418 return true; //success
6419 }
6420
6421 std::string TestSpecParser::preprocessPattern() {
6422 std::string token = m_patternName;
6423 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
6424 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
6425 m_escapeChars.clear();
6426 if (startsWith(token, "exclude:")) {
6427 m_exclusion = true;
6428 token = token.substr(8);
6429 }
6430
6431 m_patternName.clear();
6432 m_realPatternPos = 0;
6433
6434 return token;
6435 }
6436
6437 void TestSpecParser::addNamePattern() {
6438 auto token = preprocessPattern();
6439
6440 if (!token.empty()) {
6441 if (m_exclusion) {
6442 m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::NamePattern>(token, m_substring));
6443 } else {
6444 m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::NamePattern>(token, m_substring));
6445 }
6446 }
6447 m_substring.clear();
6448 m_exclusion = false;
6449 m_mode = None;
6450 }
6451
6452 void TestSpecParser::addTagPattern() {
6453 auto token = preprocessPattern();
6454
6455 if (!token.empty()) {
6456 // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
6457 // we have to create a separate hide tag and shorten the real one
6458 if (token.size() > 1 && token[0] == '.') {
6459 token.erase(token.begin());
6460 if (m_exclusion) {
6461 m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(".", m_substring));
6462 m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring));
6463 } else {
6464 m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(".", m_substring));
6465 m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring));
6466 }
6467 }
6468 if (m_exclusion) {
6469 m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring));
6470 } else {
6471 m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring));
6472 }
6473 }
6474 m_substring.clear();
6475 m_exclusion = false;
6476 m_mode = None;
6477 }
6478
6479 TestSpec parseTestSpec( std::string const& arg ) {
6480 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
6481 }
6482
6483 } // namespace Catch
6484
6485
6486
6487 #include <algorithm>
6488 #include <cstring>
6489 #include <ostream>
6490
6491 namespace {
6492 bool isWhitespace( char c ) {
6493 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
6494 }
6495
6496 bool isBreakableBefore( char c ) {
6497 static const char chars[] = "[({<|";
6498 return std::memchr( chars, c, sizeof( chars ) - 1 ) != nullptr;
6499 }
6500
6501 bool isBreakableAfter( char c ) {
6502 static const char chars[] = "])}>.,:;*+-=&/\\";
6503 return std::memchr( chars, c, sizeof( chars ) - 1 ) != nullptr;
6504 }
6505
6506 bool isBoundary( std::string const& line, size_t at ) {
6507 assert( at > 0 );
6508 assert( at <= line.size() );
6509
6510 return at == line.size() ||
6511 ( isWhitespace( line[at] ) && !isWhitespace( line[at - 1] ) ) ||
6512 isBreakableBefore( line[at] ) ||
6513 isBreakableAfter( line[at - 1] );
6514 }
6515
6516 } // namespace
6517
6518 namespace Catch {
6519 namespace TextFlow {
6520
6521 void Column::const_iterator::calcLength() {
6522 m_addHyphen = false;
6523 m_parsedTo = m_lineStart;
6524
6525 std::string const& current_line = m_column.m_string;
6526 if ( current_line[m_lineStart] == '\n' ) {
6527 ++m_parsedTo;
6528 }
6529
6530 const auto maxLineLength = m_column.m_width - indentSize();
6531 const auto maxParseTo = std::min(current_line.size(), m_lineStart + maxLineLength);
6532 while ( m_parsedTo < maxParseTo &&
6533 current_line[m_parsedTo] != '\n' ) {
6534 ++m_parsedTo;
6535 }
6536
6537 // If we encountered a newline before the column is filled,
6538 // then we linebreak at the newline and consider this line
6539 // finished.
6540 if ( m_parsedTo < m_lineStart + maxLineLength ) {
6541 m_lineLength = m_parsedTo - m_lineStart;
6542 } else {
6543 // Look for a natural linebreak boundary in the column
6544 // (We look from the end, so that the first found boundary is
6545 // the right one)
6546 size_t newLineLength = maxLineLength;
6547 while ( newLineLength > 0 && !isBoundary( current_line, m_lineStart + newLineLength ) ) {
6548 --newLineLength;
6549 }
6550 while ( newLineLength > 0 &&
6551 isWhitespace( current_line[m_lineStart + newLineLength - 1] ) ) {
6552 --newLineLength;
6553 }
6554
6555 // If we found one, then that is where we linebreak
6556 if ( newLineLength > 0 ) {
6557 m_lineLength = newLineLength;
6558 } else {
6559 // Otherwise we have to split text with a hyphen
6560 m_addHyphen = true;
6561 m_lineLength = maxLineLength - 1;
6562 }
6563 }
6564 }
6565
6566 size_t Column::const_iterator::indentSize() const {
6567 auto initial =
6568 m_lineStart == 0 ? m_column.m_initialIndent : std::string::npos;
6569 return initial == std::string::npos ? m_column.m_indent : initial;
6570 }
6571
6572 std::string
6573 Column::const_iterator::addIndentAndSuffix( size_t position,
6574 size_t length ) const {
6575 std::string ret;
6576 const auto desired_indent = indentSize();
6577 ret.reserve( desired_indent + length + m_addHyphen );
6578 ret.append( desired_indent, ' ' );
6579 ret.append( m_column.m_string, position, length );
6580 if ( m_addHyphen ) {
6581 ret.push_back( '-' );
6582 }
6583
6584 return ret;
6585 }
6586
6587 Column::const_iterator::const_iterator( Column const& column ): m_column( column ) {
6588 assert( m_column.m_width > m_column.m_indent );
6589 assert( m_column.m_initialIndent == std::string::npos ||
6590 m_column.m_width > m_column.m_initialIndent );
6591 calcLength();
6592 if ( m_lineLength == 0 ) {
6593 m_lineStart = m_column.m_string.size();
6594 }
6595 }
6596
6597 std::string Column::const_iterator::operator*() const {
6598 assert( m_lineStart <= m_parsedTo );
6599 return addIndentAndSuffix( m_lineStart, m_lineLength );
6600 }
6601
6602 Column::const_iterator& Column::const_iterator::operator++() {
6603 m_lineStart += m_lineLength;
6604 std::string const& current_line = m_column.m_string;
6605 if ( m_lineStart < current_line.size() && current_line[m_lineStart] == '\n' ) {
6606 m_lineStart += 1;
6607 } else {
6608 while ( m_lineStart < current_line.size() &&
6609 isWhitespace( current_line[m_lineStart] ) ) {
6610 ++m_lineStart;
6611 }
6612 }
6613
6614 if ( m_lineStart != current_line.size() ) {
6615 calcLength();
6616 }
6617 return *this;
6618 }
6619
6620 Column::const_iterator Column::const_iterator::operator++( int ) {
6621 const_iterator prev( *this );
6622 operator++();
6623 return prev;
6624 }
6625
6626 std::ostream& operator<<( std::ostream& os, Column const& col ) {
6627 bool first = true;
6628 for ( auto line : col ) {
6629 if ( first ) {
6630 first = false;
6631 } else {
6632 os << '\n';
6633 }
6634 os << line;
6635 }
6636 return os;
6637 }
6638
6639 Column Spacer( size_t spaceWidth ) {
6640 Column ret{ "" };
6641 ret.width( spaceWidth );
6642 return ret;
6643 }
6644
6645 Columns::iterator::iterator( Columns const& columns, EndTag ):
6646 m_columns( columns.m_columns ), m_activeIterators( 0 ) {
6647
6648 m_iterators.reserve( m_columns.size() );
6649 for ( auto const& col : m_columns ) {
6650 m_iterators.push_back( col.end() );
6651 }
6652 }
6653
6654 Columns::iterator::iterator( Columns const& columns ):
6655 m_columns( columns.m_columns ),
6656 m_activeIterators( m_columns.size() ) {
6657
6658 m_iterators.reserve( m_columns.size() );
6659 for ( auto const& col : m_columns ) {
6660 m_iterators.push_back( col.begin() );
6661 }
6662 }
6663
6664 std::string Columns::iterator::operator*() const {
6665 std::string row, padding;
6666
6667 for ( size_t i = 0; i < m_columns.size(); ++i ) {
6668 const auto width = m_columns[i].width();
6669 if ( m_iterators[i] != m_columns[i].end() ) {
6670 std::string col = *m_iterators[i];
6671 row += padding;
6672 row += col;
6673
6674 padding.clear();
6675 if ( col.size() < width ) {
6676 padding.append( width - col.size(), ' ' );
6677 }
6678 } else {
6679 padding.append( width, ' ' );
6680 }
6681 }
6682 return row;
6683 }
6684
6685 Columns::iterator& Columns::iterator::operator++() {
6686 for ( size_t i = 0; i < m_columns.size(); ++i ) {
6687 if ( m_iterators[i] != m_columns[i].end() ) {
6688 ++m_iterators[i];
6689 }
6690 }
6691 return *this;
6692 }
6693
6694 Columns::iterator Columns::iterator::operator++( int ) {
6695 iterator prev( *this );
6696 operator++();
6697 return prev;
6698 }
6699
6700 std::ostream& operator<<( std::ostream& os, Columns const& cols ) {
6701 bool first = true;
6702 for ( auto line : cols ) {
6703 if ( first ) {
6704 first = false;
6705 } else {
6706 os << '\n';
6707 }
6708 os << line;
6709 }
6710 return os;
6711 }
6712
6713 Columns Column::operator+( Column const& other ) {
6714 Columns cols;
6715 cols += *this;
6716 cols += other;
6717 return cols;
6718 }
6719
6720 Columns& Columns::operator+=( Column const& col ) {
6721 m_columns.push_back( col );
6722 return *this;
6723 }
6724
6725 Columns Columns::operator+( Column const& col ) {
6726 Columns combined = *this;
6727 combined += col;
6728 return combined;
6729 }
6730
6731 } // namespace TextFlow
6732 } // namespace Catch
6733
6734
6735
6736
6737 #include <exception>
6738
6739 namespace Catch {
6740 bool uncaught_exceptions() {
6741 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
6742 return false;
6743 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
6744 return std::uncaught_exceptions() > 0;
6745 #else
6746 return std::uncaught_exception();
6747 #endif
6748 }
6749 } // end namespace Catch
6750
6751
6752
6753 namespace Catch {
6754
6755 WildcardPattern::WildcardPattern( std::string const& pattern,
6756 CaseSensitive caseSensitivity )
6757 : m_caseSensitivity( caseSensitivity ),
6758 m_pattern( normaliseString( pattern ) )
6759 {
6760 if( startsWith( m_pattern, '*' ) ) {
6761 m_pattern = m_pattern.substr( 1 );
6762 m_wildcard = WildcardAtStart;
6763 }
6764 if( endsWith( m_pattern, '*' ) ) {
6765 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
6766 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
6767 }
6768 }
6769
6770 bool WildcardPattern::matches( std::string const& str ) const {
6771 switch( m_wildcard ) {
6772 case NoWildcard:
6773 return m_pattern == normaliseString( str );
6774 case WildcardAtStart:
6775 return endsWith( normaliseString( str ), m_pattern );
6776 case WildcardAtEnd:
6777 return startsWith( normaliseString( str ), m_pattern );
6778 case WildcardAtBothEnds:
6779 return contains( normaliseString( str ), m_pattern );
6780 default:
6781 CATCH_INTERNAL_ERROR( "Unknown enum" );
6782 }
6783 }
6784
6785 std::string WildcardPattern::normaliseString( std::string const& str ) const {
6786 return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
6787 }
6788 }
6789
6790
6791 // Note: swapping these two includes around causes MSVC to error out
6792 // while in /permissive- mode. No, I don't know why.
6793 // Tested on VS 2019, 18.{3, 4}.x
6794
6795 #include <iomanip>
6796 #include <type_traits>
6797
6798 namespace Catch {
6799
6800 namespace {
6801
6802 size_t trailingBytes(unsigned char c) {
6803 if ((c & 0xE0) == 0xC0) {
6804 return 2;
6805 }
6806 if ((c & 0xF0) == 0xE0) {
6807 return 3;
6808 }
6809 if ((c & 0xF8) == 0xF0) {
6810 return 4;
6811 }
6812 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
6813 }
6814
6815 uint32_t headerValue(unsigned char c) {
6816 if ((c & 0xE0) == 0xC0) {
6817 return c & 0x1F;
6818 }
6819 if ((c & 0xF0) == 0xE0) {
6820 return c & 0x0F;
6821 }
6822 if ((c & 0xF8) == 0xF0) {
6823 return c & 0x07;
6824 }
6825 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
6826 }
6827
6828 void hexEscapeChar(std::ostream& os, unsigned char c) {
6829 std::ios_base::fmtflags f(os.flags());
6830 os << "\\x"
6831 << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
6832 << static_cast<int>(c);
6833 os.flags(f);
6834 }
6835
6836 bool shouldNewline(XmlFormatting fmt) {
6837 return !!(static_cast<std::underlying_type_t<XmlFormatting>>(fmt & XmlFormatting::Newline));
6838 }
6839
6840 bool shouldIndent(XmlFormatting fmt) {
6841 return !!(static_cast<std::underlying_type_t<XmlFormatting>>(fmt & XmlFormatting::Indent));
6842 }
6843
6844 } // anonymous namespace
6845
6846 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
6847 return static_cast<XmlFormatting>(
6848 static_cast<std::underlying_type_t<XmlFormatting>>(lhs) |
6849 static_cast<std::underlying_type_t<XmlFormatting>>(rhs)
6850 );
6851 }
6852
6853 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
6854 return static_cast<XmlFormatting>(
6855 static_cast<std::underlying_type_t<XmlFormatting>>(lhs) &
6856 static_cast<std::underlying_type_t<XmlFormatting>>(rhs)
6857 );
6858 }
6859
6860
6861 XmlEncode::XmlEncode( StringRef str, ForWhat forWhat )
6862 : m_str( str ),
6863 m_forWhat( forWhat )
6864 {}
6865
6866 void XmlEncode::encodeTo( std::ostream& os ) const {
6867 // Apostrophe escaping not necessary if we always use " to write attributes
6868 // (see: http://www.w3.org/TR/xml/#syntax)
6869
6870 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
6871 unsigned char c = static_cast<unsigned char>(m_str[idx]);
6872 switch (c) {
6873 case '<': os << "&lt;"; break;
6874 case '&': os << "&amp;"; break;
6875
6876 case '>':
6877 // See: http://www.w3.org/TR/xml/#syntax
6878 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
6879 os << "&gt;";
6880 else
6881 os << c;
6882 break;
6883
6884 case '\"':
6885 if (m_forWhat == ForAttributes)
6886 os << "&quot;";
6887 else
6888 os << c;
6889 break;
6890
6891 default:
6892 // Check for control characters and invalid utf-8
6893
6894 // Escape control characters in standard ascii
6895 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
6896 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
6897 hexEscapeChar(os, c);
6898 break;
6899 }
6900
6901 // Plain ASCII: Write it to stream
6902 if (c < 0x7F) {
6903 os << c;
6904 break;
6905 }
6906
6907 // UTF-8 territory
6908 // Check if the encoding is valid and if it is not, hex escape bytes.
6909 // Important: We do not check the exact decoded values for validity, only the encoding format
6910 // First check that this bytes is a valid lead byte:
6911 // This means that it is not encoded as 1111 1XXX
6912 // Or as 10XX XXXX
6913 if (c < 0xC0 ||
6914 c >= 0xF8) {
6915 hexEscapeChar(os, c);
6916 break;
6917 }
6918
6919 auto encBytes = trailingBytes(c);
6920 // Are there enough bytes left to avoid accessing out-of-bounds memory?
6921 if (idx + encBytes - 1 >= m_str.size()) {
6922 hexEscapeChar(os, c);
6923 break;
6924 }
6925 // The header is valid, check data
6926 // The next encBytes bytes must together be a valid utf-8
6927 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
6928 bool valid = true;
6929 uint32_t value = headerValue(c);
6930 for (std::size_t n = 1; n < encBytes; ++n) {
6931 unsigned char nc = static_cast<unsigned char>(m_str[idx + n]);
6932 valid &= ((nc & 0xC0) == 0x80);
6933 value = (value << 6) | (nc & 0x3F);
6934 }
6935
6936 if (
6937 // Wrong bit pattern of following bytes
6938 (!valid) ||
6939 // Overlong encodings
6940 (value < 0x80) ||
6941 (0x80 <= value && value < 0x800 && encBytes > 2) ||
6942 (0x800 < value && value < 0x10000 && encBytes > 3) ||
6943 // Encoded value out of range
6944 (value >= 0x110000)
6945 ) {
6946 hexEscapeChar(os, c);
6947 break;
6948 }
6949
6950 // If we got here, this is in fact a valid(ish) utf-8 sequence
6951 for (std::size_t n = 0; n < encBytes; ++n) {
6952 os << m_str[idx + n];
6953 }
6954 idx += encBytes - 1;
6955 break;
6956 }
6957 }
6958 }
6959
6960 std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
6961 xmlEncode.encodeTo( os );
6962 return os;
6963 }
6964
6965 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
6966 : m_writer( writer ),
6967 m_fmt(fmt)
6968 {}
6969
6970 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
6971 : m_writer( other.m_writer ),
6972 m_fmt(other.m_fmt)
6973 {
6974 other.m_writer = nullptr;
6975 other.m_fmt = XmlFormatting::None;
6976 }
6977 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
6978 if ( m_writer ) {
6979 m_writer->endElement();
6980 }
6981 m_writer = other.m_writer;
6982 other.m_writer = nullptr;
6983 m_fmt = other.m_fmt;
6984 other.m_fmt = XmlFormatting::None;
6985 return *this;
6986 }
6987
6988
6989 XmlWriter::ScopedElement::~ScopedElement() {
6990 if (m_writer) {
6991 m_writer->endElement(m_fmt);
6992 }
6993 }
6994
6995 XmlWriter::ScopedElement&
6996 XmlWriter::ScopedElement::writeText( StringRef text, XmlFormatting fmt ) {
6997 m_writer->writeText( text, fmt );
6998 return *this;
6999 }
7000
7001 XmlWriter::ScopedElement&
7002 XmlWriter::ScopedElement::writeAttribute( StringRef name,
7003 StringRef attribute ) {
7004 m_writer->writeAttribute( name, attribute );
7005 return *this;
7006 }
7007
7008
7009 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
7010 {
7011 writeDeclaration();
7012 }
7013
7014 XmlWriter::~XmlWriter() {
7015 while (!m_tags.empty()) {
7016 endElement();
7017 }
7018 newlineIfNecessary();
7019 }
7020
7021 XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
7022 ensureTagClosed();
7023 newlineIfNecessary();
7024 if (shouldIndent(fmt)) {
7025 m_os << m_indent;
7026 m_indent += " ";
7027 }
7028 m_os << '<' << name;
7029 m_tags.push_back( name );
7030 m_tagIsOpen = true;
7031 applyFormatting(fmt);
7032 return *this;
7033 }
7034
7035 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
7036 ScopedElement scoped( this, fmt );
7037 startElement( name, fmt );
7038 return scoped;
7039 }
7040
7041 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
7042 m_indent = m_indent.substr(0, m_indent.size() - 2);
7043
7044 if( m_tagIsOpen ) {
7045 m_os << "/>";
7046 m_tagIsOpen = false;
7047 } else {
7048 newlineIfNecessary();
7049 if (shouldIndent(fmt)) {
7050 m_os << m_indent;
7051 }
7052 m_os << "</" << m_tags.back() << '>';
7053 }
7054 m_os << std::flush;
7055 applyFormatting(fmt);
7056 m_tags.pop_back();
7057 return *this;
7058 }
7059
7060 XmlWriter& XmlWriter::writeAttribute( StringRef name,
7061 StringRef attribute ) {
7062 if( !name.empty() && !attribute.empty() )
7063 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
7064 return *this;
7065 }
7066
7067 XmlWriter& XmlWriter::writeAttribute( StringRef name, bool attribute ) {
7068 writeAttribute(name, (attribute ? "true"_sr : "false"_sr));
7069 return *this;
7070 }
7071
7072 XmlWriter& XmlWriter::writeAttribute( StringRef name,
7073 char const* attribute ) {
7074 writeAttribute( name, StringRef( attribute ) );
7075 return *this;
7076 }
7077
7078 XmlWriter& XmlWriter::writeText( StringRef text, XmlFormatting fmt ) {
7079 CATCH_ENFORCE(!m_tags.empty(), "Cannot write text as top level element");
7080 if( !text.empty() ){
7081 bool tagWasOpen = m_tagIsOpen;
7082 ensureTagClosed();
7083 if (tagWasOpen && shouldIndent(fmt)) {
7084 m_os << m_indent;
7085 }
7086 m_os << XmlEncode( text, XmlEncode::ForTextNodes );
7087 applyFormatting(fmt);
7088 }
7089 return *this;
7090 }
7091
7092 XmlWriter& XmlWriter::writeComment( StringRef text, XmlFormatting fmt ) {
7093 ensureTagClosed();
7094 if (shouldIndent(fmt)) {
7095 m_os << m_indent;
7096 }
7097 m_os << "<!-- " << text << " -->";
7098 applyFormatting(fmt);
7099 return *this;
7100 }
7101
7102 void XmlWriter::writeStylesheetRef( StringRef url ) {
7103 m_os << R"(<?xml-stylesheet type="text/xsl" href=")" << url << R"("?>)" << '\n';
7104 }
7105
7106 void XmlWriter::ensureTagClosed() {
7107 if( m_tagIsOpen ) {
7108 m_os << '>' << std::flush;
7109 newlineIfNecessary();
7110 m_tagIsOpen = false;
7111 }
7112 }
7113
7114 void XmlWriter::applyFormatting(XmlFormatting fmt) {
7115 m_needsNewline = shouldNewline(fmt);
7116 }
7117
7118 void XmlWriter::writeDeclaration() {
7119 m_os << R"(<?xml version="1.0" encoding="UTF-8"?>)" << '\n';
7120 }
7121
7122 void XmlWriter::newlineIfNecessary() {
7123 if( m_needsNewline ) {
7124 m_os << '\n' << std::flush;
7125 m_needsNewline = false;
7126 }
7127 }
7128 }
7129
7130
7131
7132
7133
7134 namespace Catch {
7135 namespace Matchers {
7136
7137 std::string MatcherUntypedBase::toString() const {
7138 if (m_cachedToString.empty()) {
7139 m_cachedToString = describe();
7140 }
7141 return m_cachedToString;
7142 }
7143
7144 MatcherUntypedBase::~MatcherUntypedBase() = default;
7145
7146 } // namespace Matchers
7147 } // namespace Catch
7148
7149
7150
7151
7152 namespace Catch {
7153 namespace Matchers {
7154
7155 std::string IsEmptyMatcher::describe() const {
7156 return "is empty";
7157 }
7158
7159 std::string HasSizeMatcher::describe() const {
7160 ReusableStringStream sstr;
7161 sstr << "has size == " << m_target_size;
7162 return sstr.str();
7163 }
7164
7165 IsEmptyMatcher IsEmpty() {
7166 return {};
7167 }
7168
7169 HasSizeMatcher SizeIs(std::size_t sz) {
7170 return HasSizeMatcher{ sz };
7171 }
7172
7173 } // end namespace Matchers
7174 } // end namespace Catch
7175
7176
7177
7178 namespace Catch {
7179 namespace Matchers {
7180
7181 bool ExceptionMessageMatcher::match(std::exception const& ex) const {
7182 return ex.what() == m_message;
7183 }
7184
7185 std::string ExceptionMessageMatcher::describe() const {
7186 return "exception message matches \"" + m_message + '"';
7187 }
7188
7189 ExceptionMessageMatcher Message(std::string const& message) {
7190 return ExceptionMessageMatcher(message);
7191 }
7192
7193 } // namespace Matchers
7194 } // namespace Catch
7195
7196
7197
7198 #include <algorithm>
7199 #include <cmath>
7200 #include <cstdlib>
7201 #include <cstdint>
7202 #include <sstream>
7203 #include <iomanip>
7204 #include <limits>
7205
7206
7207 namespace Catch {
7208 namespace {
7209
7210 template <typename FP>
7211 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
7212 // Comparison with NaN should always be false.
7213 // This way we can rule it out before getting into the ugly details
7214 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
7215 return false;
7216 }
7217
7218 // This should also handle positive and negative zeros, infinities
7219 const auto ulpDist = ulpDistance(lhs, rhs);
7220
7221 return ulpDist <= maxUlpDiff;
7222 }
7223
7224 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
7225
7226 float nextafter(float x, float y) {
7227 return ::nextafterf(x, y);
7228 }
7229
7230 double nextafter(double x, double y) {
7231 return ::nextafter(x, y);
7232 }
7233
7234 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
7235
7236 template <typename FP>
7237 FP step(FP start, FP direction, uint64_t steps) {
7238 for (uint64_t i = 0; i < steps; ++i) {
7239 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
7240 start = Catch::nextafter(start, direction);
7241 #else
7242 start = std::nextafter(start, direction);
7243 #endif
7244 }
7245 return start;
7246 }
7247
7248 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
7249 // But without the subtraction to allow for INFINITY in comparison
7250 bool marginComparison(double lhs, double rhs, double margin) {
7251 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7252 }
7253
7254 template <typename FloatingPoint>
7255 void write(std::ostream& out, FloatingPoint num) {
7256 out << std::scientific
7257 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
7258 << num;
7259 }
7260
7261 } // end anonymous namespace
7262
7263 namespace Matchers {
7264 namespace Detail {
7265
7266 enum class FloatingPointKind : uint8_t {
7267 Float,
7268 Double
7269 };
7270
7271 } // end namespace Detail
7272
7273
7274 WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
7275 :m_target{ target }, m_margin{ margin } {
7276 CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
7277 << " Margin has to be non-negative.");
7278 }
7279
7280 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
7281 // But without the subtraction to allow for INFINITY in comparison
7282 bool WithinAbsMatcher::match(double const& matchee) const {
7283 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
7284 }
7285
7286 std::string WithinAbsMatcher::describe() const {
7287 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
7288 }
7289
7290
7291 WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, Detail::FloatingPointKind baseType)
7292 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
7293 CATCH_ENFORCE(m_type == Detail::FloatingPointKind::Double
7294 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
7295 "Provided ULP is impossibly large for a float comparison.");
7296 CATCH_ENFORCE( std::numeric_limits<double>::is_iec559,
7297 "WithinUlp matcher only supports platforms with "
7298 "IEEE-754 compatible floating point representation" );
7299 }
7300
7301 #if defined(__clang__)
7302 #pragma clang diagnostic push
7303 // Clang <3.5 reports on the default branch in the switch below
7304 #pragma clang diagnostic ignored "-Wunreachable-code"
7305 #endif
7306
7307 bool WithinUlpsMatcher::match(double const& matchee) const {
7308 switch (m_type) {
7309 case Detail::FloatingPointKind::Float:
7310 return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
7311 case Detail::FloatingPointKind::Double:
7312 return almostEqualUlps<double>(matchee, m_target, m_ulps);
7313 default:
7314 CATCH_INTERNAL_ERROR( "Unknown Detail::FloatingPointKind value" );
7315 }
7316 }
7317
7318 #if defined(__clang__)
7319 #pragma clang diagnostic pop
7320 #endif
7321
7322 std::string WithinUlpsMatcher::describe() const {
7323 std::stringstream ret;
7324
7325 ret << "is within " << m_ulps << " ULPs of ";
7326
7327 if (m_type == Detail::FloatingPointKind::Float) {
7328 write(ret, static_cast<float>(m_target));
7329 ret << 'f';
7330 } else {
7331 write(ret, m_target);
7332 }
7333
7334 ret << " ([";
7335 if (m_type == Detail::FloatingPointKind::Double) {
7336 write( ret,
7337 step( m_target,
7338 -std::numeric_limits<double>::infinity(),
7339 m_ulps ) );
7340 ret << ", ";
7341 write( ret,
7342 step( m_target,
7343 std::numeric_limits<double>::infinity(),
7344 m_ulps ) );
7345 } else {
7346 // We have to cast INFINITY to float because of MinGW, see #1782
7347 write( ret,
7348 step( static_cast<float>( m_target ),
7349 -std::numeric_limits<float>::infinity(),
7350 m_ulps ) );
7351 ret << ", ";
7352 write( ret,
7353 step( static_cast<float>( m_target ),
7354 std::numeric_limits<float>::infinity(),
7355 m_ulps ) );
7356 }
7357 ret << "])";
7358
7359 return ret.str();
7360 }
7361
7362 WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
7363 m_target(target),
7364 m_epsilon(epsilon){
7365 CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
7366 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
7367 }
7368
7369 bool WithinRelMatcher::match(double const& matchee) const {
7370 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
7371 return marginComparison(matchee, m_target,
7372 std::isinf(relMargin)? 0 : relMargin);
7373 }
7374
7375 std::string WithinRelMatcher::describe() const {
7376 Catch::ReusableStringStream sstr;
7377 sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
7378 return sstr.str();
7379 }
7380
7381
7382 WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
7383 return WithinUlpsMatcher(target, maxUlpDiff, Detail::FloatingPointKind::Double);
7384 }
7385
7386 WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
7387 return WithinUlpsMatcher(target, maxUlpDiff, Detail::FloatingPointKind::Float);
7388 }
7389
7390 WithinAbsMatcher WithinAbs(double target, double margin) {
7391 return WithinAbsMatcher(target, margin);
7392 }
7393
7394 WithinRelMatcher WithinRel(double target, double eps) {
7395 return WithinRelMatcher(target, eps);
7396 }
7397
7398 WithinRelMatcher WithinRel(double target) {
7399 return WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
7400 }
7401
7402 WithinRelMatcher WithinRel(float target, float eps) {
7403 return WithinRelMatcher(target, eps);
7404 }
7405
7406 WithinRelMatcher WithinRel(float target) {
7407 return WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
7408 }
7409
7410
7411 } // namespace Matchers
7412 } // namespace Catch
7413
7414
7415
7416
7417 std::string Catch::Matchers::Detail::finalizeDescription(const std::string& desc) {
7418 if (desc.empty()) {
7419 return "matches undescribed predicate";
7420 } else {
7421 return "matches predicate: \"" + desc + '"';
7422 }
7423 }
7424
7425
7426
7427 namespace Catch {
7428 namespace Matchers {
7429 std::string AllTrueMatcher::describe() const { return "contains only true"; }
7430
7431 AllTrueMatcher AllTrue() { return AllTrueMatcher{}; }
7432
7433 std::string NoneTrueMatcher::describe() const { return "contains no true"; }
7434
7435 NoneTrueMatcher NoneTrue() { return NoneTrueMatcher{}; }
7436
7437 std::string AnyTrueMatcher::describe() const { return "contains at least one true"; }
7438
7439 AnyTrueMatcher AnyTrue() { return AnyTrueMatcher{}; }
7440 } // namespace Matchers
7441 } // namespace Catch
7442
7443
7444
7445 #include <regex>
7446
7447 namespace Catch {
7448 namespace Matchers {
7449
7450 CasedString::CasedString( std::string const& str, CaseSensitive caseSensitivity )
7451 : m_caseSensitivity( caseSensitivity ),
7452 m_str( adjustString( str ) )
7453 {}
7454 std::string CasedString::adjustString( std::string const& str ) const {
7455 return m_caseSensitivity == CaseSensitive::No
7456 ? toLower( str )
7457 : str;
7458 }
7459 StringRef CasedString::caseSensitivitySuffix() const {
7460 return m_caseSensitivity == CaseSensitive::Yes
7461 ? StringRef()
7462 : " (case insensitive)"_sr;
7463 }
7464
7465
7466 StringMatcherBase::StringMatcherBase( StringRef operation, CasedString const& comparator )
7467 : m_comparator( comparator ),
7468 m_operation( operation ) {
7469 }
7470
7471 std::string StringMatcherBase::describe() const {
7472 std::string description;
7473 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
7474 m_comparator.caseSensitivitySuffix().size());
7475 description += m_operation;
7476 description += ": \"";
7477 description += m_comparator.m_str;
7478 description += '"';
7479 description += m_comparator.caseSensitivitySuffix();
7480 return description;
7481 }
7482
7483 StringEqualsMatcher::StringEqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals"_sr, comparator ) {}
7484
7485 bool StringEqualsMatcher::match( std::string const& source ) const {
7486 return m_comparator.adjustString( source ) == m_comparator.m_str;
7487 }
7488
7489
7490 StringContainsMatcher::StringContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains"_sr, comparator ) {}
7491
7492 bool StringContainsMatcher::match( std::string const& source ) const {
7493 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
7494 }
7495
7496
7497 StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with"_sr, comparator ) {}
7498
7499 bool StartsWithMatcher::match( std::string const& source ) const {
7500 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
7501 }
7502
7503
7504 EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with"_sr, comparator ) {}
7505
7506 bool EndsWithMatcher::match( std::string const& source ) const {
7507 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
7508 }
7509
7510
7511
7512 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive caseSensitivity): m_regex(CATCH_MOVE(regex)), m_caseSensitivity(caseSensitivity) {}
7513
7514 bool RegexMatcher::match(std::string const& matchee) const {
7515 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
7516 if (m_caseSensitivity == CaseSensitive::No) {
7517 flags |= std::regex::icase;
7518 }
7519 auto reg = std::regex(m_regex, flags);
7520 return std::regex_match(matchee, reg);
7521 }
7522
7523 std::string RegexMatcher::describe() const {
7524 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Yes)? " case sensitively" : " case insensitively");
7525 }
7526
7527
7528 StringEqualsMatcher Equals( std::string const& str, CaseSensitive caseSensitivity ) {
7529 return StringEqualsMatcher( CasedString( str, caseSensitivity) );
7530 }
7531 StringContainsMatcher ContainsSubstring( std::string const& str, CaseSensitive caseSensitivity ) {
7532 return StringContainsMatcher( CasedString( str, caseSensitivity) );
7533 }
7534 EndsWithMatcher EndsWith( std::string const& str, CaseSensitive caseSensitivity ) {
7535 return EndsWithMatcher( CasedString( str, caseSensitivity) );
7536 }
7537 StartsWithMatcher StartsWith( std::string const& str, CaseSensitive caseSensitivity ) {
7538 return StartsWithMatcher( CasedString( str, caseSensitivity) );
7539 }
7540
7541 RegexMatcher Matches(std::string const& regex, CaseSensitive caseSensitivity) {
7542 return RegexMatcher(regex, caseSensitivity);
7543 }
7544
7545 } // namespace Matchers
7546 } // namespace Catch
7547
7548
7549
7550 namespace Catch {
7551 namespace Matchers {
7552 MatcherGenericBase::~MatcherGenericBase() = default;
7553
7554 namespace Detail {
7555
7556 std::string describe_multi_matcher(StringRef combine, std::string const* descriptions_begin, std::string const* descriptions_end) {
7557 std::string description;
7558 std::size_t combined_size = 4;
7559 for ( auto desc = descriptions_begin; desc != descriptions_end; ++desc ) {
7560 combined_size += desc->size();
7561 }
7562 combined_size += static_cast<size_t>(descriptions_end - descriptions_begin - 1) * combine.size();
7563
7564 description.reserve(combined_size);
7565
7566 description += "( ";
7567 bool first = true;
7568 for( auto desc = descriptions_begin; desc != descriptions_end; ++desc ) {
7569 if( first )
7570 first = false;
7571 else
7572 description += combine;
7573 description += *desc;
7574 }
7575 description += " )";
7576 return description;
7577 }
7578
7579 } // namespace Detail
7580 } // namespace Matchers
7581 } // namespace Catch
7582
7583
7584
7585
7586 namespace Catch {
7587
7588 // This is the general overload that takes a any string matcher
7589 // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
7590 // the Equals matcher (so the header does not mention matchers)
7591 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
7592 std::string exceptionMessage = Catch::translateActiveException();
7593 MatchExpr<std::string, StringMatcher const&> expr( CATCH_MOVE(exceptionMessage), matcher, matcherString );
7594 handler.handleExpr( expr );
7595 }
7596
7597 } // namespace Catch
7598
7599
7600
7601 #include <ostream>
7602
7603 namespace Catch {
7604
7605 AutomakeReporter::~AutomakeReporter() {}
7606
7607 void AutomakeReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
7608 // Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR.
7609 m_stream << ":test-result: ";
7610 if (_testCaseStats.totals.assertions.allPassed()) {
7611 m_stream << "PASS";
7612 } else if (_testCaseStats.totals.assertions.allOk()) {
7613 m_stream << "XFAIL";
7614 } else {
7615 m_stream << "FAIL";
7616 }
7617 m_stream << ' ' << _testCaseStats.testInfo->name << '\n';
7618 StreamingReporterBase::testCaseEnded(_testCaseStats);
7619 }
7620
7621 void AutomakeReporter::skipTest(TestCaseInfo const& testInfo) {
7622 m_stream << ":test-result: SKIP " << testInfo.name << '\n';
7623 }
7624
7625 } // end namespace Catch
7626
7627
7628
7629
7630
7631
7632 namespace Catch {
7633 ReporterBase::ReporterBase( ReporterConfig&& config ):
7634 IEventListener( config.fullConfig() ),
7635 m_wrapped_stream( CATCH_MOVE(config).takeStream() ),
7636 m_stream( m_wrapped_stream->stream() ),
7637 m_colour( makeColourImpl( config.colourMode(), m_wrapped_stream.get() ) ),
7638 m_customOptions( config.customOptions() )
7639 {}
7640
7641 ReporterBase::~ReporterBase() = default;
7642
7643 void ReporterBase::listReporters(
7644 std::vector<ReporterDescription> const& descriptions ) {
7645 defaultListReporters(m_stream, descriptions, m_config->verbosity());
7646 }
7647
7648 void ReporterBase::listListeners(
7649 std::vector<ListenerDescription> const& descriptions ) {
7650 defaultListListeners( m_stream, descriptions );
7651 }
7652
7653 void ReporterBase::listTests(std::vector<TestCaseHandle> const& tests) {
7654 defaultListTests(m_stream,
7655 m_colour.get(),
7656 tests,
7657 m_config->hasTestFilters(),
7658 m_config->verbosity());
7659 }
7660
7661 void ReporterBase::listTags(std::vector<TagInfo> const& tags) {
7662 defaultListTags( m_stream, tags, m_config->hasTestFilters() );
7663 }
7664
7665 } // namespace Catch
7666
7667
7668
7669
7670 #include <ostream>
7671
7672 namespace {
7673
7674 constexpr Catch::StringRef bothOrAll( std::uint64_t count ) {
7675 switch (count) {
7676 case 1:
7677 return Catch::StringRef{};
7678 case 2:
7679 return "both "_catch_sr;
7680 default:
7681 return "all "_catch_sr;
7682 }
7683 }
7684
7685 } // anon namespace
7686
7687
7688 namespace Catch {
7689 namespace {
7690
7691 // Colour::LightGrey
7692 static constexpr Colour::Code compactDimColour = Colour::FileName;
7693
7694 #ifdef CATCH_PLATFORM_MAC
7695 static constexpr Catch::StringRef compactFailedString = "FAILED"_sr;
7696 static constexpr Catch::StringRef compactPassedString = "PASSED"_sr;
7697 #else
7698 static constexpr Catch::StringRef compactFailedString = "failed"_sr;
7699 static constexpr Catch::StringRef compactPassedString = "passed"_sr;
7700 #endif
7701
7702 // Colour, message variants:
7703 // - white: No tests ran.
7704 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
7705 // - white: Passed [both/all] N test cases (no assertions).
7706 // - red: Failed N tests cases, failed M assertions.
7707 // - green: Passed [both/all] N tests cases with M assertions.
7708 void printTotals(std::ostream& out, const Totals& totals, ColourImpl* colourImpl) {
7709 if (totals.testCases.total() == 0) {
7710 out << "No tests ran.";
7711 } else if (totals.testCases.failed == totals.testCases.total()) {
7712 auto guard = colourImpl->guardColour( Colour::ResultError ).engage( out );
7713 const StringRef qualify_assertions_failed =
7714 totals.assertions.failed == totals.assertions.total() ?
7715 bothOrAll(totals.assertions.failed) : StringRef{};
7716 out <<
7717 "Failed " << bothOrAll(totals.testCases.failed)
7718 << pluralise(totals.testCases.failed, "test case"_sr) << ", "
7719 "failed " << qualify_assertions_failed <<
7720 pluralise(totals.assertions.failed, "assertion"_sr) << '.';
7721 } else if (totals.assertions.total() == 0) {
7722 out <<
7723 "Passed " << bothOrAll(totals.testCases.total())
7724 << pluralise(totals.testCases.total(), "test case"_sr)
7725 << " (no assertions).";
7726 } else if (totals.assertions.failed) {
7727 out << colourImpl->guardColour( Colour::ResultError ) <<
7728 "Failed " << pluralise(totals.testCases.failed, "test case"_sr) << ", "
7729 "failed " << pluralise(totals.assertions.failed, "assertion"_sr) << '.';
7730 } else {
7731 out << colourImpl->guardColour( Colour::ResultSuccess ) <<
7732 "Passed " << bothOrAll(totals.testCases.passed)
7733 << pluralise(totals.testCases.passed, "test case"_sr) <<
7734 " with " << pluralise(totals.assertions.passed, "assertion"_sr) << '.';
7735 }
7736 }
7737
7738 // Implementation of CompactReporter formatting
7739 class AssertionPrinter {
7740 public:
7741 AssertionPrinter& operator= (AssertionPrinter const&) = delete;
7742 AssertionPrinter(AssertionPrinter const&) = delete;
7743 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages, ColourImpl* colourImpl_)
7744 : stream(_stream)
7745 , result(_stats.assertionResult)
7746 , messages(_stats.infoMessages)
7747 , itMessage(_stats.infoMessages.begin())
7748 , printInfoMessages(_printInfoMessages)
7749 , colourImpl(colourImpl_)
7750 {}
7751
7752 void print() {
7753 printSourceInfo();
7754
7755 itMessage = messages.begin();
7756
7757 switch (result.getResultType()) {
7758 case ResultWas::Ok:
7759 printResultType(Colour::ResultSuccess, compactPassedString);
7760 printOriginalExpression();
7761 printReconstructedExpression();
7762 if (!result.hasExpression())
7763 printRemainingMessages(Colour::None);
7764 else
7765 printRemainingMessages();
7766 break;
7767 case ResultWas::ExpressionFailed:
7768 if (result.isOk())
7769 printResultType(Colour::ResultSuccess, compactFailedString + " - but was ok"_sr);
7770 else
7771 printResultType(Colour::Error, compactFailedString);
7772 printOriginalExpression();
7773 printReconstructedExpression();
7774 printRemainingMessages();
7775 break;
7776 case ResultWas::ThrewException:
7777 printResultType(Colour::Error, compactFailedString);
7778 printIssue("unexpected exception with message:");
7779 printMessage();
7780 printExpressionWas();
7781 printRemainingMessages();
7782 break;
7783 case ResultWas::FatalErrorCondition:
7784 printResultType(Colour::Error, compactFailedString);
7785 printIssue("fatal error condition with message:");
7786 printMessage();
7787 printExpressionWas();
7788 printRemainingMessages();
7789 break;
7790 case ResultWas::DidntThrowException:
7791 printResultType(Colour::Error, compactFailedString);
7792 printIssue("expected exception, got none");
7793 printExpressionWas();
7794 printRemainingMessages();
7795 break;
7796 case ResultWas::Info:
7797 printResultType(Colour::None, "info"_sr);
7798 printMessage();
7799 printRemainingMessages();
7800 break;
7801 case ResultWas::Warning:
7802 printResultType(Colour::None, "warning"_sr);
7803 printMessage();
7804 printRemainingMessages();
7805 break;
7806 case ResultWas::ExplicitFailure:
7807 printResultType(Colour::Error, compactFailedString);
7808 printIssue("explicitly");
7809 printRemainingMessages(Colour::None);
7810 break;
7811 // These cases are here to prevent compiler warnings
7812 case ResultWas::Unknown:
7813 case ResultWas::FailureBit:
7814 case ResultWas::Exception:
7815 printResultType(Colour::Error, "** internal error **");
7816 break;
7817 }
7818 }
7819
7820 private:
7821 void printSourceInfo() const {
7822 stream << colourImpl->guardColour( Colour::FileName )
7823 << result.getSourceInfo() << ':';
7824 }
7825
7826 void printResultType(Colour::Code colour, StringRef passOrFail) const {
7827 if (!passOrFail.empty()) {
7828 stream << colourImpl->guardColour(colour) << ' ' << passOrFail;
7829 stream << ':';
7830 }
7831 }
7832
7833 void printIssue(char const* issue) const {
7834 stream << ' ' << issue;
7835 }
7836
7837 void printExpressionWas() {
7838 if (result.hasExpression()) {
7839 stream << ';';
7840 {
7841 stream << colourImpl->guardColour(compactDimColour) << " expression was:";
7842 }
7843 printOriginalExpression();
7844 }
7845 }
7846
7847 void printOriginalExpression() const {
7848 if (result.hasExpression()) {
7849 stream << ' ' << result.getExpression();
7850 }
7851 }
7852
7853 void printReconstructedExpression() const {
7854 if (result.hasExpandedExpression()) {
7855 stream << colourImpl->guardColour(compactDimColour) << " for: ";
7856 stream << result.getExpandedExpression();
7857 }
7858 }
7859
7860 void printMessage() {
7861 if (itMessage != messages.end()) {
7862 stream << " '" << itMessage->message << '\'';
7863 ++itMessage;
7864 }
7865 }
7866
7867 void printRemainingMessages(Colour::Code colour = compactDimColour) {
7868 if (itMessage == messages.end())
7869 return;
7870
7871 const auto itEnd = messages.cend();
7872 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
7873
7874 stream << colourImpl->guardColour( colour ) << " with "
7875 << pluralise( N, "message"_sr ) << ':';
7876
7877 while (itMessage != itEnd) {
7878 // If this assertion is a warning ignore any INFO messages
7879 if (printInfoMessages || itMessage->type != ResultWas::Info) {
7880 printMessage();
7881 if (itMessage != itEnd) {
7882 stream << colourImpl->guardColour(compactDimColour) << " and";
7883 }
7884 continue;
7885 }
7886 ++itMessage;
7887 }
7888 }
7889
7890 private:
7891 std::ostream& stream;
7892 AssertionResult const& result;
7893 std::vector<MessageInfo> messages;
7894 std::vector<MessageInfo>::const_iterator itMessage;
7895 bool printInfoMessages;
7896 ColourImpl* colourImpl;
7897 };
7898
7899 } // anon namespace
7900
7901 std::string CompactReporter::getDescription() {
7902 return "Reports test results on a single line, suitable for IDEs";
7903 }
7904
7905 void CompactReporter::noMatchingTestCases( StringRef unmatchedSpec ) {
7906 m_stream << "No test cases matched '" << unmatchedSpec << "'\n";
7907 }
7908
7909 void CompactReporter::testRunStarting( TestRunInfo const& ) {
7910 if ( m_config->testSpec().hasFilters() ) {
7911 m_stream << m_colour->guardColour( Colour::BrightYellow )
7912 << "Filters: "
7913 << serializeFilters( m_config->getTestsOrTags() )
7914 << '\n';
7915 }
7916 m_stream << "RNG seed: " << getSeed() << '\n';
7917 }
7918
7919 void CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
7920 AssertionResult const& result = _assertionStats.assertionResult;
7921
7922 bool printInfoMessages = true;
7923
7924 // Drop out if result was successful and we're not printing those
7925 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
7926 if( result.getResultType() != ResultWas::Warning )
7927 return;
7928 printInfoMessages = false;
7929 }
7930
7931 AssertionPrinter printer( m_stream, _assertionStats, printInfoMessages, m_colour.get() );
7932 printer.print();
7933
7934 m_stream << '\n' << std::flush;
7935 }
7936
7937 void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
7938 double dur = _sectionStats.durationInSeconds;
7939 if ( shouldShowDuration( *m_config, dur ) ) {
7940 m_stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << '\n' << std::flush;
7941 }
7942 }
7943
7944 void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
7945 printTotals( m_stream, _testRunStats.totals, m_colour.get() );
7946 m_stream << "\n\n" << std::flush;
7947 StreamingReporterBase::testRunEnded( _testRunStats );
7948 }
7949
7950 CompactReporter::~CompactReporter() {}
7951
7952 } // end namespace Catch
7953
7954
7955
7956
7957 #include <cstdio>
7958
7959 #if defined(_MSC_VER)
7960 #pragma warning(push)
7961 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
7962 // Note that 4062 (not all labels are handled and default is missing) is enabled
7963 #endif
7964
7965 #if defined(__clang__)
7966 # pragma clang diagnostic push
7967 // For simplicity, benchmarking-only helpers are always enabled
7968 # pragma clang diagnostic ignored "-Wunused-function"
7969 #endif
7970
7971
7972
7973 namespace Catch {
7974
7975 namespace {
7976
7977 // Formatter impl for ConsoleReporter
7978 class ConsoleAssertionPrinter {
7979 public:
7980 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
7981 ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
7982 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, ColourImpl* colourImpl_, bool _printInfoMessages)
7983 : stream(_stream),
7984 stats(_stats),
7985 result(_stats.assertionResult),
7986 colour(Colour::None),
7987 message(result.getMessage()),
7988 messages(_stats.infoMessages),
7989 colourImpl(colourImpl_),
7990 printInfoMessages(_printInfoMessages) {
7991 switch (result.getResultType()) {
7992 case ResultWas::Ok:
7993 colour = Colour::Success;
7994 passOrFail = "PASSED"_sr;
7995 //if( result.hasMessage() )
7996 if (_stats.infoMessages.size() == 1)
7997 messageLabel = "with message";
7998 if (_stats.infoMessages.size() > 1)
7999 messageLabel = "with messages";
8000 break;
8001 case ResultWas::ExpressionFailed:
8002 if (result.isOk()) {
8003 colour = Colour::Success;
8004 passOrFail = "FAILED - but was ok"_sr;
8005 } else {
8006 colour = Colour::Error;
8007 passOrFail = "FAILED"_sr;
8008 }
8009 if (_stats.infoMessages.size() == 1)
8010 messageLabel = "with message";
8011 if (_stats.infoMessages.size() > 1)
8012 messageLabel = "with messages";
8013 break;
8014 case ResultWas::ThrewException:
8015 colour = Colour::Error;
8016 passOrFail = "FAILED"_sr;
8017 messageLabel = "due to unexpected exception with ";
8018 if (_stats.infoMessages.size() == 1)
8019 messageLabel += "message";
8020 if (_stats.infoMessages.size() > 1)
8021 messageLabel += "messages";
8022 break;
8023 case ResultWas::FatalErrorCondition:
8024 colour = Colour::Error;
8025 passOrFail = "FAILED"_sr;
8026 messageLabel = "due to a fatal error condition";
8027 break;
8028 case ResultWas::DidntThrowException:
8029 colour = Colour::Error;
8030 passOrFail = "FAILED"_sr;
8031 messageLabel = "because no exception was thrown where one was expected";
8032 break;
8033 case ResultWas::Info:
8034 messageLabel = "info";
8035 break;
8036 case ResultWas::Warning:
8037 messageLabel = "warning";
8038 break;
8039 case ResultWas::ExplicitFailure:
8040 passOrFail = "FAILED"_sr;
8041 colour = Colour::Error;
8042 if (_stats.infoMessages.size() == 1)
8043 messageLabel = "explicitly with message";
8044 if (_stats.infoMessages.size() > 1)
8045 messageLabel = "explicitly with messages";
8046 break;
8047 // These cases are here to prevent compiler warnings
8048 case ResultWas::Unknown:
8049 case ResultWas::FailureBit:
8050 case ResultWas::Exception:
8051 passOrFail = "** internal error **"_sr;
8052 colour = Colour::Error;
8053 break;
8054 }
8055 }
8056
8057 void print() const {
8058 printSourceInfo();
8059 if (stats.totals.assertions.total() > 0) {
8060 printResultType();
8061 printOriginalExpression();
8062 printReconstructedExpression();
8063 } else {
8064 stream << '\n';
8065 }
8066 printMessage();
8067 }
8068
8069 private:
8070 void printResultType() const {
8071 if (!passOrFail.empty()) {
8072 stream << colourImpl->guardColour(colour) << passOrFail << ":\n";
8073 }
8074 }
8075 void printOriginalExpression() const {
8076 if (result.hasExpression()) {
8077 stream << colourImpl->guardColour( Colour::OriginalExpression )
8078 << " " << result.getExpressionInMacro() << '\n';
8079 }
8080 }
8081 void printReconstructedExpression() const {
8082 if (result.hasExpandedExpression()) {
8083 stream << "with expansion:\n";
8084 stream << colourImpl->guardColour( Colour::ReconstructedExpression )
8085 << TextFlow::Column( result.getExpandedExpression() )
8086 .indent( 2 )
8087 << '\n';
8088 }
8089 }
8090 void printMessage() const {
8091 if (!messageLabel.empty())
8092 stream << messageLabel << ':' << '\n';
8093 for (auto const& msg : messages) {
8094 // If this assertion is a warning ignore any INFO messages
8095 if (printInfoMessages || msg.type != ResultWas::Info)
8096 stream << TextFlow::Column(msg.message).indent(2) << '\n';
8097 }
8098 }
8099 void printSourceInfo() const {
8100 stream << colourImpl->guardColour( Colour::FileName )
8101 << result.getSourceInfo() << ": ";
8102 }
8103
8104 std::ostream& stream;
8105 AssertionStats const& stats;
8106 AssertionResult const& result;
8107 Colour::Code colour;
8108 StringRef passOrFail;
8109 std::string messageLabel;
8110 std::string message;
8111 std::vector<MessageInfo> messages;
8112 ColourImpl* colourImpl;
8113 bool printInfoMessages;
8114 };
8115
8116 std::size_t makeRatio( std::uint64_t number, std::uint64_t total ) {
8117 const auto ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
8118 return (ratio == 0 && number > 0) ? 1 : static_cast<std::size_t>(ratio);
8119 }
8120
8121 std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
8122 if (i > j && i > k)
8123 return i;
8124 else if (j > k)
8125 return j;
8126 else
8127 return k;
8128 }
8129
8130 enum class Justification { Left, Right };
8131
8132 struct ColumnInfo {
8133 std::string name;
8134 std::size_t width;
8135 Justification justification;
8136 };
8137 struct ColumnBreak {};
8138 struct RowBreak {};
8139
8140 class Duration {
8141 enum class Unit {
8142 Auto,
8143 Nanoseconds,
8144 Microseconds,
8145 Milliseconds,
8146 Seconds,
8147 Minutes
8148 };
8149 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
8150 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
8151 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
8152 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
8153
8154 double m_inNanoseconds;
8155 Unit m_units;
8156
8157 public:
8158 explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
8159 : m_inNanoseconds(inNanoseconds),
8160 m_units(units) {
8161 if (m_units == Unit::Auto) {
8162 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
8163 m_units = Unit::Nanoseconds;
8164 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
8165 m_units = Unit::Microseconds;
8166 else if (m_inNanoseconds < s_nanosecondsInASecond)
8167 m_units = Unit::Milliseconds;
8168 else if (m_inNanoseconds < s_nanosecondsInAMinute)
8169 m_units = Unit::Seconds;
8170 else
8171 m_units = Unit::Minutes;
8172 }
8173
8174 }
8175
8176 auto value() const -> double {
8177 switch (m_units) {
8178 case Unit::Microseconds:
8179 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
8180 case Unit::Milliseconds:
8181 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
8182 case Unit::Seconds:
8183 return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
8184 case Unit::Minutes:
8185 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
8186 default:
8187 return m_inNanoseconds;
8188 }
8189 }
8190 StringRef unitsAsString() const {
8191 switch (m_units) {
8192 case Unit::Nanoseconds:
8193 return "ns"_sr;
8194 case Unit::Microseconds:
8195 return "us"_sr;
8196 case Unit::Milliseconds:
8197 return "ms"_sr;
8198 case Unit::Seconds:
8199 return "s"_sr;
8200 case Unit::Minutes:
8201 return "m"_sr;
8202 default:
8203 return "** internal error **"_sr;
8204 }
8205
8206 }
8207 friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
8208 return os << duration.value() << ' ' << duration.unitsAsString();
8209 }
8210 };
8211 } // end anon namespace
8212
8213 class TablePrinter {
8214 std::ostream& m_os;
8215 std::vector<ColumnInfo> m_columnInfos;
8216 ReusableStringStream m_oss;
8217 int m_currentColumn = -1;
8218 bool m_isOpen = false;
8219
8220 public:
8221 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
8222 : m_os( os ),
8223 m_columnInfos( CATCH_MOVE( columnInfos ) ) {}
8224
8225 auto columnInfos() const -> std::vector<ColumnInfo> const& {
8226 return m_columnInfos;
8227 }
8228
8229 void open() {
8230 if (!m_isOpen) {
8231 m_isOpen = true;
8232 *this << RowBreak();
8233
8234 TextFlow::Columns headerCols;
8235 auto spacer = TextFlow::Spacer(2);
8236 for (auto const& info : m_columnInfos) {
8237 assert(info.width > 2);
8238 headerCols += TextFlow::Column(info.name).width(info.width - 2);
8239 headerCols += spacer;
8240 }
8241 m_os << headerCols << '\n';
8242
8243 m_os << lineOfChars('-') << '\n';
8244 }
8245 }
8246 void close() {
8247 if (m_isOpen) {
8248 *this << RowBreak();
8249 m_os << '\n' << std::flush;
8250 m_isOpen = false;
8251 }
8252 }
8253
8254 template<typename T>
8255 friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
8256 tp.m_oss << value;
8257 return tp;
8258 }
8259
8260 friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
8261 auto colStr = tp.m_oss.str();
8262 const auto strSize = colStr.size();
8263 tp.m_oss.str("");
8264 tp.open();
8265 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
8266 tp.m_currentColumn = -1;
8267 tp.m_os << '\n';
8268 }
8269 tp.m_currentColumn++;
8270
8271 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
8272 auto padding = (strSize + 1 < colInfo.width)
8273 ? std::string(colInfo.width - (strSize + 1), ' ')
8274 : std::string();
8275 if (colInfo.justification == Justification::Left)
8276 tp.m_os << colStr << padding << ' ';
8277 else
8278 tp.m_os << padding << colStr << ' ';
8279 return tp;
8280 }
8281
8282 friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
8283 if (tp.m_currentColumn > 0) {
8284 tp.m_os << '\n';
8285 tp.m_currentColumn = -1;
8286 }
8287 return tp;
8288 }
8289 };
8290
8291 ConsoleReporter::ConsoleReporter(ReporterConfig&& config):
8292 StreamingReporterBase( CATCH_MOVE( config ) ),
8293 m_tablePrinter(Detail::make_unique<TablePrinter>(m_stream,
8294 [&config]() -> std::vector<ColumnInfo> {
8295 if (config.fullConfig()->benchmarkNoAnalysis())
8296 {
8297 return{
8298 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, Justification::Left },
8299 { " samples", 14, Justification::Right },
8300 { " iterations", 14, Justification::Right },
8301 { " mean", 14, Justification::Right }
8302 };
8303 }
8304 else
8305 {
8306 return{
8307 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, Justification::Left },
8308 { "samples mean std dev", 14, Justification::Right },
8309 { "iterations low mean low std dev", 14, Justification::Right },
8310 { "estimated high mean high std dev", 14, Justification::Right }
8311 };
8312 }
8313 }())) {}
8314 ConsoleReporter::~ConsoleReporter() = default;
8315
8316 std::string ConsoleReporter::getDescription() {
8317 return "Reports test results as plain lines of text";
8318 }
8319
8320 void ConsoleReporter::noMatchingTestCases( StringRef unmatchedSpec ) {
8321 m_stream << "No test cases matched '" << unmatchedSpec << "'\n";
8322 }
8323
8324 void ConsoleReporter::reportInvalidTestSpec( StringRef arg ) {
8325 m_stream << "Invalid Filter: " << arg << '\n';
8326 }
8327
8328 void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
8329
8330 void ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
8331 AssertionResult const& result = _assertionStats.assertionResult;
8332
8333 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
8334
8335 // Drop out if result was successful but we're not printing them.
8336 if (!includeResults && result.getResultType() != ResultWas::Warning)
8337 return;
8338
8339 lazyPrint();
8340
8341 ConsoleAssertionPrinter printer(m_stream, _assertionStats, m_colour.get(), includeResults);
8342 printer.print();
8343 m_stream << '\n' << std::flush;
8344 }
8345
8346 void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
8347 m_tablePrinter->close();
8348 m_headerPrinted = false;
8349 StreamingReporterBase::sectionStarting(_sectionInfo);
8350 }
8351 void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
8352 m_tablePrinter->close();
8353 if (_sectionStats.missingAssertions) {
8354 lazyPrint();
8355 auto guard =
8356 m_colour->guardColour( Colour::ResultError ).engage( m_stream );
8357 if (m_sectionStack.size() > 1)
8358 m_stream << "\nNo assertions in section";
8359 else
8360 m_stream << "\nNo assertions in test case";
8361 m_stream << " '" << _sectionStats.sectionInfo.name << "'\n\n" << std::flush;
8362 }
8363 double dur = _sectionStats.durationInSeconds;
8364 if (shouldShowDuration(*m_config, dur)) {
8365 m_stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << '\n' << std::flush;
8366 }
8367 if (m_headerPrinted) {
8368 m_headerPrinted = false;
8369 }
8370 StreamingReporterBase::sectionEnded(_sectionStats);
8371 }
8372
8373 void ConsoleReporter::benchmarkPreparing( StringRef name ) {
8374 lazyPrintWithoutClosingBenchmarkTable();
8375
8376 auto nameCol = TextFlow::Column( static_cast<std::string>( name ) )
8377 .width( m_tablePrinter->columnInfos()[0].width - 2 );
8378
8379 bool firstLine = true;
8380 for (auto line : nameCol) {
8381 if (!firstLine)
8382 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
8383 else
8384 firstLine = false;
8385
8386 (*m_tablePrinter) << line << ColumnBreak();
8387 }
8388 }
8389
8390 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
8391 (*m_tablePrinter) << info.samples << ColumnBreak()
8392 << info.iterations << ColumnBreak();
8393 if (!m_config->benchmarkNoAnalysis())
8394 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
8395 }
8396 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
8397 if (m_config->benchmarkNoAnalysis())
8398 {
8399 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
8400 }
8401 else
8402 {
8403 (*m_tablePrinter) << ColumnBreak()
8404 << Duration(stats.mean.point.count()) << ColumnBreak()
8405 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
8406 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
8407 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
8408 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
8409 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
8410 }
8411 }
8412
8413 void ConsoleReporter::benchmarkFailed( StringRef error ) {
8414 auto guard = m_colour->guardColour( Colour::Red ).engage( m_stream );
8415 (*m_tablePrinter)
8416 << "Benchmark failed (" << error << ')'
8417 << ColumnBreak() << RowBreak();
8418 }
8419
8420 void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
8421 m_tablePrinter->close();
8422 StreamingReporterBase::testCaseEnded(_testCaseStats);
8423 m_headerPrinted = false;
8424 }
8425 void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
8426 printTotalsDivider(_testRunStats.totals);
8427 printTotals(_testRunStats.totals);
8428 m_stream << '\n' << std::flush;
8429 StreamingReporterBase::testRunEnded(_testRunStats);
8430 }
8431 void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
8432 StreamingReporterBase::testRunStarting(_testInfo);
8433 if ( m_config->testSpec().hasFilters() ) {
8434 m_stream << m_colour->guardColour( Colour::BrightYellow ) << "Filters: "
8435 << serializeFilters( m_config->getTestsOrTags() ) << '\n';
8436 }
8437 m_stream << "Randomness seeded to: " << getSeed() << '\n';
8438 }
8439
8440 void ConsoleReporter::lazyPrint() {
8441
8442 m_tablePrinter->close();
8443 lazyPrintWithoutClosingBenchmarkTable();
8444 }
8445
8446 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
8447
8448 if ( !m_testRunInfoPrinted ) {
8449 lazyPrintRunInfo();
8450 }
8451 if (!m_headerPrinted) {
8452 printTestCaseAndSectionHeader();
8453 m_headerPrinted = true;
8454 }
8455 }
8456 void ConsoleReporter::lazyPrintRunInfo() {
8457 m_stream << '\n'
8458 << lineOfChars( '~' ) << '\n'
8459 << m_colour->guardColour( Colour::SecondaryText )
8460 << currentTestRunInfo.name << " is a Catch2 v" << libraryVersion()
8461 << " host application.\n"
8462 << "Run with -? for options\n\n";
8463
8464 m_testRunInfoPrinted = true;
8465 }
8466 void ConsoleReporter::printTestCaseAndSectionHeader() {
8467 assert(!m_sectionStack.empty());
8468 printOpenHeader(currentTestCaseInfo->name);
8469
8470 if (m_sectionStack.size() > 1) {
8471 auto guard = m_colour->guardColour( Colour::Headers ).engage( m_stream );
8472
8473 auto
8474 it = m_sectionStack.begin() + 1, // Skip first section (test case)
8475 itEnd = m_sectionStack.end();
8476 for (; it != itEnd; ++it)
8477 printHeaderString(it->name, 2);
8478 }
8479
8480 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
8481
8482
8483 m_stream << lineOfChars( '-' ) << '\n'
8484 << m_colour->guardColour( Colour::FileName ) << lineInfo << '\n'
8485 << lineOfChars( '.' ) << "\n\n"
8486 << std::flush;
8487 }
8488
8489 void ConsoleReporter::printClosedHeader(std::string const& _name) {
8490 printOpenHeader(_name);
8491 m_stream << lineOfChars('.') << '\n';
8492 }
8493 void ConsoleReporter::printOpenHeader(std::string const& _name) {
8494 m_stream << lineOfChars('-') << '\n';
8495 {
8496 auto guard = m_colour->guardColour( Colour::Headers ).engage( m_stream );
8497 printHeaderString(_name);
8498 }
8499 }
8500
8501 void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
8502 // We want to get a bit fancy with line breaking here, so that subsequent
8503 // lines start after ":" if one is present, e.g.
8504 // ```
8505 // blablabla: Fancy
8506 // linebreaking
8507 // ```
8508 // but we also want to avoid problems with overly long indentation causing
8509 // the text to take up too many lines, e.g.
8510 // ```
8511 // blablabla: F
8512 // a
8513 // n
8514 // c
8515 // y
8516 // .
8517 // .
8518 // .
8519 // ```
8520 // So we limit the prefix indentation check to first quarter of the possible
8521 // width
8522 std::size_t idx = _string.find( ": " );
8523 if ( idx != std::string::npos && idx < CATCH_CONFIG_CONSOLE_WIDTH / 4 ) {
8524 idx += 2;
8525 } else {
8526 idx = 0;
8527 }
8528 m_stream << TextFlow::Column( _string )
8529 .indent( indent + idx )
8530 .initialIndent( indent )
8531 << '\n';
8532 }
8533
8534 struct SummaryColumn {
8535
8536 SummaryColumn( std::string _label, Colour::Code _colour )
8537 : label( CATCH_MOVE( _label ) ),
8538 colour( _colour ) {}
8539 SummaryColumn addRow( std::uint64_t count ) {
8540 ReusableStringStream rss;
8541 rss << count;
8542 std::string row = rss.str();
8543 for (auto& oldRow : rows) {
8544 while (oldRow.size() < row.size())
8545 oldRow = ' ' + oldRow;
8546 while (oldRow.size() > row.size())
8547 row = ' ' + row;
8548 }
8549 rows.push_back(row);
8550 return *this;
8551 }
8552
8553 std::string label;
8554 Colour::Code colour;
8555 std::vector<std::string> rows;
8556
8557 };
8558
8559 void ConsoleReporter::printTotals( Totals const& totals ) {
8560 if (totals.testCases.total() == 0) {
8561 m_stream << m_colour->guardColour( Colour::Warning )
8562 << "No tests ran\n";
8563 } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
8564 m_stream << m_colour->guardColour( Colour::ResultSuccess )
8565 << "All tests passed";
8566 m_stream << " ("
8567 << pluralise(totals.assertions.passed, "assertion"_sr) << " in "
8568 << pluralise(totals.testCases.passed, "test case"_sr) << ')'
8569 << '\n';
8570 } else {
8571
8572 std::vector<SummaryColumn> columns;
8573 columns.push_back(SummaryColumn("", Colour::None)
8574 .addRow(totals.testCases.total())
8575 .addRow(totals.assertions.total()));
8576 columns.push_back(SummaryColumn("passed", Colour::Success)
8577 .addRow(totals.testCases.passed)
8578 .addRow(totals.assertions.passed));
8579 columns.push_back(SummaryColumn("failed", Colour::ResultError)
8580 .addRow(totals.testCases.failed)
8581 .addRow(totals.assertions.failed));
8582 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
8583 .addRow(totals.testCases.failedButOk)
8584 .addRow(totals.assertions.failedButOk));
8585
8586 printSummaryRow("test cases"_sr, columns, 0);
8587 printSummaryRow("assertions"_sr, columns, 1);
8588 }
8589 }
8590 void ConsoleReporter::printSummaryRow(StringRef label, std::vector<SummaryColumn> const& cols, std::size_t row) {
8591 for (auto col : cols) {
8592 std::string const& value = col.rows[row];
8593 if (col.label.empty()) {
8594 m_stream << label << ": ";
8595 if ( value != "0" ) {
8596 m_stream << value;
8597 } else {
8598 m_stream << m_colour->guardColour( Colour::Warning )
8599 << "- none -";
8600 }
8601 } else if (value != "0") {
8602 m_stream << m_colour->guardColour( Colour::LightGrey ) << " | "
8603 << m_colour->guardColour( col.colour ) << value << ' '
8604 << col.label;
8605 }
8606 }
8607 m_stream << '\n';
8608 }
8609
8610 void ConsoleReporter::printTotalsDivider(Totals const& totals) {
8611 if (totals.testCases.total() > 0) {
8612 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
8613 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
8614 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
8615 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
8616 findMax(failedRatio, failedButOkRatio, passedRatio)++;
8617 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
8618 findMax(failedRatio, failedButOkRatio, passedRatio)--;
8619
8620 m_stream << m_colour->guardColour( Colour::Error )
8621 << std::string( failedRatio, '=' )
8622 << m_colour->guardColour( Colour::ResultExpectedFailure )
8623 << std::string( failedButOkRatio, '=' );
8624 if ( totals.testCases.allPassed() ) {
8625 m_stream << m_colour->guardColour( Colour::ResultSuccess )
8626 << std::string( passedRatio, '=' );
8627 } else {
8628 m_stream << m_colour->guardColour( Colour::Success )
8629 << std::string( passedRatio, '=' );
8630 }
8631 } else {
8632 m_stream << m_colour->guardColour( Colour::Warning )
8633 << std::string( CATCH_CONFIG_CONSOLE_WIDTH - 1, '=' );
8634 }
8635 m_stream << '\n';
8636 }
8637 void ConsoleReporter::printSummaryDivider() {
8638 m_stream << lineOfChars('-') << '\n';
8639 }
8640
8641 } // end namespace Catch
8642
8643 #if defined(_MSC_VER)
8644 #pragma warning(pop)
8645 #endif
8646
8647 #if defined(__clang__)
8648 # pragma clang diagnostic pop
8649 #endif
8650
8651
8652
8653
8654 #include <algorithm>
8655 #include <cassert>
8656
8657 namespace Catch {
8658 namespace {
8659 struct BySectionInfo {
8660 BySectionInfo( SectionInfo const& other ): m_other( other ) {}
8661 BySectionInfo( BySectionInfo const& other ):
8662 m_other( other.m_other ) {}
8663 bool operator()(
8664 Detail::unique_ptr<CumulativeReporterBase::SectionNode> const&
8665 node ) const {
8666 return (
8667 ( node->stats.sectionInfo.name == m_other.name ) &&
8668 ( node->stats.sectionInfo.lineInfo == m_other.lineInfo ) );
8669 }
8670 void operator=( BySectionInfo const& ) = delete;
8671
8672 private:
8673 SectionInfo const& m_other;
8674 };
8675
8676 } // namespace
8677
8678 namespace Detail {
8679 AssertionOrBenchmarkResult::AssertionOrBenchmarkResult(
8680 AssertionStats const& assertion ):
8681 m_assertion( assertion ) {}
8682
8683 AssertionOrBenchmarkResult::AssertionOrBenchmarkResult(
8684 BenchmarkStats<> const& benchmark ):
8685 m_benchmark( benchmark ) {}
8686
8687 bool AssertionOrBenchmarkResult::isAssertion() const {
8688 return m_assertion.some();
8689 }
8690 bool AssertionOrBenchmarkResult::isBenchmark() const {
8691 return m_benchmark.some();
8692 }
8693
8694 AssertionStats const& AssertionOrBenchmarkResult::asAssertion() const {
8695 assert(m_assertion.some());
8696
8697 return *m_assertion;
8698 }
8699 BenchmarkStats<> const& AssertionOrBenchmarkResult::asBenchmark() const {
8700 assert(m_benchmark.some());
8701
8702 return *m_benchmark;
8703 }
8704
8705 }
8706
8707 CumulativeReporterBase::~CumulativeReporterBase() = default;
8708
8709 void CumulativeReporterBase::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
8710 m_sectionStack.back()->assertionsAndBenchmarks.emplace_back(benchmarkStats);
8711 }
8712
8713 void
8714 CumulativeReporterBase::sectionStarting( SectionInfo const& sectionInfo ) {
8715 SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
8716 SectionNode* node;
8717 if ( m_sectionStack.empty() ) {
8718 if ( !m_rootSection ) {
8719 m_rootSection =
8720 Detail::make_unique<SectionNode>( incompleteStats );
8721 }
8722 node = m_rootSection.get();
8723 } else {
8724 SectionNode& parentNode = *m_sectionStack.back();
8725 auto it = std::find_if( parentNode.childSections.begin(),
8726 parentNode.childSections.end(),
8727 BySectionInfo( sectionInfo ) );
8728 if ( it == parentNode.childSections.end() ) {
8729 auto newNode =
8730 Detail::make_unique<SectionNode>( incompleteStats );
8731 node = newNode.get();
8732 parentNode.childSections.push_back( CATCH_MOVE( newNode ) );
8733 } else {
8734 node = it->get();
8735 }
8736 }
8737
8738 m_deepestSection = node;
8739 m_sectionStack.push_back( node );
8740 }
8741
8742 void CumulativeReporterBase::assertionEnded(
8743 AssertionStats const& assertionStats ) {
8744 assert( !m_sectionStack.empty() );
8745 // AssertionResult holds a pointer to a temporary DecomposedExpression,
8746 // which getExpandedExpression() calls to build the expression string.
8747 // Our section stack copy of the assertionResult will likely outlive the
8748 // temporary, so it must be expanded or discarded now to avoid calling
8749 // a destroyed object later.
8750 if ( m_shouldStoreFailedAssertions &&
8751 !assertionStats.assertionResult.isOk() ) {
8752 static_cast<void>(
8753 assertionStats.assertionResult.getExpandedExpression() );
8754 }
8755 if ( m_shouldStoreSuccesfulAssertions &&
8756 assertionStats.assertionResult.isOk() ) {
8757 static_cast<void>(
8758 assertionStats.assertionResult.getExpandedExpression() );
8759 }
8760 SectionNode& sectionNode = *m_sectionStack.back();
8761 sectionNode.assertionsAndBenchmarks.emplace_back( assertionStats );
8762 }
8763
8764 void CumulativeReporterBase::sectionEnded( SectionStats const& sectionStats ) {
8765 assert( !m_sectionStack.empty() );
8766 SectionNode& node = *m_sectionStack.back();
8767 node.stats = sectionStats;
8768 m_sectionStack.pop_back();
8769 }
8770
8771 void CumulativeReporterBase::testCaseEnded(
8772 TestCaseStats const& testCaseStats ) {
8773 auto node = Detail::make_unique<TestCaseNode>( testCaseStats );
8774 assert( m_sectionStack.size() == 0 );
8775 node->children.push_back( CATCH_MOVE(m_rootSection) );
8776 m_testCases.push_back( CATCH_MOVE(node) );
8777
8778 assert( m_deepestSection );
8779 m_deepestSection->stdOut = testCaseStats.stdOut;
8780 m_deepestSection->stdErr = testCaseStats.stdErr;
8781 }
8782
8783
8784 void CumulativeReporterBase::testRunEnded( TestRunStats const& testRunStats ) {
8785 assert(!m_testRun && "CumulativeReporterBase assumes there can only be one test run");
8786 m_testRun = Detail::make_unique<TestRunNode>( testRunStats );
8787 m_testRun->children.swap( m_testCases );
8788 testRunEndedCumulative();
8789 }
8790
8791 bool CumulativeReporterBase::SectionNode::hasAnyAssertions() const {
8792 return std::any_of(
8793 assertionsAndBenchmarks.begin(),
8794 assertionsAndBenchmarks.end(),
8795 []( Detail::AssertionOrBenchmarkResult const& res ) {
8796 return res.isAssertion();
8797 } );
8798 }
8799
8800 } // end namespace Catch
8801
8802
8803
8804
8805 namespace Catch {
8806
8807 void EventListenerBase::fatalErrorEncountered( StringRef ) {}
8808
8809 void EventListenerBase::benchmarkPreparing( StringRef ) {}
8810 void EventListenerBase::benchmarkStarting( BenchmarkInfo const& ) {}
8811 void EventListenerBase::benchmarkEnded( BenchmarkStats<> const& ) {}
8812 void EventListenerBase::benchmarkFailed( StringRef ) {}
8813
8814 void EventListenerBase::assertionStarting( AssertionInfo const& ) {}
8815
8816 void EventListenerBase::assertionEnded( AssertionStats const& ) {}
8817 void EventListenerBase::listReporters(
8818 std::vector<ReporterDescription> const& ) {}
8819 void EventListenerBase::listListeners(
8820 std::vector<ListenerDescription> const& ) {}
8821 void EventListenerBase::listTests( std::vector<TestCaseHandle> const& ) {}
8822 void EventListenerBase::listTags( std::vector<TagInfo> const& ) {}
8823 void EventListenerBase::noMatchingTestCases( StringRef ) {}
8824 void EventListenerBase::reportInvalidTestSpec( StringRef ) {}
8825 void EventListenerBase::testRunStarting( TestRunInfo const& ) {}
8826 void EventListenerBase::testCaseStarting( TestCaseInfo const& ) {}
8827 void EventListenerBase::testCasePartialStarting(TestCaseInfo const&, uint64_t) {}
8828 void EventListenerBase::sectionStarting( SectionInfo const& ) {}
8829 void EventListenerBase::sectionEnded( SectionStats const& ) {}
8830 void EventListenerBase::testCasePartialEnded(TestCaseStats const&, uint64_t) {}
8831 void EventListenerBase::testCaseEnded( TestCaseStats const& ) {}
8832 void EventListenerBase::testRunEnded( TestRunStats const& ) {}
8833 void EventListenerBase::skipTest( TestCaseInfo const& ) {}
8834 } // namespace Catch
8835
8836
8837
8838
8839 #include <algorithm>
8840 #include <cfloat>
8841 #include <cstdio>
8842 #include <ostream>
8843 #include <iomanip>
8844
8845 namespace Catch {
8846
8847 namespace {
8848 void listTestNamesOnly(std::ostream& out,
8849 std::vector<TestCaseHandle> const& tests) {
8850 for (auto const& test : tests) {
8851 auto const& testCaseInfo = test.getTestCaseInfo();
8852
8853 if (startsWith(testCaseInfo.name, '#')) {
8854 out << '"' << testCaseInfo.name << '"';
8855 } else {
8856 out << testCaseInfo.name;
8857 }
8858
8859 out << '\n';
8860 }
8861 out << std::flush;
8862 }
8863 } // end unnamed namespace
8864
8865
8866 // Because formatting using c++ streams is stateful, drop down to C is
8867 // required Alternatively we could use stringstream, but its performance
8868 // is... not good.
8869 std::string getFormattedDuration( double duration ) {
8870 // Max exponent + 1 is required to represent the whole part
8871 // + 1 for decimal point
8872 // + 3 for the 3 decimal places
8873 // + 1 for null terminator
8874 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
8875 char buffer[maxDoubleSize];
8876
8877 // Save previous errno, to prevent sprintf from overwriting it
8878 ErrnoGuard guard;
8879 #ifdef _MSC_VER
8880 size_t printedLength = static_cast<size_t>(
8881 sprintf_s( buffer, "%.3f", duration ) );
8882 #else
8883 size_t printedLength = static_cast<size_t>(
8884 std::snprintf( buffer, maxDoubleSize, "%.3f", duration ) );
8885 #endif
8886 return std::string( buffer, printedLength );
8887 }
8888
8889 bool shouldShowDuration( IConfig const& config, double duration ) {
8890 if ( config.showDurations() == ShowDurations::Always ) {
8891 return true;
8892 }
8893 if ( config.showDurations() == ShowDurations::Never ) {
8894 return false;
8895 }
8896 const double min = config.minDuration();
8897 return min >= 0 && duration >= min;
8898 }
8899
8900 std::string serializeFilters( std::vector<std::string> const& filters ) {
8901 // We add a ' ' separator between each filter
8902 size_t serialized_size = filters.size() - 1;
8903 for (auto const& filter : filters) {
8904 serialized_size += filter.size();
8905 }
8906
8907 std::string serialized;
8908 serialized.reserve(serialized_size);
8909 bool first = true;
8910
8911 for (auto const& filter : filters) {
8912 if (!first) {
8913 serialized.push_back(' ');
8914 }
8915 first = false;
8916 serialized.append(filter);
8917 }
8918
8919 return serialized;
8920 }
8921
8922 std::ostream& operator<<( std::ostream& out, lineOfChars value ) {
8923 for ( size_t idx = 0; idx < CATCH_CONFIG_CONSOLE_WIDTH - 1; ++idx ) {
8924 out.put( value.c );
8925 }
8926 return out;
8927 }
8928
8929 void
8930 defaultListReporters( std::ostream& out,
8931 std::vector<ReporterDescription> const& descriptions,
8932 Verbosity verbosity ) {
8933 out << "Available reporters:\n";
8934 const auto maxNameLen =
8935 std::max_element( descriptions.begin(),
8936 descriptions.end(),
8937 []( ReporterDescription const& lhs,
8938 ReporterDescription const& rhs ) {
8939 return lhs.name.size() < rhs.name.size();
8940 } )
8941 ->name.size();
8942
8943 for ( auto const& desc : descriptions ) {
8944 if ( verbosity == Verbosity::Quiet ) {
8945 out << TextFlow::Column( desc.name )
8946 .indent( 2 )
8947 .width( 5 + maxNameLen )
8948 << '\n';
8949 } else {
8950 out << TextFlow::Column( desc.name + ':' )
8951 .indent( 2 )
8952 .width( 5 + maxNameLen ) +
8953 TextFlow::Column( desc.description )
8954 .initialIndent( 0 )
8955 .indent( 2 )
8956 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 )
8957 << '\n';
8958 }
8959 }
8960 out << '\n' << std::flush;
8961 }
8962
8963 void defaultListListeners( std::ostream& out,
8964 std::vector<ListenerDescription> const& descriptions ) {
8965 out << "Registered listeners:\n";
8966
8967 if(descriptions.empty()) {
8968 return;
8969 }
8970
8971 const auto maxNameLen =
8972 std::max_element( descriptions.begin(),
8973 descriptions.end(),
8974 []( ListenerDescription const& lhs,
8975 ListenerDescription const& rhs ) {
8976 return lhs.name.size() < rhs.name.size();
8977 } )
8978 ->name.size();
8979
8980 for ( auto const& desc : descriptions ) {
8981 out << TextFlow::Column( static_cast<std::string>( desc.name ) +
8982 ':' )
8983 .indent( 2 )
8984 .width( maxNameLen + 5 ) +
8985 TextFlow::Column( desc.description )
8986 .initialIndent( 0 )
8987 .indent( 2 )
8988 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 )
8989 << '\n';
8990 }
8991
8992 out << '\n' << std::flush;
8993 }
8994
8995 void defaultListTags( std::ostream& out,
8996 std::vector<TagInfo> const& tags,
8997 bool isFiltered ) {
8998 if ( isFiltered ) {
8999 out << "Tags for matching test cases:\n";
9000 } else {
9001 out << "All available tags:\n";
9002 }
9003
9004 for ( auto const& tagCount : tags ) {
9005 ReusableStringStream rss;
9006 rss << " " << std::setw( 2 ) << tagCount.count << " ";
9007 auto str = rss.str();
9008 auto wrapper = TextFlow::Column( tagCount.all() )
9009 .initialIndent( 0 )
9010 .indent( str.size() )
9011 .width( CATCH_CONFIG_CONSOLE_WIDTH - 10 );
9012 out << str << wrapper << '\n';
9013 }
9014 out << pluralise(tags.size(), "tag"_sr) << "\n\n" << std::flush;
9015 }
9016
9017 void defaultListTests(std::ostream& out, ColourImpl* streamColour, std::vector<TestCaseHandle> const& tests, bool isFiltered, Verbosity verbosity) {
9018 // We special case this to provide the equivalent of old
9019 // `--list-test-names-only`, which could then be used by the
9020 // `--input-file` option.
9021 if (verbosity == Verbosity::Quiet) {
9022 listTestNamesOnly(out, tests);
9023 return;
9024 }
9025
9026 if (isFiltered) {
9027 out << "Matching test cases:\n";
9028 } else {
9029 out << "All available test cases:\n";
9030 }
9031
9032 for (auto const& test : tests) {
9033 auto const& testCaseInfo = test.getTestCaseInfo();
9034 Colour::Code colour = testCaseInfo.isHidden()
9035 ? Colour::SecondaryText
9036 : Colour::None;
9037 auto colourGuard = streamColour->guardColour( colour ).engage( out );
9038
9039 out << TextFlow::Column(testCaseInfo.name).indent(2) << '\n';
9040 if (verbosity >= Verbosity::High) {
9041 out << TextFlow::Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4) << '\n';
9042 }
9043 if (!testCaseInfo.tags.empty() &&
9044 verbosity > Verbosity::Quiet) {
9045 out << TextFlow::Column(testCaseInfo.tagsAsString()).indent(6) << '\n';
9046 }
9047 }
9048
9049 if (isFiltered) {
9050 out << pluralise(tests.size(), "matching test case"_sr);
9051 } else {
9052 out << pluralise(tests.size(), "test case"_sr);
9053 }
9054 out << "\n\n" << std::flush;
9055 }
9056
9057 } // namespace Catch
9058
9059
9060
9061
9062 #include <cassert>
9063 #include <ctime>
9064 #include <algorithm>
9065 #include <iomanip>
9066
9067 namespace Catch {
9068
9069 namespace {
9070 std::string getCurrentTimestamp() {
9071 time_t rawtime;
9072 std::time(&rawtime);
9073
9074 std::tm timeInfo = {};
9075 #if defined (_MSC_VER) || defined (__MINGW32__)
9076 gmtime_s(&timeInfo, &rawtime);
9077 #else
9078 gmtime_r(&rawtime, &timeInfo);
9079 #endif
9080
9081 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
9082 char timeStamp[timeStampSize];
9083 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
9084
9085 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
9086
9087 return std::string(timeStamp, timeStampSize - 1);
9088 }
9089
9090 std::string fileNameTag(std::vector<Tag> const& tags) {
9091 auto it = std::find_if(begin(tags),
9092 end(tags),
9093 [] (Tag const& tag) {
9094 return tag.original.size() > 0
9095 && tag.original[0] == '#'; });
9096 if (it != tags.end()) {
9097 return static_cast<std::string>(
9098 it->original.substr(1, it->original.size() - 1)
9099 );
9100 }
9101 return std::string();
9102 }
9103
9104 // Formats the duration in seconds to 3 decimal places.
9105 // This is done because some genius defined Maven Surefire schema
9106 // in a way that only accepts 3 decimal places, and tools like
9107 // Jenkins use that schema for validation JUnit reporter output.
9108 std::string formatDuration( double seconds ) {
9109 ReusableStringStream rss;
9110 rss << std::fixed << std::setprecision( 3 ) << seconds;
9111 return rss.str();
9112 }
9113
9114 static void normalizeNamespaceMarkers(std::string& str) {
9115 std::size_t pos = str.find( "::" );
9116 while ( pos != str.npos ) {
9117 str.replace( pos, 2, "." );
9118 pos += 1;
9119 pos = str.find( "::", pos );
9120 }
9121 }
9122
9123 } // anonymous namespace
9124
9125 JunitReporter::JunitReporter( ReporterConfig&& _config )
9126 : CumulativeReporterBase( CATCH_MOVE(_config) ),
9127 xml( m_stream )
9128 {
9129 m_preferences.shouldRedirectStdOut = true;
9130 m_preferences.shouldReportAllAssertions = true;
9131 m_shouldStoreSuccesfulAssertions = false;
9132 }
9133
9134 std::string JunitReporter::getDescription() {
9135 return "Reports test results in an XML format that looks like Ant's junitreport target";
9136 }
9137
9138 void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
9139 CumulativeReporterBase::testRunStarting( runInfo );
9140 xml.startElement( "testsuites" );
9141 suiteTimer.start();
9142 stdOutForSuite.clear();
9143 stdErrForSuite.clear();
9144 unexpectedExceptions = 0;
9145 }
9146
9147 void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
9148 m_okToFail = testCaseInfo.okToFail();
9149 }
9150
9151 void JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
9152 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
9153 unexpectedExceptions++;
9154 CumulativeReporterBase::assertionEnded( assertionStats );
9155 }
9156
9157 void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
9158 stdOutForSuite += testCaseStats.stdOut;
9159 stdErrForSuite += testCaseStats.stdErr;
9160 CumulativeReporterBase::testCaseEnded( testCaseStats );
9161 }
9162
9163 void JunitReporter::testRunEndedCumulative() {
9164 const auto suiteTime = suiteTimer.getElapsedSeconds();
9165 writeRun( *m_testRun, suiteTime );
9166 xml.endElement();
9167 }
9168
9169 void JunitReporter::writeRun( TestRunNode const& testRunNode, double suiteTime ) {
9170 XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
9171
9172 TestRunStats const& stats = testRunNode.value;
9173 xml.writeAttribute( "name"_sr, stats.runInfo.name );
9174 xml.writeAttribute( "errors"_sr, unexpectedExceptions );
9175 xml.writeAttribute( "failures"_sr, stats.totals.assertions.failed-unexpectedExceptions );
9176 xml.writeAttribute( "tests"_sr, stats.totals.assertions.total() );
9177 xml.writeAttribute( "hostname"_sr, "tbd"_sr ); // !TBD
9178 if( m_config->showDurations() == ShowDurations::Never )
9179 xml.writeAttribute( "time"_sr, ""_sr );
9180 else
9181 xml.writeAttribute( "time"_sr, formatDuration( suiteTime ) );
9182 xml.writeAttribute( "timestamp"_sr, getCurrentTimestamp() );
9183
9184 // Write properties
9185 {
9186 auto properties = xml.scopedElement("properties");
9187 xml.scopedElement("property")
9188 .writeAttribute("name"_sr, "random-seed"_sr)
9189 .writeAttribute("value"_sr, m_config->rngSeed());
9190 if (m_config->hasTestFilters()) {
9191 xml.scopedElement("property")
9192 .writeAttribute("name"_sr, "filters"_sr)
9193 .writeAttribute("value"_sr, serializeFilters(m_config->getTestsOrTags()));
9194 }
9195 }
9196
9197 // Write test cases
9198 for( auto const& child : testRunNode.children )
9199 writeTestCase( *child );
9200
9201 xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
9202 xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
9203 }
9204
9205 void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
9206 TestCaseStats const& stats = testCaseNode.value;
9207
9208 // All test cases have exactly one section - which represents the
9209 // test case itself. That section may have 0-n nested sections
9210 assert( testCaseNode.children.size() == 1 );
9211 SectionNode const& rootSection = *testCaseNode.children.front();
9212
9213 std::string className =
9214 static_cast<std::string>( stats.testInfo->className );
9215
9216 if( className.empty() ) {
9217 className = fileNameTag(stats.testInfo->tags);
9218 if ( className.empty() ) {
9219 className = "global";
9220 }
9221 }
9222
9223 if ( !m_config->name().empty() )
9224 className = static_cast<std::string>(m_config->name()) + '.' + className;
9225
9226 normalizeNamespaceMarkers(className);
9227
9228 writeSection( className, "", rootSection, stats.testInfo->okToFail() );
9229 }
9230
9231 void JunitReporter::writeSection( std::string const& className,
9232 std::string const& rootName,
9233 SectionNode const& sectionNode,
9234 bool testOkToFail) {
9235 std::string name = trim( sectionNode.stats.sectionInfo.name );
9236 if( !rootName.empty() )
9237 name = rootName + '/' + name;
9238
9239 if( sectionNode.hasAnyAssertions()
9240 || !sectionNode.stdOut.empty()
9241 || !sectionNode.stdErr.empty() ) {
9242 XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
9243 if( className.empty() ) {
9244 xml.writeAttribute( "classname"_sr, name );
9245 xml.writeAttribute( "name"_sr, "root"_sr );
9246 }
9247 else {
9248 xml.writeAttribute( "classname"_sr, className );
9249 xml.writeAttribute( "name"_sr, name );
9250 }
9251 xml.writeAttribute( "time"_sr, formatDuration( sectionNode.stats.durationInSeconds ) );
9252 // This is not ideal, but it should be enough to mimic gtest's
9253 // junit output.
9254 // Ideally the JUnit reporter would also handle `skipTest`
9255 // events and write those out appropriately.
9256 xml.writeAttribute( "status"_sr, "run"_sr );
9257
9258 if (sectionNode.stats.assertions.failedButOk) {
9259 xml.scopedElement("skipped")
9260 .writeAttribute("message", "TEST_CASE tagged with !mayfail");
9261 }
9262
9263 writeAssertions( sectionNode );
9264
9265
9266 if( !sectionNode.stdOut.empty() )
9267 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
9268 if( !sectionNode.stdErr.empty() )
9269 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
9270 }
9271 for( auto const& childNode : sectionNode.childSections )
9272 if( className.empty() )
9273 writeSection( name, "", *childNode, testOkToFail );
9274 else
9275 writeSection( className, name, *childNode, testOkToFail );
9276 }
9277
9278 void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
9279 for (auto const& assertionOrBenchmark : sectionNode.assertionsAndBenchmarks) {
9280 if (assertionOrBenchmark.isAssertion()) {
9281 writeAssertion(assertionOrBenchmark.asAssertion());
9282 }
9283 }
9284 }
9285
9286 void JunitReporter::writeAssertion( AssertionStats const& stats ) {
9287 AssertionResult const& result = stats.assertionResult;
9288 if( !result.isOk() ) {
9289 std::string elementName;
9290 switch( result.getResultType() ) {
9291 case ResultWas::ThrewException:
9292 case ResultWas::FatalErrorCondition:
9293 elementName = "error";
9294 break;
9295 case ResultWas::ExplicitFailure:
9296 case ResultWas::ExpressionFailed:
9297 case ResultWas::DidntThrowException:
9298 elementName = "failure";
9299 break;
9300
9301 // We should never see these here:
9302 case ResultWas::Info:
9303 case ResultWas::Warning:
9304 case ResultWas::Ok:
9305 case ResultWas::Unknown:
9306 case ResultWas::FailureBit:
9307 case ResultWas::Exception:
9308 elementName = "internalError";
9309 break;
9310 }
9311
9312 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
9313
9314 xml.writeAttribute( "message"_sr, result.getExpression() );
9315 xml.writeAttribute( "type"_sr, result.getTestMacroName() );
9316
9317 ReusableStringStream rss;
9318 if (stats.totals.assertions.total() > 0) {
9319 rss << "FAILED" << ":\n";
9320 if (result.hasExpression()) {
9321 rss << " ";
9322 rss << result.getExpressionInMacro();
9323 rss << '\n';
9324 }
9325 if (result.hasExpandedExpression()) {
9326 rss << "with expansion:\n";
9327 rss << TextFlow::Column(result.getExpandedExpression()).indent(2) << '\n';
9328 }
9329 } else {
9330 rss << '\n';
9331 }
9332
9333 if( !result.getMessage().empty() )
9334 rss << result.getMessage() << '\n';
9335 for( auto const& msg : stats.infoMessages )
9336 if( msg.type == ResultWas::Info )
9337 rss << msg.message << '\n';
9338
9339 rss << "at " << result.getSourceInfo();
9340 xml.writeText( rss.str(), XmlFormatting::Newline );
9341 }
9342 }
9343
9344 } // end namespace Catch
9345
9346
9347
9348
9349 #include <ostream>
9350
9351 namespace Catch {
9352 void MultiReporter::updatePreferences(IEventListener const& reporterish) {
9353 m_preferences.shouldRedirectStdOut |=
9354 reporterish.getPreferences().shouldRedirectStdOut;
9355 m_preferences.shouldReportAllAssertions |=
9356 reporterish.getPreferences().shouldReportAllAssertions;
9357 }
9358
9359 void MultiReporter::addListener( IEventListenerPtr&& listener ) {
9360 updatePreferences(*listener);
9361 m_reporterLikes.insert(m_reporterLikes.begin() + m_insertedListeners, CATCH_MOVE(listener) );
9362 ++m_insertedListeners;
9363 }
9364
9365 void MultiReporter::addReporter( IEventListenerPtr&& reporter ) {
9366 updatePreferences(*reporter);
9367
9368 // We will need to output the captured stdout if there are reporters
9369 // that do not want it captured.
9370 // We do not consider listeners, because it is generally assumed that
9371 // listeners are output-transparent, even though they can ask for stdout
9372 // capture to do something with it.
9373 m_haveNoncapturingReporters |= !reporter->getPreferences().shouldRedirectStdOut;
9374
9375 // Reporters can always be placed to the back without breaking the
9376 // reporting order
9377 m_reporterLikes.push_back( CATCH_MOVE( reporter ) );
9378 }
9379
9380 void MultiReporter::noMatchingTestCases( StringRef unmatchedSpec ) {
9381 for ( auto& reporterish : m_reporterLikes ) {
9382 reporterish->noMatchingTestCases( unmatchedSpec );
9383 }
9384 }
9385
9386 void MultiReporter::fatalErrorEncountered( StringRef error ) {
9387 for ( auto& reporterish : m_reporterLikes ) {
9388 reporterish->fatalErrorEncountered( error );
9389 }
9390 }
9391
9392 void MultiReporter::reportInvalidTestSpec( StringRef arg ) {
9393 for ( auto& reporterish : m_reporterLikes ) {
9394 reporterish->reportInvalidTestSpec( arg );
9395 }
9396 }
9397
9398 void MultiReporter::benchmarkPreparing( StringRef name ) {
9399 for (auto& reporterish : m_reporterLikes) {
9400 reporterish->benchmarkPreparing(name);
9401 }
9402 }
9403 void MultiReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
9404 for ( auto& reporterish : m_reporterLikes ) {
9405 reporterish->benchmarkStarting( benchmarkInfo );
9406 }
9407 }
9408 void MultiReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
9409 for ( auto& reporterish : m_reporterLikes ) {
9410 reporterish->benchmarkEnded( benchmarkStats );
9411 }
9412 }
9413
9414 void MultiReporter::benchmarkFailed( StringRef error ) {
9415 for (auto& reporterish : m_reporterLikes) {
9416 reporterish->benchmarkFailed(error);
9417 }
9418 }
9419
9420 void MultiReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
9421 for ( auto& reporterish : m_reporterLikes ) {
9422 reporterish->testRunStarting( testRunInfo );
9423 }
9424 }
9425
9426 void MultiReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
9427 for ( auto& reporterish : m_reporterLikes ) {
9428 reporterish->testCaseStarting( testInfo );
9429 }
9430 }
9431
9432 void
9433 MultiReporter::testCasePartialStarting( TestCaseInfo const& testInfo,
9434 uint64_t partNumber ) {
9435 for ( auto& reporterish : m_reporterLikes ) {
9436 reporterish->testCasePartialStarting( testInfo, partNumber );
9437 }
9438 }
9439
9440 void MultiReporter::sectionStarting( SectionInfo const& sectionInfo ) {
9441 for ( auto& reporterish : m_reporterLikes ) {
9442 reporterish->sectionStarting( sectionInfo );
9443 }
9444 }
9445
9446 void MultiReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
9447 for ( auto& reporterish : m_reporterLikes ) {
9448 reporterish->assertionStarting( assertionInfo );
9449 }
9450 }
9451
9452 // The return value indicates if the messages buffer should be cleared:
9453 void MultiReporter::assertionEnded( AssertionStats const& assertionStats ) {
9454 const bool reportByDefault =
9455 assertionStats.assertionResult.getResultType() != ResultWas::Ok ||
9456 m_config->includeSuccessfulResults();
9457
9458 for ( auto & reporterish : m_reporterLikes ) {
9459 if ( reportByDefault ||
9460 reporterish->getPreferences().shouldReportAllAssertions ) {
9461 reporterish->assertionEnded( assertionStats );
9462 }
9463 }
9464 }
9465
9466 void MultiReporter::sectionEnded( SectionStats const& sectionStats ) {
9467 for ( auto& reporterish : m_reporterLikes ) {
9468 reporterish->sectionEnded( sectionStats );
9469 }
9470 }
9471
9472 void MultiReporter::testCasePartialEnded( TestCaseStats const& testStats,
9473 uint64_t partNumber ) {
9474 if ( m_preferences.shouldRedirectStdOut &&
9475 m_haveNoncapturingReporters ) {
9476 if ( !testStats.stdOut.empty() ) {
9477 Catch::cout() << testStats.stdOut << std::flush;
9478 }
9479 if ( !testStats.stdErr.empty() ) {
9480 Catch::cerr() << testStats.stdErr << std::flush;
9481 }
9482 }
9483
9484 for ( auto& reporterish : m_reporterLikes ) {
9485 reporterish->testCasePartialEnded( testStats, partNumber );
9486 }
9487 }
9488
9489 void MultiReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
9490 for ( auto& reporterish : m_reporterLikes ) {
9491 reporterish->testCaseEnded( testCaseStats );
9492 }
9493 }
9494
9495 void MultiReporter::testRunEnded( TestRunStats const& testRunStats ) {
9496 for ( auto& reporterish : m_reporterLikes ) {
9497 reporterish->testRunEnded( testRunStats );
9498 }
9499 }
9500
9501
9502 void MultiReporter::skipTest( TestCaseInfo const& testInfo ) {
9503 for ( auto& reporterish : m_reporterLikes ) {
9504 reporterish->skipTest( testInfo );
9505 }
9506 }
9507
9508 void MultiReporter::listReporters(std::vector<ReporterDescription> const& descriptions) {
9509 for (auto& reporterish : m_reporterLikes) {
9510 reporterish->listReporters(descriptions);
9511 }
9512 }
9513
9514 void MultiReporter::listListeners(
9515 std::vector<ListenerDescription> const& descriptions ) {
9516 for ( auto& reporterish : m_reporterLikes ) {
9517 reporterish->listListeners( descriptions );
9518 }
9519 }
9520
9521 void MultiReporter::listTests(std::vector<TestCaseHandle> const& tests) {
9522 for (auto& reporterish : m_reporterLikes) {
9523 reporterish->listTests(tests);
9524 }
9525 }
9526
9527 void MultiReporter::listTags(std::vector<TagInfo> const& tags) {
9528 for (auto& reporterish : m_reporterLikes) {
9529 reporterish->listTags(tags);
9530 }
9531 }
9532
9533 } // end namespace Catch
9534
9535
9536
9537
9538
9539 namespace Catch {
9540 namespace Detail {
9541
9542 void registerReporterImpl( std::string const& name,
9543 IReporterFactoryPtr reporterPtr ) {
9544 CATCH_TRY {
9545 getMutableRegistryHub().registerReporter(
9546 name, CATCH_MOVE( reporterPtr ) );
9547 }
9548 CATCH_CATCH_ALL {
9549 // Do not throw when constructing global objects, instead
9550 // register the exception to be processed later
9551 getMutableRegistryHub().registerStartupException();
9552 }
9553 }
9554
9555 } // namespace Detail
9556 } // namespace Catch
9557
9558
9559
9560
9561 #include <map>
9562
9563 namespace Catch {
9564
9565 namespace {
9566 std::string createRngSeedString(uint32_t seed) {
9567 ReusableStringStream sstr;
9568 sstr << "rng-seed=" << seed;
9569 return sstr.str();
9570 }
9571 }
9572
9573 void SonarQubeReporter::testRunStarting(TestRunInfo const& testRunInfo) {
9574 CumulativeReporterBase::testRunStarting(testRunInfo);
9575
9576 xml.writeComment( createRngSeedString( m_config->rngSeed() ) );
9577 xml.startElement("testExecutions");
9578 xml.writeAttribute("version"_sr, '1');
9579 }
9580
9581 void SonarQubeReporter::writeRun( TestRunNode const& runNode ) {
9582 std::map<std::string, std::vector<TestCaseNode const*>> testsPerFile;
9583
9584 for ( auto const& child : runNode.children ) {
9585 testsPerFile[child->value.testInfo->lineInfo.file].push_back(
9586 child.get() );
9587 }
9588
9589 for ( auto const& kv : testsPerFile ) {
9590 writeTestFile( kv.first, kv.second );
9591 }
9592 }
9593
9594 void SonarQubeReporter::writeTestFile(std::string const& filename, std::vector<TestCaseNode const*> const& testCaseNodes) {
9595 XmlWriter::ScopedElement e = xml.scopedElement("file");
9596 xml.writeAttribute("path"_sr, filename);
9597
9598 for (auto const& child : testCaseNodes)
9599 writeTestCase(*child);
9600 }
9601
9602 void SonarQubeReporter::writeTestCase(TestCaseNode const& testCaseNode) {
9603 // All test cases have exactly one section - which represents the
9604 // test case itself. That section may have 0-n nested sections
9605 assert(testCaseNode.children.size() == 1);
9606 SectionNode const& rootSection = *testCaseNode.children.front();
9607 writeSection("", rootSection, testCaseNode.value.testInfo->okToFail());
9608 }
9609
9610 void SonarQubeReporter::writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail) {
9611 std::string name = trim(sectionNode.stats.sectionInfo.name);
9612 if (!rootName.empty())
9613 name = rootName + '/' + name;
9614
9615 if ( sectionNode.hasAnyAssertions()
9616 || !sectionNode.stdOut.empty()
9617 || !sectionNode.stdErr.empty() ) {
9618 XmlWriter::ScopedElement e = xml.scopedElement("testCase");
9619 xml.writeAttribute("name"_sr, name);
9620 xml.writeAttribute("duration"_sr, static_cast<long>(sectionNode.stats.durationInSeconds * 1000));
9621
9622 writeAssertions(sectionNode, okToFail);
9623 }
9624
9625 for (auto const& childNode : sectionNode.childSections)
9626 writeSection(name, *childNode, okToFail);
9627 }
9628
9629 void SonarQubeReporter::writeAssertions(SectionNode const& sectionNode, bool okToFail) {
9630 for (auto const& assertionOrBenchmark : sectionNode.assertionsAndBenchmarks) {
9631 if (assertionOrBenchmark.isAssertion()) {
9632 writeAssertion(assertionOrBenchmark.asAssertion(), okToFail);
9633 }
9634 }
9635 }
9636
9637 void SonarQubeReporter::writeAssertion(AssertionStats const& stats, bool okToFail) {
9638 AssertionResult const& result = stats.assertionResult;
9639 if (!result.isOk()) {
9640 std::string elementName;
9641 if (okToFail) {
9642 elementName = "skipped";
9643 } else {
9644 switch (result.getResultType()) {
9645 case ResultWas::ThrewException:
9646 case ResultWas::FatalErrorCondition:
9647 elementName = "error";
9648 break;
9649 case ResultWas::ExplicitFailure:
9650 elementName = "failure";
9651 break;
9652 case ResultWas::ExpressionFailed:
9653 elementName = "failure";
9654 break;
9655 case ResultWas::DidntThrowException:
9656 elementName = "failure";
9657 break;
9658
9659 // We should never see these here:
9660 case ResultWas::Info:
9661 case ResultWas::Warning:
9662 case ResultWas::Ok:
9663 case ResultWas::Unknown:
9664 case ResultWas::FailureBit:
9665 case ResultWas::Exception:
9666 elementName = "internalError";
9667 break;
9668 }
9669 }
9670
9671 XmlWriter::ScopedElement e = xml.scopedElement(elementName);
9672
9673 ReusableStringStream messageRss;
9674 messageRss << result.getTestMacroName() << '(' << result.getExpression() << ')';
9675 xml.writeAttribute("message"_sr, messageRss.str());
9676
9677 ReusableStringStream textRss;
9678 if (stats.totals.assertions.total() > 0) {
9679 textRss << "FAILED:\n";
9680 if (result.hasExpression()) {
9681 textRss << '\t' << result.getExpressionInMacro() << '\n';
9682 }
9683 if (result.hasExpandedExpression()) {
9684 textRss << "with expansion:\n\t" << result.getExpandedExpression() << '\n';
9685 }
9686 }
9687
9688 if (!result.getMessage().empty())
9689 textRss << result.getMessage() << '\n';
9690
9691 for (auto const& msg : stats.infoMessages)
9692 if (msg.type == ResultWas::Info)
9693 textRss << msg.message << '\n';
9694
9695 textRss << "at " << result.getSourceInfo();
9696 xml.writeText(textRss.str(), XmlFormatting::Newline);
9697 }
9698 }
9699
9700 } // end namespace Catch
9701
9702
9703
9704 namespace Catch {
9705
9706 StreamingReporterBase::~StreamingReporterBase() = default;
9707
9708 void
9709 StreamingReporterBase::testRunStarting( TestRunInfo const& _testRunInfo ) {
9710 currentTestRunInfo = _testRunInfo;
9711 }
9712
9713 void StreamingReporterBase::testRunEnded( TestRunStats const& ) {
9714 currentTestCaseInfo = nullptr;
9715 }
9716
9717 } // end namespace Catch
9718
9719
9720
9721 #include <algorithm>
9722 #include <iterator>
9723 #include <ostream>
9724
9725 namespace Catch {
9726
9727 namespace {
9728 // Yes, this has to be outside the class and namespaced by naming.
9729 // Making older compiler happy is hard.
9730 static constexpr StringRef tapFailedString = "not ok"_sr;
9731 static constexpr StringRef tapPassedString = "ok"_sr;
9732 static constexpr Colour::Code tapDimColour = Colour::FileName;
9733
9734 class TapAssertionPrinter {
9735 public:
9736 TapAssertionPrinter& operator= (TapAssertionPrinter const&) = delete;
9737 TapAssertionPrinter(TapAssertionPrinter const&) = delete;
9738 TapAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter, ColourImpl* colour_)
9739 : stream(_stream)
9740 , result(_stats.assertionResult)
9741 , messages(_stats.infoMessages)
9742 , itMessage(_stats.infoMessages.begin())
9743 , printInfoMessages(true)
9744 , counter(_counter)
9745 , colourImpl( colour_ ) {}
9746
9747 void print() {
9748 itMessage = messages.begin();
9749
9750 switch (result.getResultType()) {
9751 case ResultWas::Ok:
9752 printResultType(tapPassedString);
9753 printOriginalExpression();
9754 printReconstructedExpression();
9755 if (!result.hasExpression())
9756 printRemainingMessages(Colour::None);
9757 else
9758 printRemainingMessages();
9759 break;
9760 case ResultWas::ExpressionFailed:
9761 if (result.isOk()) {
9762 printResultType(tapPassedString);
9763 } else {
9764 printResultType(tapFailedString);
9765 }
9766 printOriginalExpression();
9767 printReconstructedExpression();
9768 if (result.isOk()) {
9769 printIssue(" # TODO");
9770 }
9771 printRemainingMessages();
9772 break;
9773 case ResultWas::ThrewException:
9774 printResultType(tapFailedString);
9775 printIssue("unexpected exception with message:"_sr);
9776 printMessage();
9777 printExpressionWas();
9778 printRemainingMessages();
9779 break;
9780 case ResultWas::FatalErrorCondition:
9781 printResultType(tapFailedString);
9782 printIssue("fatal error condition with message:"_sr);
9783 printMessage();
9784 printExpressionWas();
9785 printRemainingMessages();
9786 break;
9787 case ResultWas::DidntThrowException:
9788 printResultType(tapFailedString);
9789 printIssue("expected exception, got none"_sr);
9790 printExpressionWas();
9791 printRemainingMessages();
9792 break;
9793 case ResultWas::Info:
9794 printResultType("info"_sr);
9795 printMessage();
9796 printRemainingMessages();
9797 break;
9798 case ResultWas::Warning:
9799 printResultType("warning"_sr);
9800 printMessage();
9801 printRemainingMessages();
9802 break;
9803 case ResultWas::ExplicitFailure:
9804 printResultType(tapFailedString);
9805 printIssue("explicitly"_sr);
9806 printRemainingMessages(Colour::None);
9807 break;
9808 // These cases are here to prevent compiler warnings
9809 case ResultWas::Unknown:
9810 case ResultWas::FailureBit:
9811 case ResultWas::Exception:
9812 printResultType("** internal error **"_sr);
9813 break;
9814 }
9815 }
9816
9817 private:
9818 void printResultType(StringRef passOrFail) const {
9819 if (!passOrFail.empty()) {
9820 stream << passOrFail << ' ' << counter << " -";
9821 }
9822 }
9823
9824 void printIssue(StringRef issue) const {
9825 stream << ' ' << issue;
9826 }
9827
9828 void printExpressionWas() {
9829 if (result.hasExpression()) {
9830 stream << ';';
9831 stream << colourImpl->guardColour( tapDimColour )
9832 << " expression was:";
9833 printOriginalExpression();
9834 }
9835 }
9836
9837 void printOriginalExpression() const {
9838 if (result.hasExpression()) {
9839 stream << ' ' << result.getExpression();
9840 }
9841 }
9842
9843 void printReconstructedExpression() const {
9844 if (result.hasExpandedExpression()) {
9845 stream << colourImpl->guardColour( tapDimColour ) << " for: ";
9846
9847 std::string expr = result.getExpandedExpression();
9848 std::replace(expr.begin(), expr.end(), '\n', ' ');
9849 stream << expr;
9850 }
9851 }
9852
9853 void printMessage() {
9854 if (itMessage != messages.end()) {
9855 stream << " '" << itMessage->message << '\'';
9856 ++itMessage;
9857 }
9858 }
9859
9860 void printRemainingMessages(Colour::Code colour = tapDimColour) {
9861 if (itMessage == messages.end()) {
9862 return;
9863 }
9864
9865 // using messages.end() directly (or auto) yields compilation error:
9866 std::vector<MessageInfo>::const_iterator itEnd = messages.end();
9867 const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
9868
9869 stream << colourImpl->guardColour( colour ) << " with "
9870 << pluralise( N, "message"_sr ) << ':';
9871
9872 for (; itMessage != itEnd; ) {
9873 // If this assertion is a warning ignore any INFO messages
9874 if (printInfoMessages || itMessage->type != ResultWas::Info) {
9875 stream << " '" << itMessage->message << '\'';
9876 if (++itMessage != itEnd) {
9877 stream << colourImpl->guardColour(tapDimColour) << " and";
9878 }
9879 }
9880 }
9881 }
9882
9883 private:
9884 std::ostream& stream;
9885 AssertionResult const& result;
9886 std::vector<MessageInfo> messages;
9887 std::vector<MessageInfo>::const_iterator itMessage;
9888 bool printInfoMessages;
9889 std::size_t counter;
9890 ColourImpl* colourImpl;
9891 };
9892
9893 } // End anonymous namespace
9894
9895 void TAPReporter::testRunStarting( TestRunInfo const& ) {
9896 m_stream << "# rng-seed: " << m_config->rngSeed() << '\n';
9897 }
9898
9899 void TAPReporter::noMatchingTestCases( StringRef unmatchedSpec ) {
9900 m_stream << "# No test cases matched '" << unmatchedSpec << "'\n";
9901 }
9902
9903 void TAPReporter::assertionEnded(AssertionStats const& _assertionStats) {
9904 ++counter;
9905
9906 m_stream << "# " << currentTestCaseInfo->name << '\n';
9907 TapAssertionPrinter printer(m_stream, _assertionStats, counter, m_colour.get());
9908 printer.print();
9909
9910 m_stream << '\n' << std::flush;
9911 }
9912
9913 void TAPReporter::testRunEnded(TestRunStats const& _testRunStats) {
9914 m_stream << "1.." << _testRunStats.totals.assertions.total();
9915 if (_testRunStats.totals.testCases.total() == 0) {
9916 m_stream << " # Skipped: No tests ran.";
9917 }
9918 m_stream << "\n\n" << std::flush;
9919 StreamingReporterBase::testRunEnded(_testRunStats);
9920 }
9921
9922
9923
9924
9925 } // end namespace Catch
9926
9927
9928
9929
9930 #include <cassert>
9931 #include <ostream>
9932
9933 namespace Catch {
9934
9935 namespace {
9936 // if string has a : in first line will set indent to follow it on
9937 // subsequent lines
9938 void printHeaderString(std::ostream& os, std::string const& _string, std::size_t indent = 0) {
9939 std::size_t i = _string.find(": ");
9940 if (i != std::string::npos)
9941 i += 2;
9942 else
9943 i = 0;
9944 os << TextFlow::Column(_string)
9945 .indent(indent + i)
9946 .initialIndent(indent) << '\n';
9947 }
9948
9949 std::string escape(StringRef str) {
9950 std::string escaped = static_cast<std::string>(str);
9951 replaceInPlace(escaped, "|", "||");
9952 replaceInPlace(escaped, "'", "|'");
9953 replaceInPlace(escaped, "\n", "|n");
9954 replaceInPlace(escaped, "\r", "|r");
9955 replaceInPlace(escaped, "[", "|[");
9956 replaceInPlace(escaped, "]", "|]");
9957 return escaped;
9958 }
9959 } // end anonymous namespace
9960
9961
9962 TeamCityReporter::~TeamCityReporter() {}
9963
9964 void TeamCityReporter::testRunStarting( TestRunInfo const& runInfo ) {
9965 m_stream << "##teamcity[testSuiteStarted name='" << escape( runInfo.name )
9966 << "']\n";
9967 }
9968
9969 void TeamCityReporter::testRunEnded( TestRunStats const& runStats ) {
9970 m_stream << "##teamcity[testSuiteFinished name='"
9971 << escape( runStats.runInfo.name ) << "']\n";
9972 }
9973
9974 void TeamCityReporter::assertionEnded(AssertionStats const& assertionStats) {
9975 AssertionResult const& result = assertionStats.assertionResult;
9976 if (!result.isOk()) {
9977
9978 ReusableStringStream msg;
9979 if (!m_headerPrintedForThisSection)
9980 printSectionHeader(msg.get());
9981 m_headerPrintedForThisSection = true;
9982
9983 msg << result.getSourceInfo() << '\n';
9984
9985 switch (result.getResultType()) {
9986 case ResultWas::ExpressionFailed:
9987 msg << "expression failed";
9988 break;
9989 case ResultWas::ThrewException:
9990 msg << "unexpected exception";
9991 break;
9992 case ResultWas::FatalErrorCondition:
9993 msg << "fatal error condition";
9994 break;
9995 case ResultWas::DidntThrowException:
9996 msg << "no exception was thrown where one was expected";
9997 break;
9998 case ResultWas::ExplicitFailure:
9999 msg << "explicit failure";
10000 break;
10001
10002 // We shouldn't get here because of the isOk() test
10003 case ResultWas::Ok:
10004 case ResultWas::Info:
10005 case ResultWas::Warning:
10006 CATCH_ERROR("Internal error in TeamCity reporter");
10007 // These cases are here to prevent compiler warnings
10008 case ResultWas::Unknown:
10009 case ResultWas::FailureBit:
10010 case ResultWas::Exception:
10011 CATCH_ERROR("Not implemented");
10012 }
10013 if (assertionStats.infoMessages.size() == 1)
10014 msg << " with message:";
10015 if (assertionStats.infoMessages.size() > 1)
10016 msg << " with messages:";
10017 for (auto const& messageInfo : assertionStats.infoMessages)
10018 msg << "\n \"" << messageInfo.message << '"';
10019
10020
10021 if (result.hasExpression()) {
10022 msg <<
10023 "\n " << result.getExpressionInMacro() << "\n"
10024 "with expansion:\n"
10025 " " << result.getExpandedExpression() << '\n';
10026 }
10027
10028 if (currentTestCaseInfo->okToFail()) {
10029 msg << "- failure ignore as test marked as 'ok to fail'\n";
10030 m_stream << "##teamcity[testIgnored"
10031 << " name='" << escape(currentTestCaseInfo->name) << '\''
10032 << " message='" << escape(msg.str()) << '\''
10033 << "]\n";
10034 } else {
10035 m_stream << "##teamcity[testFailed"
10036 << " name='" << escape(currentTestCaseInfo->name) << '\''
10037 << " message='" << escape(msg.str()) << '\''
10038 << "]\n";
10039 }
10040 }
10041 m_stream.flush();
10042 }
10043
10044 void TeamCityReporter::testCaseStarting(TestCaseInfo const& testInfo) {
10045 m_testTimer.start();
10046 StreamingReporterBase::testCaseStarting(testInfo);
10047 m_stream << "##teamcity[testStarted name='"
10048 << escape(testInfo.name) << "']\n";
10049 m_stream.flush();
10050 }
10051
10052 void TeamCityReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
10053 StreamingReporterBase::testCaseEnded(testCaseStats);
10054 auto const& testCaseInfo = *testCaseStats.testInfo;
10055 if (!testCaseStats.stdOut.empty())
10056 m_stream << "##teamcity[testStdOut name='"
10057 << escape(testCaseInfo.name)
10058 << "' out='" << escape(testCaseStats.stdOut) << "']\n";
10059 if (!testCaseStats.stdErr.empty())
10060 m_stream << "##teamcity[testStdErr name='"
10061 << escape(testCaseInfo.name)
10062 << "' out='" << escape(testCaseStats.stdErr) << "']\n";
10063 m_stream << "##teamcity[testFinished name='"
10064 << escape(testCaseInfo.name) << "' duration='"
10065 << m_testTimer.getElapsedMilliseconds() << "']\n";
10066 m_stream.flush();
10067 }
10068
10069 void TeamCityReporter::printSectionHeader(std::ostream& os) {
10070 assert(!m_sectionStack.empty());
10071
10072 if (m_sectionStack.size() > 1) {
10073 os << lineOfChars('-') << '\n';
10074
10075 std::vector<SectionInfo>::const_iterator
10076 it = m_sectionStack.begin() + 1, // Skip first section (test case)
10077 itEnd = m_sectionStack.end();
10078 for (; it != itEnd; ++it)
10079 printHeaderString(os, it->name);
10080 os << lineOfChars('-') << '\n';
10081 }
10082
10083 SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;
10084
10085 os << lineInfo << '\n';
10086 os << lineOfChars('.') << "\n\n";
10087 }
10088
10089 } // end namespace Catch
10090
10091
10092
10093
10094 #if defined(_MSC_VER)
10095 #pragma warning(push)
10096 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
10097 // Note that 4062 (not all labels are handled
10098 // and default is missing) is enabled
10099 #endif
10100
10101 namespace Catch {
10102 XmlReporter::XmlReporter( ReporterConfig&& _config )
10103 : StreamingReporterBase( CATCH_MOVE(_config) ),
10104 m_xml(m_stream)
10105 {
10106 m_preferences.shouldRedirectStdOut = true;
10107 m_preferences.shouldReportAllAssertions = true;
10108 }
10109
10110 XmlReporter::~XmlReporter() = default;
10111
10112 std::string XmlReporter::getDescription() {
10113 return "Reports test results as an XML document";
10114 }
10115
10116 std::string XmlReporter::getStylesheetRef() const {
10117 return std::string();
10118 }
10119
10120 void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
10121 m_xml
10122 .writeAttribute( "filename"_sr, sourceInfo.file )
10123 .writeAttribute( "line"_sr, sourceInfo.line );
10124 }
10125
10126 void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
10127 StreamingReporterBase::testRunStarting( testInfo );
10128 std::string stylesheetRef = getStylesheetRef();
10129 if( !stylesheetRef.empty() )
10130 m_xml.writeStylesheetRef( stylesheetRef );
10131 m_xml.startElement("Catch2TestRun")
10132 .writeAttribute("name"_sr, m_config->name())
10133 .writeAttribute("rng-seed"_sr, m_config->rngSeed())
10134 .writeAttribute("catch2-version"_sr, libraryVersion());
10135 if (m_config->testSpec().hasFilters())
10136 m_xml.writeAttribute( "filters"_sr, serializeFilters( m_config->getTestsOrTags() ) );
10137 }
10138
10139 void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
10140 StreamingReporterBase::testCaseStarting(testInfo);
10141 m_xml.startElement( "TestCase" )
10142 .writeAttribute( "name"_sr, trim( testInfo.name ) )
10143 .writeAttribute( "tags"_sr, testInfo.tagsAsString() );
10144
10145 writeSourceInfo( testInfo.lineInfo );
10146
10147 if ( m_config->showDurations() == ShowDurations::Always )
10148 m_testCaseTimer.start();
10149 m_xml.ensureTagClosed();
10150 }
10151
10152 void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
10153 StreamingReporterBase::sectionStarting( sectionInfo );
10154 if( m_sectionDepth++ > 0 ) {
10155 m_xml.startElement( "Section" )
10156 .writeAttribute( "name"_sr, trim( sectionInfo.name ) );
10157 writeSourceInfo( sectionInfo.lineInfo );
10158 m_xml.ensureTagClosed();
10159 }
10160 }
10161
10162 void XmlReporter::assertionStarting( AssertionInfo const& ) { }
10163
10164 void XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
10165
10166 AssertionResult const& result = assertionStats.assertionResult;
10167
10168 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
10169
10170 if( includeResults || result.getResultType() == ResultWas::Warning ) {
10171 // Print any info messages in <Info> tags.
10172 for( auto const& msg : assertionStats.infoMessages ) {
10173 if( msg.type == ResultWas::Info && includeResults ) {
10174 m_xml.scopedElement( "Info" )
10175 .writeText( msg.message );
10176 } else if ( msg.type == ResultWas::Warning ) {
10177 m_xml.scopedElement( "Warning" )
10178 .writeText( msg.message );
10179 }
10180 }
10181 }
10182
10183 // Drop out if result was successful but we're not printing them.
10184 if( !includeResults && result.getResultType() != ResultWas::Warning )
10185 return;
10186
10187
10188 // Print the expression if there is one.
10189 if( result.hasExpression() ) {
10190 m_xml.startElement( "Expression" )
10191 .writeAttribute( "success"_sr, result.succeeded() )
10192 .writeAttribute( "type"_sr, result.getTestMacroName() );
10193
10194 writeSourceInfo( result.getSourceInfo() );
10195
10196 m_xml.scopedElement( "Original" )
10197 .writeText( result.getExpression() );
10198 m_xml.scopedElement( "Expanded" )
10199 .writeText( result.getExpandedExpression() );
10200 }
10201
10202 // And... Print a result applicable to each result type.
10203 switch( result.getResultType() ) {
10204 case ResultWas::ThrewException:
10205 m_xml.startElement( "Exception" );
10206 writeSourceInfo( result.getSourceInfo() );
10207 m_xml.writeText( result.getMessage() );
10208 m_xml.endElement();
10209 break;
10210 case ResultWas::FatalErrorCondition:
10211 m_xml.startElement( "FatalErrorCondition" );
10212 writeSourceInfo( result.getSourceInfo() );
10213 m_xml.writeText( result.getMessage() );
10214 m_xml.endElement();
10215 break;
10216 case ResultWas::Info:
10217 m_xml.scopedElement( "Info" )
10218 .writeText( result.getMessage() );
10219 break;
10220 case ResultWas::Warning:
10221 // Warning will already have been written
10222 break;
10223 case ResultWas::ExplicitFailure:
10224 m_xml.startElement( "Failure" );
10225 writeSourceInfo( result.getSourceInfo() );
10226 m_xml.writeText( result.getMessage() );
10227 m_xml.endElement();
10228 break;
10229 default:
10230 break;
10231 }
10232
10233 if( result.hasExpression() )
10234 m_xml.endElement();
10235 }
10236
10237 void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
10238 StreamingReporterBase::sectionEnded( sectionStats );
10239 if( --m_sectionDepth > 0 ) {
10240 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
10241 e.writeAttribute( "successes"_sr, sectionStats.assertions.passed );
10242 e.writeAttribute( "failures"_sr, sectionStats.assertions.failed );
10243 e.writeAttribute( "expectedFailures"_sr, sectionStats.assertions.failedButOk );
10244
10245 if ( m_config->showDurations() == ShowDurations::Always )
10246 e.writeAttribute( "durationInSeconds"_sr, sectionStats.durationInSeconds );
10247
10248 m_xml.endElement();
10249 }
10250 }
10251
10252 void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
10253 StreamingReporterBase::testCaseEnded( testCaseStats );
10254 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
10255 e.writeAttribute( "success"_sr, testCaseStats.totals.assertions.allOk() );
10256
10257 if ( m_config->showDurations() == ShowDurations::Always )
10258 e.writeAttribute( "durationInSeconds"_sr, m_testCaseTimer.getElapsedSeconds() );
10259
10260 if( !testCaseStats.stdOut.empty() )
10261 m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
10262 if( !testCaseStats.stdErr.empty() )
10263 m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
10264
10265 m_xml.endElement();
10266 }
10267
10268 void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
10269 StreamingReporterBase::testRunEnded( testRunStats );
10270 m_xml.scopedElement( "OverallResults" )
10271 .writeAttribute( "successes"_sr, testRunStats.totals.assertions.passed )
10272 .writeAttribute( "failures"_sr, testRunStats.totals.assertions.failed )
10273 .writeAttribute( "expectedFailures"_sr, testRunStats.totals.assertions.failedButOk );
10274 m_xml.scopedElement( "OverallResultsCases")
10275 .writeAttribute( "successes"_sr, testRunStats.totals.testCases.passed )
10276 .writeAttribute( "failures"_sr, testRunStats.totals.testCases.failed )
10277 .writeAttribute( "expectedFailures"_sr, testRunStats.totals.testCases.failedButOk );
10278 m_xml.endElement();
10279 }
10280
10281 void XmlReporter::benchmarkPreparing( StringRef name ) {
10282 m_xml.startElement("BenchmarkResults")
10283 .writeAttribute("name"_sr, name);
10284 }
10285
10286 void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
10287 m_xml.writeAttribute("samples"_sr, info.samples)
10288 .writeAttribute("resamples"_sr, info.resamples)
10289 .writeAttribute("iterations"_sr, info.iterations)
10290 .writeAttribute("clockResolution"_sr, info.clockResolution)
10291 .writeAttribute("estimatedDuration"_sr, info.estimatedDuration)
10292 .writeComment("All values in nano seconds"_sr);
10293 }
10294
10295 void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
10296 m_xml.startElement("mean")
10297 .writeAttribute("value"_sr, benchmarkStats.mean.point.count())
10298 .writeAttribute("lowerBound"_sr, benchmarkStats.mean.lower_bound.count())
10299 .writeAttribute("upperBound"_sr, benchmarkStats.mean.upper_bound.count())
10300 .writeAttribute("ci"_sr, benchmarkStats.mean.confidence_interval);
10301 m_xml.endElement();
10302 m_xml.startElement("standardDeviation")
10303 .writeAttribute("value"_sr, benchmarkStats.standardDeviation.point.count())
10304 .writeAttribute("lowerBound"_sr, benchmarkStats.standardDeviation.lower_bound.count())
10305 .writeAttribute("upperBound"_sr, benchmarkStats.standardDeviation.upper_bound.count())
10306 .writeAttribute("ci"_sr, benchmarkStats.standardDeviation.confidence_interval);
10307 m_xml.endElement();
10308 m_xml.startElement("outliers")
10309 .writeAttribute("variance"_sr, benchmarkStats.outlierVariance)
10310 .writeAttribute("lowMild"_sr, benchmarkStats.outliers.low_mild)
10311 .writeAttribute("lowSevere"_sr, benchmarkStats.outliers.low_severe)
10312 .writeAttribute("highMild"_sr, benchmarkStats.outliers.high_mild)
10313 .writeAttribute("highSevere"_sr, benchmarkStats.outliers.high_severe);
10314 m_xml.endElement();
10315 m_xml.endElement();
10316 }
10317
10318 void XmlReporter::benchmarkFailed(StringRef error) {
10319 m_xml.scopedElement("failed").
10320 writeAttribute("message"_sr, error);
10321 m_xml.endElement();
10322 }
10323
10324 void XmlReporter::listReporters(std::vector<ReporterDescription> const& descriptions) {
10325 auto outerTag = m_xml.scopedElement("AvailableReporters");
10326 for (auto const& reporter : descriptions) {
10327 auto inner = m_xml.scopedElement("Reporter");
10328 m_xml.startElement("Name", XmlFormatting::Indent)
10329 .writeText(reporter.name, XmlFormatting::None)
10330 .endElement(XmlFormatting::Newline);
10331 m_xml.startElement("Description", XmlFormatting::Indent)
10332 .writeText(reporter.description, XmlFormatting::None)
10333 .endElement(XmlFormatting::Newline);
10334 }
10335 }
10336
10337 void XmlReporter::listListeners(std::vector<ListenerDescription> const& descriptions) {
10338 auto outerTag = m_xml.scopedElement( "RegisteredListeners" );
10339 for ( auto const& listener : descriptions ) {
10340 auto inner = m_xml.scopedElement( "Listener" );
10341 m_xml.startElement( "Name", XmlFormatting::Indent )
10342 .writeText( listener.name, XmlFormatting::None )
10343 .endElement( XmlFormatting::Newline );
10344 m_xml.startElement( "Description", XmlFormatting::Indent )
10345 .writeText( listener.description, XmlFormatting::None )
10346 .endElement( XmlFormatting::Newline );
10347 }
10348 }
10349
10350 void XmlReporter::listTests(std::vector<TestCaseHandle> const& tests) {
10351 auto outerTag = m_xml.scopedElement("MatchingTests");
10352 for (auto const& test : tests) {
10353 auto innerTag = m_xml.scopedElement("TestCase");
10354 auto const& testInfo = test.getTestCaseInfo();
10355 m_xml.startElement("Name", XmlFormatting::Indent)
10356 .writeText(testInfo.name, XmlFormatting::None)
10357 .endElement(XmlFormatting::Newline);
10358 m_xml.startElement("ClassName", XmlFormatting::Indent)
10359 .writeText(testInfo.className, XmlFormatting::None)
10360 .endElement(XmlFormatting::Newline);
10361 m_xml.startElement("Tags", XmlFormatting::Indent)
10362 .writeText(testInfo.tagsAsString(), XmlFormatting::None)
10363 .endElement(XmlFormatting::Newline);
10364
10365 auto sourceTag = m_xml.scopedElement("SourceInfo");
10366 m_xml.startElement("File", XmlFormatting::Indent)
10367 .writeText(testInfo.lineInfo.file, XmlFormatting::None)
10368 .endElement(XmlFormatting::Newline);
10369 m_xml.startElement("Line", XmlFormatting::Indent)
10370 .writeText(std::to_string(testInfo.lineInfo.line), XmlFormatting::None)
10371 .endElement(XmlFormatting::Newline);
10372 }
10373 }
10374
10375 void XmlReporter::listTags(std::vector<TagInfo> const& tags) {
10376 auto outerTag = m_xml.scopedElement("TagsFromMatchingTests");
10377 for (auto const& tag : tags) {
10378 auto innerTag = m_xml.scopedElement("Tag");
10379 m_xml.startElement("Count", XmlFormatting::Indent)
10380 .writeText(std::to_string(tag.count), XmlFormatting::None)
10381 .endElement(XmlFormatting::Newline);
10382 auto aliasTag = m_xml.scopedElement("Aliases");
10383 for (auto const& alias : tag.spellings) {
10384 m_xml.startElement("Alias", XmlFormatting::Indent)
10385 .writeText(alias, XmlFormatting::None)
10386 .endElement(XmlFormatting::Newline);
10387 }
10388 }
10389 }
10390
10391 } // end namespace Catch
10392
10393 #if defined(_MSC_VER)
10394 #pragma warning(pop)
10395 #endif