49#include <initializer_list>
60#include <unordered_set>
82#elif defined(GTEST_OS_ZOS)
88#elif defined(GTEST_OS_WINDOWS_MOBILE)
93#elif defined(GTEST_OS_WINDOWS)
104#include <sys/timeb.h>
105#include <sys/types.h>
107#ifdef GTEST_OS_WINDOWS_MINGW
120#if GTEST_HAS_EXCEPTIONS
124#if GTEST_CAN_STREAM_RESULTS_
125#include <arpa/inet.h>
127#include <sys/socket.h>
128#include <sys/types.h>
133#ifdef GTEST_OS_WINDOWS
134#define vsnprintf _vsnprintf
139#include <crt_externs.h>
144#include "absl/container/flat_hash_set.h"
145#include "absl/debugging/failure_signal_handler.h"
146#include "absl/debugging/stacktrace.h"
147#include "absl/debugging/symbolize.h"
148#include "absl/flags/parse.h"
149#include "absl/flags/usage.h"
150#include "absl/strings/str_cat.h"
151#include "absl/strings/str_replace.h"
152#include "absl/strings/string_view.h"
153#include "absl/strings/strip.h"
158#if defined(__has_builtin)
159#define GTEST_HAS_BUILTIN(x) __has_builtin(x)
161#define GTEST_HAS_BUILTIN(x) 0
207#if GTEST_HAS_FILE_SYSTEM
209static FILE* OpenFileForWriting(
const std::string& output_file) {
210 FILE* fileout =
nullptr;
211 FilePath output_file_path(output_file);
212 FilePath output_dir(output_file_path.RemoveFileName());
214 if (output_dir.CreateDirectoriesRecursively()) {
217 if (fileout ==
nullptr) {
218 GTEST_LOG_(FATAL) <<
"Unable to open file \"" << output_file <<
"\"";
229 const char*
const testbridge_test_only =
231 if (testbridge_test_only !=
nullptr) {
232 return testbridge_test_only;
240 const char*
const testbridge_test_runner_fail_fast =
242 if (testbridge_test_runner_fail_fast !=
nullptr) {
243 return strcmp(testbridge_test_runner_fail_fast,
"1") == 0;
254 "True if and only if a test failure should stop further test execution.");
257 also_run_disabled_tests,
259 "Run disabled tests too, in addition to the tests normally being run.");
264 "True if and only if a failed assertion should be a debugger "
271 " should catch exceptions and treat them as test failures.");
275 "Whether to use colors in the output. Valid values: yes, no, "
276 "and auto. 'auto' means to use colors if the output is "
277 "being sent to a terminal and the TERM environment variable "
278 "is set to a terminal type that supports colors.");
284 "A colon-separated list of glob (not regex) patterns "
285 "for filtering the tests to run, optionally followed by a "
286 "'-' and a : separated list of negative patterns (tests to "
287 "exclude). A test is run if it matches one of the positive "
288 "patterns and does not match any of the negative patterns.");
291 install_failure_signal_handler,
294 "If true and supported on the current platform, " GTEST_NAME_
296 "install a signal handler that dumps debugging information when fatal "
297 "signals are raised.");
310 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
311 "optionally followed by a colon and an output file name or directory. "
312 "A directory is indicated by a trailing pathname separator. "
313 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
314 "If a directory is specified, output files will be created "
315 "within that directory, with file-names based on the test "
316 "executable's name and, if necessary, made unique by adding "
321 "True if only test failures should be displayed in text output.");
326 " should display elapsed time in text output.");
331 " prints UTF8 characters as text.");
335 "Random number seed to use when shuffling test orders. Must be in range "
336 "[1, 99999], or 0 to use a seed based on the current time.");
340 "How many times to repeat each test. Specify a negative number "
341 "for repeating forever. Useful for shaking out flaky tests.");
344 recreate_environments_when_repeating,
347 "Controls whether global test environments are recreated for each repeat "
348 "of the tests. If set to false the global test environments are only set "
349 "up once, for the first iteration, and only torn down once, for the last. "
350 "Useful for shaking out flaky tests with stable, expensive test "
351 "environments. If --gtest_repeat is set to a negative number, meaning "
352 "there is no last run, the environments will always be recreated to avoid "
357 " should include internal stack frames when "
358 "printing test failure stack traces.");
363 " should randomize tests' order on every run.");
369 "The maximum number of stack frames to print when an "
370 "assertion fails. The valid range is 0 through 100, inclusive.");
375 "This flag specifies the host name and the port number on which to stream "
376 "test results. Example: \"localhost:555\". The flag is effective only on "
382 "When this flag is specified, a failed assertion will throw an exception "
383 "if exceptions are enabled or exit the program with a non-zero code "
384 "otherwise. For use with an external test framework.");
386#if GTEST_USE_OWN_FLAGFILE_FLAG_
389 "This flag specifies the flagfile to read command-line flags from.");
403 state_ =
static_cast<uint32_t
>(1103515245ULL * state_ + 12345U) %
kMaxRange;
405 GTEST_CHECK_(range > 0) <<
"Cannot generate a number in the range [0, 0).";
407 <<
"Generation of a number in [0, " << range <<
") was requested, "
408 <<
"but this can only generate numbers in [0, " <<
kMaxRange <<
").";
413 return state_ % range;
427 for (
size_t i = 0;
i < case_list.size();
i++) {
428 sum += (case_list[
i]->*method)();
451 int line,
const char* message)
452 : data_(new AssertHelperData(type, file, line, message)) {}
459 data_->type, data_->file, data_->line,
460 AppendUserMessage(data_->message, message),
473constexpr bool kErrorOnUninstantiatedParameterizedTest =
true;
474constexpr bool kErrorOnUninstantiatedTypeParameterizedTest =
true;
477class FailureTest :
public Test {
479 explicit FailureTest(
const CodeLocation& loc, std::string error_message,
482 error_message_(
std::move(error_message)),
483 as_error_(as_error) {}
485 void TestBody()
override {
487 AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
488 loc_.line,
"") =
Message() << error_message_;
490 std::cout << error_message_ << std::endl;
495 const CodeLocation loc_;
496 const std::string error_message_;
497 const bool as_error_;
516 if (ignored.find(name) != ignored.end())
return;
518 const char kMissingInstantiation[] =
519 " is defined via TEST_P, but never instantiated. None of the test cases "
520 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
521 "ones provided expand to nothing."
523 "Ideally, TEST_P definitions should only ever be included as part of "
524 "binaries that intend to use them. (As opposed to, for example, being "
525 "placed in a library that may be linked in to get other utilities.)";
527 const char kMissingTestCase[] =
528 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
529 "defined via TEST_P . No test cases will run."
531 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
532 "code that always depend on code that provides TEST_P. Failing to do "
533 "so is often an indication of dead code, e.g. the last TEST_P was "
534 "removed but the rest got left behind.";
536 std::string message =
537 "Parameterized test suite " + name +
538 (has_test_p ? kMissingInstantiation : kMissingTestCase) +
540 "To suppress this error for this test suite, insert the following line "
541 "(in a non-header) in the namespace it is defined in:"
543 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
546 std::string full_name =
"UninstantiatedParameterizedTestSuite<" + name +
">";
548 "GoogleTestVerification", full_name.c_str(),
551 location.
file.c_str(), location.
line, [message, location] {
552 return new FailureTest(location, message,
553 kErrorOnUninstantiatedParameterizedTest);
560 test_suite_name, code_location);
569 const char* test_suite_name,
CodeLocation code_location) {
570 suites_.emplace(std::string(test_suite_name),
571 TypeParameterizedTestSuiteInfo(code_location));
575 const char* test_suite_name) {
576 auto it = suites_.find(std::string(test_suite_name));
577 if (it != suites_.end()) {
578 it->second.instantiated =
true;
580 GTEST_LOG_(ERROR) <<
"Unknown type parameterized test suit '"
581 << test_suite_name <<
"'";
587 for (
const auto& testcase : suites_) {
588 if (testcase.second.instantiated)
continue;
589 if (ignored.find(testcase.first) != ignored.end())
continue;
591 std::string message =
592 "Type parameterized test suite " + testcase.first +
593 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
594 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
596 "Ideally, TYPED_TEST_P definitions should only ever be included as "
597 "part of binaries that intend to use them. (As opposed to, for "
598 "example, being placed in a library that may be linked in to get other "
601 "To suppress this error for this test suite, insert the following line "
602 "(in a non-header) in the namespace it is defined in:"
604 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
605 testcase.first +
");";
607 std::string full_name =
608 "UninstantiatedTypeParameterizedTestSuite<" + testcase.first +
">";
610 "GoogleTestVerification", full_name.c_str(),
613 testcase.second.code_location.file.c_str(),
614 testcase.second.code_location.line, [message, testcase] {
615 return new FailureTest(testcase.second.code_location, message,
616 kErrorOnUninstantiatedTypeParameterizedTest);
625#if defined(GTEST_CUSTOM_GET_ARGVS_)
628 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
629 return ::std::vector<std::string>(custom.begin(), custom.end());
635#if GTEST_HAS_FILE_SYSTEM
638FilePath GetCurrentExecutableName() {
641#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2)
642 result.Set(FilePath(
GetArgvs()[0]).RemoveExtension(
"exe"));
644 result.Set(FilePath(
GetArgvs()[0]));
647 return result.RemoveDirectoryName();
656 const char*
const gtest_output_flag = s.c_str();
657 const char*
const colon = strchr(gtest_output_flag,
':');
658 return (colon ==
nullptr)
659 ? std::string(gtest_output_flag)
660 : std::string(gtest_output_flag,
661 static_cast<size_t>(colon - gtest_output_flag));
664#if GTEST_HAS_FILE_SYSTEM
669 const char*
const gtest_output_flag = s.c_str();
674 const char*
const colon = strchr(gtest_output_flag,
':');
675 if (colon ==
nullptr)
676 return internal::FilePath::MakeFileName(
682 internal::FilePath output_name(colon + 1);
683 if (!output_name.IsAbsolutePath())
684 output_name = internal::FilePath::ConcatPaths(
686 internal::FilePath(colon + 1));
688 if (!output_name.IsDirectory())
return output_name.string();
690 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
691 output_name, internal::GetCurrentExecutableName(),
693 return result.string();
704 const char* pattern,
const char* pattern_end) {
705 const char* name = name_str.c_str();
706 const char*
const name_begin = name;
707 const char*
const name_end = name + name_str.size();
709 const char* pattern_next = pattern;
710 const char* name_next = name;
712 while (pattern < pattern_end || name < name_end) {
713 if (pattern < pattern_end) {
716 if (name < name_end && *name == *pattern) {
723 if (name < name_end) {
733 pattern_next = pattern;
734 name_next = name + 1;
740 if (name_begin < name_next && name_next <= name_end) {
741 pattern = pattern_next;
752bool IsGlobPattern(
const std::string& pattern) {
753 return std::any_of(pattern.begin(), pattern.end(),
754 [](
const char c) { return c ==
'?' || c ==
'*'; });
757class UnitTestFilter {
759 UnitTestFilter() =
default;
762 explicit UnitTestFilter(
const std::string& filter) {
764 std::vector<std::string> all_patterns;
766 const auto exact_match_patterns_begin = std::partition(
767 all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
769 glob_patterns_.reserve(
static_cast<size_t>(
770 std::distance(all_patterns.begin(), exact_match_patterns_begin)));
771 std::move(all_patterns.begin(), exact_match_patterns_begin,
772 std::inserter(glob_patterns_, glob_patterns_.begin()));
774 exact_match_patterns_begin, all_patterns.end(),
775 std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));
780 bool MatchesName(
const std::string& name)
const {
781 return exact_match_patterns_.count(name) > 0 ||
782 std::any_of(glob_patterns_.begin(), glob_patterns_.end(),
783 [&name](
const std::string& pattern) {
784 return PatternMatchesString(
785 name, pattern.c_str(),
786 pattern.c_str() + pattern.size());
791 std::vector<std::string> glob_patterns_;
792 std::unordered_set<std::string> exact_match_patterns_;
795class PositiveAndNegativeUnitTestFilter {
802 explicit PositiveAndNegativeUnitTestFilter(
const std::string& filter) {
803 std::vector<std::string> positive_and_negative_filters;
806 SplitString(filter,
'-', &positive_and_negative_filters);
807 const auto& positive_filter = positive_and_negative_filters.front();
809 if (positive_and_negative_filters.size() > 1) {
810 positive_filter_ = UnitTestFilter(
816 auto negative_filter_string = positive_and_negative_filters[1];
817 for (std::size_t
i = 2;
i < positive_and_negative_filters.size();
i++)
818 negative_filter_string =
819 negative_filter_string +
'-' + positive_and_negative_filters[
i];
820 negative_filter_ = UnitTestFilter(negative_filter_string);
825 positive_filter_ = UnitTestFilter(positive_filter);
832 bool MatchesTest(
const std::string& test_suite_name,
833 const std::string& test_name)
const {
834 return MatchesName(test_suite_name +
"." + test_name);
839 bool MatchesName(
const std::string& name)
const {
840 return positive_filter_.MatchesName(name) &&
841 !negative_filter_.MatchesName(name);
845 UnitTestFilter positive_filter_;
846 UnitTestFilter negative_filter_;
851 const char* filter) {
852 return UnitTestFilter(filter).MatchesName(name_str);
858 const std::string& test_name) {
862 .MatchesTest(test_suite_name, test_name);
866static std::string FormatSehExceptionMessage(DWORD exception_code,
867 const char* location) {
869 message <<
"SEH exception with code 0x" << std::setbase(16) << exception_code
870 << std::setbase(10) <<
" thrown in " << location <<
".";
871 return message.GetString();
874int UnitTestOptions::GTestProcessSEH(DWORD seh_code,
const char* location) {
883 const DWORD kCxxExceptionCode = 0xe06d7363;
885 if (!
GTEST_FLAG_GET(catch_exceptions) || seh_code == kCxxExceptionCode ||
886 seh_code == EXCEPTION_BREAKPOINT ||
887 seh_code == EXCEPTION_STACK_OVERFLOW) {
888 return EXCEPTION_CONTINUE_SEARCH;
892 TestPartResult::kFatalFailure,
893 FormatSehExceptionMessage(seh_code, location) +
898 return EXCEPTION_EXECUTE_HANDLER;
907ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
908 TestPartResultArray* result)
909 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
916ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
917 InterceptMode intercept_mode, TestPartResultArray* result)
918 : intercept_mode_(intercept_mode), result_(result) {
922void ScopedFakeTestPartResultReporter::Init() {
924 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
925 old_reporter_ = impl->GetGlobalTestPartResultReporter();
926 impl->SetGlobalTestPartResultReporter(
this);
928 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
929 impl->SetTestPartResultReporterForCurrentThread(
this);
935ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
937 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
938 impl->SetGlobalTestPartResultReporter(old_reporter_);
940 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
946void ScopedFakeTestPartResultReporter::ReportTestPartResult(
947 const TestPartResult& result) {
948 result_->Append(result);
962TypeId GetTestTypeId() {
return GetTypeId<Test>(); }
966extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
974 const TestPartResultArray& results,
975 TestPartResult::Type type,
976 const std::string& substr) {
977 const std::string expected(type == TestPartResult::kFatalFailure
979 :
"1 non-fatal failure");
981 if (results.size() != 1) {
982 msg <<
"Expected: " << expected <<
"\n"
983 <<
" Actual: " << results.size() <<
" failures";
984 for (
int i = 0;
i < results.size();
i++) {
985 msg <<
"\n" << results.GetTestPartResult(
i);
987 return AssertionFailure() << msg;
990 const TestPartResult& r = results.GetTestPartResult(0);
991 if (r.type() != type) {
992 return AssertionFailure() <<
"Expected: " << expected <<
"\n"
997 if (strstr(r.message(), substr.c_str()) ==
nullptr) {
998 return AssertionFailure()
999 <<
"Expected: " << expected <<
" containing \"" << substr <<
"\"\n"
1004 return AssertionSuccess();
1010SingleFailureChecker::SingleFailureChecker(
const TestPartResultArray* results,
1011 TestPartResult::Type type,
1012 const std::string& substr)
1013 : results_(results), type_(type), substr_(substr) {}
1019SingleFailureChecker::~SingleFailureChecker() {
1023DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
1025 : unit_test_(unit_test) {}
1028 const TestPartResult& result) {
1035 : unit_test_(unit_test) {}
1038 const TestPartResult& result) {
1043TestPartResultReporterInterface*
1046 return global_test_part_result_reporter_;
1051 TestPartResultReporterInterface* reporter) {
1053 global_test_part_result_reporter_ = reporter;
1057TestPartResultReporterInterface*
1059 return per_thread_test_part_result_reporter_.
get();
1064 TestPartResultReporterInterface* reporter) {
1065 per_thread_test_part_result_reporter_.
set(reporter);
1080 return static_cast<int>(test_suites_.size());
1142 static_cast<int>(
GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1
1155 return std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() -
1163#if defined(_NEWLIB_VERSION) && !defined(CLOCK_MONOTONIC)
1164 using clock = std::chrono::system_clock;
1166 using clock = std::chrono::steady_clock;
1168 clock::time_point start_;
1175 return std::chrono::duration_cast<std::chrono::milliseconds>(
1176 std::chrono::system_clock::now() -
1177 std::chrono::system_clock::from_time_t(0))
1185#ifdef GTEST_OS_WINDOWS_MOBILE
1190LPCWSTR String::AnsiToUtf16(
const char* ansi) {
1191 if (!ansi)
return nullptr;
1192 const int length = strlen(ansi);
1193 const int unicode_length =
1194 MultiByteToWideChar(CP_ACP, 0, ansi, length,
nullptr, 0);
1195 WCHAR* unicode =
new WCHAR[unicode_length + 1];
1196 MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
1197 unicode[unicode_length] = 0;
1205const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
1206 if (!utf16_str)
return nullptr;
1207 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
nullptr,
1208 0,
nullptr,
nullptr);
1209 char* ansi =
new char[ansi_length + 1];
1210 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length,
nullptr,
1212 ansi[ansi_length] = 0;
1225 if (lhs ==
nullptr)
return rhs ==
nullptr;
1227 if (rhs ==
nullptr)
return false;
1229 return strcmp(lhs, rhs) == 0;
1232#if GTEST_HAS_STD_WSTRING
1236static void StreamWideCharsToMessage(
const wchar_t* wstr,
size_t length,
1238 for (
size_t i = 0;
i != length;) {
1239 if (wstr[
i] != L
'\0') {
1240 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length -
i));
1241 while (
i != length && wstr[
i] != L
'\0')
i++;
1252 ::std::vector< ::std::string>* dest) {
1253 ::std::vector< ::std::string> parsed;
1254 ::std::string::size_type pos = 0;
1256 const ::std::string::size_type colon = str.find(delimiter, pos);
1257 if (colon == ::std::string::npos) {
1258 parsed.push_back(str.substr(pos));
1261 parsed.push_back(str.substr(pos, colon - pos));
1278 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
1290#if GTEST_HAS_STD_WSTRING
1294 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
1307namespace edit_distance {
1309 const std::vector<size_t>& right) {
1310 std::vector<std::vector<double> > costs(
1311 left.size() + 1, std::vector<double>(right.size() + 1));
1312 std::vector<std::vector<EditType> > best_move(
1313 left.size() + 1, std::vector<EditType>(right.size() + 1));
1316 for (
size_t l_i = 0; l_i < costs.size(); ++l_i) {
1317 costs[l_i][0] =
static_cast<double>(l_i);
1321 for (
size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1322 costs[0][r_i] =
static_cast<double>(r_i);
1323 best_move[0][r_i] =
kAdd;
1326 for (
size_t l_i = 0; l_i < left.size(); ++l_i) {
1327 for (
size_t r_i = 0; r_i < right.size(); ++r_i) {
1328 if (left[l_i] == right[r_i]) {
1330 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1331 best_move[l_i + 1][r_i + 1] =
kMatch;
1335 const double add = costs[l_i + 1][r_i];
1336 const double remove = costs[l_i][r_i + 1];
1337 const double replace = costs[l_i][r_i];
1338 if (add < remove && add < replace) {
1339 costs[l_i + 1][r_i + 1] = add + 1;
1340 best_move[l_i + 1][r_i + 1] =
kAdd;
1341 }
else if (remove < add && remove < replace) {
1342 costs[l_i + 1][r_i + 1] = remove + 1;
1343 best_move[l_i + 1][r_i + 1] =
kRemove;
1347 costs[l_i + 1][r_i + 1] = replace + 1.00001;
1348 best_move[l_i + 1][r_i + 1] =
kReplace;
1354 std::vector<EditType> best_path;
1355 for (
size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1356 EditType move = best_move[l_i][r_i];
1357 best_path.push_back(move);
1358 l_i -= move !=
kAdd;
1361 std::reverse(best_path.begin(), best_path.end());
1368class InternalStrings {
1370 size_t GetId(
const std::string& str) {
1371 IdMap::iterator it = ids_.find(str);
1372 if (it != ids_.end())
return it->second;
1373 size_t id = ids_.size();
1374 return ids_[str] = id;
1378 typedef std::map<std::string, size_t> IdMap;
1385 const std::vector<std::string>& left,
1386 const std::vector<std::string>& right) {
1387 std::vector<size_t> left_ids, right_ids;
1389 InternalStrings intern_table;
1390 for (
size_t i = 0;
i < left.size(); ++
i) {
1391 left_ids.push_back(intern_table.GetId(left[
i]));
1393 for (
size_t i = 0;
i < right.size(); ++
i) {
1394 right_ids.push_back(intern_table.GetId(right[
i]));
1408 Hunk(
size_t left_start,
size_t right_start)
1409 : left_start_(left_start),
1410 right_start_(right_start),
1415 void PushLine(
char edit,
const char* line) {
1420 hunk_.push_back(std::make_pair(
' ', line));
1424 hunk_removes_.push_back(std::make_pair(
'-', line));
1428 hunk_adds_.push_back(std::make_pair(
'+', line));
1433 void PrintTo(std::ostream* os) {
1436 for (std::list<std::pair<char, const char*> >::const_iterator it =
1438 it != hunk_.end(); ++it) {
1439 *os << it->first << it->second <<
"\n";
1443 bool has_edits()
const {
return adds_ || removes_; }
1447 hunk_.splice(hunk_.end(), hunk_removes_);
1448 hunk_.splice(hunk_.end(), hunk_adds_);
1455 void PrintHeader(std::ostream* ss)
const {
1458 *ss <<
"-" << left_start_ <<
"," << (removes_ + common_);
1460 if (removes_ && adds_) {
1464 *ss <<
"+" << right_start_ <<
"," << (adds_ + common_);
1469 size_t left_start_, right_start_;
1470 size_t adds_, removes_, common_;
1471 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1484 const std::vector<std::string>& right,
1488 size_t l_i = 0, r_i = 0, edit_i = 0;
1489 std::stringstream ss;
1490 while (edit_i < edits.size()) {
1492 while (edit_i < edits.size() && edits[edit_i] ==
kMatch) {
1499 const size_t prefix_context = std::min(l_i, context);
1500 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1501 for (
size_t i = prefix_context;
i > 0; --
i) {
1502 hunk.PushLine(
' ', left[l_i -
i].c_str());
1507 size_t n_suffix = 0;
1508 for (; edit_i < edits.size(); ++edit_i) {
1509 if (n_suffix >= context) {
1511 auto it = edits.begin() +
static_cast<int>(edit_i);
1512 while (it != edits.end() && *it ==
kMatch) ++it;
1513 if (it == edits.end() ||
1514 static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
1522 n_suffix = edit ==
kMatch ? n_suffix + 1 : 0;
1525 hunk.PushLine(edit ==
kMatch ?
' ' :
'-', left[l_i].c_str());
1528 hunk.PushLine(
'+', right[r_i].c_str());
1532 l_i += edit !=
kAdd;
1536 if (!hunk.has_edits()) {
1553std::vector<std::string> SplitEscapedString(
const std::string& str) {
1554 std::vector<std::string> lines;
1555 size_t start = 0, end = str.size();
1556 if (end > 2 && str[0] ==
'"' && str[end - 1] ==
'"') {
1560 bool escaped =
false;
1561 for (
size_t i = start;
i + 1 < end; ++
i) {
1564 if (str[
i] ==
'n') {
1565 lines.push_back(str.substr(start,
i - start - 1));
1569 escaped = str[
i] ==
'\\';
1572 lines.push_back(str.substr(start, end - start));
1594 const char* rhs_expression,
1595 const std::string& lhs_value,
1596 const std::string& rhs_value,
bool ignoring_case) {
1598 msg <<
"Expected equality of these values:";
1599 msg <<
"\n " << lhs_expression;
1600 if (lhs_value != lhs_expression) {
1601 msg <<
"\n Which is: " << lhs_value;
1603 msg <<
"\n " << rhs_expression;
1604 if (rhs_value != rhs_expression) {
1605 msg <<
"\n Which is: " << rhs_value;
1608 if (ignoring_case) {
1609 msg <<
"\nIgnoring case";
1612 if (!lhs_value.empty() && !rhs_value.empty()) {
1613 const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
1614 const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
1615 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1616 msg <<
"\nWith diff:\n"
1626 const AssertionResult& assertion_result,
const char* expression_text,
1627 const char* actual_predicate_value,
const char* expected_predicate_value) {
1628 const char* actual_message = assertion_result.message();
1630 msg <<
"Value of: " << expression_text
1631 <<
"\n Actual: " << actual_predicate_value;
1632 if (actual_message[0] !=
'\0') msg <<
" (" << actual_message <<
")";
1633 msg <<
"\nExpected: " << expected_predicate_value;
1639 const char* abs_error_expr,
double val1,
1640 double val2,
double abs_error) {
1641 const double diff = fabs(val1 - val2);
1645 const double min_abs = std::min(fabs(val1), fabs(val2));
1647 const double epsilon =
1648 nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
1655 if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
1656 abs_error < epsilon) {
1658 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1659 << diff <<
", where\n"
1660 << expr1 <<
" evaluates to " << val1 <<
",\n"
1661 << expr2 <<
" evaluates to " << val2 <<
".\nThe abs_error parameter "
1662 << abs_error_expr <<
" evaluates to " << abs_error
1663 <<
" which is smaller than the minimum distance between doubles for "
1664 "numbers of this magnitude which is "
1666 <<
", thus making this EXPECT_NEAR check equivalent to "
1667 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
1670 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1671 << diff <<
", which exceeds " << abs_error_expr <<
", where\n"
1672 << expr1 <<
" evaluates to " << val1 <<
",\n"
1673 << expr2 <<
" evaluates to " << val2 <<
", and\n"
1674 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
1678template <
typename RawType>
1680 RawType val1, RawType val2) {
1688 if (lhs.AlmostEquals(rhs)) {
1696 ::std::stringstream val1_ss;
1697 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1700 ::std::stringstream val2_ss;
1701 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1705 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n"
1714AssertionResult
FloatLE(
const char* expr1,
const char* expr2,
float val1,
1721AssertionResult
DoubleLE(
const char* expr1,
const char* expr2,
double val1,
1730 const char* rhs_expression,
const char* lhs,
1742 const char* rhs_expression,
const char* lhs,
1754 const char* s2_expression,
const char* s1,
1760 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
1761 <<
"), actual: \"" << s1 <<
"\" vs \"" << s2 <<
"\"";
1767 const char* s2_expression,
const char* s1,
1773 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
1774 <<
") (ignoring case), actual: \"" << s1 <<
"\" vs \"" << s2 <<
"\"";
1788bool IsSubstringPred(
const char* needle,
const char* haystack) {
1789 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1791 return strstr(haystack, needle) !=
nullptr;
1794bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
1795 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1797 return wcsstr(haystack, needle) !=
nullptr;
1801template <
typename StringType>
1802bool IsSubstringPred(
const StringType& needle,
const StringType& haystack) {
1803 return haystack.find(needle) != StringType::npos;
1810template <
typename StringType>
1811AssertionResult IsSubstringImpl(
bool expected_to_be_substring,
1812 const char* needle_expr,
1813 const char* haystack_expr,
1814 const StringType& needle,
1815 const StringType& haystack) {
1816 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1819 const bool is_wide_string =
sizeof(needle[0]) > 1;
1820 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
1822 <<
"Value of: " << needle_expr <<
"\n"
1823 <<
" Actual: " << begin_string_quote << needle <<
"\"\n"
1824 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
1825 <<
"a substring of " << haystack_expr <<
"\n"
1826 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
1835AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1836 const char* needle,
const char* haystack) {
1837 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1840AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1841 const wchar_t* needle,
const wchar_t* haystack) {
1842 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1846 const char* haystack_expr,
const char* needle,
1847 const char* haystack) {
1848 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1852 const char* haystack_expr,
const wchar_t* needle,
1853 const wchar_t* haystack) {
1854 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1857AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1858 const ::std::string& needle,
1859 const ::std::string& haystack) {
1860 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1864 const char* haystack_expr,
1865 const ::std::string& needle,
1866 const ::std::string& haystack) {
1867 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1870#if GTEST_HAS_STD_WSTRING
1871AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1872 const ::std::wstring& needle,
1873 const ::std::wstring& haystack) {
1874 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1878 const char* haystack_expr,
1879 const ::std::wstring& needle,
1880 const ::std::wstring& haystack) {
1881 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1887#ifdef GTEST_OS_WINDOWS
1892AssertionResult HRESULTFailureHelper(
const char* expr,
const char* expected,
1894#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_TV_TITLE)
1897 const char error_text[] =
"";
1904 const DWORD kFlags =
1905 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1906 const DWORD kBufSize = 4096;
1908 char error_text[kBufSize] = {
'\0'};
1909 DWORD message_length = ::FormatMessageA(kFlags,
1911 static_cast<DWORD
>(hr),
1917 for (; message_length &&
IsSpace(error_text[message_length - 1]);
1919 error_text[message_length - 1] =
'\0';
1925 return ::testing::AssertionFailure()
1926 <<
"Expected: " << expr <<
" " << expected <<
".\n"
1927 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
1932AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
1933 if (SUCCEEDED(hr)) {
1936 return HRESULTFailureHelper(expr,
"succeeds", hr);
1939AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
1943 return HRESULTFailureHelper(expr,
"fails", hr);
1968 (
static_cast<uint32_t
>(1) << (4 + 2 * 6)) - 1;
1972 (
static_cast<uint32_t
>(1) << (3 + 3 * 6)) - 1;
1978 const uint32_t low_bits = *bits & ((
static_cast<uint32_t
>(1) << n) - 1);
1997 str[0] =
static_cast<char>(code_point);
2000 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2001 str[0] =
static_cast<char>(0xC0 | code_point);
2004 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2005 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2006 str[0] =
static_cast<char>(0xE0 | code_point);
2009 str[3] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2010 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2011 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2012 str[0] =
static_cast<char>(0xF0 | code_point);
2025 return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
2026 (second & 0xFC00) == 0xDC00;
2032 const auto first_u =
static_cast<uint32_t
>(first);
2033 const auto second_u =
static_cast<uint32_t
>(second);
2034 const uint32_t mask = (1 << 10) - 1;
2035 return (
sizeof(
wchar_t) == 2)
2036 ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
2057 if (num_chars == -1) num_chars =
static_cast<int>(wcslen(str));
2059 ::std::stringstream stream;
2060 for (
int i = 0;
i < num_chars; ++
i) {
2061 uint32_t unicode_code_point;
2063 if (str[
i] == L
'\0') {
2066 unicode_code_point =
2070 unicode_code_point =
static_cast<uint32_t
>(str[
i]);
2081 if (wide_c_str ==
nullptr)
return "(null)";
2093 if (lhs ==
nullptr)
return rhs ==
nullptr;
2095 if (rhs ==
nullptr)
return false;
2097 return wcscmp(lhs, rhs) == 0;
2102 const char* rhs_expression,
const wchar_t* lhs,
2103 const wchar_t* rhs) {
2114 const char* s2_expression,
const wchar_t* s1,
2115 const wchar_t* s2) {
2121 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
2132 if (lhs ==
nullptr)
return rhs ==
nullptr;
2133 if (rhs ==
nullptr)
return false;
2150 const wchar_t* rhs) {
2151 if (lhs ==
nullptr)
return rhs ==
nullptr;
2153 if (rhs ==
nullptr)
return false;
2155#ifdef GTEST_OS_WINDOWS
2156 return _wcsicmp(lhs, rhs) == 0;
2157#elif defined(GTEST_OS_LINUX) && !defined(GTEST_OS_LINUX_ANDROID)
2158 return wcscasecmp(lhs, rhs) == 0;
2164 left = towlower(
static_cast<wint_t
>(*lhs++));
2165 right = towlower(
static_cast<wint_t
>(*rhs++));
2166 }
while (left && left == right);
2167 return left == right;
2174 const std::string& suffix) {
2175 const size_t str_len = str.length();
2176 const size_t suffix_len = suffix.length();
2177 return (str_len >= suffix_len) &&
2189 std::stringstream ss;
2190 ss << std::setfill(
'0') << std::setw(width) <<
value;
2196 std::stringstream ss;
2197 ss << std::hex << std::uppercase <<
value;
2208 std::stringstream ss;
2209 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
2210 <<
static_cast<unsigned int>(
value);
2217 const ::std::string& str = ss->str();
2218 const char*
const start = str.c_str();
2219 const char*
const end = start + str.length();
2222 result.reserve(
static_cast<size_t>(2 * (end - start)));
2223 for (
const char*
ch = start;
ch != end; ++
ch) {
2238 const std::string user_msg_string = user_msg.
GetString();
2239 if (user_msg_string.empty()) {
2242 if (gtest_msg.empty()) {
2243 return user_msg_string;
2245 return gtest_msg +
"\n" + user_msg_string;
2254 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2264 return test_part_results_.at(
static_cast<size_t>(
i));
2272 return test_properties_.at(
static_cast<size_t>(
i));
2276void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
2279void TestResult::AddTestPartResult(
const TestPartResult& test_part_result) {
2280 test_part_results_.push_back(test_part_result);
2286void TestResult::RecordProperty(
const std::string& xml_element,
2287 const TestProperty& test_property) {
2288 if (!ValidateTestProperty(xml_element, test_property)) {
2292 const std::vector<TestProperty>::iterator property_with_matching_key =
2293 std::find_if(test_properties_.begin(), test_properties_.end(),
2294 internal::TestPropertyKeyIs(test_property.key()));
2295 if (property_with_matching_key == test_properties_.end()) {
2296 test_properties_.push_back(test_property);
2299 property_with_matching_key->SetValue(test_property.value());
2305 "disabled",
"errors",
"failures",
"name",
2306 "random_seed",
"tests",
"time",
"timestamp"};
2311 "disabled",
"errors",
"failures",
"name",
2312 "tests",
"time",
"timestamp",
"skipped"};
2316 "classname",
"name",
"status",
"time",
2317 "type_param",
"value_param",
"file",
"line"};
2322 "classname",
"name",
"status",
"time",
"type_param",
2323 "value_param",
"file",
"line",
"result",
"timestamp"};
2325template <
size_t kSize>
2327 return std::vector<std::string>(array, array + kSize);
2331 const std::string& xml_element) {
2332 if (xml_element ==
"testsuites") {
2334 }
else if (xml_element ==
"testsuite") {
2336 }
else if (xml_element ==
"testcase") {
2339 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2342 return std::vector<std::string>();
2345#if GTEST_HAS_FILE_SYSTEM
2348static std::vector<std::string> GetReservedOutputAttributesForElement(
2349 const std::string& xml_element) {
2350 if (xml_element ==
"testsuites") {
2352 }
else if (xml_element ==
"testsuite") {
2354 }
else if (xml_element ==
"testcase") {
2357 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2360 return std::vector<std::string>();
2366 for (
size_t i = 0;
i < words.size(); ++
i) {
2367 if (
i > 0 && words.size() > 2) {
2370 if (
i == words.size() - 1) {
2371 word_list <<
"and ";
2373 word_list <<
"'" << words[
i] <<
"'";
2379 const std::string& property_name,
2380 const std::vector<std::string>& reserved_names) {
2381 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2382 reserved_names.end()) {
2383 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
2393bool TestResult::ValidateTestProperty(
const std::string& xml_element,
2394 const TestProperty& test_property) {
2400void TestResult::Clear() {
2401 test_part_results_.clear();
2402 test_properties_.clear();
2403 death_test_count_ = 0;
2409 return result.skipped();
2427 return result.fatally_failed();
2437 return result.nonfatally_failed();
2448 return static_cast<int>(test_part_results_.size());
2453 return static_cast<int>(test_properties_.size());
2486 const std::string& message) {
2504bool Test::HasSameFixtureClass() {
2506 const TestSuite*
const test_suite = impl->current_test_suite();
2509 const TestInfo*
const first_test_info = test_suite->test_info_list()[0];
2510 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2511 const char*
const first_test_name = first_test_info->name();
2514 const TestInfo*
const this_test_info = impl->current_test_info();
2515 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2516 const char*
const this_test_name = this_test_info->name();
2518 if (this_fixture_id != first_fixture_id) {
2524 if (first_is_TEST || this_is_TEST) {
2531 const char*
const TEST_name =
2532 first_is_TEST ? first_test_name : this_test_name;
2533 const char*
const TEST_F_name =
2534 first_is_TEST ? this_test_name : first_test_name;
2537 <<
"All tests in the same test suite must use the same test fixture\n"
2538 <<
"class, so mixing TEST_F and TEST in the same test suite is\n"
2539 <<
"illegal. In test suite " << this_test_info->test_suite_name()
2541 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n"
2542 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n"
2543 <<
"want to change the TEST to TEST_F or move it to another test\n"
2549 <<
"All tests in the same test suite must use the same test fixture\n"
2550 <<
"class. However, in test suite "
2551 << this_test_info->test_suite_name() <<
",\n"
2552 <<
"you defined test " << first_test_name <<
" and test "
2553 << this_test_name <<
"\n"
2554 <<
"using two different test fixture classes. This can happen if\n"
2555 <<
"the two classes are from different namespaces or translation\n"
2556 <<
"units and have the same name. You should probably rename one\n"
2557 <<
"of the classes to put the tests into different test suites.";
2567#if GTEST_HAS_EXCEPTIONS
2570static std::string FormatCxxExceptionMessage(
const char* description,
2571 const char* location) {
2573 if (description !=
nullptr) {
2574 message <<
"C++ exception with description \"" << description <<
"\"";
2576 message <<
"Unknown C++ exception";
2578 message <<
" thrown in " << location <<
".";
2584 const TestPartResult& test_part_result);
2586GoogleTestFailureException::GoogleTestFailureException(
2587 const TestPartResult& failure)
2600template <
class T,
typename Result>
2602 const char* location) {
2605 return (object->*method)();
2606 } __except (internal::UnitTestOptions::GTestProcessSEH(
2607 GetExceptionCode(), location)) {
2608 return static_cast<Result
>(0);
2612 return (object->*method)();
2619template <
class T,
typename Result>
2621 const char* location) {
2646#if GTEST_HAS_EXCEPTIONS
2649 }
catch (
const AssertionException&) {
2651 }
catch (
const internal::GoogleTestFailureException&) {
2656 }
catch (
const std::exception& e) {
2658 TestPartResult::kFatalFailure,
2659 FormatCxxExceptionMessage(e.what(), location));
2662 TestPartResult::kFatalFailure,
2663 FormatCxxExceptionMessage(
nullptr, location));
2665 return static_cast<Result
>(0);
2670 return (object->*method)();
2678 if (!HasSameFixtureClass())
return;
2680 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2681 impl->os_stack_trace_getter()->UponLeavingGTest();
2682 internal::HandleExceptionsInMethodIfSupported(
this, &Test::SetUp,
"SetUp()");
2685 if (!HasFatalFailure() && !IsSkipped()) {
2686 impl->os_stack_trace_getter()->UponLeavingGTest();
2687 internal::HandleExceptionsInMethodIfSupported(
this, &Test::TestBody,
2694 impl->os_stack_trace_getter()->UponLeavingGTest();
2695 internal::HandleExceptionsInMethodIfSupported(
this, &Test::TearDown,
2700bool Test::HasFatalFailure() {
2701 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2705bool Test::HasNonfatalFailure() {
2706 return internal::GetUnitTestImpl()
2707 ->current_test_result()
2708 ->HasNonfatalFailure();
2712bool Test::IsSkipped() {
2713 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
2720TestInfo::TestInfo(
const std::string& a_test_suite_name,
2721 const std::string& a_name,
const char* a_type_param,
2722 const char* a_value_param,
2726 : test_suite_name_(a_test_suite_name),
2728 name_(a_name.begin(), a_name.end()),
2729 type_param_(a_type_param ? new
std::string(a_type_param) : nullptr),
2730 value_param_(a_value_param ? new
std::string(a_value_param) : nullptr),
2731 location_(a_code_location),
2732 fixture_class_id_(fixture_class_id),
2734 is_disabled_(false),
2735 matches_filter_(false),
2736 is_in_another_shard_(false),
2764 const char* test_suite_name,
const char* name,
const char* type_param,
2769 new TestInfo(test_suite_name, name, type_param, value_param,
2770 code_location, fixture_class_id, factory);
2779 <<
"Attempted redefinition of test suite " << test_suite_name <<
".\n"
2780 <<
"All tests in the same test suite must use the same test fixture\n"
2781 <<
"class. However, in test suite " << test_suite_name <<
", you tried\n"
2782 <<
"to define a test using a fixture class different from the one\n"
2783 <<
"used earlier. This can happen if the two fixture classes are\n"
2784 <<
"from different namespaces and have the same name. You should\n"
2785 <<
"probably rename one of the classes to put the tests into different\n"
2797 if (!parameterized_tests_registered_) {
2800 parameterized_tests_registered_ =
true;
2808void TestInfo::Run() {
2811 if (is_disabled_ && matches_filter_) repeater->
OnTestDisabled(*
this);
2817 impl->set_current_test_info(
this);
2822 internal::Timer timer;
2823 impl->os_stack_trace_getter()->UponLeavingGTest();
2828 "the test fixture's constructor");
2839 if (test !=
nullptr) {
2841 impl->os_stack_trace_getter()->UponLeavingGTest();
2843 test, &Test::DeleteSelf_,
"the test fixture's destructor");
2846 result_.set_elapsed_time(timer.Elapsed());
2853 impl->set_current_test_info(
nullptr);
2857void TestInfo::Skip() {
2858 if (!should_run_)
return;
2861 impl->set_current_test_info(
this);
2868 const TestPartResult test_part_result =
2869 TestPartResult(TestPartResult::kSkip, this->
file(), this->
line(),
"");
2870 impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
2874 repeater->OnTestEnd(*
this);
2875 impl->set_current_test_info(
nullptr);
2882 return CountIf(test_info_list_, TestPassed);
2887 return CountIf(test_info_list_, TestSkipped);
2892 return CountIf(test_info_list_, TestFailed);
2897 return CountIf(test_info_list_, TestReportableDisabled);
2902 return CountIf(test_info_list_, TestDisabled);
2907 return CountIf(test_info_list_, TestReportable);
2912 return CountIf(test_info_list_, ShouldRunTest);
2917 return static_cast<int>(test_info_list_.size());
2933 type_param_(a_type_param ? new
std::string(a_type_param) : nullptr),
2934 set_up_tc_(set_up_tc),
2935 tear_down_tc_(tear_down_tc),
2937 start_timestamp_(0),
2949 const int index = GetElementOr(test_indices_,
i, -1);
2950 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2955TestInfo* TestSuite::GetMutableTestInfo(
int i) {
2956 const int index = GetElementOr(test_indices_,
i, -1);
2957 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2962void TestSuite::AddTestInfo(TestInfo* test_info) {
2963 test_info_list_.push_back(test_info);
2964 test_indices_.push_back(
static_cast<int>(test_indices_.size()));
2968void TestSuite::Run() {
2969 if (!should_run_)
return;
2972 impl->set_current_test_suite(
this);
2986 std::stable_sort(test_info_list_.begin(), test_info_list_.end(),
2987 [](
const TestInfo*
const a,
const TestInfo*
const b) {
2988 if (const int result = std::strcmp(a->file(), b->file())) {
2992 return a->line() < b->line();
2998#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2999 repeater->OnTestCaseStart(*
this);
3002 impl->os_stack_trace_getter()->UponLeavingGTest();
3004 this, &TestSuite::RunSetUpTestSuite,
"SetUpTestSuite()");
3006 const bool skip_all =
3007 ad_hoc_test_result().Failed() || ad_hoc_test_result().Skipped();
3010 internal::Timer timer;
3011 for (
int i = 0;
i < total_test_count();
i++) {
3013 GetMutableTestInfo(
i)->Skip();
3015 GetMutableTestInfo(
i)->Run();
3018 GetMutableTestInfo(
i)->result()->Failed()) {
3019 for (
int j =
i + 1; j < total_test_count(); j++) {
3020 GetMutableTestInfo(j)->Skip();
3025 elapsed_time_ = timer.Elapsed();
3027 impl->os_stack_trace_getter()->UponLeavingGTest();
3029 this, &TestSuite::RunTearDownTestSuite,
"TearDownTestSuite()");
3032 repeater->OnTestSuiteEnd(*
this);
3034#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3035 repeater->OnTestCaseEnd(*
this);
3038 impl->set_current_test_suite(
nullptr);
3042void TestSuite::Skip() {
3043 if (!should_run_)
return;
3045 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
3046 impl->set_current_test_suite(
this);
3048 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3051 repeater->OnTestSuiteStart(*
this);
3053#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3054 repeater->OnTestCaseStart(*
this);
3057 for (
int i = 0;
i < total_test_count();
i++) {
3058 GetMutableTestInfo(
i)->Skip();
3062 repeater->OnTestSuiteEnd(*
this);
3064#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3065 repeater->OnTestCaseEnd(*
this);
3068 impl->set_current_test_suite(
nullptr);
3072void TestSuite::ClearResult() {
3073 ad_hoc_test_result_.Clear();
3074 ForEach(test_info_list_, TestInfo::ClearTestResult);
3078void TestSuite::ShuffleTests(internal::Random* random) {
3079 Shuffle(random, &test_indices_);
3083void TestSuite::UnshuffleTests() {
3084 for (
size_t i = 0;
i < test_indices_.size();
i++) {
3085 test_indices_[
i] =
static_cast<int>(
i);
3095 const char* plural_form) {
3096 return internal::StreamableToString(
count) +
" " +
3097 (
count == 1 ? singular_form : plural_form);
3116 case TestPartResult::kSkip:
3118 case TestPartResult::kSuccess:
3121 case TestPartResult::kNonFatalFailure:
3122 case TestPartResult::kFatalFailure:
3129 return "Unknown result type";
3135enum class GTestColor { kDefault, kRed, kGreen, kYellow };
3140 const TestPartResult& test_part_result) {
3141 return (
Message() << internal::FormatFileLocation(
3142 test_part_result.file_name(),
3143 test_part_result.line_number())
3146 << test_part_result.message())
3153 printf(
"%s\n", result.c_str());
3159#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE)
3163 ::OutputDebugStringA(result.c_str());
3164 ::OutputDebugStringA(
"\n");
3169#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
3170 !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \
3171 !defined(GTEST_OS_WINDOWS_MINGW)
3174static WORD GetColorAttribute(GTestColor color) {
3176 case GTestColor::kRed:
3177 return FOREGROUND_RED;
3178 case GTestColor::kGreen:
3179 return FOREGROUND_GREEN;
3180 case GTestColor::kYellow:
3181 return FOREGROUND_RED | FOREGROUND_GREEN;
3187static int GetBitOffset(WORD color_mask) {
3188 if (color_mask == 0)
return 0;
3191 while ((color_mask & 1) == 0) {
3198static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
3200 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
3201 BACKGROUND_RED | BACKGROUND_INTENSITY;
3202 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
3203 FOREGROUND_RED | FOREGROUND_INTENSITY;
3204 const WORD existing_bg = old_color_attrs & background_mask;
3207 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
3208 static const int bg_bitOffset = GetBitOffset(background_mask);
3209 static const int fg_bitOffset = GetBitOffset(foreground_mask);
3211 if (((new_color & background_mask) >> bg_bitOffset) ==
3212 ((new_color & foreground_mask) >> fg_bitOffset)) {
3213 new_color ^= FOREGROUND_INTENSITY;
3224 case GTestColor::kRed:
3226 case GTestColor::kGreen:
3228 case GTestColor::kYellow:
3238bool ShouldUseColor(
bool stdout_is_tty) {
3240 const char*
const gtest_color = c.c_str();
3242 if (String::CaseInsensitiveCStringEquals(gtest_color,
"auto")) {
3243#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
3246 return stdout_is_tty;
3250 const bool term_supports_color =
3251 term !=
nullptr && (String::CStringEquals(term,
"xterm") ||
3252 String::CStringEquals(term,
"xterm-color") ||
3253 String::CStringEquals(term,
"xterm-kitty") ||
3254 String::CStringEquals(term,
"screen") ||
3255 String::CStringEquals(term,
"tmux") ||
3256 String::CStringEquals(term,
"rxvt-unicode") ||
3257 String::CStringEquals(term,
"linux") ||
3258 String::CStringEquals(term,
"cygwin") ||
3259 String::EndsWithCaseInsensitive(term,
"-256color"));
3260 return stdout_is_tty && term_supports_color;
3264 return String::CaseInsensitiveCStringEquals(gtest_color,
"yes") ||
3265 String::CaseInsensitiveCStringEquals(gtest_color,
"true") ||
3266 String::CaseInsensitiveCStringEquals(gtest_color,
"t") ||
3267 String::CStringEquals(gtest_color,
"1");
3279static
void ColoredPrintf(GTestColor color, const
char* fmt, ...) {
3281 va_start(args, fmt);
3283 static const bool in_color_mode =
3284#if GTEST_HAS_FILE_SYSTEM
3290 const bool use_color = in_color_mode && (color != GTestColor::kDefault);
3298#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
3299 !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \
3300 !defined(GTEST_OS_WINDOWS_MINGW)
3301 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3304 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3305 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3306 const WORD old_color_attrs = buffer_info.wAttributes;
3307 const WORD new_color = GetNewColor(color, old_color_attrs);
3313 SetConsoleTextAttribute(stdout_handle, new_color);
3319 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3334 const char*
const type_param = test_info.
type_param();
3335 const char*
const value_param = test_info.
value_param();
3337 if (type_param !=
nullptr || value_param !=
nullptr) {
3339 if (type_param !=
nullptr) {
3341 if (value_param !=
nullptr) printf(
" and ");
3343 if (value_param !=
nullptr) {
3356 printf(
"%s.%s", test_suite, test);
3361 void OnTestIterationStart(
const UnitTest& unit_test,
int iteration)
override;
3362 void OnEnvironmentsSetUpStart(
const UnitTest& unit_test)
override;
3364#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3365 void OnTestCaseStart(
const TestCase& test_case)
override;
3367 void OnTestSuiteStart(
const TestSuite& test_suite)
override;
3370 void OnTestStart(
const TestInfo& test_info)
override;
3371 void OnTestDisabled(
const TestInfo& test_info)
override;
3373 void OnTestPartResult(
const TestPartResult& result)
override;
3374 void OnTestEnd(
const TestInfo& test_info)
override;
3375#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3376 void OnTestCaseEnd(
const TestCase& test_case)
override;
3378 void OnTestSuiteEnd(
const TestSuite& test_suite)
override;
3381 void OnEnvironmentsTearDownStart(
const UnitTest& unit_test)
override;
3383 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3387 static void PrintFailedTests(
const UnitTest& unit_test);
3388 static void PrintFailedTestSuites(
const UnitTest& unit_test);
3389 static void PrintSkippedTests(
const UnitTest& unit_test);
3393void PrettyUnitTestResultPrinter::OnTestIterationStart(
3394 const UnitTest& unit_test,
int iteration) {
3396 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3399 const char*
const filter = f.c_str();
3410 ColoredPrintf(GTestColor::kYellow,
"Note: This is test shard %d of %s.\n",
3411 static_cast<int>(shard_index) + 1,
3417 "Note: Randomizing tests' orders with a seed of %d .\n",
3422 printf(
"Running %s from %s.\n",
3428void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3431 printf(
"Global test environment set-up.\n");
3435#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3436void PrettyUnitTestResultPrinter::OnTestCaseStart(
const TestCase& test_case) {
3437 const std::string counts =
3440 printf(
"%s from %s", counts.c_str(), test_case.
name());
3449void PrettyUnitTestResultPrinter::OnTestSuiteStart(
3451 const std::string counts =
3454 printf(
"%s from %s", counts.c_str(), test_suite.
name());
3458 printf(
", where %s = %s\n", kTypeParamLabel, test_suite.
type_param());
3464void PrettyUnitTestResultPrinter::OnTestStart(
const TestInfo& test_info) {
3471void PrettyUnitTestResultPrinter::OnTestDisabled(
const TestInfo& test_info) {
3479void PrettyUnitTestResultPrinter::OnTestPartResult(
3480 const TestPartResult& result) {
3481 switch (result.type()) {
3483 case TestPartResult::kSuccess:
3493void PrettyUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
3505 printf(
" (%s ms)\n",
3514#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3515void PrettyUnitTestResultPrinter::OnTestCaseEnd(
const TestCase& test_case) {
3518 const std::string counts =
3521 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_case.
name(),
3522 internal::StreamableToString(test_case.
elapsed_time()).c_str());
3526void PrettyUnitTestResultPrinter::OnTestSuiteEnd(
const TestSuite& test_suite) {
3529 const std::string counts =
3532 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.
name(),
3533 internal::StreamableToString(test_suite.
elapsed_time()).c_str());
3538void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3541 printf(
"Global test environment tear-down\n");
3546void PrettyUnitTestResultPrinter::PrintFailedTests(
const UnitTest& unit_test) {
3549 printf(
"%s, listed below:\n",
FormatTestCount(failed_test_count).c_str());
3561 ColoredPrintf(GTestColor::kRed,
"[ FAILED ] ");
3562 printf(
"%s.%s", test_suite.
name(), test_info.
name());
3563 PrintFullTestCommentIfPresent(test_info);
3567 printf(
"\n%2d FAILED %s\n", failed_test_count,
3568 failed_test_count == 1 ?
"TEST" :
"TESTS");
3573void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
3574 const UnitTest& unit_test) {
3575 int suite_failure_count = 0;
3576 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
3577 const TestSuite& test_suite = *unit_test.GetTestSuite(
i);
3578 if (!test_suite.should_run()) {
3581 if (test_suite.ad_hoc_test_result().Failed()) {
3583 printf(
"%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
3584 ++suite_failure_count;
3587 if (suite_failure_count > 0) {
3588 printf(
"\n%2d FAILED TEST %s\n", suite_failure_count,
3589 suite_failure_count == 1 ?
"SUITE" :
"SUITES");
3594void PrettyUnitTestResultPrinter::PrintSkippedTests(
const UnitTest& unit_test) {
3595 const int skipped_test_count = unit_test.skipped_test_count();
3596 if (skipped_test_count == 0) {
3600 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
3601 const TestSuite& test_suite = *unit_test.GetTestSuite(
i);
3602 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
3605 for (
int j = 0; j < test_suite.total_test_count(); ++j) {
3606 const TestInfo& test_info = *test_suite.GetTestInfo(j);
3607 if (!test_info.should_run() || !test_info.result()->Skipped()) {
3611 printf(
"%s.%s", test_suite.name(), test_info.name());
3617void PrettyUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
3620 printf(
"%s from %s ran.",
3624 printf(
" (%s ms total)",
3625 internal::StreamableToString(unit_test.
elapsed_time()).c_str());
3632 if (skipped_test_count > 0) {
3634 printf(
"%s, listed below:\n",
FormatTestCount(skipped_test_count).c_str());
3635 PrintSkippedTests(unit_test);
3638 if (!unit_test.
Passed()) {
3639 PrintFailedTests(unit_test);
3640 PrintFailedTestSuites(unit_test);
3645 if (unit_test.
Passed()) {
3648 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3649 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3664 printf(
"%s.%s", test_suite, test);
3673#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3676 void OnTestSuiteStart(
const TestSuite& )
override {}
3682 void OnTestPartResult(
const TestPartResult& result)
override;
3683 void OnTestEnd(
const TestInfo& test_info)
override;
3684#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3687 void OnTestSuiteEnd(
const TestSuite& )
override {}
3692 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3697void BriefUnitTestResultPrinter::OnTestPartResult(
3698 const TestPartResult& result) {
3699 switch (result.type()) {
3701 case TestPartResult::kSuccess:
3711void BriefUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
3718 printf(
" (%s ms)\n",
3728void BriefUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
3731 printf(
"%s from %s ran.",
3735 printf(
" (%s ms total)",
3736 internal::StreamableToString(unit_test.
elapsed_time()).c_str());
3743 if (skipped_test_count > 0) {
3750 if (unit_test.
Passed()) {
3753 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3754 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3778 void OnTestIterationStart(
const UnitTest& unit_test,
int iteration)
override;
3782#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3791#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3797 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3803 bool forwarding_enabled_;
3805 std::vector<TestEventListener*> listeners_;
3811TestEventRepeater::~TestEventRepeater() {
3812 ForEach(listeners_, Delete<TestEventListener>);
3816 listeners_.push_back(listener);
3820 for (
size_t i = 0;
i < listeners_.size(); ++
i) {
3821 if (listeners_[
i] == listener) {
3822 listeners_.erase(listeners_.begin() +
static_cast<int>(
i));
3832#define GTEST_REPEATER_METHOD_(Name, Type) \
3833 void TestEventRepeater::Name(const Type& parameter) { \
3834 if (forwarding_enabled_) { \
3835 for (size_t i = 0; i < listeners_.size(); i++) { \
3836 listeners_[i]->Name(parameter); \
3842#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3843 void TestEventRepeater::Name(const Type& parameter) { \
3844 if (forwarding_enabled_) { \
3845 for (size_t i = listeners_.size(); i != 0; i--) { \
3846 listeners_[i - 1]->Name(parameter); \
3854#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3866#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3872#undef GTEST_REPEATER_METHOD_
3873#undef GTEST_REVERSE_REPEATER_METHOD_
3875void TestEventRepeater::OnTestIterationStart(
const UnitTest& unit_test,
3877 if (forwarding_enabled_) {
3878 for (
size_t i = 0;
i < listeners_.size();
i++) {
3884void TestEventRepeater::OnTestIterationEnd(
const UnitTest& unit_test,
3886 if (forwarding_enabled_) {
3887 for (
size_t i = listeners_.size();
i > 0;
i--) {
3888 listeners_[
i - 1]->OnTestIterationEnd(unit_test, iteration);
3895#if GTEST_HAS_FILE_SYSTEM
3899 explicit XmlUnitTestResultPrinter(
const char* output_file);
3901 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3902 void ListTestsMatchingFilter(
const std::vector<TestSuite*>& test_suites);
3905 static void PrintXmlTestsList(std::ostream* stream,
3906 const std::vector<TestSuite*>& test_suites);
3911 static bool IsNormalizableWhitespace(
unsigned char c) {
3912 return c ==
'\t' || c ==
'\n' || c ==
'\r';
3917 static bool IsValidXmlCharacter(
unsigned char c) {
3918 return IsNormalizableWhitespace(c) || c >= 0x20;
3925 static std::string EscapeXml(
const std::string& str,
bool is_attribute);
3928 static std::string RemoveInvalidXmlCharacters(
const std::string& str);
3931 static std::string EscapeXmlAttribute(
const std::string& str) {
3932 return EscapeXml(str,
true);
3936 static std::string EscapeXmlText(
const char* str) {
3937 return EscapeXml(str,
false);
3942 static void OutputXmlAttribute(std::ostream* stream,
3943 const std::string& element_name,
3944 const std::string& name,
3945 const std::string&
value);
3948 static void OutputXmlCDataSection(::std::ostream* stream,
const char* data);
3953 static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
3954 const TestResult& result);
3957 static void OutputXmlTestResult(::std::ostream* stream,
3958 const TestResult& result);
3961 static void OutputXmlTestInfo(::std::ostream* stream,
3962 const char* test_suite_name,
3963 const TestInfo& test_info);
3966 static void PrintXmlTestSuite(::std::ostream* stream,
3967 const TestSuite& test_suite);
3970 static void PrintXmlUnitTest(::std::ostream* stream,
3971 const UnitTest& unit_test);
3977 static std::string TestPropertiesAsXmlAttributes(
const TestResult& result);
3981 static void OutputXmlTestProperties(std::ostream* stream,
3982 const TestResult& result);
3985 const std::string output_file_;
3987 XmlUnitTestResultPrinter(
const XmlUnitTestResultPrinter&) =
delete;
3988 XmlUnitTestResultPrinter& operator=(
const XmlUnitTestResultPrinter&) =
delete;
3992XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(
const char* output_file)
3993 : output_file_(output_file) {
3994 if (output_file_.empty()) {
3995 GTEST_LOG_(FATAL) <<
"XML output file may not be null";
4000void XmlUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4002 FILE* xmlout = OpenFileForWriting(output_file_);
4003 std::stringstream stream;
4004 PrintXmlUnitTest(&stream, unit_test);
4009void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
4010 const std::vector<TestSuite*>& test_suites) {
4011 FILE* xmlout = OpenFileForWriting(output_file_);
4012 std::stringstream stream;
4013 PrintXmlTestsList(&stream, test_suites);
4028std::string XmlUnitTestResultPrinter::EscapeXml(
const std::string& str,
4029 bool is_attribute) {
4032 for (
size_t i = 0;
i < str.size(); ++
i) {
4033 const char ch = str[
i];
4057 if (IsValidXmlCharacter(
static_cast<unsigned char>(
ch))) {
4059 IsNormalizableWhitespace(
static_cast<unsigned char>(
ch)))
4069 return m.GetString();
4075std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4076 const std::string& str) {
4078 output.reserve(str.size());
4079 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4080 if (IsValidXmlCharacter(
static_cast<unsigned char>(*it)))
4104 ::std::stringstream ss;
4109 << std::setprecision(
4110 ms % 1000 == 0 ? 0 : (ms % 100 == 0 ? 1 : (ms % 10 == 0 ? 2 : 3)))
4112 ss << (static_cast<double>(ms) * 1e-3);
4116static bool PortableLocaltime(time_t seconds,
struct tm* out) {
4117#if defined(_MSC_VER)
4118 return localtime_s(out, &seconds) == 0;
4119#elif defined(__MINGW32__) || defined(__MINGW64__)
4122 struct tm* tm_ptr = localtime(&seconds);
4123 if (tm_ptr ==
nullptr)
return false;
4126#elif defined(__STDC_LIB_EXT1__)
4129 return localtime_s(&seconds, out) !=
nullptr;
4131 return localtime_r(&seconds, out) !=
nullptr;
4138 struct tm time_struct;
4139 if (!PortableLocaltime(
static_cast<time_t
>(ms / 1000), &time_struct))
4152void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4154 const char* segment = data;
4155 *stream <<
"<![CDATA[";
4157 const char*
const next_segment = strstr(segment,
"]]>");
4158 if (next_segment !=
nullptr) {
4159 stream->write(segment,
4160 static_cast<std::streamsize
>(next_segment - segment));
4161 *stream <<
"]]>]]><![CDATA[";
4162 segment = next_segment + strlen(
"]]>");
4171void XmlUnitTestResultPrinter::OutputXmlAttribute(
4172 std::ostream* stream,
const std::string& element_name,
4173 const std::string& name,
const std::string&
value) {
4174 const std::vector<std::string>& allowed_names =
4175 GetReservedOutputAttributesForElement(element_name);
4177 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4178 allowed_names.end())
4179 <<
"Attribute " << name <<
" is not allowed for element <" << element_name
4182 *stream <<
" " << name <<
"=\"" << EscapeXmlAttribute(
value) <<
"\"";
4186void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
4187 ::std::ostream* stream,
const TestResult& result) {
4189 *stream <<
" <testsuite";
4190 OutputXmlAttribute(stream,
"testsuite",
"name",
"NonTestSuiteFailure");
4191 OutputXmlAttribute(stream,
"testsuite",
"tests",
"1");
4192 OutputXmlAttribute(stream,
"testsuite",
"failures",
"1");
4193 OutputXmlAttribute(stream,
"testsuite",
"disabled",
"0");
4194 OutputXmlAttribute(stream,
"testsuite",
"skipped",
"0");
4195 OutputXmlAttribute(stream,
"testsuite",
"errors",
"0");
4196 OutputXmlAttribute(stream,
"testsuite",
"time",
4199 stream,
"testsuite",
"timestamp",
4204 *stream <<
" <testcase";
4205 OutputXmlAttribute(stream,
"testcase",
"name",
"");
4206 OutputXmlAttribute(stream,
"testcase",
"status",
"run");
4207 OutputXmlAttribute(stream,
"testcase",
"result",
"completed");
4208 OutputXmlAttribute(stream,
"testcase",
"classname",
"");
4209 OutputXmlAttribute(stream,
"testcase",
"time",
4212 stream,
"testcase",
"timestamp",
4216 OutputXmlTestResult(stream, result);
4219 *stream <<
" </testsuite>\n";
4223void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4224 const char* test_suite_name,
4225 const TestInfo& test_info) {
4226 const TestResult& result = *test_info.result();
4227 const std::string kTestsuite =
"testcase";
4229 if (test_info.is_in_another_shard()) {
4233 *stream <<
" <testcase";
4234 OutputXmlAttribute(stream, kTestsuite,
"name", test_info.name());
4236 if (test_info.value_param() !=
nullptr) {
4237 OutputXmlAttribute(stream, kTestsuite,
"value_param",
4238 test_info.value_param());
4240 if (test_info.type_param() !=
nullptr) {
4241 OutputXmlAttribute(stream, kTestsuite,
"type_param",
4242 test_info.type_param());
4245 OutputXmlAttribute(stream, kTestsuite,
"file", test_info.file());
4246 OutputXmlAttribute(stream, kTestsuite,
"line",
4253 OutputXmlAttribute(stream, kTestsuite,
"status",
4254 test_info.should_run() ?
"run" :
"notrun");
4255 OutputXmlAttribute(stream, kTestsuite,
"result",
4256 test_info.should_run()
4257 ? (result.Skipped() ?
"skipped" :
"completed")
4259 OutputXmlAttribute(stream, kTestsuite,
"time",
4262 stream, kTestsuite,
"timestamp",
4264 OutputXmlAttribute(stream, kTestsuite,
"classname", test_suite_name);
4266 OutputXmlTestResult(stream, result);
4269void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
4270 const TestResult& result) {
4273 for (
int i = 0;
i < result.total_part_count(); ++
i) {
4274 const TestPartResult& part = result.GetTestPartResult(
i);
4275 if (part.failed()) {
4276 if (++failures == 1 && skips == 0) {
4279 const std::string location =
4281 part.line_number());
4282 const std::string summary = location +
"\n" + part.summary();
4283 *stream <<
" <failure message=\"" << EscapeXmlAttribute(summary)
4285 const std::string detail = location +
"\n" + part.message();
4286 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4287 *stream <<
"</failure>\n";
4288 }
else if (part.skipped()) {
4289 if (++skips == 1 && failures == 0) {
4292 const std::string location =
4294 part.line_number());
4295 const std::string summary = location +
"\n" + part.summary();
4296 *stream <<
" <skipped message=\""
4297 << EscapeXmlAttribute(summary.c_str()) <<
"\">";
4298 const std::string detail = location +
"\n" + part.message();
4299 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4300 *stream <<
"</skipped>\n";
4304 if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
4307 if (failures == 0 && skips == 0) {
4310 OutputXmlTestProperties(stream, result);
4311 *stream <<
" </testcase>\n";
4316void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
4317 const TestSuite& test_suite) {
4318 const std::string kTestsuite =
"testsuite";
4319 *stream <<
" <" << kTestsuite;
4320 OutputXmlAttribute(stream, kTestsuite,
"name", test_suite.name());
4321 OutputXmlAttribute(stream, kTestsuite,
"tests",
4324 OutputXmlAttribute(stream, kTestsuite,
"failures",
4327 stream, kTestsuite,
"disabled",
4329 OutputXmlAttribute(stream, kTestsuite,
"skipped",
4332 OutputXmlAttribute(stream, kTestsuite,
"errors",
"0");
4334 OutputXmlAttribute(stream, kTestsuite,
"time",
4337 stream, kTestsuite,
"timestamp",
4339 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
4342 for (
int i = 0;
i < test_suite.total_test_count(); ++
i) {
4343 if (test_suite.GetTestInfo(
i)->is_reportable())
4344 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(
i));
4346 *stream <<
" </" << kTestsuite <<
">\n";
4350void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4351 const UnitTest& unit_test) {
4352 const std::string kTestsuites =
"testsuites";
4354 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4355 *stream <<
"<" << kTestsuites;
4357 OutputXmlAttribute(stream, kTestsuites,
"tests",
4359 OutputXmlAttribute(stream, kTestsuites,
"failures",
4362 stream, kTestsuites,
"disabled",
4364 OutputXmlAttribute(stream, kTestsuites,
"errors",
"0");
4365 OutputXmlAttribute(stream, kTestsuites,
"time",
4368 stream, kTestsuites,
"timestamp",
4372 OutputXmlAttribute(stream, kTestsuites,
"random_seed",
4375 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4377 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
4380 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
4381 if (unit_test.GetTestSuite(
i)->reportable_test_count() > 0)
4382 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(
i));
4387 if (unit_test.ad_hoc_test_result().Failed()) {
4388 OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4391 *stream <<
"</" << kTestsuites <<
">\n";
4394void XmlUnitTestResultPrinter::PrintXmlTestsList(
4395 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
4396 const std::string kTestsuites =
"testsuites";
4398 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4399 *stream <<
"<" << kTestsuites;
4401 int total_tests = 0;
4402 for (
auto test_suite : test_suites) {
4403 total_tests += test_suite->total_test_count();
4405 OutputXmlAttribute(stream, kTestsuites,
"tests",
4407 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
4410 for (
auto test_suite : test_suites) {
4411 PrintXmlTestSuite(stream, *test_suite);
4413 *stream <<
"</" << kTestsuites <<
">\n";
4418std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4419 const TestResult& result) {
4421 for (
int i = 0;
i < result.test_property_count(); ++
i) {
4422 const TestProperty&
property = result.GetTestProperty(
i);
4423 attributes <<
" " <<
property.key() <<
"="
4424 <<
"\"" << EscapeXmlAttribute(property.value()) <<
"\"";
4426 return attributes.GetString();
4429void XmlUnitTestResultPrinter::OutputXmlTestProperties(
4430 std::ostream* stream,
const TestResult& result) {
4431 const std::string kProperties =
"properties";
4432 const std::string kProperty =
"property";
4434 if (result.test_property_count() <= 0) {
4438 *stream <<
" <" << kProperties <<
">\n";
4439 for (
int i = 0;
i < result.test_property_count(); ++
i) {
4440 const TestProperty&
property = result.GetTestProperty(
i);
4441 *stream <<
" <" << kProperty;
4442 *stream <<
" name=\"" << EscapeXmlAttribute(property.key()) <<
"\"";
4443 *stream <<
" value=\"" << EscapeXmlAttribute(property.value()) <<
"\"";
4446 *stream <<
" </" << kProperties <<
">\n";
4452#if GTEST_HAS_FILE_SYSTEM
4454class JsonUnitTestResultPrinter :
public EmptyTestEventListener {
4456 explicit JsonUnitTestResultPrinter(
const char* output_file);
4458 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
4461 static void PrintJsonTestList(::std::ostream* stream,
4462 const std::vector<TestSuite*>& test_suites);
4466 static std::string EscapeJson(
const std::string& str);
4470 static void OutputJsonKey(std::ostream* stream,
4471 const std::string& element_name,
4472 const std::string& name,
const std::string&
value,
4473 const std::string& indent,
bool comma =
true);
4474 static void OutputJsonKey(std::ostream* stream,
4475 const std::string& element_name,
4476 const std::string& name,
int value,
4477 const std::string& indent,
bool comma =
true);
4482 static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
4483 const TestResult& result);
4486 static void OutputJsonTestResult(::std::ostream* stream,
4487 const TestResult& result);
4490 static void OutputJsonTestInfo(::std::ostream* stream,
4491 const char* test_suite_name,
4492 const TestInfo& test_info);
4495 static void PrintJsonTestSuite(::std::ostream* stream,
4496 const TestSuite& test_suite);
4499 static void PrintJsonUnitTest(::std::ostream* stream,
4500 const UnitTest& unit_test);
4504 static std::string TestPropertiesAsJson(
const TestResult& result,
4505 const std::string& indent);
4508 const std::string output_file_;
4510 JsonUnitTestResultPrinter(
const JsonUnitTestResultPrinter&) =
delete;
4511 JsonUnitTestResultPrinter& operator=(
const JsonUnitTestResultPrinter&) =
4516JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(
const char* output_file)
4517 : output_file_(output_file) {
4518 if (output_file_.empty()) {
4519 GTEST_LOG_(FATAL) <<
"JSON output file may not be null";
4523void JsonUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4525 FILE* jsonout = OpenFileForWriting(output_file_);
4526 std::stringstream stream;
4527 PrintJsonUnitTest(&stream, unit_test);
4533std::string JsonUnitTestResultPrinter::EscapeJson(
const std::string& str) {
4536 for (
size_t i = 0;
i < str.size(); ++
i) {
4537 const char ch = str[
i];
4569 return m.GetString();
4576static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
4577 ::std::stringstream ss;
4578 ss << (static_cast<double>(ms) * 1e-3) <<
"s";
4584static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
4585 struct tm time_struct;
4586 if (!PortableLocaltime(
static_cast<time_t
>(ms / 1000), &time_struct))
4597static inline std::string Indent(
size_t width) {
4598 return std::string(width,
' ');
4601void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
4602 const std::string& element_name,
4603 const std::string& name,
4604 const std::string&
value,
4605 const std::string& indent,
4607 const std::vector<std::string>& allowed_names =
4608 GetReservedOutputAttributesForElement(element_name);
4610 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4611 allowed_names.end())
4612 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
4615 *stream << indent <<
"\"" << name <<
"\": \"" << EscapeJson(
value) <<
"\"";
4616 if (comma) *stream <<
",\n";
4619void JsonUnitTestResultPrinter::OutputJsonKey(
4620 std::ostream* stream,
const std::string& element_name,
4621 const std::string& name,
int value,
const std::string& indent,
bool comma) {
4622 const std::vector<std::string>& allowed_names =
4623 GetReservedOutputAttributesForElement(element_name);
4625 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4626 allowed_names.end())
4627 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
4631 if (comma) *stream <<
",\n";
4635void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
4636 ::std::ostream* stream,
const TestResult& result) {
4638 *stream << Indent(4) <<
"{\n";
4639 OutputJsonKey(stream,
"testsuite",
"name",
"NonTestSuiteFailure", Indent(6));
4640 OutputJsonKey(stream,
"testsuite",
"tests", 1, Indent(6));
4642 OutputJsonKey(stream,
"testsuite",
"failures", 1, Indent(6));
4643 OutputJsonKey(stream,
"testsuite",
"disabled", 0, Indent(6));
4644 OutputJsonKey(stream,
"testsuite",
"skipped", 0, Indent(6));
4645 OutputJsonKey(stream,
"testsuite",
"errors", 0, Indent(6));
4646 OutputJsonKey(stream,
"testsuite",
"time",
4647 FormatTimeInMillisAsDuration(result.elapsed_time()),
4649 OutputJsonKey(stream,
"testsuite",
"timestamp",
4650 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4653 *stream << Indent(6) <<
"\"testsuite\": [\n";
4656 *stream << Indent(8) <<
"{\n";
4657 OutputJsonKey(stream,
"testcase",
"name",
"", Indent(10));
4658 OutputJsonKey(stream,
"testcase",
"status",
"RUN", Indent(10));
4659 OutputJsonKey(stream,
"testcase",
"result",
"COMPLETED", Indent(10));
4660 OutputJsonKey(stream,
"testcase",
"timestamp",
4661 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4663 OutputJsonKey(stream,
"testcase",
"time",
4664 FormatTimeInMillisAsDuration(result.elapsed_time()),
4666 OutputJsonKey(stream,
"testcase",
"classname",
"", Indent(10),
false);
4667 *stream << TestPropertiesAsJson(result, Indent(10));
4670 OutputJsonTestResult(stream, result);
4673 *stream <<
"\n" << Indent(6) <<
"]\n" << Indent(4) <<
"}";
4677void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4678 const char* test_suite_name,
4679 const TestInfo& test_info) {
4680 const TestResult& result = *test_info.result();
4681 const std::string kTestsuite =
"testcase";
4682 const std::string kIndent = Indent(10);
4684 *stream << Indent(8) <<
"{\n";
4685 OutputJsonKey(stream, kTestsuite,
"name", test_info.name(), kIndent);
4687 if (test_info.value_param() !=
nullptr) {
4688 OutputJsonKey(stream, kTestsuite,
"value_param", test_info.value_param(),
4691 if (test_info.type_param() !=
nullptr) {
4692 OutputJsonKey(stream, kTestsuite,
"type_param", test_info.type_param(),
4696 OutputJsonKey(stream, kTestsuite,
"file", test_info.file(), kIndent);
4697 OutputJsonKey(stream, kTestsuite,
"line", test_info.line(), kIndent,
false);
4699 *stream <<
"\n" << Indent(8) <<
"}";
4705 OutputJsonKey(stream, kTestsuite,
"status",
4706 test_info.should_run() ?
"RUN" :
"NOTRUN", kIndent);
4707 OutputJsonKey(stream, kTestsuite,
"result",
4708 test_info.should_run()
4709 ? (result.Skipped() ?
"SKIPPED" :
"COMPLETED")
4712 OutputJsonKey(stream, kTestsuite,
"timestamp",
4713 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4715 OutputJsonKey(stream, kTestsuite,
"time",
4716 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
4717 OutputJsonKey(stream, kTestsuite,
"classname", test_suite_name, kIndent,
4719 *stream << TestPropertiesAsJson(result, kIndent);
4721 OutputJsonTestResult(stream, result);
4724void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
4725 const TestResult& result) {
4726 const std::string kIndent = Indent(10);
4729 for (
int i = 0;
i < result.total_part_count(); ++
i) {
4730 const TestPartResult& part = result.GetTestPartResult(
i);
4731 if (part.failed()) {
4733 if (++failures == 1) {
4734 *stream << kIndent <<
"\""
4738 const std::string location =
4740 part.line_number());
4741 const std::string
message = EscapeJson(location +
"\n" + part.message());
4742 *stream << kIndent <<
" {\n"
4743 << kIndent <<
" \"failure\": \"" <<
message <<
"\",\n"
4744 << kIndent <<
" \"type\": \"\"\n"
4749 if (failures > 0) *stream <<
"\n" << kIndent <<
"]";
4750 *stream <<
"\n" << Indent(8) <<
"}";
4754void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4755 std::ostream* stream,
const TestSuite& test_suite) {
4756 const std::string kTestsuite =
"testsuite";
4757 const std::string kIndent = Indent(6);
4759 *stream << Indent(4) <<
"{\n";
4760 OutputJsonKey(stream, kTestsuite,
"name", test_suite.name(), kIndent);
4761 OutputJsonKey(stream, kTestsuite,
"tests", test_suite.reportable_test_count(),
4764 OutputJsonKey(stream, kTestsuite,
"failures",
4765 test_suite.failed_test_count(), kIndent);
4766 OutputJsonKey(stream, kTestsuite,
"disabled",
4767 test_suite.reportable_disabled_test_count(), kIndent);
4768 OutputJsonKey(stream, kTestsuite,
"errors", 0, kIndent);
4770 stream, kTestsuite,
"timestamp",
4771 FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
4773 OutputJsonKey(stream, kTestsuite,
"time",
4774 FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
4776 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
4780 *stream << kIndent <<
"\"" << kTestsuite <<
"\": [\n";
4783 for (
int i = 0;
i < test_suite.total_test_count(); ++
i) {
4784 if (test_suite.GetTestInfo(
i)->is_reportable()) {
4790 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(
i));
4793 *stream <<
"\n" << kIndent <<
"]\n" << Indent(4) <<
"}";
4797void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4798 const UnitTest& unit_test) {
4799 const std::string kTestsuites =
"testsuites";
4800 const std::string kIndent = Indent(2);
4803 OutputJsonKey(stream, kTestsuites,
"tests", unit_test.reportable_test_count(),
4805 OutputJsonKey(stream, kTestsuites,
"failures", unit_test.failed_test_count(),
4807 OutputJsonKey(stream, kTestsuites,
"disabled",
4808 unit_test.reportable_disabled_test_count(), kIndent);
4809 OutputJsonKey(stream, kTestsuites,
"errors", 0, kIndent);
4811 OutputJsonKey(stream, kTestsuites,
"random_seed", unit_test.random_seed(),
4814 OutputJsonKey(stream, kTestsuites,
"timestamp",
4815 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
4817 OutputJsonKey(stream, kTestsuites,
"time",
4818 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
4821 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4824 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
4825 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4828 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
4829 if (unit_test.GetTestSuite(
i)->reportable_test_count() > 0) {
4835 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(
i));
4841 if (unit_test.ad_hoc_test_result().Failed()) {
4845 OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4853void JsonUnitTestResultPrinter::PrintJsonTestList(
4854 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
4855 const std::string kTestsuites =
"testsuites";
4856 const std::string kIndent = Indent(2);
4858 int total_tests = 0;
4859 for (
auto test_suite : test_suites) {
4860 total_tests += test_suite->total_test_count();
4862 OutputJsonKey(stream, kTestsuites,
"tests", total_tests, kIndent);
4864 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
4865 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4867 for (
size_t i = 0;
i < test_suites.size(); ++
i) {
4871 PrintJsonTestSuite(stream, *test_suites[
i]);
4880std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4881 const TestResult& result,
const std::string& indent) {
4883 for (
int i = 0;
i < result.test_property_count(); ++
i) {
4884 const TestProperty&
property = result.GetTestProperty(
i);
4886 << indent <<
"\"" <<
property.key() <<
"\": "
4887 <<
"\"" << EscapeJson(property.value()) <<
"\"";
4889 return attributes.GetString();
4895#if GTEST_CAN_STREAM_RESULTS_
4902std::string StreamingListener::UrlEncode(
const char* str) {
4904 result.reserve(strlen(str) + 1);
4905 for (
char ch = *str;
ch !=
'\0';
ch = *++str) {
4911 result.push_back(
'%');
4915 result.push_back(
ch);
4922void StreamingListener::SocketWriter::MakeConnection() {
4924 <<
"MakeConnection() can't be called when there is already a connection.";
4927 memset(&hints, 0,
sizeof(hints));
4928 hints.ai_family = AF_UNSPEC;
4929 hints.ai_socktype = SOCK_STREAM;
4930 addrinfo* servinfo =
nullptr;
4934 const int error_num =
4935 getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4936 if (error_num != 0) {
4937 GTEST_LOG_(WARNING) <<
"stream_result_to: getaddrinfo() failed: "
4938 << gai_strerror(error_num);
4942 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr !=
nullptr;
4943 cur_addr = cur_addr->ai_next) {
4944 sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
4945 cur_addr->ai_protocol);
4946 if (sockfd_ != -1) {
4948 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4955 freeaddrinfo(servinfo);
4957 if (sockfd_ == -1) {
4958 GTEST_LOG_(WARNING) <<
"stream_result_to: failed to connect to "
4959 << host_name_ <<
":" << port_num_;
4973#ifdef GTEST_HAS_ABSL
4976 if (max_depth <= 0) {
4980 max_depth = std::min(max_depth, kMaxStackTraceDepth);
4982 std::vector<void*> raw_stack(max_depth);
4984 const int raw_stack_size =
4985 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
4987 void* caller_frame =
nullptr;
4990 caller_frame = caller_frame_;
4993 for (
int i = 0;
i < raw_stack_size; ++
i) {
4994 if (raw_stack[
i] == caller_frame &&
4997 absl::StrAppend(&result, kElidedFramesMarker,
"\n");
5002 const char* symbol =
"(unknown)";
5003 if (absl::Symbolize(raw_stack[
i], tmp,
sizeof(tmp))) {
5008 snprintf(line,
sizeof(line),
" %p: %s\n", raw_stack[
i], symbol);
5015 static_cast<void>(max_depth);
5016 static_cast<void>(skip_count);
5022#ifdef GTEST_HAS_ABSL
5023 void* caller_frame =
nullptr;
5024 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5025 caller_frame =
nullptr;
5029 caller_frame_ = caller_frame;
5033#ifdef GTEST_HAS_DEATH_TEST
5036class ScopedPrematureExitFile {
5038 explicit ScopedPrematureExitFile(
const char* premature_exit_filepath)
5039 : premature_exit_filepath_(
5040 premature_exit_filepath ? premature_exit_filepath :
"") {
5042 if (!premature_exit_filepath_.empty()) {
5046 FILE* pfile =
posix::FOpen(premature_exit_filepath_.c_str(),
"w");
5047 fwrite(
"0", 1, 1, pfile);
5052 ~ScopedPrematureExitFile() {
5053#ifndef GTEST_OS_ESP8266
5054 if (!premature_exit_filepath_.empty()) {
5055 int retval = remove(premature_exit_filepath_.c_str());
5057 GTEST_LOG_(ERROR) <<
"Failed to remove premature exit filepath \""
5058 << premature_exit_filepath_ <<
"\" with error "
5066 const std::string premature_exit_filepath_;
5068 ScopedPrematureExitFile(
const ScopedPrematureExitFile&) =
delete;
5069 ScopedPrematureExitFile& operator=(
const ScopedPrematureExitFile&) =
delete;
5078 : repeater_(new internal::TestEventRepeater()),
5079 default_result_printer_(nullptr),
5080 default_xml_generator_(nullptr) {}
5089 repeater_->
Append(listener);
5096 if (listener == default_result_printer_)
5097 default_result_printer_ =
nullptr;
5098 else if (listener == default_xml_generator_)
5099 default_xml_generator_ =
nullptr;
5100 return repeater_->
Release(listener);
5112void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5113 if (default_result_printer_ != listener) {
5116 delete Release(default_result_printer_);
5117 default_result_printer_ = listener;
5118 if (listener !=
nullptr)
Append(listener);
5127void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5128 if (default_xml_generator_ != listener) {
5131 delete Release(default_xml_generator_);
5132 default_xml_generator_ = listener;
5133 if (listener !=
nullptr)
Append(listener);
5139bool TestEventListeners::EventForwardingEnabled()
const {
5161#if defined(__BORLANDC__)
5177 return impl()->failed_test_suite_count();
5182 return impl()->total_test_suite_count();
5188 return impl()->test_suite_to_run_count();
5192#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5194 return impl()->successful_test_suite_count();
5197 return impl()->failed_test_suite_count();
5200 return impl()->total_test_suite_count();
5203 return impl()->test_suite_to_run_count();
5209 return impl()->successful_test_count();
5214 return impl()->skipped_test_count();
5222 return impl()->reportable_disabled_test_count();
5227 return impl()->disabled_test_count();
5232 return impl()->reportable_test_count();
5244 return impl()->start_timestamp();
5249 return impl()->elapsed_time();
5263 return impl()->GetTestSuite(
i);
5267#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5269 return impl()->GetTestCase(
i);
5276 return *impl()->ad_hoc_test_result();
5281TestSuite* UnitTest::GetMutableTestSuite(
int i) {
5282 return impl()->GetMutableSuiteCase(
i);
5300 if (env ==
nullptr) {
5312void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5313 const char* file_name,
int line_number,
5314 const std::string& message,
5315 const std::string& os_stack_trace)
5321 if (!impl_->gtest_trace_stack().empty()) {
5324 for (
size_t i = impl_->gtest_trace_stack().size();
i > 0; --
i) {
5325 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[
i - 1];
5332 if (os_stack_trace.c_str() !=
nullptr && !os_stack_trace.empty()) {
5338 const TestPartResult result = TestPartResult(
5339 result_type, file_name, line_number, msg.GetString().c_str());
5340 impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5343 if (result_type != TestPartResult::kSuccess &&
5344 result_type != TestPartResult::kSkip) {
5351#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
5352 !defined(GTEST_OS_WINDOWS_RT)
5357#elif (!defined(__native_client__)) && \
5358 ((defined(__clang__) || defined(__GNUC__)) && \
5359 (defined(__x86_64__) || defined(__i386__)))
5362#elif GTEST_HAS_BUILTIN(__builtin_trap)
5364#elif defined(SIGTRAP)
5370 *
static_cast<volatile int*
>(
nullptr) = 1;
5373#if GTEST_HAS_EXCEPTIONS
5374 throw internal::GoogleTestFailureException(result);
5389void UnitTest::RecordProperty(
const std::string& key,
5390 const std::string&
value) {
5400#ifdef GTEST_HAS_DEATH_TEST
5401 const bool in_death_test_child_process =
5425 const internal::ScopedPrematureExitFile premature_exit_file(
5426 in_death_test_child_process
5430 const bool in_death_test_child_process =
false;
5437#ifdef GTEST_OS_WINDOWS
5442 if (impl()->catch_exceptions() || in_death_test_child_process) {
5443#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \
5444 !defined(GTEST_OS_WINDOWS_RT)
5446 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5447 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5450#if (defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)) && \
5451 !defined(GTEST_OS_WINDOWS_MOBILE)
5455 _set_error_mode(_OUT_TO_STDERR);
5458#if defined(_MSC_VER) && !defined(GTEST_OS_WINDOWS_MOBILE)
5465 _set_abort_behavior(
5467 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
5473 if (!IsDebuggerPresent()) {
5474 (void)_CrtSetReportMode(_CRT_ASSERT,
5475 _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
5476 (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
5481 (void)in_death_test_child_process;
5486 "auxiliary test code (environments or event listeners)")
5491#if GTEST_HAS_FILE_SYSTEM
5495 return impl_->original_working_dir_.c_str();
5508#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5538UnitTest::~UnitTest() {
delete impl_; }
5542void UnitTest::PushGTestTrace(
const internal::TraceInfo& trace)
5545 impl_->gtest_trace_stack().push_back(trace);
5559 default_global_test_part_result_reporter_(this),
5560 default_per_thread_test_part_result_reporter_(this),
5562 &default_global_test_part_result_reporter_),
5563 per_thread_test_part_result_reporter_(
5564 &default_per_thread_test_part_result_reporter_),
5565 parameterized_test_registry_(),
5566 parameterized_tests_registered_(false),
5567 last_death_test_suite_(-1),
5568 current_test_suite_(nullptr),
5569 current_test_info_(nullptr),
5570 ad_hoc_test_result_(),
5571 os_stack_trace_getter_(nullptr),
5572 post_flag_parse_init_performed_(false),
5575 start_timestamp_(0),
5577#ifdef GTEST_HAS_DEATH_TEST
5578 death_test_factory_(new DefaultDeathTestFactory),
5581 catch_exceptions_(false) {
5592 delete os_stack_trace_getter_;
5601 std::string xml_element;
5604 if (current_test_info_ !=
nullptr) {
5605 xml_element =
"testcase";
5606 test_result = &(current_test_info_->result_);
5607 }
else if (current_test_suite_ !=
nullptr) {
5608 xml_element =
"testsuite";
5609 test_result = &(current_test_suite_->ad_hoc_test_result_);
5611 xml_element =
"testsuites";
5612 test_result = &ad_hoc_test_result_;
5614 test_result->RecordProperty(xml_element, test_property);
5617#ifdef GTEST_HAS_DEATH_TEST
5620void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5621 if (internal_run_death_test_flag_ !=
nullptr)
5630#if GTEST_HAS_FILE_SYSTEM
5631 if (output_format ==
"xml") {
5632 listeners()->SetDefaultXmlGenerator(
new XmlUnitTestResultPrinter(
5634 }
else if (output_format ==
"json") {
5635 listeners()->SetDefaultXmlGenerator(
new JsonUnitTestResultPrinter(
5637 }
else if (!output_format.empty()) {
5638 GTEST_LOG_(WARNING) <<
"WARNING: unrecognized output format \""
5639 << output_format <<
"\" ignored.";
5642 if (!output_format.empty()) {
5643 GTEST_LOG_(ERROR) <<
"ERROR: alternative output formats require "
5644 <<
"GTEST_HAS_FILE_SYSTEM to be enabled";
5649#if GTEST_CAN_STREAM_RESULTS_
5652void UnitTestImpl::ConfigureStreamingOutput() {
5654 if (!target.empty()) {
5655 const size_t pos = target.find(
':');
5656 if (pos != std::string::npos) {
5658 new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
5660 GTEST_LOG_(WARNING) <<
"unrecognized streaming target \"" << target
5674 if (!post_flag_parse_init_performed_) {
5675 post_flag_parse_init_performed_ =
true;
5677#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5682#ifdef GTEST_HAS_DEATH_TEST
5683 InitDeathTestSubprocessControlInfo();
5684 SuppressTestEventsIfInSubprocess();
5700#if GTEST_CAN_STREAM_RESULTS_
5702 ConfigureStreamingOutput();
5705#ifdef GTEST_HAS_ABSL
5707 absl::FailureSignalHandlerOptions options;
5708 absl::InstallFailureSignalHandler(options);
5729 return test_suite !=
nullptr &&
5730 strcmp(test_suite->
name(), name_.c_str()) == 0;
5750 const char* test_suite_name,
const char* type_param,
5754 const auto test_suite =
5755 std::find_if(test_suites_.rbegin(), test_suites_.rend(),
5758 if (test_suite != test_suites_.rend())
return *test_suite;
5761 auto*
const new_test_suite =
5762 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
5766 if (death_test_suite_filter.MatchesName(test_suite_name)) {
5771 ++last_death_test_suite_;
5772 test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
5776 test_suites_.push_back(new_test_suite);
5779 test_suite_indices_.push_back(
static_cast<int>(test_suite_indices_.size()));
5780 return new_test_suite;
5809#if GTEST_HAS_FILE_SYSTEM
5818 bool in_subprocess_for_death_test =
false;
5820#ifdef GTEST_HAS_DEATH_TEST
5821 in_subprocess_for_death_test = (internal_run_death_test_flag_ !=
nullptr);
5822#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5823 if (in_subprocess_for_death_test) {
5824 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5830 in_subprocess_for_death_test);
5834 const bool has_tests_to_run =
5848 bool failed =
false;
5857 const int repeat = in_subprocess_for_death_test ? 1 :
GTEST_FLAG_GET(repeat);
5860 const bool gtest_repeat_forever = repeat < 0;
5868 const bool recreate_environments_when_repeating =
5870 gtest_repeat_forever;
5872 for (
int i = 0; gtest_repeat_forever ||
i != repeat;
i++) {
5892 if (has_tests_to_run) {
5895 if (
i == 0 || recreate_environments_when_repeating) {
5909 const TestPartResult& test_part_result =
5911 if (test_part_result.type() == TestPartResult::kSkip) {
5912 const std::string& result = test_part_result.message();
5913 printf(
"%s\n", result.c_str());
5942 if (
i == repeat - 1 || recreate_environments_when_repeating) {
5944 std::for_each(environments_.rbegin(), environments_.rend(),
5950 elapsed_time_ = timer.
Elapsed();
5976 if (!gtest_is_initialized_before_run_all_tests) {
5979 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5981 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5982 " will start to enforce the valid usage. "
5983 "Please fix it ASAP, or IT WILL START TO FAIL.\n");
5989#if GTEST_HAS_FILE_SYSTEM
5996 if (test_shard_file !=
nullptr) {
5998 if (file ==
nullptr) {
6000 "Could not write to the test shard status file \"%s\" "
6001 "specified by the %s environment variable.\n",
6017bool ShouldShard(
const char* total_shards_env,
const char* shard_index_env,
6018 bool in_subprocess_for_death_test) {
6019 if (in_subprocess_for_death_test) {
6026 if (total_shards == -1 && shard_index == -1) {
6028 }
else if (total_shards == -1 && shard_index != -1) {
6029 const Message msg =
Message() <<
"Invalid environment variables: you have "
6036 }
else if (total_shards != -1 && shard_index == -1) {
6038 <<
"Invalid environment variables: you have "
6044 }
else if (shard_index < 0 || shard_index >= total_shards) {
6046 Message() <<
"Invalid environment variables: we require 0 <= "
6055 return total_shards > 1;
6063 if (str_val ==
nullptr) {
6069 str_val, &result)) {
6080 return (test_id % total_shards) == shard_index;
6098 const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
6105 int num_runnable_tests = 0;
6106 int num_selected_tests = 0;
6107 for (
auto* test_suite : test_suites_) {
6108 const std::string& test_suite_name = test_suite->name();
6109 test_suite->set_should_run(
false);
6111 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6112 TestInfo*
const test_info = test_suite->test_info_list()[j];
6113 const std::string test_name(test_info->
name());
6116 const bool is_disabled =
6117 disable_test_filter.MatchesName(test_suite_name) ||
6118 disable_test_filter.MatchesName(test_name);
6119 test_info->is_disabled_ = is_disabled;
6121 const bool matches_filter =
6122 gtest_flag_filter.MatchesTest(test_suite_name, test_name);
6123 test_info->matches_filter_ = matches_filter;
6125 const bool is_runnable =
6129 const bool is_in_another_shard =
6132 test_info->is_in_another_shard_ = is_in_another_shard;
6133 const bool is_selected = is_runnable && !is_in_another_shard;
6135 num_runnable_tests += is_runnable;
6136 num_selected_tests += is_selected;
6138 test_info->should_run_ = is_selected;
6139 test_suite->set_should_run(test_suite->should_run() || is_selected);
6142 return num_selected_tests;
6150 if (str !=
nullptr) {
6151 for (
int i = 0; *str !=
'\0'; ++str) {
6152 if (
i >= max_length) {
6170 const int kMaxParamLength = 250;
6172 for (
auto* test_suite : test_suites_) {
6173 bool printed_test_suite_name =
false;
6175 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6176 const TestInfo*
const test_info = test_suite->test_info_list()[j];
6177 if (test_info->matches_filter_) {
6178 if (!printed_test_suite_name) {
6179 printed_test_suite_name =
true;
6180 printf(
"%s.", test_suite->name());
6181 if (test_suite->type_param() !=
nullptr) {
6189 printf(
" %s", test_info->
name());
6201#if GTEST_HAS_FILE_SYSTEM
6203 if (output_format ==
"xml" || output_format ==
"json") {
6204 FILE* fileout = OpenFileForWriting(
6206 std::stringstream stream;
6207 if (output_format ==
"xml") {
6208 XmlUnitTestResultPrinter(
6210 .PrintXmlTestsList(&stream, test_suites_);
6211 }
else if (output_format ==
"json") {
6212 JsonUnitTestResultPrinter(
6214 .PrintJsonTestList(&stream, test_suites_);
6229 if (os_stack_trace_getter_ != getter) {
6230 delete os_stack_trace_getter_;
6231 os_stack_trace_getter_ = getter;
6239 if (os_stack_trace_getter_ ==
nullptr) {
6240#ifdef GTEST_OS_STACK_TRACE_GETTER_
6241 os_stack_trace_getter_ =
new GTEST_OS_STACK_TRACE_GETTER_;
6247 return os_stack_trace_getter_;
6252 if (current_test_info_ !=
nullptr) {
6253 return ¤t_test_info_->result_;
6255 if (current_test_suite_ !=
nullptr) {
6256 return ¤t_test_suite_->ad_hoc_test_result_;
6258 return &ad_hoc_test_result_;
6269 static_cast<int>(test_suites_.size()), &test_suite_indices_);
6272 for (
auto& test_suite : test_suites_) {
6273 test_suite->ShuffleTests(
random());
6279 for (
size_t i = 0;
i < test_suites_.size();
i++) {
6281 test_suites_[
i]->UnshuffleTests();
6283 test_suite_indices_[
i] =
static_cast<int>(
i);
6307class ClassUniqueToAlwaysTrue {};
6310bool IsTrue(
bool condition) {
return condition; }
6313#if GTEST_HAS_EXCEPTIONS
6316 if (
IsTrue(
false))
throw ClassUniqueToAlwaysTrue();
6325 const size_t prefix_len = strlen(prefix);
6326 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6327 *pstr += prefix_len;
6339 bool def_optional) {
6341 if (str ==
nullptr || flag_name ==
nullptr)
return nullptr;
6344 const std::string flag_str =
6346 const size_t flag_len = flag_str.length();
6347 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return nullptr;
6350 const char* flag_end = str + flag_len;
6353 if (def_optional && (flag_end[0] ==
'\0')) {
6360 if (flag_end[0] !=
'=')
return nullptr;
6363 return flag_end + 1;
6378 const char*
const value_str =
ParseFlagValue(str, flag_name,
true);
6381 if (value_str ==
nullptr)
return false;
6384 *
value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
6394 const char*
const value_str =
ParseFlagValue(str, flag_name,
false);
6397 if (value_str ==
nullptr)
return false;
6408template <
typename String>
6411 const char*
const value_str =
ParseFlagValue(str, flag_name,
false);
6414 if (value_str ==
nullptr)
return false;
6445 GTestColor color = GTestColor::kDefault;
6452 const char*
p = strchr(str,
'@');
6460 const char ch =
p[1];
6464 }
else if (
ch ==
'D') {
6465 color = GTestColor::kDefault;
6466 }
else if (
ch ==
'R') {
6467 color = GTestColor::kRed;
6468 }
else if (
ch ==
'G') {
6469 color = GTestColor::kGreen;
6470 }
else if (
ch ==
'Y') {
6471 color = GTestColor::kYellow;
6479 "This program contains tests written using " GTEST_NAME_
6480 ". You can use the\n"
6481 "following command line flags to control its behavior:\n"
6486 " List the names of all tests instead of running them. The name of\n"
6487 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6489 "filter=@YPOSITIVE_PATTERNS"
6490 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6491 " Run only the tests whose name matches one of the positive patterns "
6493 " none of the negative patterns. '?' matches any single character; "
6495 " matches any substring; ':' separates two patterns.\n"
6497 "also_run_disabled_tests@D\n"
6498 " Run all disabled tests too.\n"
6502 "repeat=@Y[COUNT]@D\n"
6503 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6506 " Randomize tests' orders on every iteration.\n"
6508 "random_seed=@Y[NUMBER]@D\n"
6509 " Random number seed to use for shuffling test orders (between 1 and\n"
6510 " 99999, or 0 to use a seed based on the current time).\n"
6512 "recreate_environments_when_repeating@D\n"
6513 " Sets up and tears down the global test environment on each repeat\n"
6518 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6519 " Enable/disable colored output. The default is @Gauto@D.\n"
6522 " Only print test failures.\n"
6525 " Don't print the elapsed time of each test.\n"
6528 "@Y|@G:@YFILE_PATH]@D\n"
6529 " Generate a JSON or XML report in the given directory or with the "
6531 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
6532#if GTEST_CAN_STREAM_RESULTS_
6534 "stream_result_to=@YHOST@G:@YPORT@D\n"
6535 " Stream test results to the given server.\n"
6538 "Assertion Behavior:\n"
6539#if defined(GTEST_HAS_DEATH_TEST) && !defined(GTEST_OS_WINDOWS)
6541 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6542 " Set the default death test style.\n"
6545 "break_on_failure@D\n"
6546 " Turn assertion failures into debugger break-points.\n"
6548 "throw_on_failure@D\n"
6549 " Turn assertion failures into C++ exceptions for use by an external\n"
6550 " test framework.\n"
6552 "catch_exceptions=0@D\n"
6553 " Do not report exceptions as test failures. Instead, allow them\n"
6554 " to crash the program or throw a pop-up (on Windows).\n"
6557 "list_tests@D, you can alternatively set "
6558 "the corresponding\n"
6559 "environment variable of a flag (all letters in upper-case). For example, "
6561 "disable colored text output, you can either specify "
6563 "color=no@D or set\n"
6565 "COLOR@D environment variable to @Gno@D.\n"
6567 "For more information, please read the " GTEST_NAME_
6568 " documentation at\n"
6571 "(not one in your own code or tests), please report it to\n"
6575#define GTEST_INTERNAL_PARSE_FLAG(flag_name) \
6577 auto value = GTEST_FLAG_GET(flag_name); \
6578 if (ParseFlag(arg, #flag_name, &value)) { \
6579 GTEST_FLAG_SET(flag_name, value); \
6608#if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6609static void LoadFlagsFromFile(
const std::string& path) {
6617 std::vector<std::string> lines;
6619 for (
size_t i = 0;
i < lines.size(); ++
i) {
6620 if (lines[
i].empty())
continue;
6629template <
typename CharType>
6631 std::string flagfile_value;
6632 for (
int i = 1;
i < *argc;
i++) {
6634 const char*
const arg = arg_string.c_str();
6638 bool remove_flag =
false;
6641#if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6642 }
else if (
ParseFlag(arg,
"flagfile", &flagfile_value)) {
6644 LoadFlagsFromFile(flagfile_value);
6658 for (
int j =
i; j != *argc; j++) {
6659 argv[j] = argv[j + 1];
6686#ifdef GTEST_HAS_ABSL
6687 if (*argc <= 0)
return;
6689 std::vector<char*> positional_args;
6690 std::vector<absl::UnrecognizedFlag> unrecognized_flags;
6691 absl::ParseAbseilFlagsOnly(*argc, argv, positional_args, unrecognized_flags);
6692 absl::flat_hash_set<absl::string_view> unrecognized;
6693 for (
const auto& flag : unrecognized_flags) {
6694 unrecognized.insert(flag.flag_name);
6696 absl::flat_hash_set<char*> positional;
6697 for (
const auto& arg : positional_args) {
6698 positional.insert(arg);
6703 for (; in_pos < *argc; ++in_pos) {
6704 char* arg = argv[in_pos];
6705 absl::string_view arg_str(arg);
6706 if (absl::ConsumePrefix(&arg_str,
"--")) {
6709 if (unrecognized.contains(arg_str)) {
6710 argv[out_pos++] = argv[in_pos];
6715 if (arg_str.empty()) {
6722 if (positional.contains(arg)) {
6723 argv[out_pos++] = arg;
6728 while (in_pos < *argc) {
6729 argv[out_pos++] = argv[in_pos++];
6733 argv[out_pos] =
nullptr;
6743 if (*_NSGetArgv() == argv) {
6744 *_NSGetArgc() = *argc;
6757template <
typename CharType>
6762 if (*argc <= 0)
return;
6765 for (
int i = 0;
i != *argc;
i++) {
6769#ifdef GTEST_HAS_ABSL
6770 absl::InitializeSymbolizer(
g_argvs[0].c_str());
6774 absl::SetProgramUsageMessage(absl::StrReplaceAll(
6776 {{
"@D",
""}, {
"@R",
""}, {
"@G",
""}, {
"@Y",
""}, {
"@@",
"@"}}));
6795#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6796 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6805#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6806 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6817 const auto arg0 =
"dummy";
6818 char* argv0 =
const_cast<char*
>(arg0);
6819 char** argv = &argv0;
6821#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6822 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
6828#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) || \
6829 !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
6835 std::initializer_list<const char*> environment_variables,
6836 const char* fallback,
char separator) {
6837 for (
const char* variable_name : environment_variables) {
6841 return std::string(
value).append(1, separator);
6851#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6852 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6853#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
6854 return GetDirFromEnv({
"TEST_TMPDIR",
"TEMP"},
"\\temp\\",
'\\');
6855#elif defined(GTEST_OS_LINUX_ANDROID)
6856 return GetDirFromEnv({
"TEST_TMPDIR",
"TMPDIR"},
"/data/local/tmp/",
'/');
6858 return GetDirFromEnv({
"TEST_TMPDIR",
"TMPDIR"},
"/tmp/",
'/');
6862#if GTEST_HAS_FILE_SYSTEM && !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
6865static std::string GetCurrentExecutableDirectory() {
6867 return argv_0.RemoveFileName().string();
6871#if GTEST_HAS_FILE_SYSTEM
6873#if defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
6874 return GTEST_CUSTOM_SRCDIR_FUNCTION_();
6875#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
6876 return GetDirFromEnv({
"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
6878#elif defined(GTEST_OS_LINUX_ANDROID)
6879 return GetDirFromEnv({
"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
6882 return GetDirFromEnv({
"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
6892void ScopedTrace::PushTrace(
const char* file,
int line, std::string message) {
6893 internal::TraceInfo trace;
6896 trace.message.swap(message);
virtual void TearDown()
Definition gtest.h:903
virtual void SetUp()
Definition gtest.h:900
Definition gtest-message.h:101
std::string GetString() const
Definition gtest.cc:1301
Message & operator<<(const T &val)
Definition gtest-message.h:132
Message()
Definition gtest.cc:1275
~ScopedTrace()
Definition gtest.cc:6902
virtual void OnTestPartResult(const TestPartResult &test_part_result)=0
virtual void OnTestSuiteStart(const TestSuite &)
Definition gtest.h:946
virtual void OnTestDisabled(const TestInfo &)
Definition gtest.h:957
virtual void OnEnvironmentsTearDownStart(const UnitTest &unit_test)=0
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)=0
virtual void OnTestProgramStart(const UnitTest &unit_test)=0
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)=0
virtual void OnEnvironmentsTearDownEnd(const UnitTest &unit_test)=0
virtual void OnEnvironmentsSetUpStart(const UnitTest &unit_test)=0
virtual void OnEnvironmentsSetUpEnd(const UnitTest &unit_test)=0
virtual void OnTestStart(const TestInfo &test_info)=0
virtual void OnTestEnd(const TestInfo &test_info)=0
virtual void OnTestProgramEnd(const UnitTest &unit_test)=0
TestEventListener * Release(TestEventListener *listener)
Definition gtest.cc:5095
void Append(TestEventListener *listener)
Definition gtest.cc:5088
void SuppressEventForwarding(bool)
Definition gtest.cc:5143
~TestEventListeners()
Definition gtest.cc:5082
TestEventListeners()
Definition gtest.cc:5077
const char * file() const
Definition gtest.h:566
const char * value_param() const
Definition gtest.h:560
bool should_run() const
Definition gtest.h:590
const char * type_param() const
Definition gtest.h:553
~TestInfo()
Definition gtest.cc:2741
const char * name() const
Definition gtest.h:549
const TestResult * result() const
Definition gtest.h:600
friend class internal::UnitTestImpl
Definition gtest.h:608
const char * test_suite_name() const
Definition gtest.h:541
int line() const
Definition gtest.h:569
bool HasFatalFailure() const
Definition gtest.cc:2431
bool Skipped() const
Definition gtest.cc:2413
bool HasNonfatalFailure() const
Definition gtest.cc:2441
TestResult()
Definition gtest.cc:2253
int total_part_count() const
Definition gtest.cc:2447
const TestProperty & GetTestProperty(int i) const
Definition gtest.cc:2270
TimeInMillis elapsed_time() const
Definition gtest.h:431
const TestPartResult & GetTestPartResult(int i) const
Definition gtest.cc:2262
bool Passed() const
Definition gtest.h:416
bool Failed() const
Definition gtest.cc:2418
int test_property_count() const
Definition gtest.cc:2452
int test_to_run_count() const
Definition gtest.cc:2911
int reportable_test_count() const
Definition gtest.cc:2906
const char * name() const
Definition gtest.h:695
TestSuite(const char *name, const char *a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc)
Definition gtest.cc:2929
TimeInMillis elapsed_time() const
Definition gtest.h:740
int total_test_count() const
Definition gtest.cc:2916
const char * type_param() const
Definition gtest.h:699
virtual ~TestSuite()
Definition gtest.cc:2941
const TestInfo * GetTestInfo(int i) const
Definition gtest.cc:2948
int successful_test_count() const
Definition gtest.cc:2881
bool should_run() const
Definition gtest.h:705
int failed_test_count() const
Definition gtest.cc:2891
int reportable_disabled_test_count() const
Definition gtest.cc:2896
friend class internal::UnitTestImpl
Definition gtest.h:756
int disabled_test_count() const
Definition gtest.cc:2901
bool Passed() const
Definition gtest.h:732
bool Failed() const
Definition gtest.h:735
int skipped_test_count() const
Definition gtest.cc:2886
static void RecordProperty(const std::string &key, const std::string &value)
Definition gtest.cc:2479
virtual void SetUp()
Definition gtest.cc:2471
friend class TestInfo
Definition gtest.h:245
static bool HasFatalFailure()
Definition gtest.cc:2700
virtual void TearDown()
Definition gtest.cc:2476
static bool IsSkipped()
Definition gtest.cc:2712
Test()
Definition gtest.cc:2461
int skipped_test_count() const
Definition gtest.cc:5213
const TestInfo * current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_)
Definition gtest.cc:5518
int failed_test_suite_count() const
Definition gtest.cc:5176
static UnitTest * GetInstance()
Definition gtest.cc:5156
int reportable_disabled_test_count() const
Definition gtest.cc:5221
const TestCase * current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_)
Definition gtest.cc:5509
int Run() GTEST_MUST_USE_RESULT_
Definition gtest.cc:5399
TimeInMillis start_timestamp() const
Definition gtest.cc:5243
int reportable_test_count() const
Definition gtest.cc:5231
int test_to_run_count() const
Definition gtest.cc:5239
int successful_test_count() const
Definition gtest.cc:5208
bool Failed() const
Definition gtest.cc:5258
const TestCase * GetTestCase(int i) const
Definition gtest.cc:5268
bool Passed() const
Definition gtest.cc:5254
int total_test_case_count() const
Definition gtest.cc:5199
int test_case_to_run_count() const
Definition gtest.cc:5202
const TestSuite * GetTestSuite(int i) const
Definition gtest.cc:5262
internal::ParameterizedTestSuiteRegistry & parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_)
Definition gtest.cc:5530
const TestResult & ad_hoc_test_result() const
Definition gtest.cc:5275
TestEventListeners & listeners()
Definition gtest.cc:5287
const TestSuite * current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_)
Definition gtest.cc:5501
int failed_test_case_count() const
Definition gtest.cc:5196
int successful_test_case_count() const
Definition gtest.cc:5193
int failed_test_count() const
Definition gtest.cc:5218
TimeInMillis elapsed_time() const
Definition gtest.cc:5248
int disabled_test_count() const
Definition gtest.cc:5226
int random_seed() const
Definition gtest.cc:5525
int test_suite_to_run_count() const
Definition gtest.cc:5187
int successful_test_suite_count() const
Definition gtest.cc:5171
const char * original_working_dir() const
int total_test_count() const
Definition gtest.cc:5236
int total_test_suite_count() const
Definition gtest.cc:5181
~AssertHelper()
Definition gtest.cc:454
void operator=(const Message &message) const
Definition gtest.cc:457
AssertHelper(TestPartResult::Type type, const char *file, int line, const char *message)
Definition gtest.cc:450
void OnEnvironmentsTearDownStart(const UnitTest &) override
Definition gtest.cc:3690
void OnTestIterationStart(const UnitTest &, int) override
Definition gtest.cc:3669
void OnTestCaseStart(const TestCase &) override
Definition gtest.cc:3674
void OnEnvironmentsSetUpStart(const UnitTest &) override
Definition gtest.cc:3671
void OnEnvironmentsTearDownEnd(const UnitTest &) override
Definition gtest.cc:3691
void OnTestProgramStart(const UnitTest &) override
Definition gtest.cc:3668
void OnTestProgramEnd(const UnitTest &) override
Definition gtest.cc:3693
static void PrintTestName(const char *test_suite, const char *test)
Definition gtest.cc:3663
void OnTestStart(const TestInfo &) override
Definition gtest.cc:3679
void OnTestCaseEnd(const TestCase &) override
Definition gtest.cc:3685
void OnTestDisabled(const TestInfo &) override
Definition gtest.cc:3680
void OnEnvironmentsSetUpEnd(const UnitTest &) override
Definition gtest.cc:3672
BriefUnitTestResultPrinter()=default
void ReportTestPartResult(const TestPartResult &result) override
Definition gtest.cc:1027
DefaultPerThreadTestPartResultReporter(UnitTestImpl *unit_test)
Definition gtest.cc:1033
void ReportTestPartResult(const TestPartResult &result) override
Definition gtest.cc:1037
Definition gtest-internal.h:246
Definition gtest-port.h:1887
Definition gtest-internal-inl.h:408
virtual std::string CurrentStackTrace(int max_depth, int skip_count)=0
static const char *const kElidedFramesMarker
Definition gtest-internal-inl.h:428
Definition gtest-internal-inl.h:437
void UponLeavingGTest() override
Definition gtest.cc:5021
std::string CurrentStackTrace(int max_depth, int skip_count) override
Definition gtest.cc:4971
Definition gtest-param-util.h:692
void RegisterTests()
Definition gtest-param-util.h:732
void OnTestProgramStart(const UnitTest &) override
Definition gtest.cc:3360
void OnTestProgramEnd(const UnitTest &) override
Definition gtest.cc:3384
PrettyUnitTestResultPrinter()=default
void OnEnvironmentsTearDownEnd(const UnitTest &) override
Definition gtest.cc:3382
void OnEnvironmentsSetUpEnd(const UnitTest &) override
Definition gtest.cc:3363
static void PrintTestName(const char *test_suite, const char *test)
Definition gtest.cc:3355
uint32_t Generate(uint32_t range)
Definition gtest.cc:400
static const uint32_t kMaxRange
Definition gtest-internal.h:857
void Reseed(uint32_t seed)
Definition gtest-internal.h:861
Definition gtest-string.h:63
static bool CaseInsensitiveCStringEquals(const char *lhs, const char *rhs)
Definition gtest.cc:2131
static bool CaseInsensitiveWideCStringEquals(const wchar_t *lhs, const wchar_t *rhs)
Definition gtest.cc:2149
static std::string FormatHexUInt32(uint32_t value)
Definition gtest.cc:2195
static bool CStringEquals(const char *lhs, const char *rhs)
Definition gtest.cc:1224
static bool EndsWithCaseInsensitive(const std::string &str, const std::string &suffix)
Definition gtest.cc:2173
static std::string ShowWideCString(const wchar_t *wide_c_str)
Definition gtest.cc:2080
static bool WideCStringEquals(const wchar_t *lhs, const wchar_t *rhs)
Definition gtest.cc:2092
static std::string FormatIntWidthN(int value, int width)
Definition gtest.cc:2188
static std::string FormatIntWidth2(int value)
Definition gtest.cc:2183
static std::string FormatByte(unsigned char value)
Definition gtest.cc:2207
static std::string FormatHexInt(int value)
Definition gtest.cc:2202
void OnEnvironmentsTearDownEnd(const UnitTest ¶meter) override
void OnTestStart(const TestInfo ¶meter) override
void OnTestProgramEnd(const UnitTest ¶meter) override
void OnTestSuiteEnd(const TestSuite ¶meter) override
void OnTestPartResult(const TestPartResult ¶meter) override
void OnTestCaseStart(const TestSuite ¶meter) override
void OnTestEnd(const TestInfo ¶meter) override
void OnEnvironmentsSetUpStart(const UnitTest ¶meter) override
void OnEnvironmentsSetUpEnd(const UnitTest ¶meter) override
void OnTestProgramStart(const UnitTest ¶meter) override
void OnEnvironmentsTearDownStart(const UnitTest ¶meter) override
void set_forwarding_enabled(bool enable)
Definition gtest.cc:3775
void OnTestCaseEnd(const TestCase ¶meter) override
TestEventRepeater()
Definition gtest.cc:3767
void OnTestSuiteStart(const TestSuite ¶meter) override
bool forwarding_enabled() const
Definition gtest.cc:3774
TestEventListener * Release(TestEventListener *listener)
Definition gtest.cc:3819
void Append(TestEventListener *listener)
Definition gtest.cc:3815
void OnTestDisabled(const TestInfo ¶meter) override
Definition gtest-internal.h:436
virtual Test * CreateTest()=0
bool operator()(const TestSuite *test_suite) const
Definition gtest.cc:5728
TestSuiteNameIs(const std::string &name)
Definition gtest.cc:5725
void set(const T &value)
Definition gtest-port.h:1902
const T & get() const
Definition gtest-port.h:1901
TimeInMillis Elapsed()
Definition gtest.cc:1154
Timer()
Definition gtest.cc:1151
void RegisterTestSuite(const char *test_suite_name, CodeLocation code_location)
Definition gtest.cc:568
void CheckForInstantiations()
Definition gtest.cc:585
void RegisterInstantiation(const char *test_suite_name)
Definition gtest.cc:574
Definition gtest-internal-inl.h:508
internal::ParameterizedTestSuiteRegistry & parameterized_test_registry()
Definition gtest-internal-inl.h:697
int reportable_disabled_test_count() const
Definition gtest.cc:1105
int disabled_test_count() const
Definition gtest.cc:1111
bool Failed() const
Definition gtest-internal-inl.h:584
internal::Random * random()
Definition gtest-internal-inl.h:824
int test_to_run_count() const
Definition gtest.cc:1126
void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface *reporter)
Definition gtest.cc:1063
void RecordProperty(const TestProperty &test_property)
Definition gtest.cc:5600
TestPartResultReporterInterface * GetGlobalTestPartResultReporter()
Definition gtest.cc:1044
void UnshuffleTests()
Definition gtest.cc:6278
bool RunAllTests()
Definition gtest.cc:5797
void ConfigureXmlOutput()
Definition gtest.cc:5628
TestEventListeners * listeners()
Definition gtest-internal-inl.h:608
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_
Definition gtest.cc:1140
const TestSuite * current_test_suite() const
Definition gtest-internal-inl.h:765
int test_suite_to_run_count() const
Definition gtest.cc:1085
void set_os_stack_trace_getter(OsStackTraceGetterInterface *getter)
Definition gtest.cc:6227
TestSuite * GetMutableSuiteCase(int i)
Definition gtest-internal-inl.h:602
std::set< std::string > * ignored_parameterized_test_suites()
Definition gtest-internal-inl.h:701
TestPartResultReporterInterface * GetTestPartResultReporterForCurrentThread()
Definition gtest.cc:1058
UnitTestImpl(UnitTest *parent)
Definition gtest.cc:5556
int random_seed() const
Definition gtest-internal-inl.h:821
OsStackTraceGetterInterface * os_stack_trace_getter()
Definition gtest.cc:6238
void PostFlagParsingInit()
Definition gtest.cc:5672
void SetGlobalTestPartResultReporter(TestPartResultReporterInterface *reporter)
Definition gtest.cc:1050
int total_test_count() const
Definition gtest.cc:1121
int successful_test_suite_count() const
Definition gtest.cc:1069
void ClearNonAdHocTestResult()
Definition gtest-internal-inl.h:739
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc, TestInfo *test_info)
Definition gtest-internal-inl.h:672
void ShuffleTests()
Definition gtest.cc:6263
TestInfo * current_test_info()
Definition gtest-internal-inl.h:766
TestResult * current_test_result()
Definition gtest.cc:6251
int FilterTests(ReactionToSharding shard_tests)
Definition gtest.cc:6090
int failed_test_suite_count() const
Definition gtest.cc:1074
std::vector< Environment * > & environments()
Definition gtest-internal-inl.h:771
internal::TypeParameterizedTestSuiteRegistry & type_parameterized_test_registry()
Definition gtest-internal-inl.h:708
int successful_test_count() const
Definition gtest.cc:1090
std::vector< TraceInfo > & gtest_trace_stack()
Definition gtest-internal-inl.h:774
ReactionToSharding
Definition gtest-internal-inl.h:752
@ IGNORE_SHARDING_PROTOCOL
Definition gtest-internal-inl.h:752
@ HONOR_SHARDING_PROTOCOL
Definition gtest-internal-inl.h:752
int failed_test_count() const
Definition gtest.cc:1100
void ListTestsMatchingFilter()
Definition gtest.cc:6168
int skipped_test_count() const
Definition gtest.cc:1095
int reportable_test_count() const
Definition gtest.cc:1116
virtual ~UnitTestImpl()
Definition gtest.cc:5585
bool Passed() const
Definition gtest-internal-inl.h:580
int total_test_suite_count() const
Definition gtest.cc:1079
void RegisterParameterizedTests()
Definition gtest.cc:2796
const TestSuite * GetTestSuite(int i) const
Definition gtest-internal-inl.h:590
static bool MatchesFilter(const std::string &name, const char *filter)
Definition gtest.cc:850
static std::string GetAbsolutePathToOutputFile()
static std::string GetOutputFormat()
Definition gtest.cc:654
static bool FilterMatchesTest(const std::string &test_suite_name, const std::string &test_name)
Definition gtest.cc:857
int value
Definition gmock-actions_test.cc:1714
int i
Definition gmock-matchers-comparisons_test.cc:603
const char * p
Definition gmock-matchers-containers_test.cc:379
char ch
Definition gmock-matchers-containers_test.cc:384
int * count
Definition gmock_stress_test.cc:90
#define GTEST_FLAG_PREFIX_
Definition gtest-port.h:331
#define GTEST_NAME_
Definition gtest-port.h:334
#define GTEST_DEV_EMAIL_
Definition gtest-port.h:330
#define GTEST_FLAG_SAVER_
Definition gtest-port.h:2291
#define GTEST_FLAG_PREFIX_UPPER_
Definition gtest-port.h:333
#define GTEST_NO_TAIL_CALL_
Definition gtest-port.h:864
#define GTEST_FLAG_PREFIX_DASH_
Definition gtest-port.h:332
#define GTEST_DEFINE_bool_(name, default_val, doc)
Definition gtest-port.h:2258
#define GTEST_PROJECT_URL_
Definition gtest-port.h:335
#define GTEST_LOCK_EXCLUDED_(locks)
Definition gtest-port.h:2302
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
Definition gtest-port.h:360
#define GTEST_DEFINE_string_(name, default_val, doc)
Definition gtest-port.h:2268
#define GTEST_DEFINE_int32_(name, default_val, doc)
Definition gtest-port.h:2263
#define GTEST_LOG_(severity)
Definition gtest-port.h:1053
#define GTEST_NO_INLINE_
Definition gtest-port.h:853
#define GTEST_INIT_GOOGLE_TEST_NAME_
Definition gtest-port.h:339
#define GTEST_FLAG_SET(name, value)
Definition gtest-port.h:2294
#define GTEST_DISABLE_MSC_WARNINGS_POP_()
Definition gtest-port.h:361
#define GTEST_CHECK_(condition)
Definition gtest-port.h:1078
#define GTEST_FLAG_GET(name)
Definition gtest-port.h:2293
#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
Definition gtest-port.h:765
#define GTEST_PATH_SEP_
Definition gtest-port.h:1918
#define GTEST_INTERNAL_PARSE_FLAG(flag_name)
#define GTEST_REPEATER_METHOD_(Name, Type)
Definition gtest.cc:3832
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
Definition gtest.cc:3842
#define ADD_FAILURE()
Definition gtest.h:1735
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3)
Definition gtest_pred_impl.h:182
output
Definition gmock_output_test.py:182
str message
Definition googletest-output-test.py:377
GTEST_API_ std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
Definition gtest.cc:1308
GTEST_API_ std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context=2)
Definition gtest.cc:1483
EditType
Definition gtest-internal.h:174
@ kAdd
Definition gtest-internal.h:174
@ kMatch
Definition gtest-internal.h:174
@ kRemove
Definition gtest-internal.h:174
@ kReplace
Definition gtest-internal.h:174
int IsATTY(int fd)
Definition gtest-port.h:2065
int StrCaseCmp(const char *s1, const char *s2)
Definition gtest-port.h:2059
int FileNo(FILE *file)
Definition gtest-port.h:2021
void Abort()
Definition gtest-port.h:2147
const char * GetEnv(const char *name)
Definition gtest-port.h:2122
int FClose(FILE *fp)
Definition gtest-port.h:2106
FILE * FOpen(const char *path, const char *mode)
Definition gtest-port.h:2089
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
Definition gtest.cc:2056
GTEST_API_ AssertionResult EqFailure(const char *expected_expression, const char *actual_expression, const std::string &expected_value, const std::string &actual_value, bool ignoring_case)
Definition gtest.cc:1593
GTestMutexLock MutexLock
Definition gtest-port.h:1892
std::string OutputFlagAlsoCheckEnvVar()
Definition gtest-port.cc:1370
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
Definition gtest-internal-inl.h:304
GTEST_API_ bool ShouldShard(const char *total_shards_str, const char *shard_index_str, bool in_subprocess_for_death_test)
Definition gtest.cc:6017
static bool PatternMatchesString(const std::string &name_str, const char *pattern, const char *pattern_end)
Definition gtest.cc:703
static const char kColorEncodedHelpMessage[]
Definition gtest.cc:6478
AssertionResult FloatingPointLE(const char *expr1, const char *expr2, RawType val1, RawType val2)
Definition gtest.cc:1679
void WriteToShardStatusFileIfNeeded()
int GetRandomSeedFromFlag(int32_t random_seed_flag)
Definition gtest-internal-inl.h:113
static void ColoredPrintf(GTestColor color, const char *fmt,...)
Definition gtest.cc:3279
static ::std::vector< std::string > g_argvs
Definition gtest.cc:622
static void Delete(T *x)
Definition gtest-internal-inl.h:335
int CountIf(const Container &c, Predicate predicate)
Definition gtest-internal-inl.h:275
GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
Definition gtest-port.cc:995
GTEST_API_ bool SkipPrefix(const char *prefix, const char **pstr)
Definition gtest.cc:6324
static bool TestSuitePassed(const TestSuite *test_suite)
Definition gtest.cc:434
GTEST_API_ std::string ReadEntireFile(FILE *file)
Definition gtest-port.cc:1205
static const char * ParseFlagValue(const char *str, const char *flag_name, bool def_optional)
Definition gtest.cc:6338
static bool ParseGoogleTestFlag(const char *const arg)
Definition gtest.cc:6574
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1741
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
Definition gtest-port.cc:977
GTEST_API_ void InsertSyntheticTestCase(const std::string &name, CodeLocation location, bool has_test_p)
Definition gtest.cc:513
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
Definition gtest.cc:6079
GTEST_API_ void RegisterTypeParameterizedTestSuite(const char *test_suite_name, CodeLocation code_location)
Definition gtest.cc:557
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
Definition gtest.cc:6685
static void PrintOnOneLine(const char *str, int max_length)
Definition gtest.cc:6149
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(int skip_count)
Definition gtest.cc:6298
static AssertionResult HasOneFailure(const char *, const char *, const char *, const TestPartResultArray &results, TestPartResult::Type type, const std::string &substr)
Definition gtest.cc:971
GTEST_API_ bool ParseInt32(const Message &src_text, const char *str, int32_t *value)
Definition gtest-port.cc:1282
GTEST_API_ AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
Definition gtest.cc:1638
GTEST_API_ bool IsTrue(bool condition)
Definition gtest.cc:6310
void ForEach(const Container &c, Functor functor)
Definition gtest-internal-inl.h:287
static void PrintFullTestCommentIfPresent(const TestInfo &test_info)
Definition gtest.cc:3333
static void SetUpEnvironment(Environment *env)
Definition gtest.cc:5785
GTEST_API_ std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
Definition gtest.cc:1625
bool BoolFromGTestEnv(const char *flag, bool default_val)
Definition gtest-port.cc:1324
uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second)
Definition gtest.cc:2030
bool IsUtf16SurrogatePair(wchar_t first, wchar_t second)
Definition gtest.cc:2024
int GetNextRandomSeed(int seed)
Definition gtest-internal-inl.h:130
static bool HasGoogleTestFlagPrefix(const char *str)
Definition gtest.cc:6427
GTEST_API_ AssertionResult CmpHelperSTREQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1729
E GetElementOr(const std::vector< E > &v, int i, E default_value)
Definition gtest-internal-inl.h:294
GTEST_API_ bool ParseFlag(const char *str, const char *flag, int32_t *value)
Definition gtest.cc:6392
int64_t TimeInMillis
Definition gtest-port.h:2219
static void PrintColorEncoded(const char *str)
Definition gtest.cc:6444
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1766
const char * StringFromGTestEnv(const char *flag, const char *default_val)
Definition gtest-port.cc:1381
GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(const char *case_name)
Definition gtest.cc:563
GTEST_API_ TestInfo * MakeAndRegisterTestInfo(const char *test_suite_name, const char *name, const char *type_param, const char *value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase *factory)
Definition gtest.cc:2763
constexpr uint32_t kMaxCodePoint3
Definition gtest.cc:1967
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string &message)
Definition gtest.cc:2485
void Shuffle(internal::Random *random, std::vector< E > *v)
Definition gtest-internal-inl.h:328
static bool GTestIsInitialized()
Definition gtest.cc:419
GTEST_API_ bool AlwaysTrue()
Definition gtest.cc:6312
GTEST_API_ bool g_help_flag
Definition gtest.cc:205
GTEST_API_ std::vector< std::string > GetArgvs()
Definition gtest.cc:624
static int SumOverTestSuiteList(const std::vector< TestSuite * > &case_list, int(TestSuite::*method)() const)
Definition gtest.cc:424
class UnitTestImpl * GetUnitTestImpl()
Definition gtest-internal-inl.h:966
GTEST_API_ int32_t Int32FromEnvOrDie(const char *env_var, int32_t default_val)
Definition gtest.cc:6061
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
std::string StreamableToString(const T &streamable)
Definition gtest-message.h:243
const void * TypeId
Definition gtest-internal.h:401
constexpr uint32_t kMaxCodePoint2
Definition gtest.cc:1964
GTEST_API_ const char kStackTraceMarker[]
Definition gtest.cc:201
GTEST_API_ void ReportInvalidTestSuiteType(const char *test_suite_name, CodeLocation code_location)
Definition gtest.cc:2775
GTEST_API_ int32_t Int32FromGTestEnv(const char *flag, int32_t default_val)
Definition gtest-port.cc:1338
static bool ShouldRunTestSuite(const TestSuite *test_suite)
Definition gtest.cc:445
void SplitString(const ::std::string &str, char delimiter, ::std::vector<::std::string > *dest)
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
GTEST_API_ std::string StringStreamToString(::std::stringstream *stream)
Definition gtest.cc:2216
void InitGoogleTestImpl(int *argc, CharType **argv)
Definition gtest.cc:6758
static bool TestSuiteFailed(const TestSuite *test_suite)
Definition gtest.cc:439
static void TearDownEnvironment(Environment *env)
Definition gtest.cc:5786
void(*)() SetUpTestSuiteFunc
Definition gtest-internal.h:474
Result HandleSehExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
Definition gtest.cc:2601
static void PrintTestPartResult(const TestPartResult &test_part_result)
Definition gtest.cc:3151
GTEST_API_ TypeId GetTestTypeId()
Definition gtest.cc:962
GTEST_API_ std::string CodePointToUtf8(uint32_t code_point)
Definition gtest.cc:1989
static std::string PrintTestPartResultToString(const TestPartResult &test_part_result)
Definition gtest.cc:3139
void PrintTo(const T &value, ::std::ostream *os)
Definition gtest-printers.h:464
Result HandleExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
Definition gtest.cc:2620
GTEST_API_ std::string AppendUserMessage(const std::string >est_msg, const Message &user_msg)
Definition gtest.cc:2235
void ParseGoogleTestFlagsOnlyImpl(int *argc, CharType **argv)
Definition gtest.cc:6630
static const char kValueParamLabel[]
Definition gtest.cc:3331
GTEST_API_ TimeInMillis GetTimeInMillis()
Definition gtest.cc:1174
constexpr uint32_t kMaxCodePoint1
Definition gtest.cc:1961
static const char kTypeParamLabel[]
Definition gtest.cc:3330
void(*)() TearDownTestSuiteFunc
Definition gtest-internal.h:475
GTEST_API_ AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1753
bool IsSpace(char ch)
Definition gtest-port.h:1941
constexpr uint32_t kMaxCodePoint4
Definition gtest.cc:1971
std::set< std::string > * GetIgnoredParameterizedTestSuites()
Definition gtest.cc:502
static const char * GetAnsiColorCode(GTestColor color)
Definition gtest.cc:3222
uint32_t ChopLowBits(uint32_t *bits, int n)
Definition gtest.cc:1977
Definition gmock-actions.h:151
static const char kDisableTestFilter[]
Definition gtest.cc:175
static std::vector< std::string > GetReservedAttributesForElement(const std::string &xml_element)
Definition gtest.cc:2330
static bool TestPartSkipped(const TestPartResult &result)
Definition gtest.cc:2408
GTEST_API_ AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition gtest.cc:1845
static const char kUniversalFilter[]
Definition gtest.cc:183
GTEST_API_ AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
Definition gtest.cc:1714
static std::string FormatCountableNoun(int count, const char *singular_form, const char *plural_form)
Definition gtest.cc:3094
GTEST_API_ AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition gtest.cc:1835
static std::string FormatWordList(const std::vector< std::string > &words)
Definition gtest.cc:2364
static const char kTestShardStatusFile[]
Definition gtest.cc:195
static const char kTestShardIndex[]
Definition gtest.cc:191
static bool GetDefaultFailFast()
Definition gtest.cc:239
static std::string GetDirFromEnv(std::initializer_list< const char * > environment_variables, const char *fallback, char separator)
Definition gtest.cc:6834
static std::string FormatTestCount(int test_count)
Definition gtest.cc:3101
static const char kTestTotalShards[]
Definition gtest.cc:193
AssertionResult AssertionFailure()
Definition gtest-assertion-result.cc:69
static const char kDeathTestSuiteFilter[]
Definition gtest.cc:180
GTEST_API_ std::string SrcDir()
TestInfo * RegisterTest(const char *test_suite_name, const char *test_name, const char *type_param, const char *value_param, const char *file, int line, Factory factory)
Definition gtest.h:2283
static std::string FormatTestSuiteCount(int test_suite_count)
Definition gtest.cc:3106
static const char *const kReservedOutputTestCaseAttributes[]
Definition gtest.cc:2321
static const char kDefaultOutputFormat[]
Definition gtest.cc:186
static bool TestPartFatallyFailed(const TestPartResult &result)
Definition gtest.cc:2426
static const char * GetDefaultFilter()
Definition gtest.cc:228
::std::string PrintToString(const T &value)
Definition gtest-printers.h:1148
static const char kDefaultOutputFile[]
Definition gtest.cc:188
GTEST_API_ std::string TempDir()
Definition gtest.cc:6850
std::vector< std::string > ArrayAsVector(const char *const (&array)[kSize])
Definition gtest.cc:2326
AssertionResult AssertionSuccess()
Definition gtest-assertion-result.cc:66
GTEST_API_ void InitGoogleTest()
Definition gtest.cc:6814
GTEST_API_ AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
Definition gtest.cc:1721
const int kMaxStackTraceDepth
Definition gtest.h:172
static const char *const kReservedTestCaseAttributes[]
Definition gtest.cc:2315
static bool ValidateTestPropertyName(const std::string &property_name, const std::vector< std::string > &reserved_names)
Definition gtest.cc:2378
static bool TestPartNonfatallyFailed(const TestPartResult &result)
Definition gtest.cc:2436
static const char *const kReservedTestSuiteAttributes[]
Definition gtest.cc:2310
static const char *const kReservedTestSuitesAttributes[]
Definition gtest.cc:2304
static const char * TestPartResultTypeToString(TestPartResult::Type type)
Definition gtest.cc:3114
Definition gtest-internal.h:477
int line
Definition gtest-internal.h:482
std::string file
Definition gtest-internal.h:481
MarkAsIgnored(const char *test_suite)
Definition gtest.cc:507