Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
stenzek
GitHub Repository: stenzek/duckstation
Path: blob/master/dep/googletest/src/gtest.cc
4804 views
1
// Copyright 2005, Google Inc.
2
// All rights reserved.
3
//
4
// Redistribution and use in source and binary forms, with or without
5
// modification, are permitted provided that the following conditions are
6
// met:
7
//
8
// * Redistributions of source code must retain the above copyright
9
// notice, this list of conditions and the following disclaimer.
10
// * Redistributions in binary form must reproduce the above
11
// copyright notice, this list of conditions and the following disclaimer
12
// in the documentation and/or other materials provided with the
13
// distribution.
14
// * Neither the name of Google Inc. nor the names of its
15
// contributors may be used to endorse or promote products derived from
16
// this software without specific prior written permission.
17
//
18
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30
//
31
// The Google C++ Testing and Mocking Framework (Google Test)
32
33
#include "gtest/gtest.h"
34
35
#include <ctype.h>
36
#include <stdarg.h>
37
#include <stdio.h>
38
#include <stdlib.h>
39
#include <time.h>
40
#include <wchar.h>
41
#include <wctype.h>
42
43
#include <algorithm>
44
#include <chrono> // NOLINT
45
#include <cmath>
46
#include <csignal> // NOLINT: raise(3) is used on some platforms
47
#include <cstdint>
48
#include <cstdlib>
49
#include <cstring>
50
#include <initializer_list>
51
#include <iomanip>
52
#include <ios>
53
#include <iostream>
54
#include <iterator>
55
#include <limits>
56
#include <list>
57
#include <map>
58
#include <ostream> // NOLINT
59
#include <set>
60
#include <sstream>
61
#include <unordered_set>
62
#include <utility>
63
#include <vector>
64
65
#include "gtest/gtest-assertion-result.h"
66
#include "gtest/gtest-spi.h"
67
#include "gtest/internal/custom/gtest.h"
68
#include "gtest/internal/gtest-port.h"
69
70
#ifdef GTEST_OS_LINUX
71
72
#include <fcntl.h> // NOLINT
73
#include <limits.h> // NOLINT
74
#include <sched.h> // NOLINT
75
// Declares vsnprintf(). This header is not available on Windows.
76
#include <strings.h> // NOLINT
77
#include <sys/mman.h> // NOLINT
78
#include <sys/time.h> // NOLINT
79
#include <unistd.h> // NOLINT
80
81
#include <string>
82
83
#elif defined(GTEST_OS_ZOS)
84
#include <sys/time.h> // NOLINT
85
86
// On z/OS we additionally need strings.h for strcasecmp.
87
#include <strings.h> // NOLINT
88
89
#elif defined(GTEST_OS_WINDOWS_MOBILE) // We are on Windows CE.
90
91
#include <windows.h> // NOLINT
92
#undef min
93
94
#elif defined(GTEST_OS_WINDOWS) // We are on Windows proper.
95
96
#include <windows.h> // NOLINT
97
#undef min
98
99
#ifdef _MSC_VER
100
#include <crtdbg.h> // NOLINT
101
#endif
102
103
#include <io.h> // NOLINT
104
#include <sys/stat.h> // NOLINT
105
#include <sys/timeb.h> // NOLINT
106
#include <sys/types.h> // NOLINT
107
108
#ifdef GTEST_OS_WINDOWS_MINGW
109
#include <sys/time.h> // NOLINT
110
#endif // GTEST_OS_WINDOWS_MINGW
111
112
#else
113
114
// cpplint thinks that the header is already included, so we want to
115
// silence it.
116
#include <sys/time.h> // NOLINT
117
#include <unistd.h> // NOLINT
118
119
#endif // GTEST_OS_LINUX
120
121
#if GTEST_HAS_EXCEPTIONS
122
#include <stdexcept>
123
#endif
124
125
#if GTEST_CAN_STREAM_RESULTS_
126
#include <arpa/inet.h> // NOLINT
127
#include <netdb.h> // NOLINT
128
#include <sys/socket.h> // NOLINT
129
#include <sys/types.h> // NOLINT
130
#endif
131
132
#include "src/gtest-internal-inl.h"
133
134
#ifdef GTEST_OS_WINDOWS
135
#define vsnprintf _vsnprintf
136
#endif // GTEST_OS_WINDOWS
137
138
#ifdef GTEST_OS_MAC
139
#ifndef GTEST_OS_IOS
140
#include <crt_externs.h>
141
#endif
142
#endif
143
144
#ifdef GTEST_HAS_ABSL
145
#include "absl/container/flat_hash_set.h"
146
#include "absl/debugging/failure_signal_handler.h"
147
#include "absl/debugging/stacktrace.h"
148
#include "absl/debugging/symbolize.h"
149
#include "absl/flags/parse.h"
150
#include "absl/flags/usage.h"
151
#include "absl/strings/str_cat.h"
152
#include "absl/strings/str_replace.h"
153
#include "absl/strings/string_view.h"
154
#include "absl/strings/strip.h"
155
#endif // GTEST_HAS_ABSL
156
157
// Checks builtin compiler feature |x| while avoiding an extra layer of #ifdefs
158
// at the callsite.
159
#if defined(__has_builtin)
160
#define GTEST_HAS_BUILTIN(x) __has_builtin(x)
161
#else
162
#define GTEST_HAS_BUILTIN(x) 0
163
#endif // defined(__has_builtin)
164
165
#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
166
#define GTEST_HAS_ABSL_FLAGS
167
#endif
168
169
namespace testing {
170
171
using internal::CountIf;
172
using internal::ForEach;
173
using internal::GetElementOr;
174
using internal::Shuffle;
175
176
// Constants.
177
178
// A test whose test suite name or test name matches this filter is
179
// disabled and not run.
180
static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
181
182
// A test suite whose name matches this filter is considered a death
183
// test suite and will be run before test suites whose name doesn't
184
// match this filter.
185
static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
186
187
// A test filter that matches everything.
188
static const char kUniversalFilter[] = "*";
189
190
// The default output format.
191
static const char kDefaultOutputFormat[] = "xml";
192
// The default output file.
193
static const char kDefaultOutputFile[] = "test_detail";
194
195
// These environment variables are set by Bazel.
196
// https://bazel.build/reference/test-encyclopedia#initial-conditions
197
//
198
// The environment variable name for the test shard index.
199
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
200
// The environment variable name for the total number of test shards.
201
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
202
// The environment variable name for the test shard status file.
203
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
204
// The environment variable name for the test output warnings file.
205
static const char kTestWarningsOutputFile[] = "TEST_WARNINGS_OUTPUT_FILE";
206
207
namespace internal {
208
209
// The text used in failure messages to indicate the start of the
210
// stack trace.
211
const char kStackTraceMarker[] = "\nStack trace:\n";
212
213
// g_help_flag is true if and only if the --help flag or an equivalent form
214
// is specified on the command line.
215
bool g_help_flag = false;
216
217
#if GTEST_HAS_FILE_SYSTEM
218
// Utility function to Open File for Writing
219
static FILE* OpenFileForWriting(const std::string& output_file) {
220
FILE* fileout = nullptr;
221
FilePath output_file_path(output_file);
222
FilePath output_dir(output_file_path.RemoveFileName());
223
224
if (output_dir.CreateDirectoriesRecursively()) {
225
fileout = posix::FOpen(output_file.c_str(), "w");
226
}
227
if (fileout == nullptr) {
228
GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
229
}
230
return fileout;
231
}
232
#endif // GTEST_HAS_FILE_SYSTEM
233
234
} // namespace internal
235
236
// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
237
// environment variable.
238
static const char* GetDefaultFilter() {
239
const char* const testbridge_test_only =
240
internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
241
if (testbridge_test_only != nullptr) {
242
return testbridge_test_only;
243
}
244
return kUniversalFilter;
245
}
246
247
// Bazel passes in the argument to '--test_runner_fail_fast' via the
248
// TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
249
static bool GetDefaultFailFast() {
250
const char* const testbridge_test_runner_fail_fast =
251
internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
252
if (testbridge_test_runner_fail_fast != nullptr) {
253
return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
254
}
255
return false;
256
}
257
258
} // namespace testing
259
260
GTEST_DEFINE_bool_(
261
fail_fast,
262
testing::internal::BoolFromGTestEnv("fail_fast",
263
testing::GetDefaultFailFast()),
264
"True if and only if a test failure should stop further test execution.");
265
266
GTEST_DEFINE_bool_(
267
fail_if_no_test_linked,
268
testing::internal::BoolFromGTestEnv("fail_if_no_test_linked", false),
269
"True if and only if the test should fail if no test case (including "
270
"disabled test cases) is linked.");
271
272
GTEST_DEFINE_bool_(
273
also_run_disabled_tests,
274
testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false),
275
"Run disabled tests too, in addition to the tests normally being run.");
276
277
GTEST_DEFINE_bool_(
278
break_on_failure,
279
testing::internal::BoolFromGTestEnv("break_on_failure", false),
280
"True if and only if a failed assertion should be a debugger "
281
"break-point.");
282
283
GTEST_DEFINE_bool_(catch_exceptions,
284
testing::internal::BoolFromGTestEnv("catch_exceptions",
285
true),
286
"True if and only if " GTEST_NAME_
287
" should catch exceptions and treat them as test failures.");
288
289
GTEST_DEFINE_string_(
290
color, testing::internal::StringFromGTestEnv("color", "auto"),
291
"Whether to use colors in the output. Valid values: yes, no, "
292
"and auto. 'auto' means to use colors if the output is "
293
"being sent to a terminal and the TERM environment variable "
294
"is set to a terminal type that supports colors.");
295
296
GTEST_DEFINE_string_(
297
filter,
298
testing::internal::StringFromGTestEnv("filter",
299
testing::GetDefaultFilter()),
300
"A colon-separated list of glob (not regex) patterns "
301
"for filtering the tests to run, optionally followed by a "
302
"'-' and a : separated list of negative patterns (tests to "
303
"exclude). A test is run if it matches one of the positive "
304
"patterns and does not match any of the negative patterns.");
305
306
GTEST_DEFINE_bool_(
307
install_failure_signal_handler,
308
testing::internal::BoolFromGTestEnv("install_failure_signal_handler",
309
false),
310
"If true and supported on the current platform, " GTEST_NAME_
311
" should "
312
"install a signal handler that dumps debugging information when fatal "
313
"signals are raised.");
314
315
GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
316
317
// The net priority order after flag processing is thus:
318
// --gtest_output command line flag
319
// GTEST_OUTPUT environment variable
320
// XML_OUTPUT_FILE environment variable
321
// ''
322
GTEST_DEFINE_string_(
323
output,
324
testing::internal::StringFromGTestEnv(
325
"output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()),
326
"A format (defaults to \"xml\" but can be specified to be \"json\"), "
327
"optionally followed by a colon and an output file name or directory. "
328
"A directory is indicated by a trailing pathname separator. "
329
"Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
330
"If a directory is specified, output files will be created "
331
"within that directory, with file-names based on the test "
332
"executable's name and, if necessary, made unique by adding "
333
"digits.");
334
335
GTEST_DEFINE_bool_(
336
brief, testing::internal::BoolFromGTestEnv("brief", false),
337
"True if only test failures should be displayed in text output.");
338
339
GTEST_DEFINE_bool_(print_time,
340
testing::internal::BoolFromGTestEnv("print_time", true),
341
"True if and only if " GTEST_NAME_
342
" should display elapsed time in text output.");
343
344
GTEST_DEFINE_bool_(print_utf8,
345
testing::internal::BoolFromGTestEnv("print_utf8", true),
346
"True if and only if " GTEST_NAME_
347
" prints UTF8 characters as text.");
348
349
GTEST_DEFINE_int32_(
350
random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0),
351
"Random number seed to use when shuffling test orders. Must be in range "
352
"[1, 99999], or 0 to use a seed based on the current time.");
353
354
GTEST_DEFINE_int32_(
355
repeat, testing::internal::Int32FromGTestEnv("repeat", 1),
356
"How many times to repeat each test. Specify a negative number "
357
"for repeating forever. Useful for shaking out flaky tests.");
358
359
GTEST_DEFINE_bool_(
360
recreate_environments_when_repeating,
361
testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating",
362
false),
363
"Controls whether global test environments are recreated for each repeat "
364
"of the tests. If set to false the global test environments are only set "
365
"up once, for the first iteration, and only torn down once, for the last. "
366
"Useful for shaking out flaky tests with stable, expensive test "
367
"environments. If --gtest_repeat is set to a negative number, meaning "
368
"there is no last run, the environments will always be recreated to avoid "
369
"leaks.");
370
371
GTEST_DEFINE_bool_(show_internal_stack_frames, false,
372
"True if and only if " GTEST_NAME_
373
" should include internal stack frames when "
374
"printing test failure stack traces.");
375
376
GTEST_DEFINE_bool_(shuffle,
377
testing::internal::BoolFromGTestEnv("shuffle", false),
378
"True if and only if " GTEST_NAME_
379
" should randomize tests' order on every run.");
380
381
GTEST_DEFINE_int32_(
382
stack_trace_depth,
383
testing::internal::Int32FromGTestEnv("stack_trace_depth",
384
testing::kMaxStackTraceDepth),
385
"The maximum number of stack frames to print when an "
386
"assertion fails. The valid range is 0 through 100, inclusive.");
387
388
GTEST_DEFINE_string_(
389
stream_result_to,
390
testing::internal::StringFromGTestEnv("stream_result_to", ""),
391
"This flag specifies the host name and the port number on which to stream "
392
"test results. Example: \"localhost:555\". The flag is effective only on "
393
"Linux and macOS.");
394
395
GTEST_DEFINE_bool_(
396
throw_on_failure,
397
testing::internal::BoolFromGTestEnv("throw_on_failure", false),
398
"When this flag is specified, a failed assertion will throw an exception "
399
"if exceptions are enabled or exit the program with a non-zero code "
400
"otherwise. For use with an external test framework.");
401
402
#if GTEST_USE_OWN_FLAGFILE_FLAG_
403
GTEST_DEFINE_string_(
404
flagfile, testing::internal::StringFromGTestEnv("flagfile", ""),
405
"This flag specifies the flagfile to read command-line flags from.");
406
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
407
408
namespace testing {
409
namespace internal {
410
411
const uint32_t Random::kMaxRange;
412
413
// Generates a random number from [0, range), using a Linear
414
// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
415
// than kMaxRange.
416
uint32_t Random::Generate(uint32_t range) {
417
// These constants are the same as are used in glibc's rand(3).
418
// Use wider types than necessary to prevent unsigned overflow diagnostics.
419
state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange;
420
421
GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
422
GTEST_CHECK_(range <= kMaxRange)
423
<< "Generation of a number in [0, " << range << ") was requested, "
424
<< "but this can only generate numbers in [0, " << kMaxRange << ").";
425
426
// Converting via modulus introduces a bit of downward bias, but
427
// it's simple, and a linear congruential generator isn't too good
428
// to begin with.
429
return state_ % range;
430
}
431
432
// GTestIsInitialized() returns true if and only if the user has initialized
433
// Google Test. Useful for catching the user mistake of not initializing
434
// Google Test before calling RUN_ALL_TESTS().
435
static bool GTestIsInitialized() { return !GetArgvs().empty(); }
436
437
// Iterates over a vector of TestSuites, keeping a running sum of the
438
// results of calling a given int-returning method on each.
439
// Returns the sum.
440
static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
441
int (TestSuite::*method)() const) {
442
int sum = 0;
443
for (size_t i = 0; i < case_list.size(); i++) {
444
sum += (case_list[i]->*method)();
445
}
446
return sum;
447
}
448
449
// Returns true if and only if the test suite passed.
450
static bool TestSuitePassed(const TestSuite* test_suite) {
451
return test_suite->should_run() && test_suite->Passed();
452
}
453
454
// Returns true if and only if the test suite failed.
455
static bool TestSuiteFailed(const TestSuite* test_suite) {
456
return test_suite->should_run() && test_suite->Failed();
457
}
458
459
// Returns true if and only if test_suite contains at least one test that
460
// should run.
461
static bool ShouldRunTestSuite(const TestSuite* test_suite) {
462
return test_suite->should_run();
463
}
464
465
namespace {
466
467
// Returns true if test part results of type `type` should include a stack
468
// trace.
469
bool ShouldEmitStackTraceForResultType(TestPartResult::Type type) {
470
// Suppress emission of the stack trace for SUCCEED() since it likely never
471
// requires investigation, and GTEST_SKIP() since skipping is an intentional
472
// act by the developer rather than a failure requiring investigation.
473
return type != TestPartResult::kSuccess && type != TestPartResult::kSkip;
474
}
475
476
} // namespace
477
478
// AssertHelper constructor.
479
AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
480
int line, const char* message)
481
: data_(new AssertHelperData(type, file, line, message)) {}
482
483
AssertHelper::~AssertHelper() { delete data_; }
484
485
// Message assignment, for assertion streaming support.
486
void AssertHelper::operator=(const Message& message) const {
487
UnitTest::GetInstance()->AddTestPartResult(
488
data_->type, data_->file, data_->line,
489
AppendUserMessage(data_->message, message),
490
ShouldEmitStackTraceForResultType(data_->type)
491
? UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
492
: ""
493
// Skips the stack frame for this function itself.
494
); // NOLINT
495
}
496
497
namespace {
498
499
// When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
500
// to creates test cases for it, a synthetic test case is
501
// inserted to report ether an error or a log message.
502
//
503
// This configuration bit will likely be removed at some point.
504
constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
505
constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
506
507
// A test that fails at a given file/line location with a given message.
508
class FailureTest : public Test {
509
public:
510
explicit FailureTest(const CodeLocation& loc, std::string error_message,
511
bool as_error)
512
: loc_(loc),
513
error_message_(std::move(error_message)),
514
as_error_(as_error) {}
515
516
void TestBody() override {
517
if (as_error_) {
518
AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
519
loc_.line, "") = Message() << error_message_;
520
} else {
521
std::cout << error_message_ << std::endl;
522
}
523
}
524
525
private:
526
const CodeLocation loc_;
527
const std::string error_message_;
528
const bool as_error_;
529
};
530
531
} // namespace
532
533
std::set<std::string>* GetIgnoredParameterizedTestSuites() {
534
return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
535
}
536
537
// Add a given test_suit to the list of them allow to go un-instantiated.
538
MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
539
GetIgnoredParameterizedTestSuites()->insert(test_suite);
540
}
541
542
// If this parameterized test suite has no instantiations (and that
543
// has not been marked as okay), emit a test case reporting that.
544
void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
545
bool has_test_p) {
546
const auto& ignored = *GetIgnoredParameterizedTestSuites();
547
if (ignored.find(name) != ignored.end()) return;
548
549
const char kMissingInstantiation[] = //
550
" is defined via TEST_P, but never instantiated. None of the test "
551
"cases "
552
"will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
553
"ones provided expand to nothing."
554
"\n\n"
555
"Ideally, TEST_P definitions should only ever be included as part of "
556
"binaries that intend to use them. (As opposed to, for example, being "
557
"placed in a library that may be linked in to get other utilities.)";
558
559
const char kMissingTestCase[] = //
560
" is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
561
"defined via TEST_P . No test cases will run."
562
"\n\n"
563
"Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
564
"code that always depend on code that provides TEST_P. Failing to do "
565
"so is often an indication of dead code, e.g. the last TEST_P was "
566
"removed but the rest got left behind.";
567
568
std::string message =
569
"Parameterized test suite " + name +
570
(has_test_p ? kMissingInstantiation : kMissingTestCase) +
571
"\n\n"
572
"To suppress this error for this test suite, insert the following line "
573
"(in a non-header) in the namespace it is defined in:"
574
"\n\n"
575
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
576
name + ");";
577
578
std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
579
RegisterTest( //
580
"GoogleTestVerification", full_name.c_str(),
581
nullptr, // No type parameter.
582
nullptr, // No value parameter.
583
location.file.c_str(), location.line, [message, location] {
584
return new FailureTest(location, message,
585
kErrorOnUninstantiatedParameterizedTest);
586
});
587
}
588
589
void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
590
CodeLocation code_location) {
591
GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
592
test_suite_name, std::move(code_location));
593
}
594
595
void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
596
GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
597
case_name);
598
}
599
600
void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
601
const char* test_suite_name, CodeLocation code_location) {
602
suites_.emplace(std::string(test_suite_name),
603
TypeParameterizedTestSuiteInfo(std::move(code_location)));
604
}
605
606
void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
607
const char* test_suite_name) {
608
auto it = suites_.find(std::string(test_suite_name));
609
if (it != suites_.end()) {
610
it->second.instantiated = true;
611
} else {
612
GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
613
<< test_suite_name << "'";
614
}
615
}
616
617
void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
618
const auto& ignored = *GetIgnoredParameterizedTestSuites();
619
for (const auto& testcase : suites_) {
620
if (testcase.second.instantiated) continue;
621
if (ignored.find(testcase.first) != ignored.end()) continue;
622
623
std::string message =
624
"Type parameterized test suite " + testcase.first +
625
" is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
626
"via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
627
"\n\n"
628
"Ideally, TYPED_TEST_P definitions should only ever be included as "
629
"part of binaries that intend to use them. (As opposed to, for "
630
"example, being placed in a library that may be linked in to get "
631
"other "
632
"utilities.)"
633
"\n\n"
634
"To suppress this error for this test suite, insert the following "
635
"line "
636
"(in a non-header) in the namespace it is defined in:"
637
"\n\n"
638
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
639
testcase.first + ");";
640
641
std::string full_name =
642
"UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
643
RegisterTest( //
644
"GoogleTestVerification", full_name.c_str(),
645
nullptr, // No type parameter.
646
nullptr, // No value parameter.
647
testcase.second.code_location.file.c_str(),
648
testcase.second.code_location.line, [message, testcase] {
649
return new FailureTest(testcase.second.code_location, message,
650
kErrorOnUninstantiatedTypeParameterizedTest);
651
});
652
}
653
}
654
655
// A copy of all command line arguments. Set by InitGoogleTest().
656
static ::std::vector<std::string> g_argvs;
657
658
::std::vector<std::string> GetArgvs() {
659
#if defined(GTEST_CUSTOM_GET_ARGVS_)
660
// GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
661
// ::string. This code converts it to the appropriate type.
662
const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
663
return ::std::vector<std::string>(custom.begin(), custom.end());
664
#else // defined(GTEST_CUSTOM_GET_ARGVS_)
665
return g_argvs;
666
#endif // defined(GTEST_CUSTOM_GET_ARGVS_)
667
}
668
669
#if GTEST_HAS_FILE_SYSTEM
670
// Returns the current application's name, removing directory path if that
671
// is present.
672
FilePath GetCurrentExecutableName() {
673
FilePath result;
674
675
auto args = GetArgvs();
676
if (!args.empty()) {
677
#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2)
678
result.Set(FilePath(args[0]).RemoveExtension("exe"));
679
#else
680
result.Set(FilePath(args[0]));
681
#endif // GTEST_OS_WINDOWS
682
}
683
684
return result.RemoveDirectoryName();
685
}
686
#endif // GTEST_HAS_FILE_SYSTEM
687
688
// Functions for processing the gtest_output flag.
689
690
// Returns the output format, or "" for normal printed output.
691
std::string UnitTestOptions::GetOutputFormat() {
692
std::string s = GTEST_FLAG_GET(output);
693
const char* const gtest_output_flag = s.c_str();
694
const char* const colon = strchr(gtest_output_flag, ':');
695
return (colon == nullptr)
696
? std::string(gtest_output_flag)
697
: std::string(gtest_output_flag,
698
static_cast<size_t>(colon - gtest_output_flag));
699
}
700
701
#if GTEST_HAS_FILE_SYSTEM
702
// Returns the name of the requested output file, or the default if none
703
// was explicitly specified.
704
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
705
std::string s = GTEST_FLAG_GET(output);
706
const char* const gtest_output_flag = s.c_str();
707
708
std::string format = GetOutputFormat();
709
if (format.empty()) format = std::string(kDefaultOutputFormat);
710
711
const char* const colon = strchr(gtest_output_flag, ':');
712
if (colon == nullptr)
713
return internal::FilePath::MakeFileName(
714
internal::FilePath(
715
UnitTest::GetInstance()->original_working_dir()),
716
internal::FilePath(kDefaultOutputFile), 0, format.c_str())
717
.string();
718
719
internal::FilePath output_name(colon + 1);
720
if (!output_name.IsAbsolutePath())
721
output_name = internal::FilePath::ConcatPaths(
722
internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
723
internal::FilePath(colon + 1));
724
725
if (!output_name.IsDirectory()) return output_name.string();
726
727
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
728
output_name, internal::GetCurrentExecutableName(),
729
GetOutputFormat().c_str()));
730
return result.string();
731
}
732
#endif // GTEST_HAS_FILE_SYSTEM
733
734
// Returns true if and only if the wildcard pattern matches the string. Each
735
// pattern consists of regular characters, single-character wildcards (?), and
736
// multi-character wildcards (*).
737
//
738
// This function implements a linear-time string globbing algorithm based on
739
// https://research.swtch.com/glob.
740
static bool PatternMatchesString(const std::string& name_str,
741
const char* pattern, const char* pattern_end) {
742
const char* name = name_str.c_str();
743
const char* const name_begin = name;
744
const char* const name_end = name + name_str.size();
745
746
const char* pattern_next = pattern;
747
const char* name_next = name;
748
749
while (pattern < pattern_end || name < name_end) {
750
if (pattern < pattern_end) {
751
switch (*pattern) {
752
default: // Match an ordinary character.
753
if (name < name_end && *name == *pattern) {
754
++pattern;
755
++name;
756
continue;
757
}
758
break;
759
case '?': // Match any single character.
760
if (name < name_end) {
761
++pattern;
762
++name;
763
continue;
764
}
765
break;
766
case '*':
767
// Match zero or more characters. Start by skipping over the wildcard
768
// and matching zero characters from name. If that fails, restart and
769
// match one more character than the last attempt.
770
pattern_next = pattern;
771
name_next = name + 1;
772
++pattern;
773
continue;
774
}
775
}
776
// Failed to match a character. Restart if possible.
777
if (name_begin < name_next && name_next <= name_end) {
778
pattern = pattern_next;
779
name = name_next;
780
continue;
781
}
782
return false;
783
}
784
return true;
785
}
786
787
namespace {
788
789
bool IsGlobPattern(const std::string& pattern) {
790
return std::any_of(pattern.begin(), pattern.end(),
791
[](const char c) { return c == '?' || c == '*'; });
792
}
793
794
class UnitTestFilter {
795
public:
796
UnitTestFilter() = default;
797
798
// Constructs a filter from a string of patterns separated by `:`.
799
explicit UnitTestFilter(const std::string& filter) {
800
// By design "" filter matches "" string.
801
std::vector<std::string> all_patterns;
802
SplitString(filter, ':', &all_patterns);
803
const auto exact_match_patterns_begin = std::partition(
804
all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
805
806
glob_patterns_.reserve(static_cast<size_t>(
807
std::distance(all_patterns.begin(), exact_match_patterns_begin)));
808
std::move(all_patterns.begin(), exact_match_patterns_begin,
809
std::inserter(glob_patterns_, glob_patterns_.begin()));
810
std::move(
811
exact_match_patterns_begin, all_patterns.end(),
812
std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));
813
}
814
815
// Returns true if and only if name matches at least one of the patterns in
816
// the filter.
817
bool MatchesName(const std::string& name) const {
818
return exact_match_patterns_.find(name) != exact_match_patterns_.end() ||
819
std::any_of(glob_patterns_.begin(), glob_patterns_.end(),
820
[&name](const std::string& pattern) {
821
return PatternMatchesString(
822
name, pattern.c_str(),
823
pattern.c_str() + pattern.size());
824
});
825
}
826
827
private:
828
std::vector<std::string> glob_patterns_;
829
std::unordered_set<std::string> exact_match_patterns_;
830
};
831
832
class PositiveAndNegativeUnitTestFilter {
833
public:
834
// Constructs a positive and a negative filter from a string. The string
835
// contains a positive filter optionally followed by a '-' character and a
836
// negative filter. In case only a negative filter is provided the positive
837
// filter will be assumed "*".
838
// A filter is a list of patterns separated by ':'.
839
explicit PositiveAndNegativeUnitTestFilter(const std::string& filter) {
840
std::vector<std::string> positive_and_negative_filters;
841
842
// NOTE: `SplitString` always returns a non-empty container.
843
SplitString(filter, '-', &positive_and_negative_filters);
844
const auto& positive_filter = positive_and_negative_filters.front();
845
846
if (positive_and_negative_filters.size() > 1) {
847
positive_filter_ = UnitTestFilter(
848
positive_filter.empty() ? kUniversalFilter : positive_filter);
849
850
// TODO(b/214626361): Fail on multiple '-' characters
851
// For the moment to preserve old behavior we concatenate the rest of the
852
// string parts with `-` as separator to generate the negative filter.
853
auto negative_filter_string = positive_and_negative_filters[1];
854
for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++)
855
negative_filter_string =
856
negative_filter_string + '-' + positive_and_negative_filters[i];
857
negative_filter_ = UnitTestFilter(negative_filter_string);
858
} else {
859
// In case we don't have a negative filter and positive filter is ""
860
// we do not use kUniversalFilter by design as opposed to when we have a
861
// negative filter.
862
positive_filter_ = UnitTestFilter(positive_filter);
863
}
864
}
865
866
// Returns true if and only if test name (this is generated by appending test
867
// suit name and test name via a '.' character) matches the positive filter
868
// and does not match the negative filter.
869
bool MatchesTest(const std::string& test_suite_name,
870
const std::string& test_name) const {
871
return MatchesName(test_suite_name + "." + test_name);
872
}
873
874
// Returns true if and only if name matches the positive filter and does not
875
// match the negative filter.
876
bool MatchesName(const std::string& name) const {
877
return positive_filter_.MatchesName(name) &&
878
!negative_filter_.MatchesName(name);
879
}
880
881
private:
882
UnitTestFilter positive_filter_;
883
UnitTestFilter negative_filter_;
884
};
885
} // namespace
886
887
bool UnitTestOptions::MatchesFilter(const std::string& name_str,
888
const char* filter) {
889
return UnitTestFilter(filter).MatchesName(name_str);
890
}
891
892
// Returns true if and only if the user-specified filter matches the test
893
// suite name and the test name.
894
bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
895
const std::string& test_name) {
896
// Split --gtest_filter at '-', if there is one, to separate into
897
// positive filter and negative filter portions
898
return PositiveAndNegativeUnitTestFilter(GTEST_FLAG_GET(filter))
899
.MatchesTest(test_suite_name, test_name);
900
}
901
902
#if GTEST_HAS_SEH
903
static std::string FormatSehExceptionMessage(DWORD exception_code,
904
const char* location) {
905
Message message;
906
message << "SEH exception with code 0x" << std::setbase(16) << exception_code
907
<< std::setbase(10) << " thrown in " << location << ".";
908
return message.GetString();
909
}
910
911
int UnitTestOptions::GTestProcessSEH(DWORD seh_code, const char* location) {
912
// Google Test should handle a SEH exception if:
913
// 1. the user wants it to, AND
914
// 2. this is not a breakpoint exception or stack overflow, AND
915
// 3. this is not a C++ exception (VC++ implements them via SEH,
916
// apparently).
917
//
918
// SEH exception code for C++ exceptions.
919
// (see https://support.microsoft.com/kb/185294 for more information).
920
const DWORD kCxxExceptionCode = 0xe06d7363;
921
922
if (!GTEST_FLAG_GET(catch_exceptions) || seh_code == kCxxExceptionCode ||
923
seh_code == EXCEPTION_BREAKPOINT ||
924
seh_code == EXCEPTION_STACK_OVERFLOW) {
925
return EXCEPTION_CONTINUE_SEARCH; // Don't handle these exceptions
926
}
927
928
internal::ReportFailureInUnknownLocation(
929
TestPartResult::kFatalFailure,
930
FormatSehExceptionMessage(seh_code, location) +
931
"\n"
932
"Stack trace:\n" +
933
::testing::internal::GetCurrentOsStackTraceExceptTop(1));
934
935
return EXCEPTION_EXECUTE_HANDLER;
936
}
937
#endif // GTEST_HAS_SEH
938
939
} // namespace internal
940
941
// The c'tor sets this object as the test part result reporter used by
942
// Google Test. The 'result' parameter specifies where to report the
943
// results. Intercepts only failures from the current thread.
944
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
945
TestPartResultArray* result)
946
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
947
Init();
948
}
949
950
// The c'tor sets this object as the test part result reporter used by
951
// Google Test. The 'result' parameter specifies where to report the
952
// results.
953
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
954
InterceptMode intercept_mode, TestPartResultArray* result)
955
: intercept_mode_(intercept_mode), result_(result) {
956
Init();
957
}
958
959
void ScopedFakeTestPartResultReporter::Init() {
960
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
961
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
962
old_reporter_ = impl->GetGlobalTestPartResultReporter();
963
impl->SetGlobalTestPartResultReporter(this);
964
} else {
965
old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
966
impl->SetTestPartResultReporterForCurrentThread(this);
967
}
968
}
969
970
// The d'tor restores the test part result reporter used by Google Test
971
// before.
972
ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
973
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
974
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
975
impl->SetGlobalTestPartResultReporter(old_reporter_);
976
} else {
977
impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
978
}
979
}
980
981
// Increments the test part result count and remembers the result.
982
// This method is from the TestPartResultReporterInterface interface.
983
void ScopedFakeTestPartResultReporter::ReportTestPartResult(
984
const TestPartResult& result) {
985
result_->Append(result);
986
}
987
988
namespace internal {
989
990
// Returns the type ID of ::testing::Test. We should always call this
991
// instead of GetTypeId< ::testing::Test>() to get the type ID of
992
// testing::Test. This is to work around a suspected linker bug when
993
// using Google Test as a framework on Mac OS X. The bug causes
994
// GetTypeId< ::testing::Test>() to return different values depending
995
// on whether the call is from the Google Test framework itself or
996
// from user test code. GetTestTypeId() is guaranteed to always
997
// return the same value, as it always calls GetTypeId<>() from the
998
// gtest.cc, which is within the Google Test framework.
999
TypeId GetTestTypeId() { return GetTypeId<Test>(); }
1000
1001
// The value of GetTestTypeId() as seen from within the Google Test
1002
// library. This is solely for testing GetTestTypeId().
1003
extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
1004
1005
// This predicate-formatter checks that 'results' contains a test part
1006
// failure of the given type and that the failure message contains the
1007
// given substring.
1008
static AssertionResult HasOneFailure(const char* /* results_expr */,
1009
const char* /* type_expr */,
1010
const char* /* substr_expr */,
1011
const TestPartResultArray& results,
1012
TestPartResult::Type type,
1013
const std::string& substr) {
1014
const std::string expected(type == TestPartResult::kFatalFailure
1015
? "1 fatal failure"
1016
: "1 non-fatal failure");
1017
Message msg;
1018
if (results.size() != 1) {
1019
msg << "Expected: " << expected << "\n"
1020
<< " Actual: " << results.size() << " failures";
1021
for (int i = 0; i < results.size(); i++) {
1022
msg << "\n" << results.GetTestPartResult(i);
1023
}
1024
return AssertionFailure() << msg;
1025
}
1026
1027
const TestPartResult& r = results.GetTestPartResult(0);
1028
if (r.type() != type) {
1029
return AssertionFailure() << "Expected: " << expected << "\n"
1030
<< " Actual:\n"
1031
<< r;
1032
}
1033
1034
if (strstr(r.message(), substr.c_str()) == nullptr) {
1035
return AssertionFailure()
1036
<< "Expected: " << expected << " containing \"" << substr << "\"\n"
1037
<< " Actual:\n"
1038
<< r;
1039
}
1040
1041
return AssertionSuccess();
1042
}
1043
1044
// The constructor of SingleFailureChecker remembers where to look up
1045
// test part results, what type of failure we expect, and what
1046
// substring the failure message should contain.
1047
SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
1048
TestPartResult::Type type,
1049
const std::string& substr)
1050
: results_(results), type_(type), substr_(substr) {}
1051
1052
// The destructor of SingleFailureChecker verifies that the given
1053
// TestPartResultArray contains exactly one failure that has the given
1054
// type and contains the given substring. If that's not the case, a
1055
// non-fatal failure will be generated.
1056
SingleFailureChecker::~SingleFailureChecker() {
1057
EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
1058
}
1059
1060
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
1061
UnitTestImpl* unit_test)
1062
: unit_test_(unit_test) {}
1063
1064
void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
1065
const TestPartResult& result) {
1066
unit_test_->current_test_result()->AddTestPartResult(result);
1067
unit_test_->listeners()->repeater()->OnTestPartResult(result);
1068
}
1069
1070
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
1071
UnitTestImpl* unit_test)
1072
: unit_test_(unit_test) {}
1073
1074
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
1075
const TestPartResult& result) {
1076
unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
1077
}
1078
1079
// Returns the global test part result reporter.
1080
TestPartResultReporterInterface*
1081
UnitTestImpl::GetGlobalTestPartResultReporter() {
1082
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1083
return global_test_part_result_reporter_;
1084
}
1085
1086
// Sets the global test part result reporter.
1087
void UnitTestImpl::SetGlobalTestPartResultReporter(
1088
TestPartResultReporterInterface* reporter) {
1089
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1090
global_test_part_result_reporter_ = reporter;
1091
}
1092
1093
// Returns the test part result reporter for the current thread.
1094
TestPartResultReporterInterface*
1095
UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
1096
return per_thread_test_part_result_reporter_.get();
1097
}
1098
1099
// Sets the test part result reporter for the current thread.
1100
void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
1101
TestPartResultReporterInterface* reporter) {
1102
per_thread_test_part_result_reporter_.set(reporter);
1103
}
1104
1105
// Gets the number of successful test suites.
1106
int UnitTestImpl::successful_test_suite_count() const {
1107
return CountIf(test_suites_, TestSuitePassed);
1108
}
1109
1110
// Gets the number of failed test suites.
1111
int UnitTestImpl::failed_test_suite_count() const {
1112
return CountIf(test_suites_, TestSuiteFailed);
1113
}
1114
1115
// Gets the number of all test suites.
1116
int UnitTestImpl::total_test_suite_count() const {
1117
return static_cast<int>(test_suites_.size());
1118
}
1119
1120
// Gets the number of all test suites that contain at least one test
1121
// that should run.
1122
int UnitTestImpl::test_suite_to_run_count() const {
1123
return CountIf(test_suites_, ShouldRunTestSuite);
1124
}
1125
1126
// Gets the number of successful tests.
1127
int UnitTestImpl::successful_test_count() const {
1128
return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
1129
}
1130
1131
// Gets the number of skipped tests.
1132
int UnitTestImpl::skipped_test_count() const {
1133
return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
1134
}
1135
1136
// Gets the number of failed tests.
1137
int UnitTestImpl::failed_test_count() const {
1138
return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
1139
}
1140
1141
// Gets the number of disabled tests that will be reported in the XML report.
1142
int UnitTestImpl::reportable_disabled_test_count() const {
1143
return SumOverTestSuiteList(test_suites_,
1144
&TestSuite::reportable_disabled_test_count);
1145
}
1146
1147
// Gets the number of disabled tests.
1148
int UnitTestImpl::disabled_test_count() const {
1149
return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
1150
}
1151
1152
// Gets the number of tests to be printed in the XML report.
1153
int UnitTestImpl::reportable_test_count() const {
1154
return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
1155
}
1156
1157
// Gets the number of all tests.
1158
int UnitTestImpl::total_test_count() const {
1159
return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
1160
}
1161
1162
// Gets the number of tests that should run.
1163
int UnitTestImpl::test_to_run_count() const {
1164
return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
1165
}
1166
1167
// Returns the current OS stack trace as an std::string.
1168
//
1169
// The maximum number of stack frames to be included is specified by
1170
// the gtest_stack_trace_depth flag. The skip_count parameter
1171
// specifies the number of top frames to be skipped, which doesn't
1172
// count against the number of frames to be included.
1173
//
1174
// For example, if Foo() calls Bar(), which in turn calls
1175
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1176
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1177
std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
1178
return os_stack_trace_getter()->CurrentStackTrace(
1179
static_cast<int>(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1
1180
// Skips the user-specified number of frames plus this function
1181
// itself.
1182
); // NOLINT
1183
}
1184
1185
// A helper class for measuring elapsed times.
1186
class Timer {
1187
public:
1188
Timer() : start_(clock::now()) {}
1189
1190
// Return time elapsed in milliseconds since the timer was created.
1191
TimeInMillis Elapsed() {
1192
return std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() -
1193
start_)
1194
.count();
1195
}
1196
1197
private:
1198
// Fall back to the system_clock when building with newlib on a system
1199
// without a monotonic clock.
1200
#if defined(_NEWLIB_VERSION) && !defined(CLOCK_MONOTONIC)
1201
using clock = std::chrono::system_clock;
1202
#else
1203
using clock = std::chrono::steady_clock;
1204
#endif
1205
clock::time_point start_;
1206
};
1207
1208
// Returns a timestamp as milliseconds since the epoch. Note this time may jump
1209
// around subject to adjustments by the system, to measure elapsed time use
1210
// Timer instead.
1211
TimeInMillis GetTimeInMillis() {
1212
return std::chrono::duration_cast<std::chrono::milliseconds>(
1213
std::chrono::system_clock::now() -
1214
std::chrono::system_clock::from_time_t(0))
1215
.count();
1216
}
1217
1218
// Utilities
1219
1220
// class String.
1221
1222
#ifdef GTEST_OS_WINDOWS_MOBILE
1223
// Creates a UTF-16 wide string from the given ANSI string, allocating
1224
// memory using new. The caller is responsible for deleting the return
1225
// value using delete[]. Returns the wide string, or NULL if the
1226
// input is NULL.
1227
LPCWSTR String::AnsiToUtf16(const char* ansi) {
1228
if (!ansi) return nullptr;
1229
const int length = strlen(ansi);
1230
const int unicode_length =
1231
MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
1232
WCHAR* unicode = new WCHAR[unicode_length + 1];
1233
MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
1234
unicode[unicode_length] = 0;
1235
return unicode;
1236
}
1237
1238
// Creates an ANSI string from the given wide string, allocating
1239
// memory using new. The caller is responsible for deleting the return
1240
// value using delete[]. Returns the ANSI string, or NULL if the
1241
// input is NULL.
1242
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
1243
if (!utf16_str) return nullptr;
1244
const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
1245
0, nullptr, nullptr);
1246
char* ansi = new char[ansi_length + 1];
1247
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
1248
nullptr);
1249
ansi[ansi_length] = 0;
1250
return ansi;
1251
}
1252
1253
#endif // GTEST_OS_WINDOWS_MOBILE
1254
1255
// Compares two C strings. Returns true if and only if they have the same
1256
// content.
1257
//
1258
// Unlike strcmp(), this function can handle NULL argument(s). A NULL
1259
// C string is considered different to any non-NULL C string,
1260
// including the empty string.
1261
bool String::CStringEquals(const char* lhs, const char* rhs) {
1262
if (lhs == nullptr) return rhs == nullptr;
1263
1264
if (rhs == nullptr) return false;
1265
1266
return strcmp(lhs, rhs) == 0;
1267
}
1268
1269
#if GTEST_HAS_STD_WSTRING
1270
1271
// Converts an array of wide chars to a narrow string using the UTF-8
1272
// encoding, and streams the result to the given Message object.
1273
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
1274
Message* msg) {
1275
for (size_t i = 0; i != length;) { // NOLINT
1276
if (wstr[i] != L'\0') {
1277
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
1278
while (i != length && wstr[i] != L'\0') i++;
1279
} else {
1280
*msg << '\0';
1281
i++;
1282
}
1283
}
1284
}
1285
1286
#endif // GTEST_HAS_STD_WSTRING
1287
1288
void SplitString(const ::std::string& str, char delimiter,
1289
::std::vector< ::std::string>* dest) {
1290
::std::vector< ::std::string> parsed;
1291
::std::string::size_type pos = 0;
1292
while (::testing::internal::AlwaysTrue()) {
1293
const ::std::string::size_type colon = str.find(delimiter, pos);
1294
if (colon == ::std::string::npos) {
1295
parsed.push_back(str.substr(pos));
1296
break;
1297
} else {
1298
parsed.push_back(str.substr(pos, colon - pos));
1299
pos = colon + 1;
1300
}
1301
}
1302
dest->swap(parsed);
1303
}
1304
1305
} // namespace internal
1306
1307
// Constructs an empty Message.
1308
// We allocate the stringstream separately because otherwise each use of
1309
// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
1310
// stack frame leading to huge stack frames in some cases; gcc does not reuse
1311
// the stack space.
1312
Message::Message() : ss_(new ::std::stringstream) {
1313
// By default, we want there to be enough precision when printing
1314
// a double to a Message.
1315
*ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
1316
}
1317
1318
// These two overloads allow streaming a wide C string to a Message
1319
// using the UTF-8 encoding.
1320
Message& Message::operator<<(const wchar_t* wide_c_str) {
1321
return *this << internal::String::ShowWideCString(wide_c_str);
1322
}
1323
Message& Message::operator<<(wchar_t* wide_c_str) {
1324
return *this << internal::String::ShowWideCString(wide_c_str);
1325
}
1326
1327
#if GTEST_HAS_STD_WSTRING
1328
// Converts the given wide string to a narrow string using the UTF-8
1329
// encoding, and streams the result to this Message object.
1330
Message& Message::operator<<(const ::std::wstring& wstr) {
1331
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
1332
return *this;
1333
}
1334
#endif // GTEST_HAS_STD_WSTRING
1335
1336
// Gets the text streamed to this object so far as an std::string.
1337
// Each '\0' character in the buffer is replaced with "\\0".
1338
std::string Message::GetString() const {
1339
return internal::StringStreamToString(ss_.get());
1340
}
1341
1342
namespace internal {
1343
1344
namespace edit_distance {
1345
std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
1346
const std::vector<size_t>& right) {
1347
std::vector<std::vector<double> > costs(
1348
left.size() + 1, std::vector<double>(right.size() + 1));
1349
std::vector<std::vector<EditType> > best_move(
1350
left.size() + 1, std::vector<EditType>(right.size() + 1));
1351
1352
// Populate for empty right.
1353
for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
1354
costs[l_i][0] = static_cast<double>(l_i);
1355
best_move[l_i][0] = kRemove;
1356
}
1357
// Populate for empty left.
1358
for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1359
costs[0][r_i] = static_cast<double>(r_i);
1360
best_move[0][r_i] = kAdd;
1361
}
1362
1363
for (size_t l_i = 0; l_i < left.size(); ++l_i) {
1364
for (size_t r_i = 0; r_i < right.size(); ++r_i) {
1365
if (left[l_i] == right[r_i]) {
1366
// Found a match. Consume it.
1367
costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1368
best_move[l_i + 1][r_i + 1] = kMatch;
1369
continue;
1370
}
1371
1372
const double add = costs[l_i + 1][r_i];
1373
const double remove = costs[l_i][r_i + 1];
1374
const double replace = costs[l_i][r_i];
1375
if (add < remove && add < replace) {
1376
costs[l_i + 1][r_i + 1] = add + 1;
1377
best_move[l_i + 1][r_i + 1] = kAdd;
1378
} else if (remove < add && remove < replace) {
1379
costs[l_i + 1][r_i + 1] = remove + 1;
1380
best_move[l_i + 1][r_i + 1] = kRemove;
1381
} else {
1382
// We make replace a little more expensive than add/remove to lower
1383
// their priority.
1384
costs[l_i + 1][r_i + 1] = replace + 1.00001;
1385
best_move[l_i + 1][r_i + 1] = kReplace;
1386
}
1387
}
1388
}
1389
1390
// Reconstruct the best path. We do it in reverse order.
1391
std::vector<EditType> best_path;
1392
for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1393
EditType move = best_move[l_i][r_i];
1394
best_path.push_back(move);
1395
l_i -= move != kAdd;
1396
r_i -= move != kRemove;
1397
}
1398
std::reverse(best_path.begin(), best_path.end());
1399
return best_path;
1400
}
1401
1402
namespace {
1403
1404
// Helper class to convert string into ids with deduplication.
1405
class InternalStrings {
1406
public:
1407
size_t GetId(const std::string& str) {
1408
IdMap::iterator it = ids_.find(str);
1409
if (it != ids_.end()) return it->second;
1410
size_t id = ids_.size();
1411
return ids_[str] = id;
1412
}
1413
1414
private:
1415
typedef std::map<std::string, size_t> IdMap;
1416
IdMap ids_;
1417
};
1418
1419
} // namespace
1420
1421
std::vector<EditType> CalculateOptimalEdits(
1422
const std::vector<std::string>& left,
1423
const std::vector<std::string>& right) {
1424
std::vector<size_t> left_ids, right_ids;
1425
{
1426
InternalStrings intern_table;
1427
for (size_t i = 0; i < left.size(); ++i) {
1428
left_ids.push_back(intern_table.GetId(left[i]));
1429
}
1430
for (size_t i = 0; i < right.size(); ++i) {
1431
right_ids.push_back(intern_table.GetId(right[i]));
1432
}
1433
}
1434
return CalculateOptimalEdits(left_ids, right_ids);
1435
}
1436
1437
namespace {
1438
1439
// Helper class that holds the state for one hunk and prints it out to the
1440
// stream.
1441
// It reorders adds/removes when possible to group all removes before all
1442
// adds. It also adds the hunk header before printint into the stream.
1443
class Hunk {
1444
public:
1445
Hunk(size_t left_start, size_t right_start)
1446
: left_start_(left_start),
1447
right_start_(right_start),
1448
adds_(),
1449
removes_(),
1450
common_() {}
1451
1452
void PushLine(char edit, const char* line) {
1453
switch (edit) {
1454
case ' ':
1455
++common_;
1456
FlushEdits();
1457
hunk_.push_back(std::make_pair(' ', line));
1458
break;
1459
case '-':
1460
++removes_;
1461
hunk_removes_.push_back(std::make_pair('-', line));
1462
break;
1463
case '+':
1464
++adds_;
1465
hunk_adds_.push_back(std::make_pair('+', line));
1466
break;
1467
}
1468
}
1469
1470
void PrintTo(std::ostream* os) {
1471
PrintHeader(os);
1472
FlushEdits();
1473
for (std::list<std::pair<char, const char*> >::const_iterator it =
1474
hunk_.begin();
1475
it != hunk_.end(); ++it) {
1476
*os << it->first << it->second << "\n";
1477
}
1478
}
1479
1480
bool has_edits() const { return adds_ || removes_; }
1481
1482
private:
1483
void FlushEdits() {
1484
hunk_.splice(hunk_.end(), hunk_removes_);
1485
hunk_.splice(hunk_.end(), hunk_adds_);
1486
}
1487
1488
// Print a unified diff header for one hunk.
1489
// The format is
1490
// "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1491
// where the left/right parts are omitted if unnecessary.
1492
void PrintHeader(std::ostream* ss) const {
1493
*ss << "@@ ";
1494
if (removes_) {
1495
*ss << "-" << left_start_ << "," << (removes_ + common_);
1496
}
1497
if (removes_ && adds_) {
1498
*ss << " ";
1499
}
1500
if (adds_) {
1501
*ss << "+" << right_start_ << "," << (adds_ + common_);
1502
}
1503
*ss << " @@\n";
1504
}
1505
1506
size_t left_start_, right_start_;
1507
size_t adds_, removes_, common_;
1508
std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1509
};
1510
1511
} // namespace
1512
1513
// Create a list of diff hunks in Unified diff format.
1514
// Each hunk has a header generated by PrintHeader above plus a body with
1515
// lines prefixed with ' ' for no change, '-' for deletion and '+' for
1516
// addition.
1517
// 'context' represents the desired unchanged prefix/suffix around the diff.
1518
// If two hunks are close enough that their contexts overlap, then they are
1519
// joined into one hunk.
1520
std::string CreateUnifiedDiff(const std::vector<std::string>& left,
1521
const std::vector<std::string>& right,
1522
size_t context) {
1523
const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
1524
1525
size_t l_i = 0, r_i = 0, edit_i = 0;
1526
std::stringstream ss;
1527
while (edit_i < edits.size()) {
1528
// Find first edit.
1529
while (edit_i < edits.size() && edits[edit_i] == kMatch) {
1530
++l_i;
1531
++r_i;
1532
++edit_i;
1533
}
1534
1535
// Find the first line to include in the hunk.
1536
const size_t prefix_context = std::min(l_i, context);
1537
Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1538
for (size_t i = prefix_context; i > 0; --i) {
1539
hunk.PushLine(' ', left[l_i - i].c_str());
1540
}
1541
1542
// Iterate the edits until we found enough suffix for the hunk or the input
1543
// is over.
1544
size_t n_suffix = 0;
1545
for (; edit_i < edits.size(); ++edit_i) {
1546
if (n_suffix >= context) {
1547
// Continue only if the next hunk is very close.
1548
auto it = edits.begin() + static_cast<int>(edit_i);
1549
while (it != edits.end() && *it == kMatch) ++it;
1550
if (it == edits.end() ||
1551
static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
1552
// There is no next edit or it is too far away.
1553
break;
1554
}
1555
}
1556
1557
EditType edit = edits[edit_i];
1558
// Reset count when a non match is found.
1559
n_suffix = edit == kMatch ? n_suffix + 1 : 0;
1560
1561
if (edit == kMatch || edit == kRemove || edit == kReplace) {
1562
hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
1563
}
1564
if (edit == kAdd || edit == kReplace) {
1565
hunk.PushLine('+', right[r_i].c_str());
1566
}
1567
1568
// Advance indices, depending on edit type.
1569
l_i += edit != kAdd;
1570
r_i += edit != kRemove;
1571
}
1572
1573
if (!hunk.has_edits()) {
1574
// We are done. We don't want this hunk.
1575
break;
1576
}
1577
1578
hunk.PrintTo(&ss);
1579
}
1580
return ss.str();
1581
}
1582
1583
} // namespace edit_distance
1584
1585
namespace {
1586
1587
// The string representation of the values received in EqFailure() are already
1588
// escaped. Split them on escaped '\n' boundaries. Leave all other escaped
1589
// characters the same.
1590
std::vector<std::string> SplitEscapedString(const std::string& str) {
1591
std::vector<std::string> lines;
1592
size_t start = 0, end = str.size();
1593
if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
1594
++start;
1595
--end;
1596
}
1597
bool escaped = false;
1598
for (size_t i = start; i + 1 < end; ++i) {
1599
if (escaped) {
1600
escaped = false;
1601
if (str[i] == 'n') {
1602
lines.push_back(str.substr(start, i - start - 1));
1603
start = i + 1;
1604
}
1605
} else {
1606
escaped = str[i] == '\\';
1607
}
1608
}
1609
lines.push_back(str.substr(start, end - start));
1610
return lines;
1611
}
1612
1613
} // namespace
1614
1615
// Constructs and returns the message for an equality assertion
1616
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1617
//
1618
// The first four parameters are the expressions used in the assertion
1619
// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
1620
// where foo is 5 and bar is 6, we have:
1621
//
1622
// lhs_expression: "foo"
1623
// rhs_expression: "bar"
1624
// lhs_value: "5"
1625
// rhs_value: "6"
1626
//
1627
// The ignoring_case parameter is true if and only if the assertion is a
1628
// *_STRCASEEQ*. When it's true, the string "Ignoring case" will
1629
// be inserted into the message.
1630
AssertionResult EqFailure(const char* lhs_expression,
1631
const char* rhs_expression,
1632
const std::string& lhs_value,
1633
const std::string& rhs_value, bool ignoring_case) {
1634
Message msg;
1635
msg << "Expected equality of these values:";
1636
msg << "\n " << lhs_expression;
1637
if (lhs_value != lhs_expression) {
1638
msg << "\n Which is: " << lhs_value;
1639
}
1640
msg << "\n " << rhs_expression;
1641
if (rhs_value != rhs_expression) {
1642
msg << "\n Which is: " << rhs_value;
1643
}
1644
1645
if (ignoring_case) {
1646
msg << "\nIgnoring case";
1647
}
1648
1649
if (!lhs_value.empty() && !rhs_value.empty()) {
1650
const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
1651
const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
1652
if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1653
msg << "\nWith diff:\n"
1654
<< edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
1655
}
1656
}
1657
1658
return AssertionFailure() << msg;
1659
}
1660
1661
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1662
std::string GetBoolAssertionFailureMessage(
1663
const AssertionResult& assertion_result, const char* expression_text,
1664
const char* actual_predicate_value, const char* expected_predicate_value) {
1665
const char* actual_message = assertion_result.message();
1666
Message msg;
1667
msg << "Value of: " << expression_text
1668
<< "\n Actual: " << actual_predicate_value;
1669
if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
1670
msg << "\nExpected: " << expected_predicate_value;
1671
return msg.GetString();
1672
}
1673
1674
// Helper function for implementing ASSERT_NEAR. Treats infinity as a specific
1675
// value, such that comparing infinity to infinity is equal, the distance
1676
// between -infinity and +infinity is infinity, and infinity <= infinity is
1677
// true.
1678
AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
1679
const char* abs_error_expr, double val1,
1680
double val2, double abs_error) {
1681
// We want to return success when the two values are infinity and at least
1682
// one of the following is true:
1683
// * The values are the same-signed infinity.
1684
// * The error limit itself is infinity.
1685
// This is done here so that we don't end up with a NaN when calculating the
1686
// difference in values.
1687
if (std::isinf(val1) && std::isinf(val2) &&
1688
(std::signbit(val1) == std::signbit(val2) ||
1689
(abs_error > 0.0 && std::isinf(abs_error)))) {
1690
return AssertionSuccess();
1691
}
1692
1693
const double diff = fabs(val1 - val2);
1694
if (diff <= abs_error) return AssertionSuccess();
1695
1696
// Find the value which is closest to zero.
1697
const double min_abs = std::min(fabs(val1), fabs(val2));
1698
// Find the distance to the next double from that value.
1699
const double epsilon =
1700
nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
1701
// Detect the case where abs_error is so small that EXPECT_NEAR is
1702
// effectively the same as EXPECT_EQUAL, and give an informative error
1703
// message so that the situation can be more easily understood without
1704
// requiring exotic floating-point knowledge.
1705
// Don't do an epsilon check if abs_error is zero because that implies
1706
// that an equality check was actually intended.
1707
if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
1708
abs_error < epsilon) {
1709
return AssertionFailure()
1710
<< "The difference between " << expr1 << " and " << expr2 << " is "
1711
<< diff << ", where\n"
1712
<< expr1 << " evaluates to " << val1 << ",\n"
1713
<< expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
1714
<< abs_error_expr << " evaluates to " << abs_error
1715
<< " which is smaller than the minimum distance between doubles for "
1716
"numbers of this magnitude which is "
1717
<< epsilon
1718
<< ", thus making this EXPECT_NEAR check equivalent to "
1719
"EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
1720
}
1721
return AssertionFailure()
1722
<< "The difference between " << expr1 << " and " << expr2 << " is "
1723
<< diff << ", which exceeds " << abs_error_expr << ", where\n"
1724
<< expr1 << " evaluates to " << val1 << ",\n"
1725
<< expr2 << " evaluates to " << val2 << ", and\n"
1726
<< abs_error_expr << " evaluates to " << abs_error << ".";
1727
}
1728
1729
// Helper template for implementing FloatLE() and DoubleLE().
1730
template <typename RawType>
1731
AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
1732
RawType val1, RawType val2) {
1733
// Returns success if val1 is less than val2,
1734
if (val1 < val2) {
1735
return AssertionSuccess();
1736
}
1737
1738
// or if val1 is almost equal to val2.
1739
const FloatingPoint<RawType> lhs(val1), rhs(val2);
1740
if (lhs.AlmostEquals(rhs)) {
1741
return AssertionSuccess();
1742
}
1743
1744
// Note that the above two checks will both fail if either val1 or
1745
// val2 is NaN, as the IEEE floating-point standard requires that
1746
// any predicate involving a NaN must return false.
1747
1748
::std::stringstream val1_ss;
1749
val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1750
<< val1;
1751
1752
::std::stringstream val2_ss;
1753
val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1754
<< val2;
1755
1756
return AssertionFailure()
1757
<< "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1758
<< " Actual: " << StringStreamToString(&val1_ss) << " vs "
1759
<< StringStreamToString(&val2_ss);
1760
}
1761
1762
} // namespace internal
1763
1764
// Asserts that val1 is less than, or almost equal to, val2. Fails
1765
// otherwise. In particular, it fails if either val1 or val2 is NaN.
1766
AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
1767
float val2) {
1768
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1769
}
1770
1771
// Asserts that val1 is less than, or almost equal to, val2. Fails
1772
// otherwise. In particular, it fails if either val1 or val2 is NaN.
1773
AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
1774
double val2) {
1775
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1776
}
1777
1778
namespace internal {
1779
1780
// The helper function for {ASSERT|EXPECT}_STREQ.
1781
AssertionResult CmpHelperSTREQ(const char* lhs_expression,
1782
const char* rhs_expression, const char* lhs,
1783
const char* rhs) {
1784
if (String::CStringEquals(lhs, rhs)) {
1785
return AssertionSuccess();
1786
}
1787
1788
return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
1789
PrintToString(rhs), false);
1790
}
1791
1792
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1793
AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
1794
const char* rhs_expression, const char* lhs,
1795
const char* rhs) {
1796
if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
1797
return AssertionSuccess();
1798
}
1799
1800
return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
1801
PrintToString(rhs), true);
1802
}
1803
1804
// The helper function for {ASSERT|EXPECT}_STRNE.
1805
AssertionResult CmpHelperSTRNE(const char* s1_expression,
1806
const char* s2_expression, const char* s1,
1807
const char* s2) {
1808
if (!String::CStringEquals(s1, s2)) {
1809
return AssertionSuccess();
1810
} else {
1811
return AssertionFailure()
1812
<< "Expected: (" << s1_expression << ") != (" << s2_expression
1813
<< "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
1814
}
1815
}
1816
1817
// The helper function for {ASSERT|EXPECT}_STRCASENE.
1818
AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1819
const char* s2_expression, const char* s1,
1820
const char* s2) {
1821
if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1822
return AssertionSuccess();
1823
} else {
1824
return AssertionFailure()
1825
<< "Expected: (" << s1_expression << ") != (" << s2_expression
1826
<< ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
1827
}
1828
}
1829
1830
} // namespace internal
1831
1832
namespace {
1833
1834
// Helper functions for implementing IsSubString() and IsNotSubstring().
1835
1836
// This group of overloaded functions return true if and only if needle
1837
// is a substring of haystack. NULL is considered a substring of
1838
// itself only.
1839
1840
bool IsSubstringPred(const char* needle, const char* haystack) {
1841
if (needle == nullptr || haystack == nullptr) return needle == haystack;
1842
1843
return strstr(haystack, needle) != nullptr;
1844
}
1845
1846
bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1847
if (needle == nullptr || haystack == nullptr) return needle == haystack;
1848
1849
return wcsstr(haystack, needle) != nullptr;
1850
}
1851
1852
// StringType here can be either ::std::string or ::std::wstring.
1853
template <typename StringType>
1854
bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
1855
return haystack.find(needle) != StringType::npos;
1856
}
1857
1858
// This function implements either IsSubstring() or IsNotSubstring(),
1859
// depending on the value of the expected_to_be_substring parameter.
1860
// StringType here can be const char*, const wchar_t*, ::std::string,
1861
// or ::std::wstring.
1862
template <typename StringType>
1863
AssertionResult IsSubstringImpl(bool expected_to_be_substring,
1864
const char* needle_expr,
1865
const char* haystack_expr,
1866
const StringType& needle,
1867
const StringType& haystack) {
1868
if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1869
return AssertionSuccess();
1870
1871
const bool is_wide_string = sizeof(needle[0]) > 1;
1872
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1873
return AssertionFailure()
1874
<< "Value of: " << needle_expr << "\n"
1875
<< " Actual: " << begin_string_quote << needle << "\"\n"
1876
<< "Expected: " << (expected_to_be_substring ? "" : "not ")
1877
<< "a substring of " << haystack_expr << "\n"
1878
<< "Which is: " << begin_string_quote << haystack << "\"";
1879
}
1880
1881
} // namespace
1882
1883
// IsSubstring() and IsNotSubstring() check whether needle is a
1884
// substring of haystack (NULL is considered a substring of itself
1885
// only), and return an appropriate error message when they fail.
1886
1887
AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
1888
const char* needle, const char* haystack) {
1889
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1890
}
1891
1892
AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
1893
const wchar_t* needle, const wchar_t* haystack) {
1894
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1895
}
1896
1897
AssertionResult IsNotSubstring(const char* needle_expr,
1898
const char* haystack_expr, const char* needle,
1899
const char* haystack) {
1900
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1901
}
1902
1903
AssertionResult IsNotSubstring(const char* needle_expr,
1904
const char* haystack_expr, const wchar_t* needle,
1905
const wchar_t* haystack) {
1906
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1907
}
1908
1909
AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
1910
const ::std::string& needle,
1911
const ::std::string& haystack) {
1912
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1913
}
1914
1915
AssertionResult IsNotSubstring(const char* needle_expr,
1916
const char* haystack_expr,
1917
const ::std::string& needle,
1918
const ::std::string& haystack) {
1919
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1920
}
1921
1922
#if GTEST_HAS_STD_WSTRING
1923
AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
1924
const ::std::wstring& needle,
1925
const ::std::wstring& haystack) {
1926
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1927
}
1928
1929
AssertionResult IsNotSubstring(const char* needle_expr,
1930
const char* haystack_expr,
1931
const ::std::wstring& needle,
1932
const ::std::wstring& haystack) {
1933
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1934
}
1935
#endif // GTEST_HAS_STD_WSTRING
1936
1937
namespace internal {
1938
1939
#ifdef GTEST_OS_WINDOWS
1940
1941
namespace {
1942
1943
// Helper function for IsHRESULT{SuccessFailure} predicates
1944
AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
1945
long hr) { // NOLINT
1946
#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_TV_TITLE)
1947
1948
// Windows CE doesn't support FormatMessage.
1949
const char error_text[] = "";
1950
1951
#else
1952
1953
// Looks up the human-readable system message for the HRESULT code
1954
// and since we're not passing any params to FormatMessage, we don't
1955
// want inserts expanded.
1956
const DWORD kFlags =
1957
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1958
const DWORD kBufSize = 4096;
1959
// Gets the system's human readable message string for this HRESULT.
1960
char error_text[kBufSize] = {'\0'};
1961
DWORD message_length = ::FormatMessageA(kFlags,
1962
0, // no source, we're asking system
1963
static_cast<DWORD>(hr), // the error
1964
0, // no line width restrictions
1965
error_text, // output buffer
1966
kBufSize, // buf size
1967
nullptr); // no arguments for inserts
1968
// Trims tailing white space (FormatMessage leaves a trailing CR-LF)
1969
for (; message_length && IsSpace(error_text[message_length - 1]);
1970
--message_length) {
1971
error_text[message_length - 1] = '\0';
1972
}
1973
1974
#endif // GTEST_OS_WINDOWS_MOBILE
1975
1976
const std::string error_hex("0x" + String::FormatHexInt(hr));
1977
return ::testing::AssertionFailure()
1978
<< "Expected: " << expr << " " << expected << ".\n"
1979
<< " Actual: " << error_hex << " " << error_text << "\n";
1980
}
1981
1982
} // namespace
1983
1984
AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1985
if (SUCCEEDED(hr)) {
1986
return AssertionSuccess();
1987
}
1988
return HRESULTFailureHelper(expr, "succeeds", hr);
1989
}
1990
1991
AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1992
if (FAILED(hr)) {
1993
return AssertionSuccess();
1994
}
1995
return HRESULTFailureHelper(expr, "fails", hr);
1996
}
1997
1998
#endif // GTEST_OS_WINDOWS
1999
2000
// Utility functions for encoding Unicode text (wide strings) in
2001
// UTF-8.
2002
2003
// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
2004
// like this:
2005
//
2006
// Code-point length Encoding
2007
// 0 - 7 bits 0xxxxxxx
2008
// 8 - 11 bits 110xxxxx 10xxxxxx
2009
// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2010
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2011
2012
// The maximum code-point a one-byte UTF-8 sequence can represent.
2013
constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
2014
2015
// The maximum code-point a two-byte UTF-8 sequence can represent.
2016
constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
2017
2018
// The maximum code-point a three-byte UTF-8 sequence can represent.
2019
constexpr uint32_t kMaxCodePoint3 =
2020
(static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1;
2021
2022
// The maximum code-point a four-byte UTF-8 sequence can represent.
2023
constexpr uint32_t kMaxCodePoint4 =
2024
(static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1;
2025
2026
// Chops off the n lowest bits from a bit pattern. Returns the n
2027
// lowest bits. As a side effect, the original bit pattern will be
2028
// shifted to the right by n bits.
2029
inline uint32_t ChopLowBits(uint32_t* bits, int n) {
2030
const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);
2031
*bits >>= n;
2032
return low_bits;
2033
}
2034
2035
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
2036
// code_point parameter is of type uint32_t because wchar_t may not be
2037
// wide enough to contain a code point.
2038
// If the code_point is not a valid Unicode code point
2039
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
2040
// to "(Invalid Unicode 0xXXXXXXXX)".
2041
std::string CodePointToUtf8(uint32_t code_point) {
2042
if (code_point > kMaxCodePoint4) {
2043
return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
2044
}
2045
2046
char str[5]; // Big enough for the largest valid code point.
2047
if (code_point <= kMaxCodePoint1) {
2048
str[1] = '\0';
2049
str[0] = static_cast<char>(code_point); // 0xxxxxxx
2050
} else if (code_point <= kMaxCodePoint2) {
2051
str[2] = '\0';
2052
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2053
str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2054
} else if (code_point <= kMaxCodePoint3) {
2055
str[3] = '\0';
2056
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2057
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2058
str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
2059
} else { // code_point <= kMaxCodePoint4
2060
str[4] = '\0';
2061
str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2062
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2063
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2064
str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
2065
}
2066
return str;
2067
}
2068
2069
// The following two functions only make sense if the system
2070
// uses UTF-16 for wide string encoding. All supported systems
2071
// with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
2072
2073
// Determines if the arguments constitute UTF-16 surrogate pair
2074
// and thus should be combined into a single Unicode code point
2075
// using CreateCodePointFromUtf16SurrogatePair.
2076
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2077
return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
2078
(second & 0xFC00) == 0xDC00;
2079
}
2080
2081
// Creates a Unicode code point from UTF16 surrogate pair.
2082
inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2083
wchar_t second) {
2084
const auto first_u = static_cast<uint32_t>(first);
2085
const auto second_u = static_cast<uint32_t>(second);
2086
const uint32_t mask = (1 << 10) - 1;
2087
return (sizeof(wchar_t) == 2)
2088
? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
2089
:
2090
// This function should not be called when the condition is
2091
// false, but we provide a sensible default in case it is.
2092
first_u;
2093
}
2094
2095
// Converts a wide string to a narrow string in UTF-8 encoding.
2096
// The wide string is assumed to have the following encoding:
2097
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
2098
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2099
// Parameter str points to a null-terminated wide string.
2100
// Parameter num_chars may additionally limit the number
2101
// of wchar_t characters processed. -1 is used when the entire string
2102
// should be processed.
2103
// If the string contains code points that are not valid Unicode code points
2104
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2105
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2106
// and contains invalid UTF-16 surrogate pairs, values in those pairs
2107
// will be encoded as individual Unicode characters from Basic Normal Plane.
2108
std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
2109
if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
2110
2111
::std::stringstream stream;
2112
for (int i = 0; i < num_chars; ++i) {
2113
uint32_t unicode_code_point;
2114
2115
if (str[i] == L'\0') {
2116
break;
2117
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2118
unicode_code_point =
2119
CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
2120
i++;
2121
} else {
2122
unicode_code_point = static_cast<uint32_t>(str[i]);
2123
}
2124
2125
stream << CodePointToUtf8(unicode_code_point);
2126
}
2127
return StringStreamToString(&stream);
2128
}
2129
2130
// Converts a wide C string to an std::string using the UTF-8 encoding.
2131
// NULL will be converted to "(null)".
2132
std::string String::ShowWideCString(const wchar_t* wide_c_str) {
2133
if (wide_c_str == nullptr) return "(null)";
2134
2135
return internal::WideStringToUtf8(wide_c_str, -1);
2136
}
2137
2138
// Compares two wide C strings. Returns true if and only if they have the
2139
// same content.
2140
//
2141
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2142
// C string is considered different to any non-NULL C string,
2143
// including the empty string.
2144
bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
2145
if (lhs == nullptr) return rhs == nullptr;
2146
2147
if (rhs == nullptr) return false;
2148
2149
return wcscmp(lhs, rhs) == 0;
2150
}
2151
2152
// Helper function for *_STREQ on wide strings.
2153
AssertionResult CmpHelperSTREQ(const char* lhs_expression,
2154
const char* rhs_expression, const wchar_t* lhs,
2155
const wchar_t* rhs) {
2156
if (String::WideCStringEquals(lhs, rhs)) {
2157
return AssertionSuccess();
2158
}
2159
2160
return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
2161
PrintToString(rhs), false);
2162
}
2163
2164
// Helper function for *_STRNE on wide strings.
2165
AssertionResult CmpHelperSTRNE(const char* s1_expression,
2166
const char* s2_expression, const wchar_t* s1,
2167
const wchar_t* s2) {
2168
if (!String::WideCStringEquals(s1, s2)) {
2169
return AssertionSuccess();
2170
}
2171
2172
return AssertionFailure()
2173
<< "Expected: (" << s1_expression << ") != (" << s2_expression
2174
<< "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
2175
}
2176
2177
// Compares two C strings, ignoring case. Returns true if and only if they have
2178
// the same content.
2179
//
2180
// Unlike strcasecmp(), this function can handle NULL argument(s). A
2181
// NULL C string is considered different to any non-NULL C string,
2182
// including the empty string.
2183
bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
2184
if (lhs == nullptr) return rhs == nullptr;
2185
if (rhs == nullptr) return false;
2186
return posix::StrCaseCmp(lhs, rhs) == 0;
2187
}
2188
2189
// Compares two wide C strings, ignoring case. Returns true if and only if they
2190
// have the same content.
2191
//
2192
// Unlike wcscasecmp(), this function can handle NULL argument(s).
2193
// A NULL C string is considered different to any non-NULL wide C string,
2194
// including the empty string.
2195
// NB: The implementations on different platforms slightly differ.
2196
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
2197
// environment variable. On GNU platform this method uses wcscasecmp
2198
// which compares according to LC_CTYPE category of the current locale.
2199
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
2200
// current locale.
2201
bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
2202
const wchar_t* rhs) {
2203
if (lhs == nullptr) return rhs == nullptr;
2204
2205
if (rhs == nullptr) return false;
2206
2207
#ifdef GTEST_OS_WINDOWS
2208
return _wcsicmp(lhs, rhs) == 0;
2209
#elif defined(GTEST_OS_LINUX) && !defined(GTEST_OS_LINUX_ANDROID)
2210
return wcscasecmp(lhs, rhs) == 0;
2211
#else
2212
// Android, Mac OS X and Cygwin don't define wcscasecmp.
2213
// Other unknown OSes may not define it either.
2214
wint_t left, right;
2215
do {
2216
left = towlower(static_cast<wint_t>(*lhs++));
2217
right = towlower(static_cast<wint_t>(*rhs++));
2218
} while (left && left == right);
2219
return left == right;
2220
#endif // OS selector
2221
}
2222
2223
// Returns true if and only if str ends with the given suffix, ignoring case.
2224
// Any string is considered to end with an empty suffix.
2225
bool String::EndsWithCaseInsensitive(const std::string& str,
2226
const std::string& suffix) {
2227
const size_t str_len = str.length();
2228
const size_t suffix_len = suffix.length();
2229
return (str_len >= suffix_len) &&
2230
CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
2231
suffix.c_str());
2232
}
2233
2234
// Formats an int value as "%02d".
2235
std::string String::FormatIntWidth2(int value) {
2236
return FormatIntWidthN(value, 2);
2237
}
2238
2239
// Formats an int value to given width with leading zeros.
2240
std::string String::FormatIntWidthN(int value, int width) {
2241
std::stringstream ss;
2242
ss << std::setfill('0') << std::setw(width) << value;
2243
return ss.str();
2244
}
2245
2246
// Formats an int value as "%X".
2247
std::string String::FormatHexUInt32(uint32_t value) {
2248
std::stringstream ss;
2249
ss << std::hex << std::uppercase << value;
2250
return ss.str();
2251
}
2252
2253
// Formats an int value as "%X".
2254
std::string String::FormatHexInt(int value) {
2255
return FormatHexUInt32(static_cast<uint32_t>(value));
2256
}
2257
2258
// Formats a byte as "%02X".
2259
std::string String::FormatByte(unsigned char value) {
2260
std::stringstream ss;
2261
ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
2262
<< static_cast<unsigned int>(value);
2263
return ss.str();
2264
}
2265
2266
// Converts the buffer in a stringstream to an std::string, converting NUL
2267
// bytes to "\\0" along the way.
2268
std::string StringStreamToString(::std::stringstream* ss) {
2269
const ::std::string& str = ss->str();
2270
const char* const start = str.c_str();
2271
const char* const end = start + str.length();
2272
2273
std::string result;
2274
result.reserve(static_cast<size_t>(2 * (end - start)));
2275
for (const char* ch = start; ch != end; ++ch) {
2276
if (*ch == '\0') {
2277
result += "\\0"; // Replaces NUL with "\\0";
2278
} else {
2279
result += *ch;
2280
}
2281
}
2282
2283
return result;
2284
}
2285
2286
// Appends the user-supplied message to the Google-Test-generated message.
2287
std::string AppendUserMessage(const std::string& gtest_msg,
2288
const Message& user_msg) {
2289
// Appends the user message if it's non-empty.
2290
const std::string user_msg_string = user_msg.GetString();
2291
if (user_msg_string.empty()) {
2292
return gtest_msg;
2293
}
2294
if (gtest_msg.empty()) {
2295
return user_msg_string;
2296
}
2297
return gtest_msg + "\n" + user_msg_string;
2298
}
2299
2300
} // namespace internal
2301
2302
// class TestResult
2303
2304
// Creates an empty TestResult.
2305
TestResult::TestResult()
2306
: death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2307
2308
// D'tor.
2309
TestResult::~TestResult() = default;
2310
2311
// Returns the i-th test part result among all the results. i can
2312
// range from 0 to total_part_count() - 1. If i is not in that range,
2313
// aborts the program.
2314
const TestPartResult& TestResult::GetTestPartResult(int i) const {
2315
if (i < 0 || i >= total_part_count()) internal::posix::Abort();
2316
return test_part_results_.at(static_cast<size_t>(i));
2317
}
2318
2319
// Returns the i-th test property. i can range from 0 to
2320
// test_property_count() - 1. If i is not in that range, aborts the
2321
// program.
2322
const TestProperty& TestResult::GetTestProperty(int i) const {
2323
if (i < 0 || i >= test_property_count()) internal::posix::Abort();
2324
return test_properties_.at(static_cast<size_t>(i));
2325
}
2326
2327
// Clears the test part results.
2328
void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
2329
2330
// Adds a test part result to the list.
2331
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
2332
test_part_results_.push_back(test_part_result);
2333
}
2334
2335
// Adds a test property to the list. If a property with the same key as the
2336
// supplied property is already represented, the value of this test_property
2337
// replaces the old value for that key.
2338
void TestResult::RecordProperty(const std::string& xml_element,
2339
const TestProperty& test_property) {
2340
if (!ValidateTestProperty(xml_element, test_property)) {
2341
return;
2342
}
2343
internal::MutexLock lock(&test_properties_mutex_);
2344
const std::vector<TestProperty>::iterator property_with_matching_key =
2345
std::find_if(test_properties_.begin(), test_properties_.end(),
2346
internal::TestPropertyKeyIs(test_property.key()));
2347
if (property_with_matching_key == test_properties_.end()) {
2348
test_properties_.push_back(test_property);
2349
return;
2350
}
2351
property_with_matching_key->SetValue(test_property.value());
2352
}
2353
2354
// The list of reserved attributes used in the <testsuites> element of XML
2355
// output.
2356
static const char* const kReservedTestSuitesAttributes[] = {
2357
"disabled", "errors", "failures", "name",
2358
"random_seed", "tests", "time", "timestamp"};
2359
2360
// The list of reserved attributes used in the <testsuite> element of XML
2361
// output.
2362
static const char* const kReservedTestSuiteAttributes[] = {
2363
"disabled", "errors", "failures", "name",
2364
"tests", "time", "timestamp", "skipped"};
2365
2366
// The list of reserved attributes used in the <testcase> element of XML output.
2367
static const char* const kReservedTestCaseAttributes[] = {
2368
"classname", "name", "status", "time",
2369
"type_param", "value_param", "file", "line"};
2370
2371
// Use a slightly different set for allowed output to ensure existing tests can
2372
// still RecordProperty("result") or RecordProperty("timestamp")
2373
static const char* const kReservedOutputTestCaseAttributes[] = {
2374
"classname", "name", "status", "time", "type_param",
2375
"value_param", "file", "line", "result", "timestamp"};
2376
2377
template <size_t kSize>
2378
std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
2379
return std::vector<std::string>(array, array + kSize);
2380
}
2381
2382
static std::vector<std::string> GetReservedAttributesForElement(
2383
const std::string& xml_element) {
2384
if (xml_element == "testsuites") {
2385
return ArrayAsVector(kReservedTestSuitesAttributes);
2386
} else if (xml_element == "testsuite") {
2387
return ArrayAsVector(kReservedTestSuiteAttributes);
2388
} else if (xml_element == "testcase") {
2389
return ArrayAsVector(kReservedTestCaseAttributes);
2390
} else {
2391
GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2392
}
2393
// This code is unreachable but some compilers may not realizes that.
2394
return std::vector<std::string>();
2395
}
2396
2397
#if GTEST_HAS_FILE_SYSTEM
2398
// TODO(jdesprez): Merge the two getReserved attributes once skip is improved
2399
// This function is only used when file systems are enabled.
2400
static std::vector<std::string> GetReservedOutputAttributesForElement(
2401
const std::string& xml_element) {
2402
if (xml_element == "testsuites") {
2403
return ArrayAsVector(kReservedTestSuitesAttributes);
2404
} else if (xml_element == "testsuite") {
2405
return ArrayAsVector(kReservedTestSuiteAttributes);
2406
} else if (xml_element == "testcase") {
2407
return ArrayAsVector(kReservedOutputTestCaseAttributes);
2408
} else {
2409
GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2410
}
2411
// This code is unreachable but some compilers may not realizes that.
2412
return std::vector<std::string>();
2413
}
2414
#endif
2415
2416
static std::string FormatWordList(const std::vector<std::string>& words) {
2417
Message word_list;
2418
for (size_t i = 0; i < words.size(); ++i) {
2419
if (i > 0 && words.size() > 2) {
2420
word_list << ", ";
2421
}
2422
if (i == words.size() - 1) {
2423
word_list << "and ";
2424
}
2425
word_list << "'" << words[i] << "'";
2426
}
2427
return word_list.GetString();
2428
}
2429
2430
static bool ValidateTestPropertyName(
2431
const std::string& property_name,
2432
const std::vector<std::string>& reserved_names) {
2433
if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2434
reserved_names.end()) {
2435
ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
2436
<< " (" << FormatWordList(reserved_names)
2437
<< " are reserved by " << GTEST_NAME_ << ")";
2438
return false;
2439
}
2440
return true;
2441
}
2442
2443
// Adds a failure if the key is a reserved attribute of the element named
2444
// xml_element. Returns true if the property is valid.
2445
bool TestResult::ValidateTestProperty(const std::string& xml_element,
2446
const TestProperty& test_property) {
2447
return ValidateTestPropertyName(test_property.key(),
2448
GetReservedAttributesForElement(xml_element));
2449
}
2450
2451
// Clears the object.
2452
void TestResult::Clear() {
2453
test_part_results_.clear();
2454
test_properties_.clear();
2455
death_test_count_ = 0;
2456
elapsed_time_ = 0;
2457
}
2458
2459
// Returns true off the test part was skipped.
2460
static bool TestPartSkipped(const TestPartResult& result) {
2461
return result.skipped();
2462
}
2463
2464
// Returns true if and only if the test was skipped.
2465
bool TestResult::Skipped() const {
2466
return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
2467
}
2468
2469
// Returns true if and only if the test failed.
2470
bool TestResult::Failed() const {
2471
for (int i = 0; i < total_part_count(); ++i) {
2472
if (GetTestPartResult(i).failed()) return true;
2473
}
2474
return false;
2475
}
2476
2477
// Returns true if and only if the test part fatally failed.
2478
static bool TestPartFatallyFailed(const TestPartResult& result) {
2479
return result.fatally_failed();
2480
}
2481
2482
// Returns true if and only if the test fatally failed.
2483
bool TestResult::HasFatalFailure() const {
2484
return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
2485
}
2486
2487
// Returns true if and only if the test part non-fatally failed.
2488
static bool TestPartNonfatallyFailed(const TestPartResult& result) {
2489
return result.nonfatally_failed();
2490
}
2491
2492
// Returns true if and only if the test has a non-fatal failure.
2493
bool TestResult::HasNonfatalFailure() const {
2494
return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
2495
}
2496
2497
// Gets the number of all test parts. This is the sum of the number
2498
// of successful test parts and the number of failed test parts.
2499
int TestResult::total_part_count() const {
2500
return static_cast<int>(test_part_results_.size());
2501
}
2502
2503
// Returns the number of the test properties.
2504
int TestResult::test_property_count() const {
2505
return static_cast<int>(test_properties_.size());
2506
}
2507
2508
// class Test
2509
2510
// Creates a Test object.
2511
2512
// The c'tor saves the states of all flags.
2513
Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}
2514
2515
// The d'tor restores the states of all flags. The actual work is
2516
// done by the d'tor of the gtest_flag_saver_ field, and thus not
2517
// visible here.
2518
Test::~Test() = default;
2519
2520
// Sets up the test fixture.
2521
//
2522
// A sub-class may override this.
2523
void Test::SetUp() {}
2524
2525
// Tears down the test fixture.
2526
//
2527
// A sub-class may override this.
2528
void Test::TearDown() {}
2529
2530
// Allows user supplied key value pairs to be recorded for later output.
2531
void Test::RecordProperty(const std::string& key, const std::string& value) {
2532
UnitTest::GetInstance()->RecordProperty(key, value);
2533
}
2534
2535
namespace internal {
2536
2537
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
2538
const std::string& message) {
2539
// This function is a friend of UnitTest and as such has access to
2540
// AddTestPartResult.
2541
UnitTest::GetInstance()->AddTestPartResult(
2542
result_type,
2543
nullptr, // No info about the source file where the exception occurred.
2544
-1, // We have no info on which line caused the exception.
2545
message,
2546
""); // No stack trace, either.
2547
}
2548
2549
} // namespace internal
2550
2551
// Google Test requires all tests in the same test suite to use the same test
2552
// fixture class. This function checks if the current test has the
2553
// same fixture class as the first test in the current test suite. If
2554
// yes, it returns true; otherwise it generates a Google Test failure and
2555
// returns false.
2556
bool Test::HasSameFixtureClass() {
2557
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2558
const TestSuite* const test_suite = impl->current_test_suite();
2559
2560
// Info about the first test in the current test suite.
2561
const TestInfo* const first_test_info = test_suite->test_info_list()[0];
2562
const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2563
const char* const first_test_name = first_test_info->name();
2564
2565
// Info about the current test.
2566
const TestInfo* const this_test_info = impl->current_test_info();
2567
const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2568
const char* const this_test_name = this_test_info->name();
2569
2570
if (this_fixture_id != first_fixture_id) {
2571
// Is the first test defined using TEST?
2572
const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2573
// Is this test defined using TEST?
2574
const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2575
2576
if (first_is_TEST || this_is_TEST) {
2577
// Both TEST and TEST_F appear in same test suite, which is incorrect.
2578
// Tell the user how to fix this.
2579
2580
// Gets the name of the TEST and the name of the TEST_F. Note
2581
// that first_is_TEST and this_is_TEST cannot both be true, as
2582
// the fixture IDs are different for the two tests.
2583
const char* const TEST_name =
2584
first_is_TEST ? first_test_name : this_test_name;
2585
const char* const TEST_F_name =
2586
first_is_TEST ? this_test_name : first_test_name;
2587
2588
ADD_FAILURE()
2589
<< "All tests in the same test suite must use the same test fixture\n"
2590
<< "class, so mixing TEST_F and TEST in the same test suite is\n"
2591
<< "illegal. In test suite " << this_test_info->test_suite_name()
2592
<< ",\n"
2593
<< "test " << TEST_F_name << " is defined using TEST_F but\n"
2594
<< "test " << TEST_name << " is defined using TEST. You probably\n"
2595
<< "want to change the TEST to TEST_F or move it to another test\n"
2596
<< "case.";
2597
} else {
2598
// Two fixture classes with the same name appear in two different
2599
// namespaces, which is not allowed. Tell the user how to fix this.
2600
ADD_FAILURE()
2601
<< "All tests in the same test suite must use the same test fixture\n"
2602
<< "class. However, in test suite "
2603
<< this_test_info->test_suite_name() << ",\n"
2604
<< "you defined test " << first_test_name << " and test "
2605
<< this_test_name << "\n"
2606
<< "using two different test fixture classes. This can happen if\n"
2607
<< "the two classes are from different namespaces or translation\n"
2608
<< "units and have the same name. You should probably rename one\n"
2609
<< "of the classes to put the tests into different test suites.";
2610
}
2611
return false;
2612
}
2613
2614
return true;
2615
}
2616
2617
namespace internal {
2618
2619
#if GTEST_HAS_EXCEPTIONS
2620
2621
// Adds an "exception thrown" fatal failure to the current test.
2622
static std::string FormatCxxExceptionMessage(const char* description,
2623
const char* location) {
2624
Message message;
2625
if (description != nullptr) {
2626
message << "C++ exception with description \"" << description << "\"";
2627
} else {
2628
message << "Unknown C++ exception";
2629
}
2630
message << " thrown in " << location << ".";
2631
2632
return message.GetString();
2633
}
2634
2635
static std::string PrintTestPartResultToString(
2636
const TestPartResult& test_part_result);
2637
2638
GoogleTestFailureException::GoogleTestFailureException(
2639
const TestPartResult& failure)
2640
: ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
2641
2642
#endif // GTEST_HAS_EXCEPTIONS
2643
2644
// We put these helper functions in the internal namespace as IBM's xlC
2645
// compiler rejects the code if they were declared static.
2646
2647
// Runs the given method and handles SEH exceptions it throws, when
2648
// SEH is supported; returns the 0-value for type Result in case of an
2649
// SEH exception. (Microsoft compilers cannot handle SEH and C++
2650
// exceptions in the same function. Therefore, we provide a separate
2651
// wrapper function for handling SEH exceptions.)
2652
template <class T, typename Result>
2653
Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
2654
const char* location) {
2655
#if GTEST_HAS_SEH
2656
__try {
2657
return (object->*method)();
2658
} __except (internal::UnitTestOptions::GTestProcessSEH( // NOLINT
2659
GetExceptionCode(), location)) {
2660
return static_cast<Result>(0);
2661
}
2662
#else
2663
(void)location;
2664
return (object->*method)();
2665
#endif // GTEST_HAS_SEH
2666
}
2667
2668
// Runs the given method and catches and reports C++ and/or SEH-style
2669
// exceptions, if they are supported; returns the 0-value for type
2670
// Result in case of an SEH exception.
2671
template <class T, typename Result>
2672
Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
2673
const char* location) {
2674
// NOTE: The user code can affect the way in which Google Test handles
2675
// exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2676
// RUN_ALL_TESTS() starts. It is technically possible to check the flag
2677
// after the exception is caught and either report or re-throw the
2678
// exception based on the flag's value:
2679
//
2680
// try {
2681
// // Perform the test method.
2682
// } catch (...) {
2683
// if (GTEST_FLAG_GET(catch_exceptions))
2684
// // Report the exception as failure.
2685
// else
2686
// throw; // Re-throws the original exception.
2687
// }
2688
//
2689
// However, the purpose of this flag is to allow the program to drop into
2690
// the debugger when the exception is thrown. On most platforms, once the
2691
// control enters the catch block, the exception origin information is
2692
// lost and the debugger will stop the program at the point of the
2693
// re-throw in this function -- instead of at the point of the original
2694
// throw statement in the code under test. For this reason, we perform
2695
// the check early, sacrificing the ability to affect Google Test's
2696
// exception handling in the method where the exception is thrown.
2697
if (internal::GetUnitTestImpl()->catch_exceptions()) {
2698
#if GTEST_HAS_EXCEPTIONS
2699
try {
2700
return HandleSehExceptionsInMethodIfSupported(object, method, location);
2701
} catch (const AssertionException&) { // NOLINT
2702
// This failure was reported already.
2703
} catch (const internal::GoogleTestFailureException&) { // NOLINT
2704
// This exception type can only be thrown by a failed Google
2705
// Test assertion with the intention of letting another testing
2706
// framework catch it. Therefore we just re-throw it.
2707
throw;
2708
} catch (const std::exception& e) { // NOLINT
2709
internal::ReportFailureInUnknownLocation(
2710
TestPartResult::kFatalFailure,
2711
FormatCxxExceptionMessage(e.what(), location));
2712
} catch (...) { // NOLINT
2713
internal::ReportFailureInUnknownLocation(
2714
TestPartResult::kFatalFailure,
2715
FormatCxxExceptionMessage(nullptr, location));
2716
}
2717
return static_cast<Result>(0);
2718
#else
2719
return HandleSehExceptionsInMethodIfSupported(object, method, location);
2720
#endif // GTEST_HAS_EXCEPTIONS
2721
} else {
2722
return (object->*method)();
2723
}
2724
}
2725
2726
} // namespace internal
2727
2728
// Runs the test and updates the test result.
2729
void Test::Run() {
2730
if (!HasSameFixtureClass()) return;
2731
2732
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2733
impl->os_stack_trace_getter()->UponLeavingGTest();
2734
internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2735
// We will run the test only if SetUp() was successful and didn't call
2736
// GTEST_SKIP().
2737
if (!HasFatalFailure() && !IsSkipped()) {
2738
impl->os_stack_trace_getter()->UponLeavingGTest();
2739
internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
2740
"the test body");
2741
}
2742
2743
// However, we want to clean up as much as possible. Hence we will
2744
// always call TearDown(), even if SetUp() or the test body has
2745
// failed.
2746
impl->os_stack_trace_getter()->UponLeavingGTest();
2747
internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
2748
"TearDown()");
2749
}
2750
2751
// Returns true if and only if the current test has a fatal failure.
2752
bool Test::HasFatalFailure() {
2753
return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2754
}
2755
2756
// Returns true if and only if the current test has a non-fatal failure.
2757
bool Test::HasNonfatalFailure() {
2758
return internal::GetUnitTestImpl()
2759
->current_test_result()
2760
->HasNonfatalFailure();
2761
}
2762
2763
// Returns true if and only if the current test was skipped.
2764
bool Test::IsSkipped() {
2765
return internal::GetUnitTestImpl()->current_test_result()->Skipped();
2766
}
2767
2768
// class TestInfo
2769
2770
// Constructs a TestInfo object. It assumes ownership of the test factory
2771
// object.
2772
TestInfo::TestInfo(std::string a_test_suite_name, std::string a_name,
2773
const char* a_type_param, const char* a_value_param,
2774
internal::CodeLocation a_code_location,
2775
internal::TypeId fixture_class_id,
2776
internal::TestFactoryBase* factory)
2777
: test_suite_name_(std::move(a_test_suite_name)),
2778
name_(std::move(a_name)),
2779
type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2780
value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
2781
location_(std::move(a_code_location)),
2782
fixture_class_id_(fixture_class_id),
2783
should_run_(false),
2784
is_disabled_(false),
2785
matches_filter_(false),
2786
is_in_another_shard_(false),
2787
factory_(factory),
2788
result_() {}
2789
2790
// Destructs a TestInfo object.
2791
TestInfo::~TestInfo() { delete factory_; }
2792
2793
namespace internal {
2794
2795
// Creates a new TestInfo object and registers it with Google Test;
2796
// returns the created object.
2797
//
2798
// Arguments:
2799
//
2800
// test_suite_name: name of the test suite
2801
// name: name of the test
2802
// type_param: the name of the test's type parameter, or NULL if
2803
// this is not a typed or a type-parameterized test.
2804
// value_param: text representation of the test's value parameter,
2805
// or NULL if this is not a value-parameterized test.
2806
// code_location: code location where the test is defined
2807
// fixture_class_id: ID of the test fixture class
2808
// set_up_tc: pointer to the function that sets up the test suite
2809
// tear_down_tc: pointer to the function that tears down the test suite
2810
// factory: pointer to the factory that creates a test object.
2811
// The newly created TestInfo instance will assume
2812
// ownership of the factory object.
2813
TestInfo* MakeAndRegisterTestInfo(
2814
std::string test_suite_name, const char* name, const char* type_param,
2815
const char* value_param, CodeLocation code_location,
2816
TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
2817
TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
2818
TestInfo* const test_info =
2819
new TestInfo(std::move(test_suite_name), name, type_param, value_param,
2820
std::move(code_location), fixture_class_id, factory);
2821
GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2822
return test_info;
2823
}
2824
2825
void ReportInvalidTestSuiteType(const char* test_suite_name,
2826
const CodeLocation& code_location) {
2827
Message errors;
2828
errors
2829
<< "Attempted redefinition of test suite " << test_suite_name << ".\n"
2830
<< "All tests in the same test suite must use the same test fixture\n"
2831
<< "class. However, in test suite " << test_suite_name << ", you tried\n"
2832
<< "to define a test using a fixture class different from the one\n"
2833
<< "used earlier. This can happen if the two fixture classes are\n"
2834
<< "from different namespaces and have the same name. You should\n"
2835
<< "probably rename one of the classes to put the tests into different\n"
2836
<< "test suites.";
2837
2838
GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
2839
code_location.line)
2840
<< " " << errors.GetString();
2841
}
2842
2843
// This method expands all parameterized tests registered with macros TEST_P
2844
// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
2845
// This will be done just once during the program runtime.
2846
void UnitTestImpl::RegisterParameterizedTests() {
2847
if (!parameterized_tests_registered_) {
2848
parameterized_test_registry_.RegisterTests();
2849
type_parameterized_test_registry_.CheckForInstantiations();
2850
parameterized_tests_registered_ = true;
2851
}
2852
}
2853
2854
} // namespace internal
2855
2856
// Creates the test object, runs it, records its result, and then
2857
// deletes it.
2858
void TestInfo::Run() {
2859
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2860
if (!should_run_) {
2861
if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*this);
2862
return;
2863
}
2864
2865
// Tells UnitTest where to store test result.
2866
UnitTest::GetInstance()->set_current_test_info(this);
2867
2868
// Notifies the unit test event listeners that a test is about to start.
2869
repeater->OnTestStart(*this);
2870
result_.set_start_timestamp(internal::GetTimeInMillis());
2871
internal::Timer timer;
2872
UnitTest::GetInstance()->UponLeavingGTest();
2873
2874
// Creates the test object.
2875
Test* const test = internal::HandleExceptionsInMethodIfSupported(
2876
factory_, &internal::TestFactoryBase::CreateTest,
2877
"the test fixture's constructor");
2878
2879
// Runs the test if the constructor didn't generate a fatal failure or invoke
2880
// GTEST_SKIP().
2881
// Note that the object will not be null
2882
if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
2883
// This doesn't throw as all user code that can throw are wrapped into
2884
// exception handling code.
2885
test->Run();
2886
}
2887
2888
if (test != nullptr) {
2889
// Deletes the test object.
2890
UnitTest::GetInstance()->UponLeavingGTest();
2891
internal::HandleExceptionsInMethodIfSupported(
2892
test, &Test::DeleteSelf_, "the test fixture's destructor");
2893
}
2894
2895
result_.set_elapsed_time(timer.Elapsed());
2896
2897
// Notifies the unit test event listener that a test has just finished.
2898
repeater->OnTestEnd(*this);
2899
2900
// Tells UnitTest to stop associating assertion results to this
2901
// test.
2902
UnitTest::GetInstance()->set_current_test_info(nullptr);
2903
}
2904
2905
// Skip and records a skipped test result for this object.
2906
void TestInfo::Skip() {
2907
if (!should_run_) return;
2908
2909
UnitTest::GetInstance()->set_current_test_info(this);
2910
2911
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2912
2913
// Notifies the unit test event listeners that a test is about to start.
2914
repeater->OnTestStart(*this);
2915
2916
const TestPartResult test_part_result =
2917
TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
2918
internal::GetUnitTestImpl()
2919
->GetTestPartResultReporterForCurrentThread()
2920
->ReportTestPartResult(test_part_result);
2921
2922
// Notifies the unit test event listener that a test has just finished.
2923
repeater->OnTestEnd(*this);
2924
UnitTest::GetInstance()->set_current_test_info(nullptr);
2925
}
2926
2927
// class TestSuite
2928
2929
// Gets the number of successful tests in this test suite.
2930
int TestSuite::successful_test_count() const {
2931
return CountIf(test_info_list_, TestPassed);
2932
}
2933
2934
// Gets the number of successful tests in this test suite.
2935
int TestSuite::skipped_test_count() const {
2936
return CountIf(test_info_list_, TestSkipped);
2937
}
2938
2939
// Gets the number of failed tests in this test suite.
2940
int TestSuite::failed_test_count() const {
2941
return CountIf(test_info_list_, TestFailed);
2942
}
2943
2944
// Gets the number of disabled tests that will be reported in the XML report.
2945
int TestSuite::reportable_disabled_test_count() const {
2946
return CountIf(test_info_list_, TestReportableDisabled);
2947
}
2948
2949
// Gets the number of disabled tests in this test suite.
2950
int TestSuite::disabled_test_count() const {
2951
return CountIf(test_info_list_, TestDisabled);
2952
}
2953
2954
// Gets the number of tests to be printed in the XML report.
2955
int TestSuite::reportable_test_count() const {
2956
return CountIf(test_info_list_, TestReportable);
2957
}
2958
2959
// Get the number of tests in this test suite that should run.
2960
int TestSuite::test_to_run_count() const {
2961
return CountIf(test_info_list_, ShouldRunTest);
2962
}
2963
2964
// Gets the number of all tests.
2965
int TestSuite::total_test_count() const {
2966
return static_cast<int>(test_info_list_.size());
2967
}
2968
2969
// Creates a TestSuite with the given name.
2970
//
2971
// Arguments:
2972
//
2973
// a_name: name of the test suite
2974
// a_type_param: the name of the test suite's type parameter, or NULL if
2975
// this is not a typed or a type-parameterized test suite.
2976
// set_up_tc: pointer to the function that sets up the test suite
2977
// tear_down_tc: pointer to the function that tears down the test suite
2978
TestSuite::TestSuite(const std::string& a_name, const char* a_type_param,
2979
internal::SetUpTestSuiteFunc set_up_tc,
2980
internal::TearDownTestSuiteFunc tear_down_tc)
2981
: name_(a_name),
2982
type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2983
set_up_tc_(set_up_tc),
2984
tear_down_tc_(tear_down_tc),
2985
should_run_(false),
2986
start_timestamp_(0),
2987
elapsed_time_(0) {}
2988
2989
// Destructor of TestSuite.
2990
TestSuite::~TestSuite() {
2991
// Deletes every Test in the collection.
2992
ForEach(test_info_list_, internal::Delete<TestInfo>);
2993
}
2994
2995
// Returns the i-th test among all the tests. i can range from 0 to
2996
// total_test_count() - 1. If i is not in that range, returns NULL.
2997
const TestInfo* TestSuite::GetTestInfo(int i) const {
2998
const int index = GetElementOr(test_indices_, i, -1);
2999
return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
3000
}
3001
3002
// Returns the i-th test among all the tests. i can range from 0 to
3003
// total_test_count() - 1. If i is not in that range, returns NULL.
3004
TestInfo* TestSuite::GetMutableTestInfo(int i) {
3005
const int index = GetElementOr(test_indices_, i, -1);
3006
return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
3007
}
3008
3009
// Adds a test to this test suite. Will delete the test upon
3010
// destruction of the TestSuite object.
3011
void TestSuite::AddTestInfo(TestInfo* test_info) {
3012
test_info_list_.push_back(test_info);
3013
test_indices_.push_back(static_cast<int>(test_indices_.size()));
3014
}
3015
3016
// Runs every test in this TestSuite.
3017
void TestSuite::Run() {
3018
if (!should_run_) return;
3019
3020
UnitTest::GetInstance()->set_current_test_suite(this);
3021
3022
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3023
3024
// Ensure our tests are in a deterministic order.
3025
//
3026
// We do this by sorting lexicographically on (file, line number), providing
3027
// an order matching what the user can see in the source code.
3028
//
3029
// In the common case the line number comparison shouldn't be necessary,
3030
// because the registrations made by the TEST macro are executed in order
3031
// within a translation unit. But this is not true of the manual registration
3032
// API, and in more exotic scenarios a single file may be part of multiple
3033
// translation units.
3034
std::stable_sort(test_info_list_.begin(), test_info_list_.end(),
3035
[](const TestInfo* const a, const TestInfo* const b) {
3036
if (const int result = std::strcmp(a->file(), b->file())) {
3037
return result < 0;
3038
}
3039
3040
return a->line() < b->line();
3041
});
3042
3043
// Call both legacy and the new API
3044
repeater->OnTestSuiteStart(*this);
3045
// Legacy API is deprecated but still available
3046
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3047
repeater->OnTestCaseStart(*this);
3048
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3049
3050
UnitTest::GetInstance()->UponLeavingGTest();
3051
internal::HandleExceptionsInMethodIfSupported(
3052
this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
3053
3054
const bool skip_all =
3055
ad_hoc_test_result().Failed() || ad_hoc_test_result().Skipped();
3056
3057
start_timestamp_ = internal::GetTimeInMillis();
3058
internal::Timer timer;
3059
for (int i = 0; i < total_test_count(); i++) {
3060
if (skip_all) {
3061
GetMutableTestInfo(i)->Skip();
3062
} else {
3063
GetMutableTestInfo(i)->Run();
3064
}
3065
if (GTEST_FLAG_GET(fail_fast) &&
3066
GetMutableTestInfo(i)->result()->Failed()) {
3067
for (int j = i + 1; j < total_test_count(); j++) {
3068
GetMutableTestInfo(j)->Skip();
3069
}
3070
break;
3071
}
3072
}
3073
elapsed_time_ = timer.Elapsed();
3074
3075
UnitTest::GetInstance()->UponLeavingGTest();
3076
internal::HandleExceptionsInMethodIfSupported(
3077
this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
3078
3079
// Call both legacy and the new API
3080
repeater->OnTestSuiteEnd(*this);
3081
// Legacy API is deprecated but still available
3082
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3083
repeater->OnTestCaseEnd(*this);
3084
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3085
3086
UnitTest::GetInstance()->set_current_test_suite(nullptr);
3087
}
3088
3089
// Skips all tests under this TestSuite.
3090
void TestSuite::Skip() {
3091
if (!should_run_) return;
3092
3093
UnitTest::GetInstance()->set_current_test_suite(this);
3094
3095
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3096
3097
// Call both legacy and the new API
3098
repeater->OnTestSuiteStart(*this);
3099
// Legacy API is deprecated but still available
3100
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3101
repeater->OnTestCaseStart(*this);
3102
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3103
3104
for (int i = 0; i < total_test_count(); i++) {
3105
GetMutableTestInfo(i)->Skip();
3106
}
3107
3108
// Call both legacy and the new API
3109
repeater->OnTestSuiteEnd(*this);
3110
// Legacy API is deprecated but still available
3111
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3112
repeater->OnTestCaseEnd(*this);
3113
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3114
3115
UnitTest::GetInstance()->set_current_test_suite(nullptr);
3116
}
3117
3118
// Clears the results of all tests in this test suite.
3119
void TestSuite::ClearResult() {
3120
ad_hoc_test_result_.Clear();
3121
ForEach(test_info_list_, TestInfo::ClearTestResult);
3122
}
3123
3124
// Shuffles the tests in this test suite.
3125
void TestSuite::ShuffleTests(internal::Random* random) {
3126
Shuffle(random, &test_indices_);
3127
}
3128
3129
// Restores the test order to before the first shuffle.
3130
void TestSuite::UnshuffleTests() {
3131
for (size_t i = 0; i < test_indices_.size(); i++) {
3132
test_indices_[i] = static_cast<int>(i);
3133
}
3134
}
3135
3136
// Formats a countable noun. Depending on its quantity, either the
3137
// singular form or the plural form is used. e.g.
3138
//
3139
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3140
// FormatCountableNoun(5, "book", "books") returns "5 books".
3141
static std::string FormatCountableNoun(int count, const char* singular_form,
3142
const char* plural_form) {
3143
return internal::StreamableToString(count) + " " +
3144
(count == 1 ? singular_form : plural_form);
3145
}
3146
3147
// Formats the count of tests.
3148
static std::string FormatTestCount(int test_count) {
3149
return FormatCountableNoun(test_count, "test", "tests");
3150
}
3151
3152
// Formats the count of test suites.
3153
static std::string FormatTestSuiteCount(int test_suite_count) {
3154
return FormatCountableNoun(test_suite_count, "test suite", "test suites");
3155
}
3156
3157
// Converts a TestPartResult::Type enum to human-friendly string
3158
// representation. Both kNonFatalFailure and kFatalFailure are translated
3159
// to "Failure", as the user usually doesn't care about the difference
3160
// between the two when viewing the test result.
3161
static const char* TestPartResultTypeToString(TestPartResult::Type type) {
3162
switch (type) {
3163
case TestPartResult::kSkip:
3164
return "Skipped\n";
3165
case TestPartResult::kSuccess:
3166
return "Success";
3167
3168
case TestPartResult::kNonFatalFailure:
3169
case TestPartResult::kFatalFailure:
3170
#ifdef _MSC_VER
3171
return "error: ";
3172
#else
3173
return "Failure\n";
3174
#endif
3175
default:
3176
return "Unknown result type";
3177
}
3178
}
3179
3180
namespace internal {
3181
namespace {
3182
enum class GTestColor { kDefault, kRed, kGreen, kYellow };
3183
} // namespace
3184
3185
// Prints a TestPartResult to an std::string.
3186
static std::string PrintTestPartResultToString(
3187
const TestPartResult& test_part_result) {
3188
return (Message() << internal::FormatFileLocation(
3189
test_part_result.file_name(),
3190
test_part_result.line_number())
3191
<< " "
3192
<< TestPartResultTypeToString(test_part_result.type())
3193
<< test_part_result.message())
3194
.GetString();
3195
}
3196
3197
// Prints a TestPartResult.
3198
static void PrintTestPartResult(const TestPartResult& test_part_result) {
3199
const std::string& result = PrintTestPartResultToString(test_part_result);
3200
printf("%s\n", result.c_str());
3201
fflush(stdout);
3202
// If the test program runs in Visual Studio or a debugger, the
3203
// following statements add the test part result message to the Output
3204
// window such that the user can double-click on it to jump to the
3205
// corresponding source code location; otherwise they do nothing.
3206
#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE)
3207
// We don't call OutputDebugString*() on Windows Mobile, as printing
3208
// to stdout is done by OutputDebugString() there already - we don't
3209
// want the same message printed twice.
3210
::OutputDebugStringA(result.c_str());
3211
::OutputDebugStringA("\n");
3212
#endif
3213
}
3214
3215
// class PrettyUnitTestResultPrinter
3216
#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
3217
!defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \
3218
!defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW)
3219
3220
// Returns the character attribute for the given color.
3221
static WORD GetColorAttribute(GTestColor color) {
3222
switch (color) {
3223
case GTestColor::kRed:
3224
return FOREGROUND_RED;
3225
case GTestColor::kGreen:
3226
return FOREGROUND_GREEN;
3227
case GTestColor::kYellow:
3228
return FOREGROUND_RED | FOREGROUND_GREEN;
3229
default:
3230
return 0;
3231
}
3232
}
3233
3234
static int GetBitOffset(WORD color_mask) {
3235
if (color_mask == 0) return 0;
3236
3237
int bitOffset = 0;
3238
while ((color_mask & 1) == 0) {
3239
color_mask >>= 1;
3240
++bitOffset;
3241
}
3242
return bitOffset;
3243
}
3244
3245
static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
3246
// Let's reuse the BG
3247
static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
3248
BACKGROUND_RED | BACKGROUND_INTENSITY;
3249
static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
3250
FOREGROUND_RED | FOREGROUND_INTENSITY;
3251
const WORD existing_bg = old_color_attrs & background_mask;
3252
3253
WORD new_color =
3254
GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
3255
static const int bg_bitOffset = GetBitOffset(background_mask);
3256
static const int fg_bitOffset = GetBitOffset(foreground_mask);
3257
3258
if (((new_color & background_mask) >> bg_bitOffset) ==
3259
((new_color & foreground_mask) >> fg_bitOffset)) {
3260
new_color ^= FOREGROUND_INTENSITY; // invert intensity
3261
}
3262
return new_color;
3263
}
3264
3265
#else
3266
3267
// Returns the ANSI color code for the given color. GTestColor::kDefault is
3268
// an invalid input.
3269
static const char* GetAnsiColorCode(GTestColor color) {
3270
switch (color) {
3271
case GTestColor::kRed:
3272
return "1";
3273
case GTestColor::kGreen:
3274
return "2";
3275
case GTestColor::kYellow:
3276
return "3";
3277
default:
3278
assert(false);
3279
return "9";
3280
}
3281
}
3282
3283
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3284
3285
// Returns true if and only if Google Test should use colors in the output.
3286
bool ShouldUseColor(bool stdout_is_tty) {
3287
std::string c = GTEST_FLAG_GET(color);
3288
const char* const gtest_color = c.c_str();
3289
3290
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3291
#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
3292
// On Windows the TERM variable is usually not set, but the
3293
// console there does support colors.
3294
return stdout_is_tty;
3295
#else
3296
// On non-Windows platforms, we rely on the TERM variable.
3297
const char* const term = posix::GetEnv("TERM");
3298
const bool term_supports_color =
3299
term != nullptr && (String::CStringEquals(term, "xterm") ||
3300
String::CStringEquals(term, "xterm-color") ||
3301
String::CStringEquals(term, "xterm-kitty") ||
3302
String::CStringEquals(term, "alacritty") ||
3303
String::CStringEquals(term, "screen") ||
3304
String::CStringEquals(term, "tmux") ||
3305
String::CStringEquals(term, "rxvt-unicode") ||
3306
String::CStringEquals(term, "linux") ||
3307
String::CStringEquals(term, "cygwin") ||
3308
String::EndsWithCaseInsensitive(term, "-256color"));
3309
return stdout_is_tty && term_supports_color;
3310
#endif // GTEST_OS_WINDOWS
3311
}
3312
3313
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3314
String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3315
String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3316
String::CStringEquals(gtest_color, "1");
3317
// We take "yes", "true", "t", and "1" as meaning "yes". If the
3318
// value is neither one of these nor "auto", we treat it as "no" to
3319
// be conservative.
3320
}
3321
3322
// Helpers for printing colored strings to stdout. Note that on Windows, we
3323
// cannot simply emit special characters and have the terminal change colors.
3324
// This routine must actually emit the characters rather than return a string
3325
// that would be colored when printed, as can be done on Linux.
3326
3327
GTEST_ATTRIBUTE_PRINTF_(2, 3)
3328
static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3329
va_list args;
3330
va_start(args, fmt);
3331
3332
static const bool in_color_mode =
3333
// We don't condition this on GTEST_HAS_FILE_SYSTEM because we still need
3334
// to be able to detect terminal I/O regardless.
3335
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3336
3337
const bool use_color = in_color_mode && (color != GTestColor::kDefault);
3338
3339
if (!use_color) {
3340
vprintf(fmt, args);
3341
va_end(args);
3342
return;
3343
}
3344
3345
#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
3346
!defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \
3347
!defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW)
3348
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3349
3350
// Gets the current text color.
3351
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3352
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3353
const WORD old_color_attrs = buffer_info.wAttributes;
3354
const WORD new_color = GetNewColor(color, old_color_attrs);
3355
3356
// We need to flush the stream buffers into the console before each
3357
// SetConsoleTextAttribute call lest it affect the text that is already
3358
// printed but has not yet reached the console.
3359
fflush(stdout);
3360
SetConsoleTextAttribute(stdout_handle, new_color);
3361
3362
vprintf(fmt, args);
3363
3364
fflush(stdout);
3365
// Restores the text color.
3366
SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3367
#else
3368
printf("\033[0;3%sm", GetAnsiColorCode(color));
3369
vprintf(fmt, args);
3370
printf("\033[m"); // Resets the terminal to default.
3371
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3372
va_end(args);
3373
}
3374
3375
// Text printed in Google Test's text output and --gtest_list_tests
3376
// output to label the type parameter and value parameter for a test.
3377
static const char kTypeParamLabel[] = "TypeParam";
3378
static const char kValueParamLabel[] = "GetParam()";
3379
3380
static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3381
const char* const type_param = test_info.type_param();
3382
const char* const value_param = test_info.value_param();
3383
3384
if (type_param != nullptr || value_param != nullptr) {
3385
printf(", where ");
3386
if (type_param != nullptr) {
3387
printf("%s = %s", kTypeParamLabel, type_param);
3388
if (value_param != nullptr) printf(" and ");
3389
}
3390
if (value_param != nullptr) {
3391
printf("%s = %s", kValueParamLabel, value_param);
3392
}
3393
}
3394
}
3395
3396
// This class implements the TestEventListener interface.
3397
//
3398
// Class PrettyUnitTestResultPrinter is copyable.
3399
class PrettyUnitTestResultPrinter : public TestEventListener {
3400
public:
3401
PrettyUnitTestResultPrinter() = default;
3402
static void PrintTestName(const char* test_suite, const char* test) {
3403
printf("%s.%s", test_suite, test);
3404
}
3405
3406
// The following methods override what's in the TestEventListener class.
3407
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
3408
void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
3409
void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
3410
void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
3411
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3412
void OnTestCaseStart(const TestCase& test_case) override;
3413
#else
3414
void OnTestSuiteStart(const TestSuite& test_suite) override;
3415
#endif // OnTestCaseStart
3416
3417
void OnTestStart(const TestInfo& test_info) override;
3418
void OnTestDisabled(const TestInfo& test_info) override;
3419
3420
void OnTestPartResult(const TestPartResult& result) override;
3421
void OnTestEnd(const TestInfo& test_info) override;
3422
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3423
void OnTestCaseEnd(const TestCase& test_case) override;
3424
#else
3425
void OnTestSuiteEnd(const TestSuite& test_suite) override;
3426
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3427
3428
void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
3429
void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
3430
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3431
void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
3432
3433
private:
3434
static void PrintFailedTests(const UnitTest& unit_test);
3435
static void PrintFailedTestSuites(const UnitTest& unit_test);
3436
static void PrintSkippedTests(const UnitTest& unit_test);
3437
};
3438
3439
// Fired before each iteration of tests starts.
3440
void PrettyUnitTestResultPrinter::OnTestIterationStart(
3441
const UnitTest& unit_test, int iteration) {
3442
if (GTEST_FLAG_GET(repeat) != 1)
3443
printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3444
3445
std::string f = GTEST_FLAG_GET(filter);
3446
const char* const filter = f.c_str();
3447
3448
// Prints the filter if it's not *. This reminds the user that some
3449
// tests may be skipped.
3450
if (!String::CStringEquals(filter, kUniversalFilter)) {
3451
ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
3452
filter);
3453
}
3454
3455
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
3456
const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
3457
ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
3458
static_cast<int>(shard_index) + 1,
3459
internal::posix::GetEnv(kTestTotalShards));
3460
}
3461
3462
if (GTEST_FLAG_GET(shuffle)) {
3463
ColoredPrintf(GTestColor::kYellow,
3464
"Note: Randomizing tests' orders with a seed of %d .\n",
3465
unit_test.random_seed());
3466
}
3467
3468
ColoredPrintf(GTestColor::kGreen, "[==========] ");
3469
printf("Running %s from %s.\n",
3470
FormatTestCount(unit_test.test_to_run_count()).c_str(),
3471
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3472
fflush(stdout);
3473
}
3474
3475
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3476
const UnitTest& /*unit_test*/) {
3477
ColoredPrintf(GTestColor::kGreen, "[----------] ");
3478
printf("Global test environment set-up.\n");
3479
fflush(stdout);
3480
}
3481
3482
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3483
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
3484
const std::string counts =
3485
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3486
ColoredPrintf(GTestColor::kGreen, "[----------] ");
3487
printf("%s from %s", counts.c_str(), test_case.name());
3488
if (test_case.type_param() == nullptr) {
3489
printf("\n");
3490
} else {
3491
printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
3492
}
3493
fflush(stdout);
3494
}
3495
#else
3496
void PrettyUnitTestResultPrinter::OnTestSuiteStart(
3497
const TestSuite& test_suite) {
3498
const std::string counts =
3499
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
3500
ColoredPrintf(GTestColor::kGreen, "[----------] ");
3501
printf("%s from %s", counts.c_str(), test_suite.name());
3502
if (test_suite.type_param() == nullptr) {
3503
printf("\n");
3504
} else {
3505
printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
3506
}
3507
fflush(stdout);
3508
}
3509
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3510
3511
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
3512
ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
3513
PrintTestName(test_info.test_suite_name(), test_info.name());
3514
printf("\n");
3515
fflush(stdout);
3516
}
3517
3518
void PrettyUnitTestResultPrinter::OnTestDisabled(const TestInfo& test_info) {
3519
ColoredPrintf(GTestColor::kYellow, "[ DISABLED ] ");
3520
PrintTestName(test_info.test_suite_name(), test_info.name());
3521
printf("\n");
3522
fflush(stdout);
3523
}
3524
3525
// Called after an assertion failure.
3526
void PrettyUnitTestResultPrinter::OnTestPartResult(
3527
const TestPartResult& result) {
3528
switch (result.type()) {
3529
// If the test part succeeded, we don't need to do anything.
3530
case TestPartResult::kSuccess:
3531
return;
3532
default:
3533
// Print failure message from the assertion
3534
// (e.g. expected this and got that).
3535
PrintTestPartResult(result);
3536
fflush(stdout);
3537
}
3538
}
3539
3540
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
3541
if (test_info.result()->Passed()) {
3542
ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
3543
} else if (test_info.result()->Skipped()) {
3544
ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
3545
} else {
3546
ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3547
}
3548
PrintTestName(test_info.test_suite_name(), test_info.name());
3549
if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
3550
3551
if (GTEST_FLAG_GET(print_time)) {
3552
printf(" (%s ms)\n",
3553
internal::StreamableToString(test_info.result()->elapsed_time())
3554
.c_str());
3555
} else {
3556
printf("\n");
3557
}
3558
fflush(stdout);
3559
}
3560
3561
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3562
void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
3563
if (!GTEST_FLAG_GET(print_time)) return;
3564
3565
const std::string counts =
3566
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3567
ColoredPrintf(GTestColor::kGreen, "[----------] ");
3568
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
3569
internal::StreamableToString(test_case.elapsed_time()).c_str());
3570
fflush(stdout);
3571
}
3572
#else
3573
void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
3574
if (!GTEST_FLAG_GET(print_time)) return;
3575
3576
const std::string counts =
3577
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
3578
ColoredPrintf(GTestColor::kGreen, "[----------] ");
3579
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
3580
internal::StreamableToString(test_suite.elapsed_time()).c_str());
3581
fflush(stdout);
3582
}
3583
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3584
3585
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3586
const UnitTest& /*unit_test*/) {
3587
ColoredPrintf(GTestColor::kGreen, "[----------] ");
3588
printf("Global test environment tear-down\n");
3589
fflush(stdout);
3590
}
3591
3592
// Internal helper for printing the list of failed tests.
3593
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
3594
const int failed_test_count = unit_test.failed_test_count();
3595
ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3596
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
3597
3598
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3599
const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3600
if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
3601
continue;
3602
}
3603
for (int j = 0; j < test_suite.total_test_count(); ++j) {
3604
const TestInfo& test_info = *test_suite.GetTestInfo(j);
3605
if (!test_info.should_run() || !test_info.result()->Failed()) {
3606
continue;
3607
}
3608
ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3609
printf("%s.%s", test_suite.name(), test_info.name());
3610
PrintFullTestCommentIfPresent(test_info);
3611
printf("\n");
3612
}
3613
}
3614
printf("\n%2d FAILED %s\n", failed_test_count,
3615
failed_test_count == 1 ? "TEST" : "TESTS");
3616
}
3617
3618
// Internal helper for printing the list of test suite failures not covered by
3619
// PrintFailedTests.
3620
void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
3621
const UnitTest& unit_test) {
3622
int suite_failure_count = 0;
3623
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3624
const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3625
if (!test_suite.should_run()) {
3626
continue;
3627
}
3628
if (test_suite.ad_hoc_test_result().Failed()) {
3629
ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3630
printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
3631
++suite_failure_count;
3632
}
3633
}
3634
if (suite_failure_count > 0) {
3635
printf("\n%2d FAILED TEST %s\n", suite_failure_count,
3636
suite_failure_count == 1 ? "SUITE" : "SUITES");
3637
}
3638
}
3639
3640
// Internal helper for printing the list of skipped tests.
3641
void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
3642
const int skipped_test_count = unit_test.skipped_test_count();
3643
if (skipped_test_count == 0) {
3644
return;
3645
}
3646
3647
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3648
const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3649
if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
3650
continue;
3651
}
3652
for (int j = 0; j < test_suite.total_test_count(); ++j) {
3653
const TestInfo& test_info = *test_suite.GetTestInfo(j);
3654
if (!test_info.should_run() || !test_info.result()->Skipped()) {
3655
continue;
3656
}
3657
ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
3658
printf("%s.%s", test_suite.name(), test_info.name());
3659
printf("\n");
3660
}
3661
}
3662
}
3663
3664
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3665
int /*iteration*/) {
3666
ColoredPrintf(GTestColor::kGreen, "[==========] ");
3667
printf("%s from %s ran.",
3668
FormatTestCount(unit_test.test_to_run_count()).c_str(),
3669
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3670
if (GTEST_FLAG_GET(print_time)) {
3671
printf(" (%s ms total)",
3672
internal::StreamableToString(unit_test.elapsed_time()).c_str());
3673
}
3674
printf("\n");
3675
ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
3676
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3677
3678
const int skipped_test_count = unit_test.skipped_test_count();
3679
if (skipped_test_count > 0) {
3680
ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
3681
printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
3682
PrintSkippedTests(unit_test);
3683
}
3684
3685
if (!unit_test.Passed()) {
3686
PrintFailedTests(unit_test);
3687
PrintFailedTestSuites(unit_test);
3688
}
3689
3690
int num_disabled = unit_test.reportable_disabled_test_count();
3691
if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
3692
if (unit_test.Passed()) {
3693
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
3694
}
3695
ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
3696
num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
3697
}
3698
// Ensure that Google Test output is printed before, e.g., heapchecker output.
3699
fflush(stdout);
3700
}
3701
3702
// End PrettyUnitTestResultPrinter
3703
3704
// This class implements the TestEventListener interface.
3705
//
3706
// Class BriefUnitTestResultPrinter is copyable.
3707
class BriefUnitTestResultPrinter : public TestEventListener {
3708
public:
3709
BriefUnitTestResultPrinter() = default;
3710
static void PrintTestName(const char* test_suite, const char* test) {
3711
printf("%s.%s", test_suite, test);
3712
}
3713
3714
// The following methods override what's in the TestEventListener class.
3715
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
3716
void OnTestIterationStart(const UnitTest& /*unit_test*/,
3717
int /*iteration*/) override {}
3718
void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
3719
void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
3720
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3721
void OnTestCaseStart(const TestCase& /*test_case*/) override {}
3722
#else
3723
void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
3724
#endif // OnTestCaseStart
3725
3726
void OnTestStart(const TestInfo& /*test_info*/) override {}
3727
void OnTestDisabled(const TestInfo& /*test_info*/) override {}
3728
3729
void OnTestPartResult(const TestPartResult& result) override;
3730
void OnTestEnd(const TestInfo& test_info) override;
3731
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3732
void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
3733
#else
3734
void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
3735
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3736
3737
void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
3738
void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
3739
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3740
void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
3741
};
3742
3743
// Called after an assertion failure.
3744
void BriefUnitTestResultPrinter::OnTestPartResult(
3745
const TestPartResult& result) {
3746
switch (result.type()) {
3747
// If the test part succeeded, we don't need to do anything.
3748
case TestPartResult::kSuccess:
3749
return;
3750
default:
3751
// Print failure message from the assertion
3752
// (e.g. expected this and got that).
3753
PrintTestPartResult(result);
3754
fflush(stdout);
3755
}
3756
}
3757
3758
void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
3759
if (test_info.result()->Failed()) {
3760
ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
3761
PrintTestName(test_info.test_suite_name(), test_info.name());
3762
PrintFullTestCommentIfPresent(test_info);
3763
3764
if (GTEST_FLAG_GET(print_time)) {
3765
printf(" (%s ms)\n",
3766
internal::StreamableToString(test_info.result()->elapsed_time())
3767
.c_str());
3768
} else {
3769
printf("\n");
3770
}
3771
fflush(stdout);
3772
}
3773
}
3774
3775
void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3776
int /*iteration*/) {
3777
ColoredPrintf(GTestColor::kGreen, "[==========] ");
3778
printf("%s from %s ran.",
3779
FormatTestCount(unit_test.test_to_run_count()).c_str(),
3780
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3781
if (GTEST_FLAG_GET(print_time)) {
3782
printf(" (%s ms total)",
3783
internal::StreamableToString(unit_test.elapsed_time()).c_str());
3784
}
3785
printf("\n");
3786
ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
3787
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3788
3789
const int skipped_test_count = unit_test.skipped_test_count();
3790
if (skipped_test_count > 0) {
3791
ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
3792
printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
3793
}
3794
3795
int num_disabled = unit_test.reportable_disabled_test_count();
3796
if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
3797
if (unit_test.Passed()) {
3798
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
3799
}
3800
ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
3801
num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
3802
}
3803
// Ensure that Google Test output is printed before, e.g., heapchecker output.
3804
fflush(stdout);
3805
}
3806
3807
// End BriefUnitTestResultPrinter
3808
3809
// class TestEventRepeater
3810
//
3811
// This class forwards events to other event listeners.
3812
class TestEventRepeater : public TestEventListener {
3813
public:
3814
TestEventRepeater() : forwarding_enabled_(true) {}
3815
~TestEventRepeater() override;
3816
void Append(TestEventListener* listener);
3817
TestEventListener* Release(TestEventListener* listener);
3818
3819
// Controls whether events will be forwarded to listeners_. Set to false
3820
// in death test child processes.
3821
bool forwarding_enabled() const { return forwarding_enabled_; }
3822
void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
3823
3824
void OnTestProgramStart(const UnitTest& parameter) override;
3825
void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
3826
void OnEnvironmentsSetUpStart(const UnitTest& parameter) override;
3827
void OnEnvironmentsSetUpEnd(const UnitTest& parameter) override;
3828
// Legacy API is deprecated but still available
3829
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3830
void OnTestCaseStart(const TestSuite& parameter) override;
3831
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3832
void OnTestSuiteStart(const TestSuite& parameter) override;
3833
void OnTestStart(const TestInfo& parameter) override;
3834
void OnTestDisabled(const TestInfo& parameter) override;
3835
void OnTestPartResult(const TestPartResult& parameter) override;
3836
void OnTestEnd(const TestInfo& parameter) override;
3837
// Legacy API is deprecated but still available
3838
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3839
void OnTestCaseEnd(const TestCase& parameter) override;
3840
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3841
void OnTestSuiteEnd(const TestSuite& parameter) override;
3842
void OnEnvironmentsTearDownStart(const UnitTest& parameter) override;
3843
void OnEnvironmentsTearDownEnd(const UnitTest& parameter) override;
3844
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3845
void OnTestProgramEnd(const UnitTest& parameter) override;
3846
3847
private:
3848
// Controls whether events will be forwarded to listeners_. Set to false
3849
// in death test child processes.
3850
bool forwarding_enabled_;
3851
// The list of listeners that receive events.
3852
std::vector<TestEventListener*> listeners_;
3853
3854
TestEventRepeater(const TestEventRepeater&) = delete;
3855
TestEventRepeater& operator=(const TestEventRepeater&) = delete;
3856
};
3857
3858
TestEventRepeater::~TestEventRepeater() {
3859
ForEach(listeners_, Delete<TestEventListener>);
3860
}
3861
3862
void TestEventRepeater::Append(TestEventListener* listener) {
3863
listeners_.push_back(listener);
3864
}
3865
3866
TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
3867
for (size_t i = 0; i < listeners_.size(); ++i) {
3868
if (listeners_[i] == listener) {
3869
listeners_.erase(listeners_.begin() + static_cast<int>(i));
3870
return listener;
3871
}
3872
}
3873
3874
return nullptr;
3875
}
3876
3877
// Since most methods are very similar, use macros to reduce boilerplate.
3878
// This defines a member that forwards the call to all listeners.
3879
#define GTEST_REPEATER_METHOD_(Name, Type) \
3880
void TestEventRepeater::Name(const Type& parameter) { \
3881
if (forwarding_enabled_) { \
3882
for (size_t i = 0; i < listeners_.size(); i++) { \
3883
listeners_[i]->Name(parameter); \
3884
} \
3885
} \
3886
}
3887
// This defines a member that forwards the call to all listeners in reverse
3888
// order.
3889
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3890
void TestEventRepeater::Name(const Type& parameter) { \
3891
if (forwarding_enabled_) { \
3892
for (size_t i = listeners_.size(); i != 0; i--) { \
3893
listeners_[i - 1]->Name(parameter); \
3894
} \
3895
} \
3896
}
3897
3898
GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
3899
GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
3900
// Legacy API is deprecated but still available
3901
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3902
GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
3903
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3904
GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
3905
GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
3906
GTEST_REPEATER_METHOD_(OnTestDisabled, TestInfo)
3907
GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
3908
GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
3909
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
3910
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
3911
GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
3912
// Legacy API is deprecated but still available
3913
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3914
GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
3915
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3916
GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
3917
GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
3918
3919
#undef GTEST_REPEATER_METHOD_
3920
#undef GTEST_REVERSE_REPEATER_METHOD_
3921
3922
void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
3923
int iteration) {
3924
if (forwarding_enabled_) {
3925
for (size_t i = 0; i < listeners_.size(); i++) {
3926
listeners_[i]->OnTestIterationStart(unit_test, iteration);
3927
}
3928
}
3929
}
3930
3931
void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
3932
int iteration) {
3933
if (forwarding_enabled_) {
3934
for (size_t i = listeners_.size(); i > 0; i--) {
3935
listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
3936
}
3937
}
3938
}
3939
3940
// End TestEventRepeater
3941
3942
#if GTEST_HAS_FILE_SYSTEM
3943
// This class generates an XML output file.
3944
class XmlUnitTestResultPrinter : public EmptyTestEventListener {
3945
public:
3946
explicit XmlUnitTestResultPrinter(const char* output_file);
3947
3948
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3949
void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
3950
3951
// Prints an XML summary of all unit tests.
3952
static void PrintXmlTestsList(std::ostream* stream,
3953
const std::vector<TestSuite*>& test_suites);
3954
3955
private:
3956
// Is c a whitespace character that is normalized to a space character
3957
// when it appears in an XML attribute value?
3958
static bool IsNormalizableWhitespace(unsigned char c) {
3959
return c == '\t' || c == '\n' || c == '\r';
3960
}
3961
3962
// May c appear in a well-formed XML document?
3963
// https://www.w3.org/TR/REC-xml/#charsets
3964
static bool IsValidXmlCharacter(unsigned char c) {
3965
return IsNormalizableWhitespace(c) || c >= 0x20;
3966
}
3967
3968
// Returns an XML-escaped copy of the input string str. If
3969
// is_attribute is true, the text is meant to appear as an attribute
3970
// value, and normalizable whitespace is preserved by replacing it
3971
// with character references.
3972
static std::string EscapeXml(const std::string& str, bool is_attribute);
3973
3974
// Returns the given string with all characters invalid in XML removed.
3975
static std::string RemoveInvalidXmlCharacters(const std::string& str);
3976
3977
// Convenience wrapper around EscapeXml when str is an attribute value.
3978
static std::string EscapeXmlAttribute(const std::string& str) {
3979
return EscapeXml(str, true);
3980
}
3981
3982
// Convenience wrapper around EscapeXml when str is not an attribute value.
3983
static std::string EscapeXmlText(const char* str) {
3984
return EscapeXml(str, false);
3985
}
3986
3987
// Verifies that the given attribute belongs to the given element and
3988
// streams the attribute as XML.
3989
static void OutputXmlAttribute(std::ostream* stream,
3990
const std::string& element_name,
3991
const std::string& name,
3992
const std::string& value);
3993
3994
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3995
static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3996
3997
// Streams a test suite XML stanza containing the given test result.
3998
//
3999
// Requires: result.Failed()
4000
static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
4001
const TestResult& result);
4002
4003
// Streams a test case XML stanza containing the given test result.
4004
//
4005
// Requires: result.Failed()
4006
static void OutputXmlTestCaseForTestResult(::std::ostream* stream,
4007
const TestResult& result);
4008
4009
// Streams an XML representation of a TestResult object.
4010
static void OutputXmlTestResult(::std::ostream* stream,
4011
const TestResult& result);
4012
4013
// Streams an XML representation of a TestInfo object.
4014
static void OutputXmlTestInfo(::std::ostream* stream,
4015
const char* test_suite_name,
4016
const TestInfo& test_info);
4017
4018
// Prints an XML representation of a TestSuite object
4019
static void PrintXmlTestSuite(::std::ostream* stream,
4020
const TestSuite& test_suite);
4021
4022
// Prints an XML summary of unit_test to output stream out.
4023
static void PrintXmlUnitTest(::std::ostream* stream,
4024
const UnitTest& unit_test);
4025
4026
// Streams an XML representation of the test properties of a TestResult
4027
// object.
4028
static void OutputXmlTestProperties(std::ostream* stream,
4029
const TestResult& result,
4030
const std::string& indent);
4031
4032
// The output file.
4033
const std::string output_file_;
4034
4035
XmlUnitTestResultPrinter(const XmlUnitTestResultPrinter&) = delete;
4036
XmlUnitTestResultPrinter& operator=(const XmlUnitTestResultPrinter&) = delete;
4037
};
4038
4039
// Creates a new XmlUnitTestResultPrinter.
4040
XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4041
: output_file_(output_file) {
4042
if (output_file_.empty()) {
4043
GTEST_LOG_(FATAL) << "XML output file may not be null";
4044
}
4045
}
4046
4047
// Called after the unit test ends.
4048
void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4049
int /*iteration*/) {
4050
FILE* xmlout = OpenFileForWriting(output_file_);
4051
std::stringstream stream;
4052
PrintXmlUnitTest(&stream, unit_test);
4053
fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4054
fclose(xmlout);
4055
}
4056
4057
void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
4058
const std::vector<TestSuite*>& test_suites) {
4059
FILE* xmlout = OpenFileForWriting(output_file_);
4060
std::stringstream stream;
4061
PrintXmlTestsList(&stream, test_suites);
4062
fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4063
fclose(xmlout);
4064
}
4065
4066
// Returns an XML-escaped copy of the input string str. If is_attribute
4067
// is true, the text is meant to appear as an attribute value, and
4068
// normalizable whitespace is preserved by replacing it with character
4069
// references.
4070
//
4071
// Invalid XML characters in str, if any, are stripped from the output.
4072
// It is expected that most, if not all, of the text processed by this
4073
// module will consist of ordinary English text.
4074
// If this module is ever modified to produce version 1.1 XML output,
4075
// most invalid characters can be retained using character references.
4076
std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
4077
bool is_attribute) {
4078
Message m;
4079
4080
for (size_t i = 0; i < str.size(); ++i) {
4081
const char ch = str[i];
4082
switch (ch) {
4083
case '<':
4084
m << "&lt;";
4085
break;
4086
case '>':
4087
m << "&gt;";
4088
break;
4089
case '&':
4090
m << "&amp;";
4091
break;
4092
case '\'':
4093
if (is_attribute)
4094
m << "&apos;";
4095
else
4096
m << '\'';
4097
break;
4098
case '"':
4099
if (is_attribute)
4100
m << "&quot;";
4101
else
4102
m << '"';
4103
break;
4104
default:
4105
if (IsValidXmlCharacter(static_cast<unsigned char>(ch))) {
4106
if (is_attribute &&
4107
IsNormalizableWhitespace(static_cast<unsigned char>(ch)))
4108
m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4109
<< ";";
4110
else
4111
m << ch;
4112
}
4113
break;
4114
}
4115
}
4116
4117
return m.GetString();
4118
}
4119
4120
// Returns the given string with all characters invalid in XML removed.
4121
// Currently invalid characters are dropped from the string. An
4122
// alternative is to replace them with certain characters such as . or ?.
4123
std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4124
const std::string& str) {
4125
std::string output;
4126
output.reserve(str.size());
4127
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4128
if (IsValidXmlCharacter(static_cast<unsigned char>(*it)))
4129
output.push_back(*it);
4130
4131
return output;
4132
}
4133
4134
// The following routines generate an XML representation of a UnitTest
4135
// object.
4136
//
4137
// This is how Google Test concepts map to the DTD:
4138
//
4139
// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4140
// <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
4141
// <testcase name="test-name"> <-- corresponds to a TestInfo object
4142
// <failure message="...">...</failure>
4143
// <failure message="...">...</failure>
4144
// <failure message="...">...</failure>
4145
// <-- individual assertion failures
4146
// </testcase>
4147
// </testsuite>
4148
// </testsuites>
4149
4150
// Formats the given time in milliseconds as seconds.
4151
std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4152
::std::stringstream ss;
4153
// For the exact N seconds, makes sure output has a trailing decimal point.
4154
// Sets precision so that we won't have many trailing zeros (e.g., 300 ms
4155
// will be just 0.3, 410 ms 0.41, and so on)
4156
ss << std::fixed
4157
<< std::setprecision(
4158
ms % 1000 == 0 ? 0 : (ms % 100 == 0 ? 1 : (ms % 10 == 0 ? 2 : 3)))
4159
<< std::showpoint;
4160
ss << (static_cast<double>(ms) * 1e-3);
4161
return ss.str();
4162
}
4163
4164
static bool PortableLocaltime(time_t seconds, struct tm* out) {
4165
#if defined(_MSC_VER)
4166
return localtime_s(out, &seconds) == 0;
4167
#elif defined(__MINGW32__) || defined(__MINGW64__)
4168
// MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
4169
// Windows' localtime(), which has a thread-local tm buffer.
4170
struct tm* tm_ptr = localtime(&seconds); // NOLINT
4171
if (tm_ptr == nullptr) return false;
4172
*out = *tm_ptr;
4173
return true;
4174
#elif defined(__STDC_LIB_EXT1__)
4175
// Uses localtime_s when available as localtime_r is only available from
4176
// C23 standard.
4177
return localtime_s(&seconds, out) != nullptr;
4178
#else
4179
return localtime_r(&seconds, out) != nullptr;
4180
#endif
4181
}
4182
4183
// Converts the given epoch time in milliseconds to a date string in the ISO
4184
// 8601 format, without the timezone information.
4185
std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4186
struct tm time_struct;
4187
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
4188
return "";
4189
// YYYY-MM-DDThh:mm:ss.sss
4190
return StreamableToString(time_struct.tm_year + 1900) + "-" +
4191
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
4192
String::FormatIntWidth2(time_struct.tm_mday) + "T" +
4193
String::FormatIntWidth2(time_struct.tm_hour) + ":" +
4194
String::FormatIntWidth2(time_struct.tm_min) + ":" +
4195
String::FormatIntWidth2(time_struct.tm_sec) + "." +
4196
String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
4197
}
4198
4199
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4200
void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4201
const char* data) {
4202
const char* segment = data;
4203
*stream << "<![CDATA[";
4204
for (;;) {
4205
const char* const next_segment = strstr(segment, "]]>");
4206
if (next_segment != nullptr) {
4207
stream->write(segment,
4208
static_cast<std::streamsize>(next_segment - segment));
4209
*stream << "]]>]]&gt;<![CDATA[";
4210
segment = next_segment + strlen("]]>");
4211
} else {
4212
*stream << segment;
4213
break;
4214
}
4215
}
4216
*stream << "]]>";
4217
}
4218
4219
void XmlUnitTestResultPrinter::OutputXmlAttribute(
4220
std::ostream* stream, const std::string& element_name,
4221
const std::string& name, const std::string& value) {
4222
const std::vector<std::string>& allowed_names =
4223
GetReservedOutputAttributesForElement(element_name);
4224
4225
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4226
allowed_names.end())
4227
<< "Attribute " << name << " is not allowed for element <" << element_name
4228
<< ">.";
4229
4230
*stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
4231
}
4232
4233
// Streams a test suite XML stanza containing the given test result.
4234
void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
4235
::std::ostream* stream, const TestResult& result) {
4236
// Output the boilerplate for a minimal test suite with one test.
4237
*stream << " <testsuite";
4238
OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
4239
OutputXmlAttribute(stream, "testsuite", "tests", "1");
4240
OutputXmlAttribute(stream, "testsuite", "failures", "1");
4241
OutputXmlAttribute(stream, "testsuite", "disabled", "0");
4242
OutputXmlAttribute(stream, "testsuite", "skipped", "0");
4243
OutputXmlAttribute(stream, "testsuite", "errors", "0");
4244
OutputXmlAttribute(stream, "testsuite", "time",
4245
FormatTimeInMillisAsSeconds(result.elapsed_time()));
4246
OutputXmlAttribute(
4247
stream, "testsuite", "timestamp",
4248
FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4249
*stream << ">";
4250
4251
OutputXmlTestCaseForTestResult(stream, result);
4252
4253
// Complete the test suite.
4254
*stream << " </testsuite>\n";
4255
}
4256
4257
// Streams a test case XML stanza containing the given test result.
4258
void XmlUnitTestResultPrinter::OutputXmlTestCaseForTestResult(
4259
::std::ostream* stream, const TestResult& result) {
4260
// Output the boilerplate for a minimal test case with a single test.
4261
*stream << " <testcase";
4262
OutputXmlAttribute(stream, "testcase", "name", "");
4263
OutputXmlAttribute(stream, "testcase", "status", "run");
4264
OutputXmlAttribute(stream, "testcase", "result", "completed");
4265
OutputXmlAttribute(stream, "testcase", "classname", "");
4266
OutputXmlAttribute(stream, "testcase", "time",
4267
FormatTimeInMillisAsSeconds(result.elapsed_time()));
4268
OutputXmlAttribute(
4269
stream, "testcase", "timestamp",
4270
FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4271
4272
// Output the actual test result.
4273
OutputXmlTestResult(stream, result);
4274
}
4275
4276
// Prints an XML representation of a TestInfo object.
4277
void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4278
const char* test_suite_name,
4279
const TestInfo& test_info) {
4280
const TestResult& result = *test_info.result();
4281
const std::string kTestsuite = "testcase";
4282
4283
if (test_info.is_in_another_shard()) {
4284
return;
4285
}
4286
4287
*stream << " <testcase";
4288
OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
4289
4290
if (test_info.value_param() != nullptr) {
4291
OutputXmlAttribute(stream, kTestsuite, "value_param",
4292
test_info.value_param());
4293
}
4294
if (test_info.type_param() != nullptr) {
4295
OutputXmlAttribute(stream, kTestsuite, "type_param",
4296
test_info.type_param());
4297
}
4298
4299
OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
4300
OutputXmlAttribute(stream, kTestsuite, "line",
4301
StreamableToString(test_info.line()));
4302
if (GTEST_FLAG_GET(list_tests)) {
4303
*stream << " />\n";
4304
return;
4305
}
4306
4307
OutputXmlAttribute(stream, kTestsuite, "status",
4308
test_info.should_run() ? "run" : "notrun");
4309
OutputXmlAttribute(stream, kTestsuite, "result",
4310
test_info.should_run()
4311
? (result.Skipped() ? "skipped" : "completed")
4312
: "suppressed");
4313
OutputXmlAttribute(stream, kTestsuite, "time",
4314
FormatTimeInMillisAsSeconds(result.elapsed_time()));
4315
OutputXmlAttribute(
4316
stream, kTestsuite, "timestamp",
4317
FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4318
OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
4319
4320
OutputXmlTestResult(stream, result);
4321
}
4322
4323
void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
4324
const TestResult& result) {
4325
int failures = 0;
4326
int skips = 0;
4327
for (int i = 0; i < result.total_part_count(); ++i) {
4328
const TestPartResult& part = result.GetTestPartResult(i);
4329
if (part.failed()) {
4330
if (++failures == 1 && skips == 0) {
4331
*stream << ">\n";
4332
}
4333
const std::string location =
4334
internal::FormatCompilerIndependentFileLocation(part.file_name(),
4335
part.line_number());
4336
const std::string summary = location + "\n" + part.summary();
4337
*stream << " <failure message=\"" << EscapeXmlAttribute(summary)
4338
<< "\" type=\"\">";
4339
const std::string detail = location + "\n" + part.message();
4340
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4341
*stream << "</failure>\n";
4342
} else if (part.skipped()) {
4343
if (++skips == 1 && failures == 0) {
4344
*stream << ">\n";
4345
}
4346
const std::string location =
4347
internal::FormatCompilerIndependentFileLocation(part.file_name(),
4348
part.line_number());
4349
const std::string summary = location + "\n" + part.summary();
4350
*stream << " <skipped message=\""
4351
<< EscapeXmlAttribute(summary.c_str()) << "\">";
4352
const std::string detail = location + "\n" + part.message();
4353
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4354
*stream << "</skipped>\n";
4355
}
4356
}
4357
4358
if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
4359
*stream << " />\n";
4360
} else {
4361
if (failures == 0 && skips == 0) {
4362
*stream << ">\n";
4363
}
4364
OutputXmlTestProperties(stream, result, /*indent=*/" ");
4365
*stream << " </testcase>\n";
4366
}
4367
}
4368
4369
// Prints an XML representation of a TestSuite object
4370
void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
4371
const TestSuite& test_suite) {
4372
const std::string kTestsuite = "testsuite";
4373
*stream << " <" << kTestsuite;
4374
OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
4375
OutputXmlAttribute(stream, kTestsuite, "tests",
4376
StreamableToString(test_suite.reportable_test_count()));
4377
if (!GTEST_FLAG_GET(list_tests)) {
4378
OutputXmlAttribute(stream, kTestsuite, "failures",
4379
StreamableToString(test_suite.failed_test_count()));
4380
OutputXmlAttribute(
4381
stream, kTestsuite, "disabled",
4382
StreamableToString(test_suite.reportable_disabled_test_count()));
4383
OutputXmlAttribute(stream, kTestsuite, "skipped",
4384
StreamableToString(test_suite.skipped_test_count()));
4385
4386
OutputXmlAttribute(stream, kTestsuite, "errors", "0");
4387
4388
OutputXmlAttribute(stream, kTestsuite, "time",
4389
FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
4390
OutputXmlAttribute(
4391
stream, kTestsuite, "timestamp",
4392
FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
4393
}
4394
*stream << ">\n";
4395
OutputXmlTestProperties(stream, test_suite.ad_hoc_test_result(),
4396
/*indent=*/" ");
4397
for (int i = 0; i < test_suite.total_test_count(); ++i) {
4398
if (test_suite.GetTestInfo(i)->is_reportable())
4399
OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4400
}
4401
if (test_suite.ad_hoc_test_result().Failed()) {
4402
OutputXmlTestCaseForTestResult(stream, test_suite.ad_hoc_test_result());
4403
}
4404
4405
*stream << " </" << kTestsuite << ">\n";
4406
}
4407
4408
// Prints an XML summary of unit_test to output stream out.
4409
void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4410
const UnitTest& unit_test) {
4411
const std::string kTestsuites = "testsuites";
4412
4413
*stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4414
*stream << "<" << kTestsuites;
4415
4416
OutputXmlAttribute(stream, kTestsuites, "tests",
4417
StreamableToString(unit_test.reportable_test_count()));
4418
OutputXmlAttribute(stream, kTestsuites, "failures",
4419
StreamableToString(unit_test.failed_test_count()));
4420
OutputXmlAttribute(
4421
stream, kTestsuites, "disabled",
4422
StreamableToString(unit_test.reportable_disabled_test_count()));
4423
OutputXmlAttribute(stream, kTestsuites, "errors", "0");
4424
OutputXmlAttribute(stream, kTestsuites, "time",
4425
FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
4426
OutputXmlAttribute(
4427
stream, kTestsuites, "timestamp",
4428
FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
4429
4430
if (GTEST_FLAG_GET(shuffle)) {
4431
OutputXmlAttribute(stream, kTestsuites, "random_seed",
4432
StreamableToString(unit_test.random_seed()));
4433
}
4434
4435
OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4436
*stream << ">\n";
4437
4438
OutputXmlTestProperties(stream, unit_test.ad_hoc_test_result(),
4439
/*indent=*/" ");
4440
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4441
if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
4442
PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
4443
}
4444
4445
// If there was a test failure outside of one of the test suites (like in a
4446
// test environment) include that in the output.
4447
if (unit_test.ad_hoc_test_result().Failed()) {
4448
OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4449
}
4450
4451
*stream << "</" << kTestsuites << ">\n";
4452
}
4453
4454
void XmlUnitTestResultPrinter::PrintXmlTestsList(
4455
std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
4456
const std::string kTestsuites = "testsuites";
4457
4458
*stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4459
*stream << "<" << kTestsuites;
4460
4461
int total_tests = 0;
4462
for (auto test_suite : test_suites) {
4463
total_tests += test_suite->total_test_count();
4464
}
4465
OutputXmlAttribute(stream, kTestsuites, "tests",
4466
StreamableToString(total_tests));
4467
OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4468
*stream << ">\n";
4469
4470
for (auto test_suite : test_suites) {
4471
PrintXmlTestSuite(stream, *test_suite);
4472
}
4473
*stream << "</" << kTestsuites << ">\n";
4474
}
4475
4476
void XmlUnitTestResultPrinter::OutputXmlTestProperties(
4477
std::ostream* stream, const TestResult& result, const std::string& indent) {
4478
const std::string kProperties = "properties";
4479
const std::string kProperty = "property";
4480
4481
if (result.test_property_count() <= 0) {
4482
return;
4483
}
4484
4485
*stream << indent << "<" << kProperties << ">\n";
4486
for (int i = 0; i < result.test_property_count(); ++i) {
4487
const TestProperty& property = result.GetTestProperty(i);
4488
*stream << indent << " <" << kProperty;
4489
*stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
4490
*stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
4491
*stream << "/>\n";
4492
}
4493
*stream << indent << "</" << kProperties << ">\n";
4494
}
4495
4496
// End XmlUnitTestResultPrinter
4497
#endif // GTEST_HAS_FILE_SYSTEM
4498
4499
#if GTEST_HAS_FILE_SYSTEM
4500
// This class generates an JSON output file.
4501
class JsonUnitTestResultPrinter : public EmptyTestEventListener {
4502
public:
4503
explicit JsonUnitTestResultPrinter(const char* output_file);
4504
4505
void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4506
4507
// Prints an JSON summary of all unit tests.
4508
static void PrintJsonTestList(::std::ostream* stream,
4509
const std::vector<TestSuite*>& test_suites);
4510
4511
private:
4512
// Returns an JSON-escaped copy of the input string str.
4513
static std::string EscapeJson(const std::string& str);
4514
4515
//// Verifies that the given attribute belongs to the given element and
4516
//// streams the attribute as JSON.
4517
static void OutputJsonKey(std::ostream* stream,
4518
const std::string& element_name,
4519
const std::string& name, const std::string& value,
4520
const std::string& indent, bool comma = true);
4521
static void OutputJsonKey(std::ostream* stream,
4522
const std::string& element_name,
4523
const std::string& name, int value,
4524
const std::string& indent, bool comma = true);
4525
4526
// Streams a test suite JSON stanza containing the given test result.
4527
//
4528
// Requires: result.Failed()
4529
static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
4530
const TestResult& result);
4531
4532
// Streams a test case JSON stanza containing the given test result.
4533
//
4534
// Requires: result.Failed()
4535
static void OutputJsonTestCaseForTestResult(::std::ostream* stream,
4536
const TestResult& result);
4537
4538
// Streams a JSON representation of a TestResult object.
4539
static void OutputJsonTestResult(::std::ostream* stream,
4540
const TestResult& result);
4541
4542
// Streams a JSON representation of a TestInfo object.
4543
static void OutputJsonTestInfo(::std::ostream* stream,
4544
const char* test_suite_name,
4545
const TestInfo& test_info);
4546
4547
// Prints a JSON representation of a TestSuite object
4548
static void PrintJsonTestSuite(::std::ostream* stream,
4549
const TestSuite& test_suite);
4550
4551
// Prints a JSON summary of unit_test to output stream out.
4552
static void PrintJsonUnitTest(::std::ostream* stream,
4553
const UnitTest& unit_test);
4554
4555
// Produces a string representing the test properties in a result as
4556
// a JSON dictionary.
4557
static std::string TestPropertiesAsJson(const TestResult& result,
4558
const std::string& indent);
4559
4560
// The output file.
4561
const std::string output_file_;
4562
4563
JsonUnitTestResultPrinter(const JsonUnitTestResultPrinter&) = delete;
4564
JsonUnitTestResultPrinter& operator=(const JsonUnitTestResultPrinter&) =
4565
delete;
4566
};
4567
4568
// Creates a new JsonUnitTestResultPrinter.
4569
JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
4570
: output_file_(output_file) {
4571
if (output_file_.empty()) {
4572
GTEST_LOG_(FATAL) << "JSON output file may not be null";
4573
}
4574
}
4575
4576
void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4577
int /*iteration*/) {
4578
FILE* jsonout = OpenFileForWriting(output_file_);
4579
std::stringstream stream;
4580
PrintJsonUnitTest(&stream, unit_test);
4581
fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
4582
fclose(jsonout);
4583
}
4584
4585
// Returns an JSON-escaped copy of the input string str.
4586
std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
4587
Message m;
4588
4589
for (size_t i = 0; i < str.size(); ++i) {
4590
const char ch = str[i];
4591
switch (ch) {
4592
case '\\':
4593
case '"':
4594
case '/':
4595
m << '\\' << ch;
4596
break;
4597
case '\b':
4598
m << "\\b";
4599
break;
4600
case '\t':
4601
m << "\\t";
4602
break;
4603
case '\n':
4604
m << "\\n";
4605
break;
4606
case '\f':
4607
m << "\\f";
4608
break;
4609
case '\r':
4610
m << "\\r";
4611
break;
4612
default:
4613
if (ch < ' ') {
4614
m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
4615
} else {
4616
m << ch;
4617
}
4618
break;
4619
}
4620
}
4621
4622
return m.GetString();
4623
}
4624
4625
// The following routines generate an JSON representation of a UnitTest
4626
// object.
4627
4628
// Formats the given time in milliseconds as seconds.
4629
static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
4630
::std::stringstream ss;
4631
ss << (static_cast<double>(ms) * 1e-3) << "s";
4632
return ss.str();
4633
}
4634
4635
// Converts the given epoch time in milliseconds to a date string in the
4636
// RFC3339 format, without the timezone information.
4637
static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
4638
struct tm time_struct;
4639
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
4640
return "";
4641
// YYYY-MM-DDThh:mm:ss
4642
return StreamableToString(time_struct.tm_year + 1900) + "-" +
4643
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
4644
String::FormatIntWidth2(time_struct.tm_mday) + "T" +
4645
String::FormatIntWidth2(time_struct.tm_hour) + ":" +
4646
String::FormatIntWidth2(time_struct.tm_min) + ":" +
4647
String::FormatIntWidth2(time_struct.tm_sec) + "Z";
4648
}
4649
4650
static inline std::string Indent(size_t width) {
4651
return std::string(width, ' ');
4652
}
4653
4654
void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
4655
const std::string& element_name,
4656
const std::string& name,
4657
const std::string& value,
4658
const std::string& indent,
4659
bool comma) {
4660
const std::vector<std::string>& allowed_names =
4661
GetReservedOutputAttributesForElement(element_name);
4662
4663
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4664
allowed_names.end())
4665
<< "Key \"" << name << "\" is not allowed for value \"" << element_name
4666
<< "\".";
4667
4668
*stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
4669
if (comma) *stream << ",\n";
4670
}
4671
4672
void JsonUnitTestResultPrinter::OutputJsonKey(
4673
std::ostream* stream, const std::string& element_name,
4674
const std::string& name, int value, const std::string& indent, bool comma) {
4675
const std::vector<std::string>& allowed_names =
4676
GetReservedOutputAttributesForElement(element_name);
4677
4678
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4679
allowed_names.end())
4680
<< "Key \"" << name << "\" is not allowed for value \"" << element_name
4681
<< "\".";
4682
4683
*stream << indent << "\"" << name << "\": " << StreamableToString(value);
4684
if (comma) *stream << ",\n";
4685
}
4686
4687
// Streams a test suite JSON stanza containing the given test result.
4688
void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
4689
::std::ostream* stream, const TestResult& result) {
4690
// Output the boilerplate for a new test suite.
4691
*stream << Indent(4) << "{\n";
4692
OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
4693
OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
4694
if (!GTEST_FLAG_GET(list_tests)) {
4695
OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
4696
OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
4697
OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
4698
OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
4699
OutputJsonKey(stream, "testsuite", "time",
4700
FormatTimeInMillisAsDuration(result.elapsed_time()),
4701
Indent(6));
4702
OutputJsonKey(stream, "testsuite", "timestamp",
4703
FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4704
Indent(6));
4705
}
4706
*stream << Indent(6) << "\"testsuite\": [\n";
4707
4708
OutputJsonTestCaseForTestResult(stream, result);
4709
4710
// Finish the test suite.
4711
*stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
4712
}
4713
4714
// Streams a test case JSON stanza containing the given test result.
4715
void JsonUnitTestResultPrinter::OutputJsonTestCaseForTestResult(
4716
::std::ostream* stream, const TestResult& result) {
4717
// Output the boilerplate for a new test case.
4718
*stream << Indent(8) << "{\n";
4719
OutputJsonKey(stream, "testcase", "name", "", Indent(10));
4720
OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
4721
OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
4722
OutputJsonKey(stream, "testcase", "timestamp",
4723
FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4724
Indent(10));
4725
OutputJsonKey(stream, "testcase", "time",
4726
FormatTimeInMillisAsDuration(result.elapsed_time()),
4727
Indent(10));
4728
OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
4729
*stream << TestPropertiesAsJson(result, Indent(10));
4730
4731
// Output the actual test result.
4732
OutputJsonTestResult(stream, result);
4733
}
4734
4735
// Prints a JSON representation of a TestInfo object.
4736
void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4737
const char* test_suite_name,
4738
const TestInfo& test_info) {
4739
const TestResult& result = *test_info.result();
4740
const std::string kTestsuite = "testcase";
4741
const std::string kIndent = Indent(10);
4742
4743
*stream << Indent(8) << "{\n";
4744
OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
4745
4746
if (test_info.value_param() != nullptr) {
4747
OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
4748
kIndent);
4749
}
4750
if (test_info.type_param() != nullptr) {
4751
OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
4752
kIndent);
4753
}
4754
4755
OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
4756
OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
4757
if (GTEST_FLAG_GET(list_tests)) {
4758
*stream << "\n" << Indent(8) << "}";
4759
return;
4760
} else {
4761
*stream << ",\n";
4762
}
4763
4764
OutputJsonKey(stream, kTestsuite, "status",
4765
test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
4766
OutputJsonKey(stream, kTestsuite, "result",
4767
test_info.should_run()
4768
? (result.Skipped() ? "SKIPPED" : "COMPLETED")
4769
: "SUPPRESSED",
4770
kIndent);
4771
OutputJsonKey(stream, kTestsuite, "timestamp",
4772
FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4773
kIndent);
4774
OutputJsonKey(stream, kTestsuite, "time",
4775
FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
4776
OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
4777
false);
4778
*stream << TestPropertiesAsJson(result, kIndent);
4779
4780
OutputJsonTestResult(stream, result);
4781
}
4782
4783
void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
4784
const TestResult& result) {
4785
const std::string kIndent = Indent(10);
4786
4787
{
4788
int failures = 0;
4789
for (int i = 0; i < result.total_part_count(); ++i) {
4790
const TestPartResult& part = result.GetTestPartResult(i);
4791
if (part.failed()) {
4792
*stream << ",\n";
4793
if (++failures == 1) {
4794
*stream << kIndent << "\"" << "failures" << "\": [\n";
4795
}
4796
const std::string location =
4797
internal::FormatCompilerIndependentFileLocation(part.file_name(),
4798
part.line_number());
4799
const std::string message =
4800
EscapeJson(location + "\n" + part.message());
4801
*stream << kIndent << " {\n"
4802
<< kIndent << " \"failure\": \"" << message << "\",\n"
4803
<< kIndent << " \"type\": \"\"\n"
4804
<< kIndent << " }";
4805
}
4806
}
4807
4808
if (failures > 0) *stream << "\n" << kIndent << "]";
4809
}
4810
4811
{
4812
int skipped = 0;
4813
for (int i = 0; i < result.total_part_count(); ++i) {
4814
const TestPartResult& part = result.GetTestPartResult(i);
4815
if (part.skipped()) {
4816
*stream << ",\n";
4817
if (++skipped == 1) {
4818
*stream << kIndent << "\"" << "skipped" << "\": [\n";
4819
}
4820
const std::string location =
4821
internal::FormatCompilerIndependentFileLocation(part.file_name(),
4822
part.line_number());
4823
const std::string message =
4824
EscapeJson(location + "\n" + part.message());
4825
*stream << kIndent << " {\n"
4826
<< kIndent << " \"message\": \"" << message << "\"\n"
4827
<< kIndent << " }";
4828
}
4829
}
4830
4831
if (skipped > 0) *stream << "\n" << kIndent << "]";
4832
}
4833
4834
*stream << "\n" << Indent(8) << "}";
4835
}
4836
4837
// Prints an JSON representation of a TestSuite object
4838
void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4839
std::ostream* stream, const TestSuite& test_suite) {
4840
const std::string kTestsuite = "testsuite";
4841
const std::string kIndent = Indent(6);
4842
4843
*stream << Indent(4) << "{\n";
4844
OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
4845
OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
4846
kIndent);
4847
if (!GTEST_FLAG_GET(list_tests)) {
4848
OutputJsonKey(stream, kTestsuite, "failures",
4849
test_suite.failed_test_count(), kIndent);
4850
OutputJsonKey(stream, kTestsuite, "disabled",
4851
test_suite.reportable_disabled_test_count(), kIndent);
4852
OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
4853
OutputJsonKey(
4854
stream, kTestsuite, "timestamp",
4855
FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
4856
kIndent);
4857
OutputJsonKey(stream, kTestsuite, "time",
4858
FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
4859
kIndent, false);
4860
*stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
4861
<< ",\n";
4862
}
4863
4864
*stream << kIndent << "\"" << kTestsuite << "\": [\n";
4865
4866
bool comma = false;
4867
for (int i = 0; i < test_suite.total_test_count(); ++i) {
4868
if (test_suite.GetTestInfo(i)->is_reportable()) {
4869
if (comma) {
4870
*stream << ",\n";
4871
} else {
4872
comma = true;
4873
}
4874
OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4875
}
4876
}
4877
4878
// If there was a failure in the test suite setup or teardown include that in
4879
// the output.
4880
if (test_suite.ad_hoc_test_result().Failed()) {
4881
if (comma) {
4882
*stream << ",\n";
4883
}
4884
OutputJsonTestCaseForTestResult(stream, test_suite.ad_hoc_test_result());
4885
}
4886
4887
*stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
4888
}
4889
4890
// Prints a JSON summary of unit_test to output stream out.
4891
void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4892
const UnitTest& unit_test) {
4893
const std::string kTestsuites = "testsuites";
4894
const std::string kIndent = Indent(2);
4895
*stream << "{\n";
4896
4897
OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
4898
kIndent);
4899
OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
4900
kIndent);
4901
OutputJsonKey(stream, kTestsuites, "disabled",
4902
unit_test.reportable_disabled_test_count(), kIndent);
4903
OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
4904
if (GTEST_FLAG_GET(shuffle)) {
4905
OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
4906
kIndent);
4907
}
4908
OutputJsonKey(stream, kTestsuites, "timestamp",
4909
FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
4910
kIndent);
4911
OutputJsonKey(stream, kTestsuites, "time",
4912
FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
4913
false);
4914
4915
*stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4916
<< ",\n";
4917
4918
OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4919
*stream << kIndent << "\"" << kTestsuites << "\": [\n";
4920
4921
bool comma = false;
4922
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4923
if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
4924
if (comma) {
4925
*stream << ",\n";
4926
} else {
4927
comma = true;
4928
}
4929
PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
4930
}
4931
}
4932
4933
// If there was a test failure outside of one of the test suites (like in a
4934
// test environment) include that in the output.
4935
if (unit_test.ad_hoc_test_result().Failed()) {
4936
if (comma) {
4937
*stream << ",\n";
4938
}
4939
OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4940
}
4941
4942
*stream << "\n"
4943
<< kIndent << "]\n"
4944
<< "}\n";
4945
}
4946
4947
void JsonUnitTestResultPrinter::PrintJsonTestList(
4948
std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
4949
const std::string kTestsuites = "testsuites";
4950
const std::string kIndent = Indent(2);
4951
*stream << "{\n";
4952
int total_tests = 0;
4953
for (auto test_suite : test_suites) {
4954
total_tests += test_suite->total_test_count();
4955
}
4956
OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
4957
4958
OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4959
*stream << kIndent << "\"" << kTestsuites << "\": [\n";
4960
4961
for (size_t i = 0; i < test_suites.size(); ++i) {
4962
if (i != 0) {
4963
*stream << ",\n";
4964
}
4965
PrintJsonTestSuite(stream, *test_suites[i]);
4966
}
4967
4968
*stream << "\n"
4969
<< kIndent << "]\n"
4970
<< "}\n";
4971
}
4972
// Produces a string representing the test properties in a result as
4973
// a JSON dictionary.
4974
std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4975
const TestResult& result, const std::string& indent) {
4976
Message attributes;
4977
for (int i = 0; i < result.test_property_count(); ++i) {
4978
const TestProperty& property = result.GetTestProperty(i);
4979
attributes << ",\n"
4980
<< indent << "\"" << property.key() << "\": " << "\""
4981
<< EscapeJson(property.value()) << "\"";
4982
}
4983
return attributes.GetString();
4984
}
4985
4986
// End JsonUnitTestResultPrinter
4987
#endif // GTEST_HAS_FILE_SYSTEM
4988
4989
#if GTEST_CAN_STREAM_RESULTS_
4990
4991
// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4992
// replaces them by "%xx" where xx is their hexadecimal value. For
4993
// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4994
// in both time and space -- important as the input str may contain an
4995
// arbitrarily long test failure message and stack trace.
4996
std::string StreamingListener::UrlEncode(const char* str) {
4997
std::string result;
4998
result.reserve(strlen(str) + 1);
4999
for (char ch = *str; ch != '\0'; ch = *++str) {
5000
switch (ch) {
5001
case '%':
5002
case '=':
5003
case '&':
5004
case '\n':
5005
result.push_back('%');
5006
result.append(String::FormatByte(static_cast<unsigned char>(ch)));
5007
break;
5008
default:
5009
result.push_back(ch);
5010
break;
5011
}
5012
}
5013
return result;
5014
}
5015
5016
void StreamingListener::SocketWriter::MakeConnection() {
5017
GTEST_CHECK_(sockfd_ == -1)
5018
<< "MakeConnection() can't be called when there is already a connection.";
5019
5020
addrinfo hints;
5021
memset(&hints, 0, sizeof(hints));
5022
hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
5023
hints.ai_socktype = SOCK_STREAM;
5024
addrinfo* servinfo = nullptr;
5025
5026
// Use the getaddrinfo() to get a linked list of IP addresses for
5027
// the given host name.
5028
const int error_num =
5029
getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5030
if (error_num != 0) {
5031
GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5032
<< gai_strerror(error_num);
5033
}
5034
5035
// Loop through all the results and connect to the first we can.
5036
for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
5037
cur_addr = cur_addr->ai_next) {
5038
sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
5039
cur_addr->ai_protocol);
5040
if (sockfd_ != -1) {
5041
// Connect the client socket to the server socket.
5042
if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5043
close(sockfd_);
5044
sockfd_ = -1;
5045
}
5046
}
5047
}
5048
5049
freeaddrinfo(servinfo); // all done with this structure
5050
5051
if (sockfd_ == -1) {
5052
GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5053
<< host_name_ << ":" << port_num_;
5054
}
5055
}
5056
5057
// End of class Streaming Listener
5058
#endif // GTEST_CAN_STREAM_RESULTS__
5059
5060
// class OsStackTraceGetter
5061
5062
const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5063
"... " GTEST_NAME_ " internal frames ...";
5064
5065
std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
5066
GTEST_LOCK_EXCLUDED_(mutex_) {
5067
#ifdef GTEST_HAS_ABSL
5068
std::string result;
5069
5070
if (max_depth <= 0) {
5071
return result;
5072
}
5073
5074
max_depth = std::min(max_depth, kMaxStackTraceDepth);
5075
5076
std::vector<void*> raw_stack(max_depth);
5077
// Skips the frames requested by the caller, plus this function.
5078
const int raw_stack_size =
5079
absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
5080
5081
void* caller_frame = nullptr;
5082
{
5083
MutexLock lock(&mutex_);
5084
caller_frame = caller_frame_;
5085
}
5086
5087
for (int i = 0; i < raw_stack_size; ++i) {
5088
if (raw_stack[i] == caller_frame &&
5089
!GTEST_FLAG_GET(show_internal_stack_frames)) {
5090
// Add a marker to the trace and stop adding frames.
5091
absl::StrAppend(&result, kElidedFramesMarker, "\n");
5092
break;
5093
}
5094
5095
char tmp[1024];
5096
const char* symbol = "(unknown)";
5097
if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
5098
symbol = tmp;
5099
}
5100
5101
char line[1024];
5102
snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
5103
result += line;
5104
}
5105
5106
return result;
5107
5108
#else // !GTEST_HAS_ABSL
5109
static_cast<void>(max_depth);
5110
static_cast<void>(skip_count);
5111
return "";
5112
#endif // GTEST_HAS_ABSL
5113
}
5114
5115
void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
5116
#ifdef GTEST_HAS_ABSL
5117
void* caller_frame = nullptr;
5118
if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5119
caller_frame = nullptr;
5120
}
5121
5122
MutexLock lock(&mutex_);
5123
caller_frame_ = caller_frame;
5124
#endif // GTEST_HAS_ABSL
5125
}
5126
5127
#ifdef GTEST_HAS_DEATH_TEST
5128
// A helper class that creates the premature-exit file in its
5129
// constructor and deletes the file in its destructor.
5130
class ScopedPrematureExitFile {
5131
public:
5132
explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5133
: premature_exit_filepath_(
5134
premature_exit_filepath ? premature_exit_filepath : "") {
5135
// If a path to the premature-exit file is specified...
5136
if (!premature_exit_filepath_.empty()) {
5137
// create the file with a single "0" character in it. I/O
5138
// errors are ignored as there's nothing better we can do and we
5139
// don't want to fail the test because of this.
5140
FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), "w");
5141
fwrite("0", 1, 1, pfile);
5142
fclose(pfile);
5143
}
5144
}
5145
5146
~ScopedPrematureExitFile() {
5147
#ifndef GTEST_OS_ESP8266
5148
if (!premature_exit_filepath_.empty()) {
5149
int retval = remove(premature_exit_filepath_.c_str());
5150
if (retval) {
5151
GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
5152
<< premature_exit_filepath_ << "\" with error "
5153
<< retval;
5154
}
5155
}
5156
#endif
5157
}
5158
5159
private:
5160
const std::string premature_exit_filepath_;
5161
5162
ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete;
5163
ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete;
5164
};
5165
#endif // GTEST_HAS_DEATH_TEST
5166
5167
} // namespace internal
5168
5169
// class TestEventListeners
5170
5171
TestEventListeners::TestEventListeners()
5172
: repeater_(new internal::TestEventRepeater()),
5173
default_result_printer_(nullptr),
5174
default_xml_generator_(nullptr) {}
5175
5176
TestEventListeners::~TestEventListeners() { delete repeater_; }
5177
5178
// Returns the standard listener responsible for the default console
5179
// output. Can be removed from the listeners list to shut down default
5180
// console output. Note that removing this object from the listener list
5181
// with Release transfers its ownership to the user.
5182
void TestEventListeners::Append(TestEventListener* listener) {
5183
repeater_->Append(listener);
5184
}
5185
5186
// Removes the given event listener from the list and returns it. It then
5187
// becomes the caller's responsibility to delete the listener. Returns
5188
// NULL if the listener is not found in the list.
5189
TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5190
if (listener == default_result_printer_)
5191
default_result_printer_ = nullptr;
5192
else if (listener == default_xml_generator_)
5193
default_xml_generator_ = nullptr;
5194
return repeater_->Release(listener);
5195
}
5196
5197
// Returns repeater that broadcasts the TestEventListener events to all
5198
// subscribers.
5199
TestEventListener* TestEventListeners::repeater() { return repeater_; }
5200
5201
// Sets the default_result_printer attribute to the provided listener.
5202
// The listener is also added to the listener list and previous
5203
// default_result_printer is removed from it and deleted. The listener can
5204
// also be NULL in which case it will not be added to the list. Does
5205
// nothing if the previous and the current listener objects are the same.
5206
void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5207
if (default_result_printer_ != listener) {
5208
// It is an error to pass this method a listener that is already in the
5209
// list.
5210
delete Release(default_result_printer_);
5211
default_result_printer_ = listener;
5212
if (listener != nullptr) Append(listener);
5213
}
5214
}
5215
5216
// Sets the default_xml_generator attribute to the provided listener. The
5217
// listener is also added to the listener list and previous
5218
// default_xml_generator is removed from it and deleted. The listener can
5219
// also be NULL in which case it will not be added to the list. Does
5220
// nothing if the previous and the current listener objects are the same.
5221
void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5222
if (default_xml_generator_ != listener) {
5223
// It is an error to pass this method a listener that is already in the
5224
// list.
5225
delete Release(default_xml_generator_);
5226
default_xml_generator_ = listener;
5227
if (listener != nullptr) Append(listener);
5228
}
5229
}
5230
5231
// Controls whether events will be forwarded by the repeater to the
5232
// listeners in the list.
5233
bool TestEventListeners::EventForwardingEnabled() const {
5234
return repeater_->forwarding_enabled();
5235
}
5236
5237
void TestEventListeners::SuppressEventForwarding(bool suppress) {
5238
repeater_->set_forwarding_enabled(!suppress);
5239
}
5240
5241
// class UnitTest
5242
5243
// Gets the singleton UnitTest object. The first time this method is
5244
// called, a UnitTest object is constructed and returned. Consecutive
5245
// calls will return the same object.
5246
//
5247
// We don't protect this under mutex_ as a user is not supposed to
5248
// call this before main() starts, from which point on the return
5249
// value will never change.
5250
UnitTest* UnitTest::GetInstance() {
5251
// CodeGear C++Builder insists on a public destructor for the
5252
// default implementation. Use this implementation to keep good OO
5253
// design with private destructor.
5254
5255
#if defined(__BORLANDC__)
5256
static UnitTest* const instance = new UnitTest;
5257
return instance;
5258
#else
5259
static UnitTest instance;
5260
return &instance;
5261
#endif // defined(__BORLANDC__)
5262
}
5263
5264
// Gets the number of successful test suites.
5265
int UnitTest::successful_test_suite_count() const {
5266
return impl()->successful_test_suite_count();
5267
}
5268
5269
// Gets the number of failed test suites.
5270
int UnitTest::failed_test_suite_count() const {
5271
return impl()->failed_test_suite_count();
5272
}
5273
5274
// Gets the number of all test suites.
5275
int UnitTest::total_test_suite_count() const {
5276
return impl()->total_test_suite_count();
5277
}
5278
5279
// Gets the number of all test suites that contain at least one test
5280
// that should run.
5281
int UnitTest::test_suite_to_run_count() const {
5282
return impl()->test_suite_to_run_count();
5283
}
5284
5285
// Legacy API is deprecated but still available
5286
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5287
int UnitTest::successful_test_case_count() const {
5288
return impl()->successful_test_suite_count();
5289
}
5290
int UnitTest::failed_test_case_count() const {
5291
return impl()->failed_test_suite_count();
5292
}
5293
int UnitTest::total_test_case_count() const {
5294
return impl()->total_test_suite_count();
5295
}
5296
int UnitTest::test_case_to_run_count() const {
5297
return impl()->test_suite_to_run_count();
5298
}
5299
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5300
5301
// Gets the number of successful tests.
5302
int UnitTest::successful_test_count() const {
5303
return impl()->successful_test_count();
5304
}
5305
5306
// Gets the number of skipped tests.
5307
int UnitTest::skipped_test_count() const {
5308
return impl()->skipped_test_count();
5309
}
5310
5311
// Gets the number of failed tests.
5312
int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5313
5314
// Gets the number of disabled tests that will be reported in the XML report.
5315
int UnitTest::reportable_disabled_test_count() const {
5316
return impl()->reportable_disabled_test_count();
5317
}
5318
5319
// Gets the number of disabled tests.
5320
int UnitTest::disabled_test_count() const {
5321
return impl()->disabled_test_count();
5322
}
5323
5324
// Gets the number of tests to be printed in the XML report.
5325
int UnitTest::reportable_test_count() const {
5326
return impl()->reportable_test_count();
5327
}
5328
5329
// Gets the number of all tests.
5330
int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5331
5332
// Gets the number of tests that should run.
5333
int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5334
5335
// Gets the time of the test program start, in ms from the start of the
5336
// UNIX epoch.
5337
internal::TimeInMillis UnitTest::start_timestamp() const {
5338
return impl()->start_timestamp();
5339
}
5340
5341
// Gets the elapsed time, in milliseconds.
5342
internal::TimeInMillis UnitTest::elapsed_time() const {
5343
return impl()->elapsed_time();
5344
}
5345
5346
// Returns true if and only if the unit test passed (i.e. all test suites
5347
// passed).
5348
bool UnitTest::Passed() const { return impl()->Passed(); }
5349
5350
// Returns true if and only if the unit test failed (i.e. some test suite
5351
// failed or something outside of all tests failed).
5352
bool UnitTest::Failed() const { return impl()->Failed(); }
5353
5354
// Gets the i-th test suite among all the test suites. i can range from 0 to
5355
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
5356
const TestSuite* UnitTest::GetTestSuite(int i) const {
5357
return impl()->GetTestSuite(i);
5358
}
5359
5360
// Legacy API is deprecated but still available
5361
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5362
const TestCase* UnitTest::GetTestCase(int i) const {
5363
return impl()->GetTestCase(i);
5364
}
5365
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5366
5367
// Returns the TestResult containing information on test failures and
5368
// properties logged outside of individual test suites.
5369
const TestResult& UnitTest::ad_hoc_test_result() const {
5370
return *impl()->ad_hoc_test_result();
5371
}
5372
5373
// Gets the i-th test suite among all the test suites. i can range from 0 to
5374
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
5375
TestSuite* UnitTest::GetMutableTestSuite(int i) {
5376
return impl()->GetMutableSuiteCase(i);
5377
}
5378
5379
void UnitTest::UponLeavingGTest() {
5380
impl()->os_stack_trace_getter()->UponLeavingGTest();
5381
}
5382
5383
// Sets the TestSuite object for the test that's currently running.
5384
void UnitTest::set_current_test_suite(TestSuite* a_current_test_suite) {
5385
internal::MutexLock lock(&mutex_);
5386
impl_->set_current_test_suite(a_current_test_suite);
5387
}
5388
5389
// Sets the TestInfo object for the test that's currently running.
5390
void UnitTest::set_current_test_info(TestInfo* a_current_test_info) {
5391
internal::MutexLock lock(&mutex_);
5392
impl_->set_current_test_info(a_current_test_info);
5393
}
5394
5395
// Returns the list of event listeners that can be used to track events
5396
// inside Google Test.
5397
TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
5398
5399
// Registers and returns a global test environment. When a test
5400
// program is run, all global test environments will be set-up in the
5401
// order they were registered. After all tests in the program have
5402
// finished, all global test environments will be torn-down in the
5403
// *reverse* order they were registered.
5404
//
5405
// The UnitTest object takes ownership of the given environment.
5406
//
5407
// We don't protect this under mutex_, as we only support calling it
5408
// from the main thread.
5409
Environment* UnitTest::AddEnvironment(Environment* env) {
5410
if (env == nullptr) {
5411
return nullptr;
5412
}
5413
5414
impl_->environments().push_back(env);
5415
return env;
5416
}
5417
5418
// Adds a TestPartResult to the current TestResult object. All Google Test
5419
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5420
// this to report their results. The user code should use the
5421
// assertion macros instead of calling this directly.
5422
void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5423
const char* file_name, int line_number,
5424
const std::string& message,
5425
const std::string& os_stack_trace)
5426
GTEST_LOCK_EXCLUDED_(mutex_) {
5427
Message msg;
5428
msg << message;
5429
5430
internal::MutexLock lock(&mutex_);
5431
if (!impl_->gtest_trace_stack().empty()) {
5432
msg << "\n" << GTEST_NAME_ << " trace:";
5433
5434
for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
5435
const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5436
msg << "\n"
5437
<< internal::FormatFileLocation(trace.file, trace.line) << " "
5438
<< trace.message;
5439
}
5440
}
5441
5442
if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
5443
msg << internal::kStackTraceMarker << os_stack_trace;
5444
} else {
5445
msg << "\n";
5446
}
5447
5448
const TestPartResult result = TestPartResult(
5449
result_type, file_name, line_number, msg.GetString().c_str());
5450
impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5451
result);
5452
5453
if (result_type != TestPartResult::kSuccess &&
5454
result_type != TestPartResult::kSkip) {
5455
// gtest_break_on_failure takes precedence over
5456
// gtest_throw_on_failure. This allows a user to set the latter
5457
// in the code (perhaps in order to use Google Test assertions
5458
// with another testing framework) and specify the former on the
5459
// command line for debugging.
5460
if (GTEST_FLAG_GET(break_on_failure)) {
5461
#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
5462
!defined(GTEST_OS_WINDOWS_RT)
5463
// Using DebugBreak on Windows allows gtest to still break into a debugger
5464
// when a failure happens and both the --gtest_break_on_failure and
5465
// the --gtest_catch_exceptions flags are specified.
5466
DebugBreak();
5467
#elif (!defined(__native_client__)) && \
5468
((defined(__clang__) || defined(__GNUC__)) && \
5469
(defined(__x86_64__) || defined(__i386__)))
5470
// with clang/gcc we can achieve the same effect on x86 by invoking int3
5471
asm("int3");
5472
#elif GTEST_HAS_BUILTIN(__builtin_trap)
5473
__builtin_trap();
5474
#elif defined(SIGTRAP)
5475
raise(SIGTRAP);
5476
#else
5477
// Dereference nullptr through a volatile pointer to prevent the compiler
5478
// from removing. We use this rather than abort() or __builtin_trap() for
5479
// portability: some debuggers don't correctly trap abort().
5480
*static_cast<volatile int*>(nullptr) = 1;
5481
#endif // GTEST_OS_WINDOWS
5482
} else if (GTEST_FLAG_GET(throw_on_failure)) {
5483
#if GTEST_HAS_EXCEPTIONS
5484
throw internal::GoogleTestFailureException(result);
5485
#else
5486
// We cannot call abort() as it generates a pop-up in debug mode
5487
// that cannot be suppressed in VC 7.1 or below.
5488
exit(1);
5489
#endif
5490
}
5491
}
5492
}
5493
5494
// Adds a TestProperty to the current TestResult object when invoked from
5495
// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
5496
// from SetUpTestSuite or TearDownTestSuite, or to the global property set
5497
// when invoked elsewhere. If the result already contains a property with
5498
// the same key, the value will be updated.
5499
void UnitTest::RecordProperty(const std::string& key,
5500
const std::string& value) {
5501
impl_->RecordProperty(TestProperty(key, value));
5502
}
5503
5504
// Runs all tests in this UnitTest object and prints the result.
5505
// Returns 0 if successful, or 1 otherwise.
5506
//
5507
// We don't protect this under mutex_, as we only support calling it
5508
// from the main thread.
5509
int UnitTest::Run() {
5510
#ifdef GTEST_HAS_DEATH_TEST
5511
const bool in_death_test_child_process =
5512
!GTEST_FLAG_GET(internal_run_death_test).empty();
5513
5514
// Google Test implements this protocol for catching that a test
5515
// program exits before returning control to Google Test:
5516
//
5517
// 1. Upon start, Google Test creates a file whose absolute path
5518
// is specified by the environment variable
5519
// TEST_PREMATURE_EXIT_FILE.
5520
// 2. When Google Test has finished its work, it deletes the file.
5521
//
5522
// This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5523
// running a Google-Test-based test program and check the existence
5524
// of the file at the end of the test execution to see if it has
5525
// exited prematurely.
5526
5527
// If we are in the child process of a death test, don't
5528
// create/delete the premature exit file, as doing so is unnecessary
5529
// and will confuse the parent process. Otherwise, create/delete
5530
// the file upon entering/leaving this function. If the program
5531
// somehow exits before this function has a chance to return, the
5532
// premature-exit file will be left undeleted, causing a test runner
5533
// that understands the premature-exit-file protocol to report the
5534
// test as having failed.
5535
const internal::ScopedPrematureExitFile premature_exit_file(
5536
in_death_test_child_process
5537
? nullptr
5538
: internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5539
#else
5540
const bool in_death_test_child_process = false;
5541
#endif // GTEST_HAS_DEATH_TEST
5542
5543
// Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5544
// used for the duration of the program.
5545
impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions));
5546
5547
#ifdef GTEST_OS_WINDOWS
5548
// Either the user wants Google Test to catch exceptions thrown by the
5549
// tests or this is executing in the context of death test child
5550
// process. In either case the user does not want to see pop-up dialogs
5551
// about crashes - they are expected.
5552
if (impl()->catch_exceptions() || in_death_test_child_process) {
5553
#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \
5554
!defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_GAMES)
5555
// SetErrorMode doesn't exist on CE.
5556
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5557
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5558
#endif // !GTEST_OS_WINDOWS_MOBILE
5559
5560
#if (defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)) && \
5561
!defined(GTEST_OS_WINDOWS_MOBILE)
5562
// Death test children can be terminated with _abort(). On Windows,
5563
// _abort() can show a dialog with a warning message. This forces the
5564
// abort message to go to stderr instead.
5565
_set_error_mode(_OUT_TO_STDERR);
5566
#endif
5567
5568
#if defined(_MSC_VER) && !defined(GTEST_OS_WINDOWS_MOBILE)
5569
// In the debug version, Visual Studio pops up a separate dialog
5570
// offering a choice to debug the aborted program. We need to suppress
5571
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5572
// executed. Google Test will notify the user of any unexpected
5573
// failure via stderr.
5574
if (!GTEST_FLAG_GET(break_on_failure))
5575
_set_abort_behavior(
5576
0x0, // Clear the following flags:
5577
_WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5578
5579
// In debug mode, the Windows CRT can crash with an assertion over invalid
5580
// input (e.g. passing an invalid file descriptor). The default handling
5581
// for these assertions is to pop up a dialog and wait for user input.
5582
// Instead ask the CRT to dump such assertions to stderr non-interactively.
5583
if (!IsDebuggerPresent()) {
5584
(void)_CrtSetReportMode(_CRT_ASSERT,
5585
_CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
5586
(void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
5587
}
5588
#endif
5589
}
5590
#else
5591
(void)in_death_test_child_process; // Needed inside the #if block above
5592
#endif // GTEST_OS_WINDOWS
5593
5594
return internal::HandleExceptionsInMethodIfSupported(
5595
impl(), &internal::UnitTestImpl::RunAllTests,
5596
"auxiliary test code (environments or event listeners)")
5597
? 0
5598
: 1;
5599
}
5600
5601
#if GTEST_HAS_FILE_SYSTEM
5602
// Returns the working directory when the first TEST() or TEST_F() was
5603
// executed.
5604
const char* UnitTest::original_working_dir() const {
5605
return impl_->original_working_dir_.c_str();
5606
}
5607
#endif // GTEST_HAS_FILE_SYSTEM
5608
5609
// Returns the TestSuite object for the test that's currently running,
5610
// or NULL if no test is running.
5611
const TestSuite* UnitTest::current_test_suite() const
5612
GTEST_LOCK_EXCLUDED_(mutex_) {
5613
internal::MutexLock lock(&mutex_);
5614
return impl_->current_test_suite();
5615
}
5616
5617
// Legacy API is still available but deprecated
5618
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5619
const TestCase* UnitTest::current_test_case() const
5620
GTEST_LOCK_EXCLUDED_(mutex_) {
5621
internal::MutexLock lock(&mutex_);
5622
return impl_->current_test_suite();
5623
}
5624
#endif
5625
5626
// Returns the TestInfo object for the test that's currently running,
5627
// or NULL if no test is running.
5628
const TestInfo* UnitTest::current_test_info() const
5629
GTEST_LOCK_EXCLUDED_(mutex_) {
5630
internal::MutexLock lock(&mutex_);
5631
return impl_->current_test_info();
5632
}
5633
5634
// Returns the random seed used at the start of the current test run.
5635
int UnitTest::random_seed() const { return impl_->random_seed(); }
5636
5637
// Returns ParameterizedTestSuiteRegistry object used to keep track of
5638
// value-parameterized tests and instantiate and register them.
5639
internal::ParameterizedTestSuiteRegistry&
5640
UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
5641
return impl_->parameterized_test_registry();
5642
}
5643
5644
// Creates an empty UnitTest.
5645
UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
5646
5647
// Destructor of UnitTest.
5648
UnitTest::~UnitTest() { delete impl_; }
5649
5650
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5651
// Google Test trace stack.
5652
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5653
GTEST_LOCK_EXCLUDED_(mutex_) {
5654
internal::MutexLock lock(&mutex_);
5655
impl_->gtest_trace_stack().push_back(trace);
5656
}
5657
5658
// Pops a trace from the per-thread Google Test trace stack.
5659
void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
5660
internal::MutexLock lock(&mutex_);
5661
impl_->gtest_trace_stack().pop_back();
5662
}
5663
5664
namespace internal {
5665
5666
UnitTestImpl::UnitTestImpl(UnitTest* parent)
5667
: parent_(parent),
5668
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
5669
default_global_test_part_result_reporter_(this),
5670
default_per_thread_test_part_result_reporter_(this),
5671
GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_reporter_(
5672
&default_global_test_part_result_reporter_),
5673
per_thread_test_part_result_reporter_(
5674
&default_per_thread_test_part_result_reporter_),
5675
parameterized_test_registry_(),
5676
parameterized_tests_registered_(false),
5677
last_death_test_suite_(-1),
5678
current_test_suite_(nullptr),
5679
current_test_info_(nullptr),
5680
ad_hoc_test_result_(),
5681
os_stack_trace_getter_(nullptr),
5682
post_flag_parse_init_performed_(false),
5683
random_seed_(0), // Will be overridden by the flag before first use.
5684
random_(0), // Will be reseeded before first use.
5685
start_timestamp_(0),
5686
elapsed_time_(0),
5687
#ifdef GTEST_HAS_DEATH_TEST
5688
death_test_factory_(new DefaultDeathTestFactory),
5689
#endif
5690
// Will be overridden by the flag before first use.
5691
catch_exceptions_(false) {
5692
listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5693
}
5694
5695
UnitTestImpl::~UnitTestImpl() {
5696
// Deletes every TestSuite.
5697
ForEach(test_suites_, internal::Delete<TestSuite>);
5698
5699
// Deletes every Environment.
5700
ForEach(environments_, internal::Delete<Environment>);
5701
5702
delete os_stack_trace_getter_;
5703
}
5704
5705
// Adds a TestProperty to the current TestResult object when invoked in a
5706
// context of a test, to current test suite's ad_hoc_test_result when invoke
5707
// from SetUpTestSuite/TearDownTestSuite, or to the global property set
5708
// otherwise. If the result already contains a property with the same key,
5709
// the value will be updated.
5710
void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5711
std::string xml_element;
5712
TestResult* test_result; // TestResult appropriate for property recording.
5713
5714
if (current_test_info_ != nullptr) {
5715
xml_element = "testcase";
5716
test_result = &(current_test_info_->result_);
5717
} else if (current_test_suite_ != nullptr) {
5718
xml_element = "testsuite";
5719
test_result = &(current_test_suite_->ad_hoc_test_result_);
5720
} else {
5721
xml_element = "testsuites";
5722
test_result = &ad_hoc_test_result_;
5723
}
5724
test_result->RecordProperty(xml_element, test_property);
5725
}
5726
5727
#ifdef GTEST_HAS_DEATH_TEST
5728
// Disables event forwarding if the control is currently in a death test
5729
// subprocess. Must not be called before InitGoogleTest.
5730
void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5731
if (internal_run_death_test_flag_ != nullptr)
5732
listeners()->SuppressEventForwarding(true);
5733
}
5734
#endif // GTEST_HAS_DEATH_TEST
5735
5736
// Initializes event listeners performing XML output as specified by
5737
// UnitTestOptions. Must not be called before InitGoogleTest.
5738
void UnitTestImpl::ConfigureXmlOutput() {
5739
const std::string& output_format = UnitTestOptions::GetOutputFormat();
5740
#if GTEST_HAS_FILE_SYSTEM
5741
if (output_format == "xml") {
5742
listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5743
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5744
} else if (output_format == "json") {
5745
listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
5746
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5747
} else if (!output_format.empty()) {
5748
GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
5749
<< output_format << "\" ignored.";
5750
}
5751
#else
5752
if (!output_format.empty()) {
5753
GTEST_LOG_(ERROR) << "ERROR: alternative output formats require "
5754
<< "GTEST_HAS_FILE_SYSTEM to be enabled";
5755
}
5756
#endif // GTEST_HAS_FILE_SYSTEM
5757
}
5758
5759
#if GTEST_CAN_STREAM_RESULTS_
5760
// Initializes event listeners for streaming test results in string form.
5761
// Must not be called before InitGoogleTest.
5762
void UnitTestImpl::ConfigureStreamingOutput() {
5763
const std::string& target = GTEST_FLAG_GET(stream_result_to);
5764
if (!target.empty()) {
5765
const size_t pos = target.find(':');
5766
if (pos != std::string::npos) {
5767
listeners()->Append(
5768
new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
5769
} else {
5770
GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
5771
<< "\" ignored.";
5772
}
5773
}
5774
}
5775
#endif // GTEST_CAN_STREAM_RESULTS_
5776
5777
// Performs initialization dependent upon flag values obtained in
5778
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5779
// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5780
// this function is also called from RunAllTests. Since this function can be
5781
// called more than once, it has to be idempotent.
5782
void UnitTestImpl::PostFlagParsingInit() {
5783
// Ensures that this function does not execute more than once.
5784
if (!post_flag_parse_init_performed_) {
5785
post_flag_parse_init_performed_ = true;
5786
5787
#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5788
// Register to send notifications about key process state changes.
5789
listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5790
#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5791
5792
#ifdef GTEST_HAS_DEATH_TEST
5793
InitDeathTestSubprocessControlInfo();
5794
SuppressTestEventsIfInSubprocess();
5795
#endif // GTEST_HAS_DEATH_TEST
5796
5797
// Registers parameterized tests. This makes parameterized tests
5798
// available to the UnitTest reflection API without running
5799
// RUN_ALL_TESTS.
5800
RegisterParameterizedTests();
5801
5802
// Configures listeners for XML output. This makes it possible for users
5803
// to shut down the default XML output before invoking RUN_ALL_TESTS.
5804
ConfigureXmlOutput();
5805
5806
if (GTEST_FLAG_GET(brief)) {
5807
listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
5808
}
5809
5810
#if GTEST_CAN_STREAM_RESULTS_
5811
// Configures listeners for streaming test results to the specified server.
5812
ConfigureStreamingOutput();
5813
#endif // GTEST_CAN_STREAM_RESULTS_
5814
5815
#ifdef GTEST_HAS_ABSL
5816
if (GTEST_FLAG_GET(install_failure_signal_handler)) {
5817
absl::FailureSignalHandlerOptions options;
5818
absl::InstallFailureSignalHandler(options);
5819
}
5820
#endif // GTEST_HAS_ABSL
5821
}
5822
}
5823
5824
// Finds and returns a TestSuite with the given name. If one doesn't
5825
// exist, creates one and returns it. It's the CALLER'S
5826
// RESPONSIBILITY to ensure that this function is only called WHEN THE
5827
// TESTS ARE NOT SHUFFLED.
5828
//
5829
// Arguments:
5830
//
5831
// test_suite_name: name of the test suite
5832
// type_param: the name of the test suite's type parameter, or NULL if
5833
// this is not a typed or a type-parameterized test suite.
5834
// set_up_tc: pointer to the function that sets up the test suite
5835
// tear_down_tc: pointer to the function that tears down the test suite
5836
TestSuite* UnitTestImpl::GetTestSuite(
5837
const std::string& test_suite_name, const char* type_param,
5838
internal::SetUpTestSuiteFunc set_up_tc,
5839
internal::TearDownTestSuiteFunc tear_down_tc) {
5840
// During initialization, all TestInfos for a given suite are added in
5841
// sequence. To optimize this case, see if the most recently added suite is
5842
// the one being requested now.
5843
if (!test_suites_.empty() &&
5844
(*test_suites_.rbegin())->name_ == test_suite_name) {
5845
return *test_suites_.rbegin();
5846
}
5847
5848
// Fall back to searching the collection.
5849
auto item_it = test_suites_by_name_.find(test_suite_name);
5850
if (item_it != test_suites_by_name_.end()) {
5851
return item_it->second;
5852
}
5853
5854
// Not found. Create a new instance.
5855
auto* const new_test_suite =
5856
new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
5857
test_suites_by_name_.emplace(test_suite_name, new_test_suite);
5858
5859
const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter);
5860
// Is this a death test suite?
5861
if (death_test_suite_filter.MatchesName(test_suite_name)) {
5862
// Yes. Inserts the test suite after the last death test suite
5863
// defined so far. This only works when the test suites haven't
5864
// been shuffled. Otherwise we may end up running a death test
5865
// after a non-death test.
5866
++last_death_test_suite_;
5867
test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
5868
new_test_suite);
5869
} else {
5870
// No. Appends to the end of the list.
5871
test_suites_.push_back(new_test_suite);
5872
}
5873
5874
test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
5875
return new_test_suite;
5876
}
5877
5878
// Helpers for setting up / tearing down the given environment. They
5879
// are for use in the ForEach() function.
5880
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5881
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5882
5883
// If the environment variable TEST_WARNINGS_OUTPUT_FILE was provided, appends
5884
// `str` to the file, creating the file if necessary.
5885
#if GTEST_HAS_FILE_SYSTEM
5886
static void AppendToTestWarningsOutputFile(const std::string& str) {
5887
const char* const filename = posix::GetEnv(kTestWarningsOutputFile);
5888
if (filename == nullptr) {
5889
return;
5890
}
5891
auto* const file = posix::FOpen(filename, "a");
5892
if (file == nullptr) {
5893
return;
5894
}
5895
GTEST_CHECK_(fwrite(str.data(), 1, str.size(), file) == str.size());
5896
GTEST_CHECK_(posix::FClose(file) == 0);
5897
}
5898
#endif // GTEST_HAS_FILE_SYSTEM
5899
5900
// Runs all tests in this UnitTest object, prints the result, and
5901
// returns true if all tests are successful. If any exception is
5902
// thrown during a test, the test is considered to be failed, but the
5903
// rest of the tests will still be run.
5904
//
5905
// When parameterized tests are enabled, it expands and registers
5906
// parameterized tests first in RegisterParameterizedTests().
5907
// All other functions called from RunAllTests() may safely assume that
5908
// parameterized tests are ready to be counted and run.
5909
bool UnitTestImpl::RunAllTests() {
5910
// True if and only if Google Test is initialized before RUN_ALL_TESTS() is
5911
// called.
5912
const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
5913
5914
// Do not run any test if the --help flag was specified.
5915
if (g_help_flag) return true;
5916
5917
// Repeats the call to the post-flag parsing initialization in case the
5918
// user didn't call InitGoogleTest.
5919
PostFlagParsingInit();
5920
5921
// Handle the case where the program has no tests linked.
5922
// Sometimes this is a programmer mistake, but sometimes it is intended.
5923
if (total_test_count() == 0) {
5924
constexpr char kNoTestLinkedMessage[] =
5925
"This test program does NOT link in any test case.";
5926
constexpr char kNoTestLinkedFatal[] =
5927
"This is INVALID. Please make sure to link in at least one test case.";
5928
constexpr char kNoTestLinkedWarning[] =
5929
"Please make sure this is intended.";
5930
const bool fail_if_no_test_linked = GTEST_FLAG_GET(fail_if_no_test_linked);
5931
ColoredPrintf(
5932
GTestColor::kRed, "%s %s\n", kNoTestLinkedMessage,
5933
fail_if_no_test_linked ? kNoTestLinkedFatal : kNoTestLinkedWarning);
5934
if (fail_if_no_test_linked) {
5935
return false;
5936
}
5937
#if GTEST_HAS_FILE_SYSTEM
5938
AppendToTestWarningsOutputFile(std::string(kNoTestLinkedMessage) + ' ' +
5939
kNoTestLinkedWarning + '\n');
5940
#endif // GTEST_HAS_FILE_SYSTEM
5941
}
5942
5943
#if GTEST_HAS_FILE_SYSTEM
5944
// Even if sharding is not on, test runners may want to use the
5945
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5946
// protocol.
5947
internal::WriteToShardStatusFileIfNeeded();
5948
#endif // GTEST_HAS_FILE_SYSTEM
5949
5950
// True if and only if we are in a subprocess for running a thread-safe-style
5951
// death test.
5952
bool in_subprocess_for_death_test = false;
5953
5954
#ifdef GTEST_HAS_DEATH_TEST
5955
in_subprocess_for_death_test = (internal_run_death_test_flag_ != nullptr);
5956
#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5957
if (in_subprocess_for_death_test) {
5958
GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5959
}
5960
#endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5961
#endif // GTEST_HAS_DEATH_TEST
5962
5963
const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5964
in_subprocess_for_death_test);
5965
5966
// Compares the full test names with the filter to decide which
5967
// tests to run.
5968
const bool has_tests_to_run =
5969
FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
5970
: IGNORE_SHARDING_PROTOCOL) > 0;
5971
5972
// Lists the tests and exits if the --gtest_list_tests flag was specified.
5973
if (GTEST_FLAG_GET(list_tests)) {
5974
// This must be called *after* FilterTests() has been called.
5975
ListTestsMatchingFilter();
5976
return true;
5977
}
5978
5979
random_seed_ = GetRandomSeedFromFlag(GTEST_FLAG_GET(random_seed));
5980
5981
// True if and only if at least one test has failed.
5982
bool failed = false;
5983
5984
TestEventListener* repeater = listeners()->repeater();
5985
5986
start_timestamp_ = GetTimeInMillis();
5987
repeater->OnTestProgramStart(*parent_);
5988
5989
// How many times to repeat the tests? We don't want to repeat them
5990
// when we are inside the subprocess of a death test.
5991
const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat);
5992
5993
// Repeats forever if the repeat count is negative.
5994
const bool gtest_repeat_forever = repeat < 0;
5995
5996
// Should test environments be set up and torn down for each repeat, or only
5997
// set up on the first and torn down on the last iteration? If there is no
5998
// "last" iteration because the tests will repeat forever, always recreate the
5999
// environments to avoid leaks in case one of the environments is using
6000
// resources that are external to this process. Without this check there would
6001
// be no way to clean up those external resources automatically.
6002
const bool recreate_environments_when_repeating =
6003
GTEST_FLAG_GET(recreate_environments_when_repeating) ||
6004
gtest_repeat_forever;
6005
6006
for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
6007
// We want to preserve failures generated by ad-hoc test
6008
// assertions executed before RUN_ALL_TESTS().
6009
ClearNonAdHocTestResult();
6010
6011
Timer timer;
6012
6013
// Shuffles test suites and tests if requested.
6014
if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) {
6015
random()->Reseed(static_cast<uint32_t>(random_seed_));
6016
// This should be done before calling OnTestIterationStart(),
6017
// such that a test event listener can see the actual test order
6018
// in the event.
6019
ShuffleTests();
6020
}
6021
6022
// Tells the unit test event listeners that the tests are about to start.
6023
repeater->OnTestIterationStart(*parent_, i);
6024
6025
// Runs each test suite if there is at least one test to run.
6026
if (has_tests_to_run) {
6027
// Sets up all environments beforehand. If test environments aren't
6028
// recreated for each iteration, only do so on the first iteration.
6029
if (i == 0 || recreate_environments_when_repeating) {
6030
repeater->OnEnvironmentsSetUpStart(*parent_);
6031
ForEach(environments_, SetUpEnvironment);
6032
repeater->OnEnvironmentsSetUpEnd(*parent_);
6033
}
6034
6035
// Runs the tests only if there was no fatal failure or skip triggered
6036
// during global set-up.
6037
if (Test::IsSkipped()) {
6038
// Emit diagnostics when global set-up calls skip, as it will not be
6039
// emitted by default.
6040
TestResult& test_result =
6041
*internal::GetUnitTestImpl()->current_test_result();
6042
for (int j = 0; j < test_result.total_part_count(); ++j) {
6043
const TestPartResult& test_part_result =
6044
test_result.GetTestPartResult(j);
6045
if (test_part_result.type() == TestPartResult::kSkip) {
6046
const std::string& result = test_part_result.message();
6047
printf("%s\n", result.c_str());
6048
}
6049
}
6050
fflush(stdout);
6051
} else if (!Test::HasFatalFailure()) {
6052
for (int test_index = 0; test_index < total_test_suite_count();
6053
test_index++) {
6054
GetMutableSuiteCase(test_index)->Run();
6055
if (GTEST_FLAG_GET(fail_fast) &&
6056
GetMutableSuiteCase(test_index)->Failed()) {
6057
for (int j = test_index + 1; j < total_test_suite_count(); j++) {
6058
GetMutableSuiteCase(j)->Skip();
6059
}
6060
break;
6061
}
6062
}
6063
} else if (Test::HasFatalFailure()) {
6064
// If there was a fatal failure during the global setup then we know we
6065
// aren't going to run any tests. Explicitly mark all of the tests as
6066
// skipped to make this obvious in the output.
6067
for (int test_index = 0; test_index < total_test_suite_count();
6068
test_index++) {
6069
GetMutableSuiteCase(test_index)->Skip();
6070
}
6071
}
6072
6073
// Tears down all environments in reverse order afterwards. If test
6074
// environments aren't recreated for each iteration, only do so on the
6075
// last iteration.
6076
if (i == repeat - 1 || recreate_environments_when_repeating) {
6077
repeater->OnEnvironmentsTearDownStart(*parent_);
6078
std::for_each(environments_.rbegin(), environments_.rend(),
6079
TearDownEnvironment);
6080
repeater->OnEnvironmentsTearDownEnd(*parent_);
6081
}
6082
}
6083
6084
elapsed_time_ = timer.Elapsed();
6085
6086
// Tells the unit test event listener that the tests have just finished.
6087
repeater->OnTestIterationEnd(*parent_, i);
6088
6089
// Gets the result and clears it.
6090
if (!Passed()) {
6091
failed = true;
6092
}
6093
6094
// Restores the original test order after the iteration. This
6095
// allows the user to quickly repro a failure that happens in the
6096
// N-th iteration without repeating the first (N - 1) iterations.
6097
// This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6098
// case the user somehow changes the value of the flag somewhere
6099
// (it's always safe to unshuffle the tests).
6100
UnshuffleTests();
6101
6102
if (GTEST_FLAG_GET(shuffle)) {
6103
// Picks a new random seed for each iteration.
6104
random_seed_ = GetNextRandomSeed(random_seed_);
6105
}
6106
}
6107
6108
repeater->OnTestProgramEnd(*parent_);
6109
// Destroy environments in normal code, not in static teardown.
6110
bool delete_environment_on_teardown = true;
6111
if (delete_environment_on_teardown) {
6112
ForEach(environments_, internal::Delete<Environment>);
6113
environments_.clear();
6114
}
6115
6116
// Try to warn the user if no tests matched the test filter.
6117
if (ShouldWarnIfNoTestsMatchFilter()) {
6118
const std::string filter_warning =
6119
std::string("filter \"") + GTEST_FLAG_GET(filter) +
6120
"\" did not match any test; no tests were run\n";
6121
ColoredPrintf(GTestColor::kRed, "WARNING: %s", filter_warning.c_str());
6122
#if GTEST_HAS_FILE_SYSTEM
6123
AppendToTestWarningsOutputFile(filter_warning);
6124
#endif // GTEST_HAS_FILE_SYSTEM
6125
}
6126
6127
if (!gtest_is_initialized_before_run_all_tests) {
6128
ColoredPrintf(
6129
GTestColor::kRed,
6130
"\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
6131
"This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
6132
"() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
6133
" will start to enforce the valid usage. "
6134
"Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
6135
}
6136
6137
return !failed;
6138
}
6139
6140
#if GTEST_HAS_FILE_SYSTEM
6141
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6142
// if the variable is present. If a file already exists at this location, this
6143
// function will write over it. If the variable is present, but the file cannot
6144
// be created, prints an error and exits.
6145
void WriteToShardStatusFileIfNeeded() {
6146
const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
6147
if (test_shard_file != nullptr) {
6148
FILE* const file = posix::FOpen(test_shard_file, "w");
6149
if (file == nullptr) {
6150
ColoredPrintf(GTestColor::kRed,
6151
"Could not write to the test shard status file \"%s\" "
6152
"specified by the %s environment variable.\n",
6153
test_shard_file, kTestShardStatusFile);
6154
fflush(stdout);
6155
exit(EXIT_FAILURE);
6156
}
6157
fclose(file);
6158
}
6159
}
6160
#endif // GTEST_HAS_FILE_SYSTEM
6161
6162
// Checks whether sharding is enabled by examining the relevant
6163
// environment variable values. If the variables are present,
6164
// but inconsistent (i.e., shard_index >= total_shards), prints
6165
// an error and exits. If in_subprocess_for_death_test, sharding is
6166
// disabled because it must only be applied to the original test
6167
// process. Otherwise, we could filter out death tests we intended to execute.
6168
bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
6169
bool in_subprocess_for_death_test) {
6170
if (in_subprocess_for_death_test) {
6171
return false;
6172
}
6173
6174
const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6175
const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6176
6177
if (total_shards == -1 && shard_index == -1) {
6178
return false;
6179
} else if (total_shards == -1 && shard_index != -1) {
6180
const Message msg = Message() << "Invalid environment variables: you have "
6181
<< kTestShardIndex << " = " << shard_index
6182
<< ", but have left " << kTestTotalShards
6183
<< " unset.\n";
6184
ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
6185
fflush(stdout);
6186
exit(EXIT_FAILURE);
6187
} else if (total_shards != -1 && shard_index == -1) {
6188
const Message msg = Message()
6189
<< "Invalid environment variables: you have "
6190
<< kTestTotalShards << " = " << total_shards
6191
<< ", but have left " << kTestShardIndex << " unset.\n";
6192
ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
6193
fflush(stdout);
6194
exit(EXIT_FAILURE);
6195
} else if (shard_index < 0 || shard_index >= total_shards) {
6196
const Message msg =
6197
Message() << "Invalid environment variables: we require 0 <= "
6198
<< kTestShardIndex << " < " << kTestTotalShards
6199
<< ", but you have " << kTestShardIndex << "=" << shard_index
6200
<< ", " << kTestTotalShards << "=" << total_shards << ".\n";
6201
ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
6202
fflush(stdout);
6203
exit(EXIT_FAILURE);
6204
}
6205
6206
return total_shards > 1;
6207
}
6208
6209
// Parses the environment variable var as an Int32. If it is unset,
6210
// returns default_val. If it is not an Int32, prints an error
6211
// and aborts.
6212
int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {
6213
const char* str_val = posix::GetEnv(var);
6214
if (str_val == nullptr) {
6215
return default_val;
6216
}
6217
6218
int32_t result;
6219
if (!ParseInt32(Message() << "The value of environment variable " << var,
6220
str_val, &result)) {
6221
exit(EXIT_FAILURE);
6222
}
6223
return result;
6224
}
6225
6226
// Given the total number of shards, the shard index, and the test id,
6227
// returns true if and only if the test should be run on this shard. The test id
6228
// is some arbitrary but unique non-negative integer assigned to each test
6229
// method. Assumes that 0 <= shard_index < total_shards.
6230
bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6231
return (test_id % total_shards) == shard_index;
6232
}
6233
6234
// Compares the name of each test with the user-specified filter to
6235
// decide whether the test should be run, then records the result in
6236
// each TestSuite and TestInfo object.
6237
// If shard_tests == true, further filters tests based on sharding
6238
// variables in the environment - see
6239
// https://github.com/google/googletest/blob/main/docs/advanced.md
6240
// . Returns the number of tests that should run.
6241
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6242
const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
6243
? Int32FromEnvOrDie(kTestTotalShards, -1)
6244
: -1;
6245
const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
6246
? Int32FromEnvOrDie(kTestShardIndex, -1)
6247
: -1;
6248
6249
const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
6250
GTEST_FLAG_GET(filter));
6251
const UnitTestFilter disable_test_filter(kDisableTestFilter);
6252
// num_runnable_tests are the number of tests that will
6253
// run across all shards (i.e., match filter and are not disabled).
6254
// num_selected_tests are the number of tests to be run on
6255
// this shard.
6256
int num_runnable_tests = 0;
6257
int num_selected_tests = 0;
6258
for (auto* test_suite : test_suites_) {
6259
const std::string& test_suite_name = test_suite->name_;
6260
test_suite->set_should_run(false);
6261
6262
for (TestInfo* test_info : test_suite->test_info_list()) {
6263
const std::string& test_name = test_info->name_;
6264
// A test is disabled if test suite name or test name matches
6265
// kDisableTestFilter.
6266
const bool is_disabled =
6267
disable_test_filter.MatchesName(test_suite_name) ||
6268
disable_test_filter.MatchesName(test_name);
6269
test_info->is_disabled_ = is_disabled;
6270
6271
const bool matches_filter =
6272
gtest_flag_filter.MatchesTest(test_suite_name, test_name);
6273
test_info->matches_filter_ = matches_filter;
6274
6275
const bool is_runnable =
6276
(GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) &&
6277
matches_filter;
6278
6279
const bool is_in_another_shard =
6280
shard_tests != IGNORE_SHARDING_PROTOCOL &&
6281
!ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6282
test_info->is_in_another_shard_ = is_in_another_shard;
6283
const bool is_selected = is_runnable && !is_in_another_shard;
6284
6285
num_runnable_tests += is_runnable;
6286
num_selected_tests += is_selected;
6287
6288
test_info->should_run_ = is_selected;
6289
test_suite->set_should_run(test_suite->should_run() || is_selected);
6290
}
6291
}
6292
return num_selected_tests;
6293
}
6294
6295
// Returns true if a warning should be issued if no tests match the test filter
6296
// flag. We can't simply count the number of tests that ran because, for
6297
// instance, test sharding and death tests might mean no tests are expected to
6298
// run in this process, but will run in another process.
6299
bool UnitTestImpl::ShouldWarnIfNoTestsMatchFilter() const {
6300
if (total_test_count() == 0) {
6301
// No tests were linked in to program.
6302
// This case is handled by a different warning.
6303
return false;
6304
}
6305
const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
6306
GTEST_FLAG_GET(filter));
6307
for (auto* test_suite : test_suites_) {
6308
const std::string& test_suite_name = test_suite->name_;
6309
for (TestInfo* test_info : test_suite->test_info_list()) {
6310
const std::string& test_name = test_info->name_;
6311
if (gtest_flag_filter.MatchesTest(test_suite_name, test_name)) {
6312
return false;
6313
}
6314
}
6315
}
6316
return true;
6317
}
6318
6319
// Prints the given C-string on a single line by replacing all '\n'
6320
// characters with string "\\n". If the output takes more than
6321
// max_length characters, only prints the first max_length characters
6322
// and "...".
6323
static void PrintOnOneLine(const char* str, int max_length) {
6324
if (str != nullptr) {
6325
for (int i = 0; *str != '\0'; ++str) {
6326
if (i >= max_length) {
6327
printf("...");
6328
break;
6329
}
6330
if (*str == '\n') {
6331
printf("\\n");
6332
i += 2;
6333
} else {
6334
printf("%c", *str);
6335
++i;
6336
}
6337
}
6338
}
6339
}
6340
6341
// Prints the names of the tests matching the user-specified filter flag.
6342
void UnitTestImpl::ListTestsMatchingFilter() {
6343
// Print at most this many characters for each type/value parameter.
6344
const int kMaxParamLength = 250;
6345
6346
for (auto* test_suite : test_suites_) {
6347
bool printed_test_suite_name = false;
6348
6349
for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6350
const TestInfo* const test_info = test_suite->test_info_list()[j];
6351
if (test_info->matches_filter_) {
6352
if (!printed_test_suite_name) {
6353
printed_test_suite_name = true;
6354
printf("%s.", test_suite->name());
6355
if (test_suite->type_param() != nullptr) {
6356
printf(" # %s = ", kTypeParamLabel);
6357
// We print the type parameter on a single line to make
6358
// the output easy to parse by a program.
6359
PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
6360
}
6361
printf("\n");
6362
}
6363
printf(" %s", test_info->name());
6364
if (test_info->value_param() != nullptr) {
6365
printf(" # %s = ", kValueParamLabel);
6366
// We print the value parameter on a single line to make the
6367
// output easy to parse by a program.
6368
PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6369
}
6370
printf("\n");
6371
}
6372
}
6373
}
6374
fflush(stdout);
6375
#if GTEST_HAS_FILE_SYSTEM
6376
const std::string& output_format = UnitTestOptions::GetOutputFormat();
6377
if (output_format == "xml" || output_format == "json") {
6378
FILE* fileout =
6379
OpenFileForWriting(UnitTestOptions::GetAbsolutePathToOutputFile());
6380
std::stringstream stream;
6381
if (output_format == "xml") {
6382
XmlUnitTestResultPrinter(
6383
UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6384
.PrintXmlTestsList(&stream, test_suites_);
6385
} else if (output_format == "json") {
6386
JsonUnitTestResultPrinter(
6387
UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6388
.PrintJsonTestList(&stream, test_suites_);
6389
}
6390
fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
6391
fclose(fileout);
6392
}
6393
#endif // GTEST_HAS_FILE_SYSTEM
6394
}
6395
6396
// Sets the OS stack trace getter.
6397
//
6398
// Does nothing if the input and the current OS stack trace getter are
6399
// the same; otherwise, deletes the old getter and makes the input the
6400
// current getter.
6401
void UnitTestImpl::set_os_stack_trace_getter(
6402
OsStackTraceGetterInterface* getter) {
6403
if (os_stack_trace_getter_ != getter) {
6404
delete os_stack_trace_getter_;
6405
os_stack_trace_getter_ = getter;
6406
}
6407
}
6408
6409
// Returns the current OS stack trace getter if it is not NULL;
6410
// otherwise, creates an OsStackTraceGetter, makes it the current
6411
// getter, and returns it.
6412
OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6413
if (os_stack_trace_getter_ == nullptr) {
6414
#ifdef GTEST_OS_STACK_TRACE_GETTER_
6415
os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
6416
#else
6417
os_stack_trace_getter_ = new OsStackTraceGetter;
6418
#endif // GTEST_OS_STACK_TRACE_GETTER_
6419
}
6420
6421
return os_stack_trace_getter_;
6422
}
6423
6424
// Returns the most specific TestResult currently running.
6425
TestResult* UnitTestImpl::current_test_result() {
6426
if (current_test_info_ != nullptr) {
6427
return &current_test_info_->result_;
6428
}
6429
if (current_test_suite_ != nullptr) {
6430
return &current_test_suite_->ad_hoc_test_result_;
6431
}
6432
return &ad_hoc_test_result_;
6433
}
6434
6435
// Shuffles all test suites, and the tests within each test suite,
6436
// making sure that death tests are still run first.
6437
void UnitTestImpl::ShuffleTests() {
6438
// Shuffles the death test suites.
6439
ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
6440
6441
// Shuffles the non-death test suites.
6442
ShuffleRange(random(), last_death_test_suite_ + 1,
6443
static_cast<int>(test_suites_.size()), &test_suite_indices_);
6444
6445
// Shuffles the tests inside each test suite.
6446
for (auto& test_suite : test_suites_) {
6447
test_suite->ShuffleTests(random());
6448
}
6449
}
6450
6451
// Restores the test suites and tests to their order before the first shuffle.
6452
void UnitTestImpl::UnshuffleTests() {
6453
for (size_t i = 0; i < test_suites_.size(); i++) {
6454
// Unshuffles the tests in each test suite.
6455
test_suites_[i]->UnshuffleTests();
6456
// Resets the index of each test suite.
6457
test_suite_indices_[i] = static_cast<int>(i);
6458
}
6459
}
6460
6461
// Returns the current OS stack trace as an std::string.
6462
//
6463
// The maximum number of stack frames to be included is specified by
6464
// the gtest_stack_trace_depth flag. The skip_count parameter
6465
// specifies the number of top frames to be skipped, which doesn't
6466
// count against the number of frames to be included.
6467
//
6468
// For example, if Foo() calls Bar(), which in turn calls
6469
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6470
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
6471
GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string
6472
GetCurrentOsStackTraceExceptTop(int skip_count) {
6473
// We pass skip_count + 1 to skip this wrapper function in addition
6474
// to what the user really wants to skip.
6475
return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6476
}
6477
6478
// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6479
// suppress unreachable code warnings.
6480
namespace {
6481
class ClassUniqueToAlwaysTrue {};
6482
} // namespace
6483
6484
bool IsTrue(bool condition) { return condition; }
6485
6486
bool AlwaysTrue() {
6487
#if GTEST_HAS_EXCEPTIONS
6488
// This condition is always false so AlwaysTrue() never actually throws,
6489
// but it makes the compiler think that it may throw.
6490
if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
6491
#endif // GTEST_HAS_EXCEPTIONS
6492
return true;
6493
}
6494
6495
// If *pstr starts with the given prefix, modifies *pstr to be right
6496
// past the prefix and returns true; otherwise leaves *pstr unchanged
6497
// and returns false. None of pstr, *pstr, and prefix can be NULL.
6498
bool SkipPrefix(const char* prefix, const char** pstr) {
6499
const size_t prefix_len = strlen(prefix);
6500
if (strncmp(*pstr, prefix, prefix_len) == 0) {
6501
*pstr += prefix_len;
6502
return true;
6503
}
6504
return false;
6505
}
6506
6507
// Parses a string as a command line flag. The string should have
6508
// the format "--flag=value". When def_optional is true, the "=value"
6509
// part can be omitted.
6510
//
6511
// Returns the value of the flag, or NULL if the parsing failed.
6512
static const char* ParseFlagValue(const char* str, const char* flag_name,
6513
bool def_optional) {
6514
// str and flag must not be NULL.
6515
if (str == nullptr || flag_name == nullptr) return nullptr;
6516
6517
// The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6518
const std::string flag_str =
6519
std::string("--") + GTEST_FLAG_PREFIX_ + flag_name;
6520
const size_t flag_len = flag_str.length();
6521
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
6522
6523
// Skips the flag name.
6524
const char* flag_end = str + flag_len;
6525
6526
// When def_optional is true, it's OK to not have a "=value" part.
6527
if (def_optional && (flag_end[0] == '\0')) {
6528
return flag_end;
6529
}
6530
6531
// If def_optional is true and there are more characters after the
6532
// flag name, or if def_optional is false, there must be a '=' after
6533
// the flag name.
6534
if (flag_end[0] != '=') return nullptr;
6535
6536
// Returns the string after "=".
6537
return flag_end + 1;
6538
}
6539
6540
// Parses a string for a bool flag, in the form of either
6541
// "--flag=value" or "--flag".
6542
//
6543
// In the former case, the value is taken as true as long as it does
6544
// not start with '0', 'f', or 'F'.
6545
//
6546
// In the latter case, the value is taken as true.
6547
//
6548
// On success, stores the value of the flag in *value, and returns
6549
// true. On failure, returns false without changing *value.
6550
static bool ParseFlag(const char* str, const char* flag_name, bool* value) {
6551
// Gets the value of the flag as a string.
6552
const char* const value_str = ParseFlagValue(str, flag_name, true);
6553
6554
// Aborts if the parsing failed.
6555
if (value_str == nullptr) return false;
6556
6557
// Converts the string value to a bool.
6558
*value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6559
return true;
6560
}
6561
6562
// Parses a string for an int32_t flag, in the form of "--flag=value".
6563
//
6564
// On success, stores the value of the flag in *value, and returns
6565
// true. On failure, returns false without changing *value.
6566
bool ParseFlag(const char* str, const char* flag_name, int32_t* value) {
6567
// Gets the value of the flag as a string.
6568
const char* const value_str = ParseFlagValue(str, flag_name, false);
6569
6570
// Aborts if the parsing failed.
6571
if (value_str == nullptr) return false;
6572
6573
// Sets *value to the value of the flag.
6574
return ParseInt32(Message() << "The value of flag --" << flag_name, value_str,
6575
value);
6576
}
6577
6578
// Parses a string for a string flag, in the form of "--flag=value".
6579
//
6580
// On success, stores the value of the flag in *value, and returns
6581
// true. On failure, returns false without changing *value.
6582
template <typename String>
6583
static bool ParseFlag(const char* str, const char* flag_name, String* value) {
6584
// Gets the value of the flag as a string.
6585
const char* const value_str = ParseFlagValue(str, flag_name, false);
6586
6587
// Aborts if the parsing failed.
6588
if (value_str == nullptr) return false;
6589
6590
// Sets *value to the value of the flag.
6591
*value = value_str;
6592
return true;
6593
}
6594
6595
// Determines whether a string has a prefix that Google Test uses for its
6596
// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6597
// If Google Test detects that a command line flag has its prefix but is not
6598
// recognized, it will print its help message. Flags starting with
6599
// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6600
// internal flags and do not trigger the help message.
6601
static bool HasGoogleTestFlagPrefix(const char* str) {
6602
return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
6603
SkipPrefix("/", &str)) &&
6604
!SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6605
(SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6606
SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6607
}
6608
6609
// Prints a string containing code-encoded text. The following escape
6610
// sequences can be used in the string to control the text color:
6611
//
6612
// @@ prints a single '@' character.
6613
// @R changes the color to red.
6614
// @G changes the color to green.
6615
// @Y changes the color to yellow.
6616
// @D changes to the default terminal text color.
6617
//
6618
static void PrintColorEncoded(const char* str) {
6619
GTestColor color = GTestColor::kDefault; // The current color.
6620
6621
// Conceptually, we split the string into segments divided by escape
6622
// sequences. Then we print one segment at a time. At the end of
6623
// each iteration, the str pointer advances to the beginning of the
6624
// next segment.
6625
for (;;) {
6626
const char* p = strchr(str, '@');
6627
if (p == nullptr) {
6628
ColoredPrintf(color, "%s", str);
6629
return;
6630
}
6631
6632
ColoredPrintf(color, "%s", std::string(str, p).c_str());
6633
6634
const char ch = p[1];
6635
str = p + 2;
6636
if (ch == '@') {
6637
ColoredPrintf(color, "@");
6638
} else if (ch == 'D') {
6639
color = GTestColor::kDefault;
6640
} else if (ch == 'R') {
6641
color = GTestColor::kRed;
6642
} else if (ch == 'G') {
6643
color = GTestColor::kGreen;
6644
} else if (ch == 'Y') {
6645
color = GTestColor::kYellow;
6646
} else {
6647
--str;
6648
}
6649
}
6650
}
6651
6652
static const char kColorEncodedHelpMessage[] =
6653
"This program contains tests written using " GTEST_NAME_
6654
". You can use the\n"
6655
"following command line flags to control its behavior:\n"
6656
"\n"
6657
"Test Selection:\n"
6658
" @G--" GTEST_FLAG_PREFIX_
6659
"list_tests@D\n"
6660
" List the names of all tests instead of running them. The name of\n"
6661
" TEST(Foo, Bar) is \"Foo.Bar\".\n"
6662
" @G--" GTEST_FLAG_PREFIX_
6663
"filter=@YPOSITIVE_PATTERNS"
6664
"[@G-@YNEGATIVE_PATTERNS]@D\n"
6665
" Run only the tests whose name matches one of the positive patterns "
6666
"but\n"
6667
" none of the negative patterns. '?' matches any single character; "
6668
"'*'\n"
6669
" matches any substring; ':' separates two patterns.\n"
6670
" @G--" GTEST_FLAG_PREFIX_
6671
"also_run_disabled_tests@D\n"
6672
" Run all disabled tests too.\n"
6673
"\n"
6674
"Test Execution:\n"
6675
" @G--" GTEST_FLAG_PREFIX_
6676
"repeat=@Y[COUNT]@D\n"
6677
" Run the tests repeatedly; use a negative count to repeat forever.\n"
6678
" @G--" GTEST_FLAG_PREFIX_
6679
"shuffle@D\n"
6680
" Randomize tests' orders on every iteration.\n"
6681
" @G--" GTEST_FLAG_PREFIX_
6682
"random_seed=@Y[NUMBER]@D\n"
6683
" Random number seed to use for shuffling test orders (between 1 and\n"
6684
" 99999, or 0 to use a seed based on the current time).\n"
6685
" @G--" GTEST_FLAG_PREFIX_
6686
"recreate_environments_when_repeating@D\n"
6687
" Sets up and tears down the global test environment on each repeat\n"
6688
" of the test.\n"
6689
"\n"
6690
"Test Output:\n"
6691
" @G--" GTEST_FLAG_PREFIX_
6692
"color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6693
" Enable/disable colored output. The default is @Gauto@D.\n"
6694
" @G--" GTEST_FLAG_PREFIX_
6695
"brief=1@D\n"
6696
" Only print test failures.\n"
6697
" @G--" GTEST_FLAG_PREFIX_
6698
"print_time=0@D\n"
6699
" Don't print the elapsed time of each test.\n"
6700
" @G--" GTEST_FLAG_PREFIX_
6701
"output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
6702
"@Y|@G:@YFILE_PATH]@D\n"
6703
" Generate a JSON or XML report in the given directory or with the "
6704
"given\n"
6705
" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
6706
#if GTEST_CAN_STREAM_RESULTS_
6707
" @G--" GTEST_FLAG_PREFIX_
6708
"stream_result_to=@YHOST@G:@YPORT@D\n"
6709
" Stream test results to the given server.\n"
6710
#endif // GTEST_CAN_STREAM_RESULTS_
6711
"\n"
6712
"Assertion Behavior:\n"
6713
#if defined(GTEST_HAS_DEATH_TEST) && !defined(GTEST_OS_WINDOWS)
6714
" @G--" GTEST_FLAG_PREFIX_
6715
"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6716
" Set the default death test style.\n"
6717
#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6718
" @G--" GTEST_FLAG_PREFIX_
6719
"break_on_failure@D\n"
6720
" Turn assertion failures into debugger break-points.\n"
6721
" @G--" GTEST_FLAG_PREFIX_
6722
"throw_on_failure@D\n"
6723
" Turn assertion failures into C++ exceptions for use by an external\n"
6724
" test framework.\n"
6725
" @G--" GTEST_FLAG_PREFIX_
6726
"catch_exceptions=0@D\n"
6727
" Do not report exceptions as test failures. Instead, allow them\n"
6728
" to crash the program or throw a pop-up (on Windows).\n"
6729
"\n"
6730
"Except for @G--" GTEST_FLAG_PREFIX_
6731
"list_tests@D, you can alternatively set "
6732
"the corresponding\n"
6733
"environment variable of a flag (all letters in upper-case). For example, "
6734
"to\n"
6735
"disable colored text output, you can either specify "
6736
"@G--" GTEST_FLAG_PREFIX_
6737
"color=no@D or set\n"
6738
"the @G" GTEST_FLAG_PREFIX_UPPER_
6739
"COLOR@D environment variable to @Gno@D.\n"
6740
"\n"
6741
"For more information, please read the " GTEST_NAME_
6742
" documentation at\n"
6743
"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
6744
"\n"
6745
"(not one in your own code or tests), please report it to\n"
6746
"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6747
6748
static bool ParseGoogleTestFlag(const char* const arg) {
6749
#define GTEST_INTERNAL_PARSE_FLAG(flag_name) \
6750
do { \
6751
auto value = GTEST_FLAG_GET(flag_name); \
6752
if (ParseFlag(arg, #flag_name, &value)) { \
6753
GTEST_FLAG_SET(flag_name, value); \
6754
return true; \
6755
} \
6756
} while (false)
6757
6758
GTEST_INTERNAL_PARSE_FLAG(also_run_disabled_tests);
6759
GTEST_INTERNAL_PARSE_FLAG(break_on_failure);
6760
GTEST_INTERNAL_PARSE_FLAG(catch_exceptions);
6761
GTEST_INTERNAL_PARSE_FLAG(color);
6762
GTEST_INTERNAL_PARSE_FLAG(death_test_style);
6763
GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork);
6764
GTEST_INTERNAL_PARSE_FLAG(fail_fast);
6765
GTEST_INTERNAL_PARSE_FLAG(fail_if_no_test_linked);
6766
GTEST_INTERNAL_PARSE_FLAG(filter);
6767
GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test);
6768
GTEST_INTERNAL_PARSE_FLAG(list_tests);
6769
GTEST_INTERNAL_PARSE_FLAG(output);
6770
GTEST_INTERNAL_PARSE_FLAG(brief);
6771
GTEST_INTERNAL_PARSE_FLAG(print_time);
6772
GTEST_INTERNAL_PARSE_FLAG(print_utf8);
6773
GTEST_INTERNAL_PARSE_FLAG(random_seed);
6774
GTEST_INTERNAL_PARSE_FLAG(repeat);
6775
GTEST_INTERNAL_PARSE_FLAG(recreate_environments_when_repeating);
6776
GTEST_INTERNAL_PARSE_FLAG(shuffle);
6777
GTEST_INTERNAL_PARSE_FLAG(stack_trace_depth);
6778
GTEST_INTERNAL_PARSE_FLAG(stream_result_to);
6779
GTEST_INTERNAL_PARSE_FLAG(throw_on_failure);
6780
return false;
6781
}
6782
6783
#if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6784
static void LoadFlagsFromFile(const std::string& path) {
6785
FILE* flagfile = posix::FOpen(path.c_str(), "r");
6786
if (!flagfile) {
6787
GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG_GET(flagfile)
6788
<< "\"";
6789
}
6790
std::string contents(ReadEntireFile(flagfile));
6791
posix::FClose(flagfile);
6792
std::vector<std::string> lines;
6793
SplitString(contents, '\n', &lines);
6794
for (size_t i = 0; i < lines.size(); ++i) {
6795
if (lines[i].empty()) continue;
6796
if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true;
6797
}
6798
}
6799
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6800
6801
// Parses the command line for Google Test flags, without initializing
6802
// other parts of Google Test. The type parameter CharType can be
6803
// instantiated to either char or wchar_t.
6804
template <typename CharType>
6805
void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6806
std::string flagfile_value;
6807
for (int i = 1; i < *argc; i++) {
6808
const std::string arg_string = StreamableToString(argv[i]);
6809
const char* const arg = arg_string.c_str();
6810
6811
using internal::ParseFlag;
6812
6813
bool remove_flag = false;
6814
if (ParseGoogleTestFlag(arg)) {
6815
remove_flag = true;
6816
#if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6817
} else if (ParseFlag(arg, "flagfile", &flagfile_value)) {
6818
GTEST_FLAG_SET(flagfile, flagfile_value);
6819
LoadFlagsFromFile(flagfile_value);
6820
remove_flag = true;
6821
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6822
} else if (arg_string == "--help" || HasGoogleTestFlagPrefix(arg)) {
6823
// Both help flag and unrecognized Google Test flags (excluding
6824
// internal ones) trigger help display.
6825
g_help_flag = true;
6826
}
6827
6828
if (remove_flag) {
6829
// Shift the remainder of the argv list left by one.
6830
for (int j = i + 1; j < *argc; ++j) {
6831
argv[j - 1] = argv[j];
6832
}
6833
6834
// Decrements the argument count.
6835
(*argc)--;
6836
6837
// Terminate the array with nullptr.
6838
argv[*argc] = nullptr;
6839
6840
// We also need to decrement the iterator as we just removed
6841
// an element.
6842
i--;
6843
}
6844
}
6845
6846
if (g_help_flag) {
6847
// We print the help here instead of in RUN_ALL_TESTS(), as the
6848
// latter may not be called at all if the user is using Google
6849
// Test with another testing framework.
6850
PrintColorEncoded(kColorEncodedHelpMessage);
6851
}
6852
}
6853
6854
// Parses the command line for Google Test flags, without initializing
6855
// other parts of Google Test. This function updates argc and argv by removing
6856
// flags that are known to GoogleTest (including other user flags defined using
6857
// ABSL_FLAG if GoogleTest is built with GTEST_USE_ABSL). Other arguments
6858
// remain in place. Unrecognized flags are not reported and do not cause the
6859
// program to exit.
6860
void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6861
#ifdef GTEST_HAS_ABSL_FLAGS
6862
if (*argc <= 0) return;
6863
6864
std::vector<char*> positional_args;
6865
std::vector<absl::UnrecognizedFlag> unrecognized_flags;
6866
absl::ParseAbseilFlagsOnly(*argc, argv, positional_args, unrecognized_flags);
6867
absl::flat_hash_set<absl::string_view> unrecognized;
6868
for (const auto& flag : unrecognized_flags) {
6869
unrecognized.insert(flag.flag_name);
6870
}
6871
absl::flat_hash_set<char*> positional;
6872
for (const auto& arg : positional_args) {
6873
positional.insert(arg);
6874
}
6875
6876
int out_pos = 1;
6877
int in_pos = 1;
6878
for (; in_pos < *argc; ++in_pos) {
6879
char* arg = argv[in_pos];
6880
absl::string_view arg_str(arg);
6881
if (absl::ConsumePrefix(&arg_str, "--")) {
6882
// Flag-like argument. If the flag was unrecognized, keep it.
6883
// If it was a GoogleTest flag, remove it.
6884
if (unrecognized.contains(arg_str)) {
6885
argv[out_pos++] = argv[in_pos];
6886
continue;
6887
}
6888
}
6889
6890
if (arg_str.empty()) {
6891
++in_pos;
6892
break; // '--' indicates that the rest of the arguments are positional
6893
}
6894
6895
// Probably a positional argument. If it is in fact positional, keep it.
6896
// If it was a value for the flag argument, remove it.
6897
if (positional.contains(arg)) {
6898
argv[out_pos++] = arg;
6899
}
6900
}
6901
6902
// The rest are positional args for sure.
6903
while (in_pos < *argc) {
6904
argv[out_pos++] = argv[in_pos++];
6905
}
6906
6907
*argc = out_pos;
6908
argv[out_pos] = nullptr;
6909
#else
6910
ParseGoogleTestFlagsOnlyImpl(argc, argv);
6911
#endif
6912
6913
// Fix the value of *_NSGetArgc() on macOS, but if and only if
6914
// *_NSGetArgv() == argv
6915
// Only applicable to char** version of argv
6916
#ifdef GTEST_OS_MAC
6917
#ifndef GTEST_OS_IOS
6918
if (*_NSGetArgv() == argv) {
6919
*_NSGetArgc() = *argc;
6920
}
6921
#endif
6922
#endif
6923
}
6924
void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6925
ParseGoogleTestFlagsOnlyImpl(argc, argv);
6926
}
6927
6928
// The internal implementation of InitGoogleTest().
6929
//
6930
// The type parameter CharType can be instantiated to either char or
6931
// wchar_t.
6932
template <typename CharType>
6933
void InitGoogleTestImpl(int* argc, CharType** argv) {
6934
// We don't want to run the initialization code twice.
6935
if (GTestIsInitialized()) return;
6936
6937
if (*argc <= 0) return;
6938
6939
g_argvs.clear();
6940
for (int i = 0; i != *argc; i++) {
6941
g_argvs.push_back(StreamableToString(argv[i]));
6942
}
6943
6944
#ifdef GTEST_HAS_ABSL
6945
absl::InitializeSymbolizer(g_argvs[0].c_str());
6946
6947
#ifdef GTEST_HAS_ABSL_FLAGS
6948
// When using the Abseil Flags library, set the program usage message to the
6949
// help message, but remove the color-encoding from the message first.
6950
absl::SetProgramUsageMessage(absl::StrReplaceAll(
6951
kColorEncodedHelpMessage,
6952
{{"@D", ""}, {"@R", ""}, {"@G", ""}, {"@Y", ""}, {"@@", "@"}}));
6953
#endif // GTEST_HAS_ABSL_FLAGS
6954
#endif // GTEST_HAS_ABSL
6955
6956
ParseGoogleTestFlagsOnly(argc, argv);
6957
GetUnitTestImpl()->PostFlagParsingInit();
6958
}
6959
6960
} // namespace internal
6961
6962
// Initializes Google Test. This must be called before calling
6963
// RUN_ALL_TESTS(). In particular, it parses a command line for the
6964
// flags that Google Test recognizes. Whenever a Google Test flag is
6965
// seen, it is removed from argv, and *argc is decremented.
6966
//
6967
// No value is returned. Instead, the Google Test flag variables are
6968
// updated.
6969
//
6970
// Calling the function for the second time has no user-visible effect.
6971
void InitGoogleTest(int* argc, char** argv) {
6972
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6973
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6974
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6975
internal::InitGoogleTestImpl(argc, argv);
6976
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6977
}
6978
6979
// This overloaded version can be used in Windows programs compiled in
6980
// UNICODE mode.
6981
void InitGoogleTest(int* argc, wchar_t** argv) {
6982
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6983
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6984
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6985
internal::InitGoogleTestImpl(argc, argv);
6986
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6987
}
6988
6989
// This overloaded version can be used on Arduino/embedded platforms where
6990
// there is no argc/argv.
6991
void InitGoogleTest() {
6992
// Since Arduino doesn't have a command line, fake out the argc/argv arguments
6993
int argc = 1;
6994
const auto arg0 = "dummy";
6995
char* argv0 = const_cast<char*>(arg0);
6996
char** argv = &argv0;
6997
6998
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6999
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
7000
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7001
internal::InitGoogleTestImpl(&argc, argv);
7002
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7003
}
7004
7005
#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) || \
7006
!defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
7007
// Returns the value of the first environment variable that is set and contains
7008
// a non-empty string. If there are none, returns the "fallback" string. Adds
7009
// the director-separator character as a suffix if not provided in the
7010
// environment variable value.
7011
static std::string GetDirFromEnv(
7012
std::initializer_list<const char*> environment_variables,
7013
const char* fallback, char separator) {
7014
for (const char* variable_name : environment_variables) {
7015
const char* value = internal::posix::GetEnv(variable_name);
7016
if (value != nullptr && value[0] != '\0') {
7017
if (value[strlen(value) - 1] != separator) {
7018
return std::string(value).append(1, separator);
7019
}
7020
return value;
7021
}
7022
}
7023
return fallback;
7024
}
7025
#endif
7026
7027
std::string TempDir() {
7028
#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
7029
return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
7030
#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
7031
return GetDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\');
7032
#elif defined(GTEST_OS_LINUX_ANDROID)
7033
return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/');
7034
#else
7035
return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/');
7036
#endif
7037
}
7038
7039
#if GTEST_HAS_FILE_SYSTEM && !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
7040
// Returns the directory path (including terminating separator) of the current
7041
// executable as derived from argv[0].
7042
static std::string GetCurrentExecutableDirectory() {
7043
internal::FilePath argv_0(internal::GetArgvs()[0]);
7044
return argv_0.RemoveFileName().string();
7045
}
7046
#endif
7047
7048
#if GTEST_HAS_FILE_SYSTEM
7049
std::string SrcDir() {
7050
#if defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
7051
return GTEST_CUSTOM_SRCDIR_FUNCTION_();
7052
#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
7053
return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
7054
'\\');
7055
#elif defined(GTEST_OS_LINUX_ANDROID)
7056
return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
7057
'/');
7058
#else
7059
return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
7060
'/');
7061
#endif
7062
}
7063
#endif
7064
7065
// Class ScopedTrace
7066
7067
// Pushes the given source file location and message onto a per-thread
7068
// trace stack maintained by Google Test.
7069
void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
7070
internal::TraceInfo trace;
7071
trace.file = file;
7072
trace.line = line;
7073
trace.message.swap(message);
7074
7075
UnitTest::GetInstance()->PushGTestTrace(trace);
7076
}
7077
7078
// Pops the info pushed by the c'tor.
7079
ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
7080
UnitTest::GetInstance()->PopGTestTrace();
7081
}
7082
7083
} // namespace testing
7084
7085