Wire Sysio Wire Sysion 1.0.0
Loading...
Searching...
No Matches
gtest.cc
Go to the documentation of this file.
1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// The Google C++ Testing and Mocking Framework (Google Test)
33
34#include "gtest/gtest.h"
36#include "gtest/gtest-spi.h"
37
38#include <ctype.h>
39#include <math.h>
40#include <stdarg.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <time.h>
44#include <wchar.h>
45#include <wctype.h>
46
47#include <algorithm>
48#include <iomanip>
49#include <limits>
50#include <list>
51#include <map>
52#include <ostream> // NOLINT
53#include <sstream>
54#include <vector>
55
56#if GTEST_OS_LINUX
57
58// TODO(kenton@google.com): Use autoconf to detect availability of
59// gettimeofday().
60# define GTEST_HAS_GETTIMEOFDAY_ 1
61
62# include <fcntl.h> // NOLINT
63# include <limits.h> // NOLINT
64# include <sched.h> // NOLINT
65// Declares vsnprintf(). This header is not available on Windows.
66# include <strings.h> // NOLINT
67# include <sys/mman.h> // NOLINT
68# include <sys/time.h> // NOLINT
69# include <unistd.h> // NOLINT
70# include <string>
71
72#elif GTEST_OS_SYMBIAN
73# define GTEST_HAS_GETTIMEOFDAY_ 1
74# include <sys/time.h> // NOLINT
75
76#elif GTEST_OS_ZOS
77# define GTEST_HAS_GETTIMEOFDAY_ 1
78# include <sys/time.h> // NOLINT
79
80// On z/OS we additionally need strings.h for strcasecmp.
81# include <strings.h> // NOLINT
82
83#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
84
85# include <windows.h> // NOLINT
86# undef min
87
88#elif GTEST_OS_WINDOWS // We are on Windows proper.
89
90# include <io.h> // NOLINT
91# include <sys/timeb.h> // NOLINT
92# include <sys/types.h> // NOLINT
93# include <sys/stat.h> // NOLINT
94
95# if GTEST_OS_WINDOWS_MINGW
96// MinGW has gettimeofday() but not _ftime64().
97// TODO(kenton@google.com): Use autoconf to detect availability of
98// gettimeofday().
99// TODO(kenton@google.com): There are other ways to get the time on
100// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
101// supports these. consider using them instead.
102# define GTEST_HAS_GETTIMEOFDAY_ 1
103# include <sys/time.h> // NOLINT
104# endif // GTEST_OS_WINDOWS_MINGW
105
106// cpplint thinks that the header is already included, so we want to
107// silence it.
108# include <windows.h> // NOLINT
109# undef min
110
111#else
112
113// Assume other platforms have gettimeofday().
114// TODO(kenton@google.com): Use autoconf to detect availability of
115// gettimeofday().
116# define GTEST_HAS_GETTIMEOFDAY_ 1
117
118// cpplint thinks that the header is already included, so we want to
119// silence it.
120# include <sys/time.h> // NOLINT
121# include <unistd.h> // NOLINT
122
123#endif // GTEST_OS_LINUX
124
125#if GTEST_HAS_EXCEPTIONS
126# include <stdexcept>
127#endif
128
129#if GTEST_CAN_STREAM_RESULTS_
130# include <arpa/inet.h> // NOLINT
131# include <netdb.h> // NOLINT
132# include <sys/socket.h> // NOLINT
133# include <sys/types.h> // NOLINT
134#endif
135
137
138#if GTEST_OS_WINDOWS
139# define vsnprintf _vsnprintf
140#endif // GTEST_OS_WINDOWS
141
142namespace testing {
143
148
149// Constants.
150
151// A test whose test case name or test name matches this filter is
152// disabled and not run.
153static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
154
155// A test case whose name matches this filter is considered a death
156// test case and will be run before test cases whose name doesn't
157// match this filter.
158static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
159
160// A test filter that matches everything.
161static const char kUniversalFilter[] = "*";
162
163// The default output format.
164static const char kDefaultOutputFormat[] = "xml";
165// The default output file.
166static const char kDefaultOutputFile[] = "test_detail";
167
168// The environment variable name for the test shard index.
169static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
170// The environment variable name for the total number of test shards.
171static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
172// The environment variable name for the test shard status file.
173static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
174
175namespace internal {
176
177// The text used in failure messages to indicate the start of the
178// stack trace.
179const char kStackTraceMarker[] = "\nStack trace:\n";
180
181// g_help_flag is true iff the --help flag or an equivalent form is
182// specified on the command line.
183bool g_help_flag = false;
184
185} // namespace internal
186
187// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
188// environment variable.
189static const char* GetDefaultFilter() {
190 const char* const testbridge_test_only =
191 internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
192 if (testbridge_test_only != NULL) {
193 return testbridge_test_only;
194 }
195 return kUniversalFilter;
196}
197
199 also_run_disabled_tests,
200 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
201 "Run disabled tests too, in addition to the tests normally being run.");
202
204 break_on_failure,
205 internal::BoolFromGTestEnv("break_on_failure", false),
206 "True iff a failed assertion should be a debugger break-point.");
207
209 catch_exceptions,
210 internal::BoolFromGTestEnv("catch_exceptions", true),
211 "True iff " GTEST_NAME_
212 " should catch exceptions and treat them as test failures.");
213
215 color,
216 internal::StringFromGTestEnv("color", "auto"),
217 "Whether to use colors in the output. Valid values: yes, no, "
218 "and auto. 'auto' means to use colors if the output is "
219 "being sent to a terminal and the TERM environment variable "
220 "is set to a terminal type that supports colors.");
221
223 filter,
224 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
225 "A colon-separated list of glob (not regex) patterns "
226 "for filtering the tests to run, optionally followed by a "
227 "'-' and a : separated list of negative patterns (tests to "
228 "exclude). A test is run if it matches one of the positive "
229 "patterns and does not match any of the negative patterns.");
230
231GTEST_DEFINE_bool_(list_tests, false,
232 "List all tests without running them.");
233
234// The net priority order after flag processing is thus:
235// --gtest_output command line flag
236// GTEST_OUTPUT environment variable
237// XML_OUTPUT_FILE environment variable
238// ''
240 output,
243 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
244 "optionally followed by a colon and an output file name or directory. "
245 "A directory is indicated by a trailing pathname separator. "
246 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
247 "If a directory is specified, output files will be created "
248 "within that directory, with file-names based on the test "
249 "executable's name and, if necessary, made unique by adding "
250 "digits.");
251
253 print_time,
254 internal::BoolFromGTestEnv("print_time", true),
255 "True iff " GTEST_NAME_
256 " should display elapsed time in text output.");
257
259 print_utf8,
260 internal::BoolFromGTestEnv("print_utf8", true),
261 "True iff " GTEST_NAME_
262 " prints UTF8 characters as text.");
263
265 random_seed,
266 internal::Int32FromGTestEnv("random_seed", 0),
267 "Random number seed to use when shuffling test orders. Must be in range "
268 "[1, 99999], or 0 to use a seed based on the current time.");
269
271 repeat,
272 internal::Int32FromGTestEnv("repeat", 1),
273 "How many times to repeat each test. Specify a negative number "
274 "for repeating forever. Useful for shaking out flaky tests.");
275
277 show_internal_stack_frames, false,
278 "True iff " GTEST_NAME_ " should include internal stack frames when "
279 "printing test failure stack traces.");
280
282 shuffle,
283 internal::BoolFromGTestEnv("shuffle", false),
284 "True iff " GTEST_NAME_
285 " should randomize tests' order on every run.");
286
288 stack_trace_depth,
289 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
290 "The maximum number of stack frames to print when an "
291 "assertion fails. The valid range is 0 through 100, inclusive.");
292
294 stream_result_to,
295 internal::StringFromGTestEnv("stream_result_to", ""),
296 "This flag specifies the host name and the port number on which to stream "
297 "test results. Example: \"localhost:555\". The flag is effective only on "
298 "Linux.");
299
301 throw_on_failure,
302 internal::BoolFromGTestEnv("throw_on_failure", false),
303 "When this flag is specified, a failed assertion will throw an exception "
304 "if exceptions are enabled or exit the program with a non-zero code "
305 "otherwise. For use with an external test framework.");
306
307#if GTEST_USE_OWN_FLAGFILE_FLAG_
309 flagfile,
310 internal::StringFromGTestEnv("flagfile", ""),
311 "This flag specifies the flagfile to read command-line flags from.");
312#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
313
314namespace internal {
315
316// Generates a random number from [0, range), using a Linear
317// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
318// than kMaxRange.
320 // These constants are the same as are used in glibc's rand(3).
321 // Use wider types than necessary to prevent unsigned overflow diagnostics.
322 state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
323
324 GTEST_CHECK_(range > 0)
325 << "Cannot generate a number in the range [0, 0).";
326 GTEST_CHECK_(range <= kMaxRange)
327 << "Generation of a number in [0, " << range << ") was requested, "
328 << "but this can only generate numbers in [0, " << kMaxRange << ").";
329
330 // Converting via modulus introduces a bit of downward bias, but
331 // it's simple, and a linear congruential generator isn't too good
332 // to begin with.
333 return state_ % range;
334}
335
336// GTestIsInitialized() returns true iff the user has initialized
337// Google Test. Useful for catching the user mistake of not initializing
338// Google Test before calling RUN_ALL_TESTS().
339static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
340
341// Iterates over a vector of TestCases, keeping a running sum of the
342// results of calling a given int-returning method on each.
343// Returns the sum.
344static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
345 int (TestCase::*method)() const) {
346 int sum = 0;
347 for (size_t i = 0; i < case_list.size(); i++) {
348 sum += (case_list[i]->*method)();
349 }
350 return sum;
351}
352
353// Returns true iff the test case passed.
354static bool TestCasePassed(const TestCase* test_case) {
355 return test_case->should_run() && test_case->Passed();
356}
357
358// Returns true iff the test case failed.
359static bool TestCaseFailed(const TestCase* test_case) {
360 return test_case->should_run() && test_case->Failed();
361}
362
363// Returns true iff test_case contains at least one test that should
364// run.
365static bool ShouldRunTestCase(const TestCase* test_case) {
366 return test_case->should_run();
367}
368
369// AssertHelper constructor.
371 const char* file,
372 int line,
373 const char* message)
374 : data_(new AssertHelperData(type, file, line, message)) {
375}
376
378 delete data_;
379}
380
381// Message assignment, for assertion streaming support.
382void AssertHelper::operator=(const Message& message) const {
384 AddTestPartResult(data_->type, data_->file, data_->line,
385 AppendUserMessage(data_->message, message),
386 UnitTest::GetInstance()->impl()
388 // Skips the stack frame for this function itself.
389 ); // NOLINT
390}
391
392// Mutex for linked pointers.
394
395// A copy of all command line arguments. Set by InitGoogleTest().
396::std::vector<std::string> g_argvs;
397
398::std::vector<std::string> GetArgvs() {
399#if defined(GTEST_CUSTOM_GET_ARGVS_)
400 // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
401 // ::string. This code converts it to the appropriate type.
402 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
403 return ::std::vector<std::string>(custom.begin(), custom.end());
404#else // defined(GTEST_CUSTOM_GET_ARGVS_)
405 return g_argvs;
406#endif // defined(GTEST_CUSTOM_GET_ARGVS_)
407}
408
409// Returns the current application's name, removing directory path if that
410// is present.
412 FilePath result;
413
414#if GTEST_OS_WINDOWS
415 result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
416#else
417 result.Set(FilePath(GetArgvs()[0]));
418#endif // GTEST_OS_WINDOWS
419
420 return result.RemoveDirectoryName();
421}
422
423// Functions for processing the gtest_output flag.
424
425// Returns the output format, or "" for normal printed output.
427 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
428 if (gtest_output_flag == NULL) return std::string("");
429
430 const char* const colon = strchr(gtest_output_flag, ':');
431 return (colon == NULL) ?
432 std::string(gtest_output_flag) :
433 std::string(gtest_output_flag, colon - gtest_output_flag);
434}
435
436// Returns the name of the requested output file, or the default if none
437// was explicitly specified.
439 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
440 if (gtest_output_flag == NULL)
441 return "";
442
443 std::string format = GetOutputFormat();
444 if (format.empty())
445 format = std::string(kDefaultOutputFormat);
446
447 const char* const colon = strchr(gtest_output_flag, ':');
448 if (colon == NULL)
451 UnitTest::GetInstance()->original_working_dir()),
452 internal::FilePath(kDefaultOutputFile), 0,
453 format.c_str()).string();
454
455 internal::FilePath output_name(colon + 1);
456 if (!output_name.IsAbsolutePath())
457 // TODO(wan@google.com): on Windows \some\path is not an absolute
458 // path (as its meaning depends on the current drive), yet the
459 // following logic for turning it into an absolute path is wrong.
460 // Fix it.
462 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
463 internal::FilePath(colon + 1));
464
465 if (!output_name.IsDirectory())
466 return output_name.string();
467
470 GetOutputFormat().c_str()));
471 return result.string();
472}
473
474// Returns true iff the wildcard pattern matches the string. The
475// first ':' or '\0' character in pattern marks the end of it.
476//
477// This recursive algorithm isn't very efficient, but is clear and
478// works well enough for matching test names, which are short.
480 const char *str) {
481 switch (*pattern) {
482 case '\0':
483 case ':': // Either ':' or '\0' marks the end of the pattern.
484 return *str == '\0';
485 case '?': // Matches any single character.
486 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
487 case '*': // Matches any string (possibly empty) of characters.
488 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
489 PatternMatchesString(pattern + 1, str);
490 default: // Non-special character. Matches itself.
491 return *pattern == *str &&
492 PatternMatchesString(pattern + 1, str + 1);
493 }
494}
495
497 const std::string& name, const char* filter) {
498 const char *cur_pattern = filter;
499 for (;;) {
500 if (PatternMatchesString(cur_pattern, name.c_str())) {
501 return true;
502 }
503
504 // Finds the next pattern in the filter.
505 cur_pattern = strchr(cur_pattern, ':');
506
507 // Returns if no more pattern can be found.
508 if (cur_pattern == NULL) {
509 return false;
510 }
511
512 // Skips the pattern separater (the ':' character).
513 cur_pattern++;
514 }
515}
516
517// Returns true iff the user-specified filter matches the test case
518// name and the test name.
519bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
520 const std::string &test_name) {
521 const std::string& full_name = test_case_name + "." + test_name.c_str();
522
523 // Split --gtest_filter at '-', if there is one, to separate into
524 // positive filter and negative filter portions
525 const char* const p = GTEST_FLAG(filter).c_str();
526 const char* const dash = strchr(p, '-');
527 std::string positive;
528 std::string negative;
529 if (dash == NULL) {
530 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
531 negative = "";
532 } else {
533 positive = std::string(p, dash); // Everything up to the dash
534 negative = std::string(dash + 1); // Everything after the dash
535 if (positive.empty()) {
536 // Treat '-test1' as the same as '*-test1'
537 positive = kUniversalFilter;
538 }
539 }
540
541 // A filter is a colon-separated list of patterns. It matches a
542 // test if any pattern in it matches the test.
543 return (MatchesFilter(full_name, positive.c_str()) &&
544 !MatchesFilter(full_name, negative.c_str()));
545}
546
547#if GTEST_HAS_SEH
548// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
549// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
550// This function is useful as an __except condition.
551int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
552 // Google Test should handle a SEH exception if:
553 // 1. the user wants it to, AND
554 // 2. this is not a breakpoint exception, AND
555 // 3. this is not a C++ exception (VC++ implements them via SEH,
556 // apparently).
557 //
558 // SEH exception code for C++ exceptions.
559 // (see http://support.microsoft.com/kb/185294 for more information).
560 const DWORD kCxxExceptionCode = 0xe06d7363;
561
562 bool should_handle = true;
563
564 if (!GTEST_FLAG(catch_exceptions))
565 should_handle = false;
566 else if (exception_code == EXCEPTION_BREAKPOINT)
567 should_handle = false;
568 else if (exception_code == kCxxExceptionCode)
569 should_handle = false;
570
571 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
572}
573#endif // GTEST_HAS_SEH
574
575} // namespace internal
576
577// The c'tor sets this object as the test part result reporter used by
578// Google Test. The 'result' parameter specifies where to report the
579// results. Intercepts only failures from the current thread.
581 TestPartResultArray* result)
582 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
583 result_(result) {
584 Init();
585}
586
587// The c'tor sets this object as the test part result reporter used by
588// Google Test. The 'result' parameter specifies where to report the
589// results.
591 InterceptMode intercept_mode, TestPartResultArray* result)
592 : intercept_mode_(intercept_mode),
593 result_(result) {
594 Init();
595}
596
597void ScopedFakeTestPartResultReporter::Init() {
599 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
600 old_reporter_ = impl->GetGlobalTestPartResultReporter();
602 } else {
603 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
605 }
606}
607
608// The d'tor restores the test part result reporter used by Google Test
609// before.
618
619// Increments the test part result count and remembers the result.
620// This method is from the TestPartResultReporterInterface interface.
622 const TestPartResult& result) {
623 result_->Append(result);
624}
625
626namespace internal {
627
628// Returns the type ID of ::testing::Test. We should always call this
629// instead of GetTypeId< ::testing::Test>() to get the type ID of
630// testing::Test. This is to work around a suspected linker bug when
631// using Google Test as a framework on Mac OS X. The bug causes
632// GetTypeId< ::testing::Test>() to return different values depending
633// on whether the call is from the Google Test framework itself or
634// from user test code. GetTestTypeId() is guaranteed to always
635// return the same value, as it always calls GetTypeId<>() from the
636// gtest.cc, which is within the Google Test framework.
638 return GetTypeId<Test>();
639}
640
641// The value of GetTestTypeId() as seen from within the Google Test
642// library. This is solely for testing GetTestTypeId().
643extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
644
645// This predicate-formatter checks that 'results' contains a test part
646// failure of the given type and that the failure message contains the
647// given substring.
648static AssertionResult HasOneFailure(const char* /* results_expr */,
649 const char* /* type_expr */,
650 const char* /* substr_expr */,
653 const std::string& substr) {
654 const std::string expected(type == TestPartResult::kFatalFailure ?
655 "1 fatal failure" :
656 "1 non-fatal failure");
657 Message msg;
658 if (results.size() != 1) {
659 msg << "Expected: " << expected << "\n"
660 << " Actual: " << results.size() << " failures";
661 for (int i = 0; i < results.size(); i++) {
662 msg << "\n" << results.GetTestPartResult(i);
663 }
664 return AssertionFailure() << msg;
665 }
666
667 const TestPartResult& r = results.GetTestPartResult(0);
668 if (r.type() != type) {
669 return AssertionFailure() << "Expected: " << expected << "\n"
670 << " Actual:\n"
671 << r;
672 }
673
674 if (strstr(r.message(), substr.c_str()) == NULL) {
675 return AssertionFailure() << "Expected: " << expected << " containing \""
676 << substr << "\"\n"
677 << " Actual:\n"
678 << r;
679 }
680
681 return AssertionSuccess();
682}
683
684// The constructor of SingleFailureChecker remembers where to look up
685// test part results, what type of failure we expect, and what
686// substring the failure message should contain.
689 const std::string& substr)
690 : results_(results), type_(type), substr_(substr) {}
691
692// The destructor of SingleFailureChecker verifies that the given
693// TestPartResultArray contains exactly one failure that has the given
694// type and contains the given substring. If that's not the case, a
695// non-fatal failure will be generated.
697 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
698}
699
702
704 const TestPartResult& result) {
705 unit_test_->current_test_result()->AddTestPartResult(result);
706 unit_test_->listeners()->repeater()->OnTestPartResult(result);
707}
708
711
716
717// Returns the global test part result reporter.
720 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
721 return global_test_part_result_repoter_;
722}
723
724// Sets the global test part result reporter.
727 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
728 global_test_part_result_repoter_ = reporter;
729}
730
731// Returns the test part result reporter for the current thread.
734 return per_thread_test_part_result_reporter_.get();
735}
736
737// Sets the test part result reporter for the current thread.
740 per_thread_test_part_result_reporter_.set(reporter);
741}
742
743// Gets the number of successful test cases.
745 return CountIf(test_cases_, TestCasePassed);
746}
747
748// Gets the number of failed test cases.
750 return CountIf(test_cases_, TestCaseFailed);
751}
752
753// Gets the number of all test cases.
755 return static_cast<int>(test_cases_.size());
756}
757
758// Gets the number of all test cases that contain at least one test
759// that should run.
761 return CountIf(test_cases_, ShouldRunTestCase);
762}
763
764// Gets the number of successful tests.
766 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
767}
768
769// Gets the number of failed tests.
771 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
772}
773
774// Gets the number of disabled tests that will be reported in the XML report.
776 return SumOverTestCaseList(test_cases_,
778}
779
780// Gets the number of disabled tests.
782 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
783}
784
785// Gets the number of tests to be printed in the XML report.
787 return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
788}
789
790// Gets the number of all tests.
792 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
793}
794
795// Gets the number of tests that should run.
797 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
798}
799
800// Returns the current OS stack trace as an std::string.
801//
802// The maximum number of stack frames to be included is specified by
803// the gtest_stack_trace_depth flag. The skip_count parameter
804// specifies the number of top frames to be skipped, which doesn't
805// count against the number of frames to be included.
806//
807// For example, if Foo() calls Bar(), which in turn calls
808// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
809// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
812 static_cast<int>(GTEST_FLAG(stack_trace_depth)),
813 skip_count + 1
814 // Skips the user-specified number of frames plus this function
815 // itself.
816 ); // NOLINT
817}
818
819// Returns the current time in milliseconds.
821#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
822 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
823 // http://analogous.blogspot.com/2005/04/epoch.html
824 const TimeInMillis kJavaEpochToWinFileTimeDelta =
825 static_cast<TimeInMillis>(116444736UL) * 100000UL;
826 const DWORD kTenthMicrosInMilliSecond = 10000;
827
828 SYSTEMTIME now_systime;
829 FILETIME now_filetime;
830 ULARGE_INTEGER now_int64;
831 // TODO(kenton@google.com): Shouldn't this just use
832 // GetSystemTimeAsFileTime()?
833 GetSystemTime(&now_systime);
834 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
835 now_int64.LowPart = now_filetime.dwLowDateTime;
836 now_int64.HighPart = now_filetime.dwHighDateTime;
837 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
838 kJavaEpochToWinFileTimeDelta;
839 return now_int64.QuadPart;
840 }
841 return 0;
842#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
843 __timeb64 now;
844
845 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
846 // (deprecated function) there.
847 // TODO(kenton@google.com): Use GetTickCount()? Or use
848 // SystemTimeToFileTime()
850 _ftime64(&now);
852
853 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
854#elif GTEST_HAS_GETTIMEOFDAY_
855 struct timeval now;
856 gettimeofday(&now, NULL);
857 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
858#else
859# error "Don't know how to get the current time on your system."
860#endif
861}
862
863// Utilities
864
865// class String.
866
867#if GTEST_OS_WINDOWS_MOBILE
868// Creates a UTF-16 wide string from the given ANSI string, allocating
869// memory using new. The caller is responsible for deleting the return
870// value using delete[]. Returns the wide string, or NULL if the
871// input is NULL.
872LPCWSTR String::AnsiToUtf16(const char* ansi) {
873 if (!ansi) return NULL;
874 const int length = strlen(ansi);
875 const int unicode_length =
876 MultiByteToWideChar(CP_ACP, 0, ansi, length,
877 NULL, 0);
878 WCHAR* unicode = new WCHAR[unicode_length + 1];
879 MultiByteToWideChar(CP_ACP, 0, ansi, length,
880 unicode, unicode_length);
881 unicode[unicode_length] = 0;
882 return unicode;
883}
884
885// Creates an ANSI string from the given wide string, allocating
886// memory using new. The caller is responsible for deleting the return
887// value using delete[]. Returns the ANSI string, or NULL if the
888// input is NULL.
889const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
890 if (!utf16_str) return NULL;
891 const int ansi_length =
892 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
893 NULL, 0, NULL, NULL);
894 char* ansi = new char[ansi_length + 1];
895 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
896 ansi, ansi_length, NULL, NULL);
897 ansi[ansi_length] = 0;
898 return ansi;
899}
900
901#endif // GTEST_OS_WINDOWS_MOBILE
902
903// Compares two C strings. Returns true iff they have the same content.
904//
905// Unlike strcmp(), this function can handle NULL argument(s). A NULL
906// C string is considered different to any non-NULL C string,
907// including the empty string.
908bool String::CStringEquals(const char * lhs, const char * rhs) {
909 if ( lhs == NULL ) return rhs == NULL;
910
911 if ( rhs == NULL ) return false;
912
913 return strcmp(lhs, rhs) == 0;
914}
915
916#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
917
918// Converts an array of wide chars to a narrow string using the UTF-8
919// encoding, and streams the result to the given Message object.
920static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
921 Message* msg) {
922 for (size_t i = 0; i != length; ) { // NOLINT
923 if (wstr[i] != L'\0') {
924 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
925 while (i != length && wstr[i] != L'\0')
926 i++;
927 } else {
928 *msg << '\0';
929 i++;
930 }
931 }
932}
933
934#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
935
936void SplitString(const ::std::string& str, char delimiter,
937 ::std::vector< ::std::string>* dest) {
938 ::std::vector< ::std::string> parsed;
939 ::std::string::size_type pos = 0;
941 const ::std::string::size_type colon = str.find(delimiter, pos);
942 if (colon == ::std::string::npos) {
943 parsed.push_back(str.substr(pos));
944 break;
945 } else {
946 parsed.push_back(str.substr(pos, colon - pos));
947 pos = colon + 1;
948 }
949 }
950 dest->swap(parsed);
951}
952
953} // namespace internal
954
955// Constructs an empty Message.
956// We allocate the stringstream separately because otherwise each use of
957// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
958// stack frame leading to huge stack frames in some cases; gcc does not reuse
959// the stack space.
960Message::Message() : ss_(new ::std::stringstream) {
961 // By default, we want there to be enough precision when printing
962 // a double to a Message.
963 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
964}
965
966// These two overloads allow streaming a wide C string to a Message
967// using the UTF-8 encoding.
968Message& Message::operator <<(const wchar_t* wide_c_str) {
969 return *this << internal::String::ShowWideCString(wide_c_str);
970}
971Message& Message::operator <<(wchar_t* wide_c_str) {
972 return *this << internal::String::ShowWideCString(wide_c_str);
973}
974
975#if GTEST_HAS_STD_WSTRING
976// Converts the given wide string to a narrow string using the UTF-8
977// encoding, and streams the result to this Message object.
978Message& Message::operator <<(const ::std::wstring& wstr) {
979 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
980 return *this;
981}
982#endif // GTEST_HAS_STD_WSTRING
983
984#if GTEST_HAS_GLOBAL_WSTRING
985// Converts the given wide string to a narrow string using the UTF-8
986// encoding, and streams the result to this Message object.
987Message& Message::operator <<(const ::wstring& wstr) {
988 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
989 return *this;
990}
991#endif // GTEST_HAS_GLOBAL_WSTRING
992
993// Gets the text streamed to this object so far as an std::string.
994// Each '\0' character in the buffer is replaced with "\\0".
995std::string Message::GetString() const {
997}
998
999// AssertionResult constructors.
1000// Used in EXPECT_TRUE/FALSE(assertion_result).
1002 : success_(other.success_),
1003 message_(other.message_.get() != NULL ?
1004 new ::std::string(*other.message_) :
1005 static_cast< ::std::string*>(NULL)) {
1006}
1007
1008// Swaps two AssertionResults.
1009void AssertionResult::swap(AssertionResult& other) {
1010 using std::swap;
1011 swap(success_, other.success_);
1012 swap(message_, other.message_);
1013}
1014
1015// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
1017 AssertionResult negation(!success_);
1018 if (message_.get() != NULL)
1019 negation << *message_;
1020 return negation;
1021}
1022
1023// Makes a successful assertion result.
1027
1028// Makes a failed assertion result.
1032
1033// Makes a failed assertion result with the given failure message.
1034// Deprecated; use AssertionFailure() << message.
1036 return AssertionFailure() << message;
1037}
1038
1039namespace internal {
1040
1041namespace edit_distance {
1042std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
1043 const std::vector<size_t>& right) {
1044 std::vector<std::vector<double> > costs(
1045 left.size() + 1, std::vector<double>(right.size() + 1));
1046 std::vector<std::vector<EditType> > best_move(
1047 left.size() + 1, std::vector<EditType>(right.size() + 1));
1048
1049 // Populate for empty right.
1050 for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
1051 costs[l_i][0] = static_cast<double>(l_i);
1052 best_move[l_i][0] = kRemove;
1053 }
1054 // Populate for empty left.
1055 for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1056 costs[0][r_i] = static_cast<double>(r_i);
1057 best_move[0][r_i] = kAdd;
1058 }
1059
1060 for (size_t l_i = 0; l_i < left.size(); ++l_i) {
1061 for (size_t r_i = 0; r_i < right.size(); ++r_i) {
1062 if (left[l_i] == right[r_i]) {
1063 // Found a match. Consume it.
1064 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1065 best_move[l_i + 1][r_i + 1] = kMatch;
1066 continue;
1067 }
1068
1069 const double add = costs[l_i + 1][r_i];
1070 const double remove = costs[l_i][r_i + 1];
1071 const double replace = costs[l_i][r_i];
1072 if (add < remove && add < replace) {
1073 costs[l_i + 1][r_i + 1] = add + 1;
1074 best_move[l_i + 1][r_i + 1] = kAdd;
1075 } else if (remove < add && remove < replace) {
1076 costs[l_i + 1][r_i + 1] = remove + 1;
1077 best_move[l_i + 1][r_i + 1] = kRemove;
1078 } else {
1079 // We make replace a little more expensive than add/remove to lower
1080 // their priority.
1081 costs[l_i + 1][r_i + 1] = replace + 1.00001;
1082 best_move[l_i + 1][r_i + 1] = kReplace;
1083 }
1084 }
1085 }
1086
1087 // Reconstruct the best path. We do it in reverse order.
1088 std::vector<EditType> best_path;
1089 for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1090 EditType move = best_move[l_i][r_i];
1091 best_path.push_back(move);
1092 l_i -= move != kAdd;
1093 r_i -= move != kRemove;
1094 }
1095 std::reverse(best_path.begin(), best_path.end());
1096 return best_path;
1097}
1098
1099namespace {
1100
1101// Helper class to convert string into ids with deduplication.
1102class InternalStrings {
1103 public:
1104 size_t GetId(const std::string& str) {
1105 IdMap::iterator it = ids_.find(str);
1106 if (it != ids_.end()) return it->second;
1107 size_t id = ids_.size();
1108 return ids_[str] = id;
1109 }
1110
1111 private:
1112 typedef std::map<std::string, size_t> IdMap;
1113 IdMap ids_;
1114};
1115
1116} // namespace
1117
1118std::vector<EditType> CalculateOptimalEdits(
1119 const std::vector<std::string>& left,
1120 const std::vector<std::string>& right) {
1121 std::vector<size_t> left_ids, right_ids;
1122 {
1123 InternalStrings intern_table;
1124 for (size_t i = 0; i < left.size(); ++i) {
1125 left_ids.push_back(intern_table.GetId(left[i]));
1126 }
1127 for (size_t i = 0; i < right.size(); ++i) {
1128 right_ids.push_back(intern_table.GetId(right[i]));
1129 }
1130 }
1131 return CalculateOptimalEdits(left_ids, right_ids);
1132}
1133
1134namespace {
1135
1136// Helper class that holds the state for one hunk and prints it out to the
1137// stream.
1138// It reorders adds/removes when possible to group all removes before all
1139// adds. It also adds the hunk header before printint into the stream.
1140class Hunk {
1141 public:
1142 Hunk(size_t left_start, size_t right_start)
1143 : left_start_(left_start),
1144 right_start_(right_start),
1145 adds_(),
1146 removes_(),
1147 common_() {}
1148
1149 void PushLine(char edit, const char* line) {
1150 switch (edit) {
1151 case ' ':
1152 ++common_;
1153 FlushEdits();
1154 hunk_.push_back(std::make_pair(' ', line));
1155 break;
1156 case '-':
1157 ++removes_;
1158 hunk_removes_.push_back(std::make_pair('-', line));
1159 break;
1160 case '+':
1161 ++adds_;
1162 hunk_adds_.push_back(std::make_pair('+', line));
1163 break;
1164 }
1165 }
1166
1167 void PrintTo(std::ostream* os) {
1168 PrintHeader(os);
1169 FlushEdits();
1170 for (std::list<std::pair<char, const char*> >::const_iterator it =
1171 hunk_.begin();
1172 it != hunk_.end(); ++it) {
1173 *os << it->first << it->second << "\n";
1174 }
1175 }
1176
1177 bool has_edits() const { return adds_ || removes_; }
1178
1179 private:
1180 void FlushEdits() {
1181 hunk_.splice(hunk_.end(), hunk_removes_);
1182 hunk_.splice(hunk_.end(), hunk_adds_);
1183 }
1184
1185 // Print a unified diff header for one hunk.
1186 // The format is
1187 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1188 // where the left/right parts are omitted if unnecessary.
1189 void PrintHeader(std::ostream* ss) const {
1190 *ss << "@@ ";
1191 if (removes_) {
1192 *ss << "-" << left_start_ << "," << (removes_ + common_);
1193 }
1194 if (removes_ && adds_) {
1195 *ss << " ";
1196 }
1197 if (adds_) {
1198 *ss << "+" << right_start_ << "," << (adds_ + common_);
1199 }
1200 *ss << " @@\n";
1201 }
1202
1203 size_t left_start_, right_start_;
1204 size_t adds_, removes_, common_;
1205 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1206};
1207
1208} // namespace
1209
1210// Create a list of diff hunks in Unified diff format.
1211// Each hunk has a header generated by PrintHeader above plus a body with
1212// lines prefixed with ' ' for no change, '-' for deletion and '+' for
1213// addition.
1214// 'context' represents the desired unchanged prefix/suffix around the diff.
1215// If two hunks are close enough that their contexts overlap, then they are
1216// joined into one hunk.
1217std::string CreateUnifiedDiff(const std::vector<std::string>& left,
1218 const std::vector<std::string>& right,
1219 size_t context) {
1220 const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
1221
1222 size_t l_i = 0, r_i = 0, edit_i = 0;
1223 std::stringstream ss;
1224 while (edit_i < edits.size()) {
1225 // Find first edit.
1226 while (edit_i < edits.size() && edits[edit_i] == kMatch) {
1227 ++l_i;
1228 ++r_i;
1229 ++edit_i;
1230 }
1231
1232 // Find the first line to include in the hunk.
1233 const size_t prefix_context = std::min(l_i, context);
1234 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1235 for (size_t i = prefix_context; i > 0; --i) {
1236 hunk.PushLine(' ', left[l_i - i].c_str());
1237 }
1238
1239 // Iterate the edits until we found enough suffix for the hunk or the input
1240 // is over.
1241 size_t n_suffix = 0;
1242 for (; edit_i < edits.size(); ++edit_i) {
1243 if (n_suffix >= context) {
1244 // Continue only if the next hunk is very close.
1245 std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
1246 while (it != edits.end() && *it == kMatch) ++it;
1247 if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
1248 // There is no next edit or it is too far away.
1249 break;
1250 }
1251 }
1252
1253 EditType edit = edits[edit_i];
1254 // Reset count when a non match is found.
1255 n_suffix = edit == kMatch ? n_suffix + 1 : 0;
1256
1257 if (edit == kMatch || edit == kRemove || edit == kReplace) {
1258 hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
1259 }
1260 if (edit == kAdd || edit == kReplace) {
1261 hunk.PushLine('+', right[r_i].c_str());
1262 }
1263
1264 // Advance indices, depending on edit type.
1265 l_i += edit != kAdd;
1266 r_i += edit != kRemove;
1267 }
1268
1269 if (!hunk.has_edits()) {
1270 // We are done. We don't want this hunk.
1271 break;
1272 }
1273
1274 hunk.PrintTo(&ss);
1275 }
1276 return ss.str();
1277}
1278
1279} // namespace edit_distance
1280
1281namespace {
1282
1283// The string representation of the values received in EqFailure() are already
1284// escaped. Split them on escaped '\n' boundaries. Leave all other escaped
1285// characters the same.
1286std::vector<std::string> SplitEscapedString(const std::string& str) {
1287 std::vector<std::string> lines;
1288 size_t start = 0, end = str.size();
1289 if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
1290 ++start;
1291 --end;
1292 }
1293 bool escaped = false;
1294 for (size_t i = start; i + 1 < end; ++i) {
1295 if (escaped) {
1296 escaped = false;
1297 if (str[i] == 'n') {
1298 lines.push_back(str.substr(start, i - start - 1));
1299 start = i + 1;
1300 }
1301 } else {
1302 escaped = str[i] == '\\';
1303 }
1304 }
1305 lines.push_back(str.substr(start, end - start));
1306 return lines;
1307}
1308
1309} // namespace
1310
1311// Constructs and returns the message for an equality assertion
1312// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1313//
1314// The first four parameters are the expressions used in the assertion
1315// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
1316// where foo is 5 and bar is 6, we have:
1317//
1318// lhs_expression: "foo"
1319// rhs_expression: "bar"
1320// lhs_value: "5"
1321// rhs_value: "6"
1322//
1323// The ignoring_case parameter is true iff the assertion is a
1324// *_STRCASEEQ*. When it's true, the string "Ignoring case" will
1325// be inserted into the message.
1326AssertionResult EqFailure(const char* lhs_expression,
1327 const char* rhs_expression,
1328 const std::string& lhs_value,
1329 const std::string& rhs_value,
1330 bool ignoring_case) {
1331 Message msg;
1332 msg << "Expected equality of these values:";
1333 msg << "\n " << lhs_expression;
1334 if (lhs_value != lhs_expression) {
1335 msg << "\n Which is: " << lhs_value;
1336 }
1337 msg << "\n " << rhs_expression;
1338 if (rhs_value != rhs_expression) {
1339 msg << "\n Which is: " << rhs_value;
1340 }
1341
1342 if (ignoring_case) {
1343 msg << "\nIgnoring case";
1344 }
1345
1346 if (!lhs_value.empty() && !rhs_value.empty()) {
1347 const std::vector<std::string> lhs_lines =
1348 SplitEscapedString(lhs_value);
1349 const std::vector<std::string> rhs_lines =
1350 SplitEscapedString(rhs_value);
1351 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1352 msg << "\nWith diff:\n"
1353 << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
1354 }
1355 }
1356
1357 return AssertionFailure() << msg;
1358}
1359
1360// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1362 const AssertionResult& assertion_result,
1363 const char* expression_text,
1364 const char* actual_predicate_value,
1365 const char* expected_predicate_value) {
1366 const char* actual_message = assertion_result.message();
1367 Message msg;
1368 msg << "Value of: " << expression_text
1369 << "\n Actual: " << actual_predicate_value;
1370 if (actual_message[0] != '\0')
1371 msg << " (" << actual_message << ")";
1372 msg << "\nExpected: " << expected_predicate_value;
1373 return msg.GetString();
1374}
1375
1376// Helper function for implementing ASSERT_NEAR.
1378 const char* expr2,
1379 const char* abs_error_expr,
1380 double val1,
1381 double val2,
1382 double abs_error) {
1383 const double diff = fabs(val1 - val2);
1384 if (diff <= abs_error) return AssertionSuccess();
1385
1386 // TODO(wan): do not print the value of an expression if it's
1387 // already a literal.
1388 return AssertionFailure()
1389 << "The difference between " << expr1 << " and " << expr2
1390 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1391 << expr1 << " evaluates to " << val1 << ",\n"
1392 << expr2 << " evaluates to " << val2 << ", and\n"
1393 << abs_error_expr << " evaluates to " << abs_error << ".";
1394}
1395
1396
1397// Helper template for implementing FloatLE() and DoubleLE().
1398template <typename RawType>
1400 const char* expr2,
1401 RawType val1,
1402 RawType val2) {
1403 // Returns success if val1 is less than val2,
1404 if (val1 < val2) {
1405 return AssertionSuccess();
1406 }
1407
1408 // or if val1 is almost equal to val2.
1409 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1410 if (lhs.AlmostEquals(rhs)) {
1411 return AssertionSuccess();
1412 }
1413
1414 // Note that the above two checks will both fail if either val1 or
1415 // val2 is NaN, as the IEEE floating-point standard requires that
1416 // any predicate involving a NaN must return false.
1417
1418 ::std::stringstream val1_ss;
1419 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1420 << val1;
1421
1422 ::std::stringstream val2_ss;
1423 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1424 << val2;
1425
1426 return AssertionFailure()
1427 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1428 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
1429 << StringStreamToString(&val2_ss);
1430}
1431
1432} // namespace internal
1433
1434// Asserts that val1 is less than, or almost equal to, val2. Fails
1435// otherwise. In particular, it fails if either val1 or val2 is NaN.
1436AssertionResult FloatLE(const char* expr1, const char* expr2,
1437 float val1, float val2) {
1438 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1439}
1440
1441// Asserts that val1 is less than, or almost equal to, val2. Fails
1442// otherwise. In particular, it fails if either val1 or val2 is NaN.
1443AssertionResult DoubleLE(const char* expr1, const char* expr2,
1444 double val1, double val2) {
1445 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1446}
1447
1448namespace internal {
1449
1450// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1451// arguments.
1452AssertionResult CmpHelperEQ(const char* lhs_expression,
1453 const char* rhs_expression,
1454 BiggestInt lhs,
1455 BiggestInt rhs) {
1456 if (lhs == rhs) {
1457 return AssertionSuccess();
1458 }
1459
1460 return EqFailure(lhs_expression,
1461 rhs_expression,
1464 false);
1465}
1466
1467// A macro for implementing the helper functions needed to implement
1468// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1469// just to avoid copy-and-paste of similar code.
1470#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1471AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1472 BiggestInt val1, BiggestInt val2) {\
1473 if (val1 op val2) {\
1474 return AssertionSuccess();\
1475 } else {\
1476 return AssertionFailure() \
1477 << "Expected: (" << expr1 << ") " #op " (" << expr2\
1478 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1479 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1480 }\
1481}
1482
1483// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1484// enum arguments.
1486// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1487// enum arguments.
1489// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1490// enum arguments.
1492// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1493// enum arguments.
1495// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1496// enum arguments.
1498
1499#undef GTEST_IMPL_CMP_HELPER_
1500
1501// The helper function for {ASSERT|EXPECT}_STREQ.
1502AssertionResult CmpHelperSTREQ(const char* lhs_expression,
1503 const char* rhs_expression,
1504 const char* lhs,
1505 const char* rhs) {
1506 if (String::CStringEquals(lhs, rhs)) {
1507 return AssertionSuccess();
1508 }
1509
1510 return EqFailure(lhs_expression,
1511 rhs_expression,
1512 PrintToString(lhs),
1513 PrintToString(rhs),
1514 false);
1515}
1516
1517// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1518AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
1519 const char* rhs_expression,
1520 const char* lhs,
1521 const char* rhs) {
1523 return AssertionSuccess();
1524 }
1525
1526 return EqFailure(lhs_expression,
1527 rhs_expression,
1528 PrintToString(lhs),
1529 PrintToString(rhs),
1530 true);
1531}
1532
1533// The helper function for {ASSERT|EXPECT}_STRNE.
1534AssertionResult CmpHelperSTRNE(const char* s1_expression,
1535 const char* s2_expression,
1536 const char* s1,
1537 const char* s2) {
1538 if (!String::CStringEquals(s1, s2)) {
1539 return AssertionSuccess();
1540 } else {
1541 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1542 << s2_expression << "), actual: \""
1543 << s1 << "\" vs \"" << s2 << "\"";
1544 }
1545}
1546
1547// The helper function for {ASSERT|EXPECT}_STRCASENE.
1548AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1549 const char* s2_expression,
1550 const char* s1,
1551 const char* s2) {
1553 return AssertionSuccess();
1554 } else {
1555 return AssertionFailure()
1556 << "Expected: (" << s1_expression << ") != ("
1557 << s2_expression << ") (ignoring case), actual: \""
1558 << s1 << "\" vs \"" << s2 << "\"";
1559 }
1560}
1561
1562} // namespace internal
1563
1564namespace {
1565
1566// Helper functions for implementing IsSubString() and IsNotSubstring().
1567
1568// This group of overloaded functions return true iff needle is a
1569// substring of haystack. NULL is considered a substring of itself
1570// only.
1571
1572bool IsSubstringPred(const char* needle, const char* haystack) {
1573 if (needle == NULL || haystack == NULL)
1574 return needle == haystack;
1575
1576 return strstr(haystack, needle) != NULL;
1577}
1578
1579bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1580 if (needle == NULL || haystack == NULL)
1581 return needle == haystack;
1582
1583 return wcsstr(haystack, needle) != NULL;
1584}
1585
1586// StringType here can be either ::std::string or ::std::wstring.
1587template <typename StringType>
1588bool IsSubstringPred(const StringType& needle,
1589 const StringType& haystack) {
1590 return haystack.find(needle) != StringType::npos;
1591}
1592
1593// This function implements either IsSubstring() or IsNotSubstring(),
1594// depending on the value of the expected_to_be_substring parameter.
1595// StringType here can be const char*, const wchar_t*, ::std::string,
1596// or ::std::wstring.
1597template <typename StringType>
1598AssertionResult IsSubstringImpl(
1599 bool expected_to_be_substring,
1600 const char* needle_expr, const char* haystack_expr,
1601 const StringType& needle, const StringType& haystack) {
1602 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1603 return AssertionSuccess();
1604
1605 const bool is_wide_string = sizeof(needle[0]) > 1;
1606 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1607 return AssertionFailure()
1608 << "Value of: " << needle_expr << "\n"
1609 << " Actual: " << begin_string_quote << needle << "\"\n"
1610 << "Expected: " << (expected_to_be_substring ? "" : "not ")
1611 << "a substring of " << haystack_expr << "\n"
1612 << "Which is: " << begin_string_quote << haystack << "\"";
1613}
1614
1615} // namespace
1616
1617// IsSubstring() and IsNotSubstring() check whether needle is a
1618// substring of haystack (NULL is considered a substring of itself
1619// only), and return an appropriate error message when they fail.
1620
1622 const char* needle_expr, const char* haystack_expr,
1623 const char* needle, const char* haystack) {
1624 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1625}
1626
1628 const char* needle_expr, const char* haystack_expr,
1629 const wchar_t* needle, const wchar_t* haystack) {
1630 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1631}
1632
1634 const char* needle_expr, const char* haystack_expr,
1635 const char* needle, const char* haystack) {
1636 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1637}
1638
1640 const char* needle_expr, const char* haystack_expr,
1641 const wchar_t* needle, const wchar_t* haystack) {
1642 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1643}
1644
1646 const char* needle_expr, const char* haystack_expr,
1647 const ::std::string& needle, const ::std::string& haystack) {
1648 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1649}
1650
1652 const char* needle_expr, const char* haystack_expr,
1653 const ::std::string& needle, const ::std::string& haystack) {
1654 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1655}
1656
1657#if GTEST_HAS_STD_WSTRING
1658AssertionResult IsSubstring(
1659 const char* needle_expr, const char* haystack_expr,
1660 const ::std::wstring& needle, const ::std::wstring& haystack) {
1661 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1662}
1663
1664AssertionResult IsNotSubstring(
1665 const char* needle_expr, const char* haystack_expr,
1666 const ::std::wstring& needle, const ::std::wstring& haystack) {
1667 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1668}
1669#endif // GTEST_HAS_STD_WSTRING
1670
1671namespace internal {
1672
1673#if GTEST_OS_WINDOWS
1674
1675namespace {
1676
1677// Helper function for IsHRESULT{SuccessFailure} predicates
1678AssertionResult HRESULTFailureHelper(const char* expr,
1679 const char* expected,
1680 long hr) { // NOLINT
1681# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
1682
1683 // Windows CE doesn't support FormatMessage.
1684 const char error_text[] = "";
1685
1686# else
1687
1688 // Looks up the human-readable system message for the HRESULT code
1689 // and since we're not passing any params to FormatMessage, we don't
1690 // want inserts expanded.
1691 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1692 FORMAT_MESSAGE_IGNORE_INSERTS;
1693 const DWORD kBufSize = 4096;
1694 // Gets the system's human readable message string for this HRESULT.
1695 char error_text[kBufSize] = { '\0' };
1696 DWORD message_length = ::FormatMessageA(kFlags,
1697 0, // no source, we're asking system
1698 hr, // the error
1699 0, // no line width restrictions
1700 error_text, // output buffer
1701 kBufSize, // buf size
1702 NULL); // no arguments for inserts
1703 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
1704 for (; message_length && IsSpace(error_text[message_length - 1]);
1705 --message_length) {
1706 error_text[message_length - 1] = '\0';
1707 }
1708
1709# endif // GTEST_OS_WINDOWS_MOBILE
1710
1711 const std::string error_hex("0x" + String::FormatHexInt(hr));
1712 return ::testing::AssertionFailure()
1713 << "Expected: " << expr << " " << expected << ".\n"
1714 << " Actual: " << error_hex << " " << error_text << "\n";
1715}
1716
1717} // namespace
1718
1719AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1720 if (SUCCEEDED(hr)) {
1721 return AssertionSuccess();
1722 }
1723 return HRESULTFailureHelper(expr, "succeeds", hr);
1724}
1725
1726AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1727 if (FAILED(hr)) {
1728 return AssertionSuccess();
1729 }
1730 return HRESULTFailureHelper(expr, "fails", hr);
1731}
1732
1733#endif // GTEST_OS_WINDOWS
1734
1735// Utility functions for encoding Unicode text (wide strings) in
1736// UTF-8.
1737
1738// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
1739// like this:
1740//
1741// Code-point length Encoding
1742// 0 - 7 bits 0xxxxxxx
1743// 8 - 11 bits 110xxxxx 10xxxxxx
1744// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1745// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1746
1747// The maximum code-point a one-byte UTF-8 sequence can represent.
1748const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1749
1750// The maximum code-point a two-byte UTF-8 sequence can represent.
1751const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1752
1753// The maximum code-point a three-byte UTF-8 sequence can represent.
1754const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1755
1756// The maximum code-point a four-byte UTF-8 sequence can represent.
1757const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1758
1759// Chops off the n lowest bits from a bit pattern. Returns the n
1760// lowest bits. As a side effect, the original bit pattern will be
1761// shifted to the right by n bits.
1762inline UInt32 ChopLowBits(UInt32* bits, int n) {
1763 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1764 *bits >>= n;
1765 return low_bits;
1766}
1767
1768// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1769// code_point parameter is of type UInt32 because wchar_t may not be
1770// wide enough to contain a code point.
1771// If the code_point is not a valid Unicode code point
1772// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
1773// to "(Invalid Unicode 0xXXXXXXXX)".
1774std::string CodePointToUtf8(UInt32 code_point) {
1775 if (code_point > kMaxCodePoint4) {
1776 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
1777 }
1778
1779 char str[5]; // Big enough for the largest valid code point.
1780 if (code_point <= kMaxCodePoint1) {
1781 str[1] = '\0';
1782 str[0] = static_cast<char>(code_point); // 0xxxxxxx
1783 } else if (code_point <= kMaxCodePoint2) {
1784 str[2] = '\0';
1785 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1786 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1787 } else if (code_point <= kMaxCodePoint3) {
1788 str[3] = '\0';
1789 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1790 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1791 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1792 } else { // code_point <= kMaxCodePoint4
1793 str[4] = '\0';
1794 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1795 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1796 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1797 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1798 }
1799 return str;
1800}
1801
1802// The following two functions only make sense if the system
1803// uses UTF-16 for wide string encoding. All supported systems
1804// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1805
1806// Determines if the arguments constitute UTF-16 surrogate pair
1807// and thus should be combined into a single Unicode code point
1808// using CreateCodePointFromUtf16SurrogatePair.
1809inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1810 return sizeof(wchar_t) == 2 &&
1811 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1812}
1813
1814// Creates a Unicode code point from UTF16 surrogate pair.
1816 wchar_t second) {
1817 const UInt32 mask = (1 << 10) - 1;
1818 return (sizeof(wchar_t) == 2) ?
1819 (((first & mask) << 10) | (second & mask)) + 0x10000 :
1820 // This function should not be called when the condition is
1821 // false, but we provide a sensible default in case it is.
1822 static_cast<UInt32>(first);
1823}
1824
1825// Converts a wide string to a narrow string in UTF-8 encoding.
1826// The wide string is assumed to have the following encoding:
1827// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1828// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1829// Parameter str points to a null-terminated wide string.
1830// Parameter num_chars may additionally limit the number
1831// of wchar_t characters processed. -1 is used when the entire string
1832// should be processed.
1833// If the string contains code points that are not valid Unicode code points
1834// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1835// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1836// and contains invalid UTF-16 surrogate pairs, values in those pairs
1837// will be encoded as individual Unicode characters from Basic Normal Plane.
1838std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
1839 if (num_chars == -1)
1840 num_chars = static_cast<int>(wcslen(str));
1841
1842 ::std::stringstream stream;
1843 for (int i = 0; i < num_chars; ++i) {
1844 UInt32 unicode_code_point;
1845
1846 if (str[i] == L'\0') {
1847 break;
1848 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1849 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1850 str[i + 1]);
1851 i++;
1852 } else {
1853 unicode_code_point = static_cast<UInt32>(str[i]);
1854 }
1855
1856 stream << CodePointToUtf8(unicode_code_point);
1857 }
1858 return StringStreamToString(&stream);
1859}
1860
1861// Converts a wide C string to an std::string using the UTF-8 encoding.
1862// NULL will be converted to "(null)".
1863std::string String::ShowWideCString(const wchar_t * wide_c_str) {
1864 if (wide_c_str == NULL) return "(null)";
1865
1866 return internal::WideStringToUtf8(wide_c_str, -1);
1867}
1868
1869// Compares two wide C strings. Returns true iff they have the same
1870// content.
1871//
1872// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1873// C string is considered different to any non-NULL C string,
1874// including the empty string.
1875bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1876 if (lhs == NULL) return rhs == NULL;
1877
1878 if (rhs == NULL) return false;
1879
1880 return wcscmp(lhs, rhs) == 0;
1881}
1882
1883// Helper function for *_STREQ on wide strings.
1884AssertionResult CmpHelperSTREQ(const char* lhs_expression,
1885 const char* rhs_expression,
1886 const wchar_t* lhs,
1887 const wchar_t* rhs) {
1888 if (String::WideCStringEquals(lhs, rhs)) {
1889 return AssertionSuccess();
1890 }
1891
1892 return EqFailure(lhs_expression,
1893 rhs_expression,
1894 PrintToString(lhs),
1895 PrintToString(rhs),
1896 false);
1897}
1898
1899// Helper function for *_STRNE on wide strings.
1900AssertionResult CmpHelperSTRNE(const char* s1_expression,
1901 const char* s2_expression,
1902 const wchar_t* s1,
1903 const wchar_t* s2) {
1904 if (!String::WideCStringEquals(s1, s2)) {
1905 return AssertionSuccess();
1906 }
1907
1908 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1909 << s2_expression << "), actual: "
1910 << PrintToString(s1)
1911 << " vs " << PrintToString(s2);
1912}
1913
1914// Compares two C strings, ignoring case. Returns true iff they have
1915// the same content.
1916//
1917// Unlike strcasecmp(), this function can handle NULL argument(s). A
1918// NULL C string is considered different to any non-NULL C string,
1919// including the empty string.
1920bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1921 if (lhs == NULL)
1922 return rhs == NULL;
1923 if (rhs == NULL)
1924 return false;
1925 return posix::StrCaseCmp(lhs, rhs) == 0;
1926}
1927
1928 // Compares two wide C strings, ignoring case. Returns true iff they
1929 // have the same content.
1930 //
1931 // Unlike wcscasecmp(), this function can handle NULL argument(s).
1932 // A NULL C string is considered different to any non-NULL wide C string,
1933 // including the empty string.
1934 // NB: The implementations on different platforms slightly differ.
1935 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1936 // environment variable. On GNU platform this method uses wcscasecmp
1937 // which compares according to LC_CTYPE category of the current locale.
1938 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1939 // current locale.
1941 const wchar_t* rhs) {
1942 if (lhs == NULL) return rhs == NULL;
1943
1944 if (rhs == NULL) return false;
1945
1946#if GTEST_OS_WINDOWS
1947 return _wcsicmp(lhs, rhs) == 0;
1948#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
1949 return wcscasecmp(lhs, rhs) == 0;
1950#else
1951 // Android, Mac OS X and Cygwin don't define wcscasecmp.
1952 // Other unknown OSes may not define it either.
1953 wint_t left, right;
1954 do {
1955 left = towlower(*lhs++);
1956 right = towlower(*rhs++);
1957 } while (left && left == right);
1958 return left == right;
1959#endif // OS selector
1960}
1961
1962// Returns true iff str ends with the given suffix, ignoring case.
1963// Any string is considered to end with an empty suffix.
1965 const std::string& str, const std::string& suffix) {
1966 const size_t str_len = str.length();
1967 const size_t suffix_len = suffix.length();
1968 return (str_len >= suffix_len) &&
1969 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
1970 suffix.c_str());
1971}
1972
1973// Formats an int value as "%02d".
1975 std::stringstream ss;
1976 ss << std::setfill('0') << std::setw(2) << value;
1977 return ss.str();
1978}
1979
1980// Formats an int value as "%X".
1981std::string String::FormatHexInt(int value) {
1982 std::stringstream ss;
1983 ss << std::hex << std::uppercase << value;
1984 return ss.str();
1985}
1986
1987// Formats a byte as "%02X".
1988std::string String::FormatByte(unsigned char value) {
1989 std::stringstream ss;
1990 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
1991 << static_cast<unsigned int>(value);
1992 return ss.str();
1993}
1994
1995// Converts the buffer in a stringstream to an std::string, converting NUL
1996// bytes to "\\0" along the way.
1997std::string StringStreamToString(::std::stringstream* ss) {
1998 const ::std::string& str = ss->str();
1999 const char* const start = str.c_str();
2000 const char* const end = start + str.length();
2001
2002 std::string result;
2003 result.reserve(2 * (end - start));
2004 for (const char* ch = start; ch != end; ++ch) {
2005 if (*ch == '\0') {
2006 result += "\\0"; // Replaces NUL with "\\0";
2007 } else {
2008 result += *ch;
2009 }
2010 }
2011
2012 return result;
2013}
2014
2015// Appends the user-supplied message to the Google-Test-generated message.
2016std::string AppendUserMessage(const std::string& gtest_msg,
2017 const Message& user_msg) {
2018 // Appends the user message if it's non-empty.
2019 const std::string user_msg_string = user_msg.GetString();
2020 if (user_msg_string.empty()) {
2021 return gtest_msg;
2022 }
2023
2024 return gtest_msg + "\n" + user_msg_string;
2025}
2026
2027} // namespace internal
2028
2029// class TestResult
2030
2031// Creates an empty TestResult.
2033 : death_test_count_(0),
2034 elapsed_time_(0) {
2035}
2036
2037// D'tor.
2040
2041// Returns the i-th test part result among all the results. i can
2042// range from 0 to total_part_count() - 1. If i is not in that range,
2043// aborts the program.
2045 if (i < 0 || i >= total_part_count())
2047 return test_part_results_.at(i);
2048}
2049
2050// Returns the i-th test property. i can range from 0 to
2051// test_property_count() - 1. If i is not in that range, aborts the
2052// program.
2054 if (i < 0 || i >= test_property_count())
2056 return test_properties_.at(i);
2057}
2058
2059// Clears the test part results.
2060void TestResult::ClearTestPartResults() {
2061 test_part_results_.clear();
2062}
2063
2064// Adds a test part result to the list.
2065void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
2066 test_part_results_.push_back(test_part_result);
2067}
2068
2069// Adds a test property to the list. If a property with the same key as the
2070// supplied property is already represented, the value of this test_property
2071// replaces the old value for that key.
2072void TestResult::RecordProperty(const std::string& xml_element,
2073 const TestProperty& test_property) {
2074 if (!ValidateTestProperty(xml_element, test_property)) {
2075 return;
2076 }
2077 internal::MutexLock lock(&test_properites_mutex_);
2078 const std::vector<TestProperty>::iterator property_with_matching_key =
2079 std::find_if(test_properties_.begin(), test_properties_.end(),
2080 internal::TestPropertyKeyIs(test_property.key()));
2081 if (property_with_matching_key == test_properties_.end()) {
2082 test_properties_.push_back(test_property);
2083 return;
2084 }
2085 property_with_matching_key->SetValue(test_property.value());
2086}
2087
2088// The list of reserved attributes used in the <testsuites> element of XML
2089// output.
2090static const char* const kReservedTestSuitesAttributes[] = {
2091 "disabled",
2092 "errors",
2093 "failures",
2094 "name",
2095 "random_seed",
2096 "tests",
2097 "time",
2098 "timestamp"
2099};
2100
2101// The list of reserved attributes used in the <testsuite> element of XML
2102// output.
2103static const char* const kReservedTestSuiteAttributes[] = {
2104 "disabled",
2105 "errors",
2106 "failures",
2107 "name",
2108 "tests",
2109 "time"
2110};
2111
2112// The list of reserved attributes used in the <testcase> element of XML output.
2113static const char* const kReservedTestCaseAttributes[] = {
2114 "classname",
2115 "name",
2116 "status",
2117 "time",
2118 "type_param",
2119 "value_param"
2120};
2121
2122template <int kSize>
2123std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
2124 return std::vector<std::string>(array, array + kSize);
2125}
2126
2127static std::vector<std::string> GetReservedAttributesForElement(
2128 const std::string& xml_element) {
2129 if (xml_element == "testsuites") {
2130 return ArrayAsVector(kReservedTestSuitesAttributes);
2131 } else if (xml_element == "testsuite") {
2132 return ArrayAsVector(kReservedTestSuiteAttributes);
2133 } else if (xml_element == "testcase") {
2134 return ArrayAsVector(kReservedTestCaseAttributes);
2135 } else {
2136 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2137 }
2138 // This code is unreachable but some compilers may not realizes that.
2139 return std::vector<std::string>();
2140}
2141
2142static std::string FormatWordList(const std::vector<std::string>& words) {
2143 Message word_list;
2144 for (size_t i = 0; i < words.size(); ++i) {
2145 if (i > 0 && words.size() > 2) {
2146 word_list << ", ";
2147 }
2148 if (i == words.size() - 1) {
2149 word_list << "and ";
2150 }
2151 word_list << "'" << words[i] << "'";
2152 }
2153 return word_list.GetString();
2154}
2155
2156static bool ValidateTestPropertyName(
2157 const std::string& property_name,
2158 const std::vector<std::string>& reserved_names) {
2159 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2160 reserved_names.end()) {
2161 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
2162 << " (" << FormatWordList(reserved_names)
2163 << " are reserved by " << GTEST_NAME_ << ")";
2164 return false;
2165 }
2166 return true;
2167}
2168
2169// Adds a failure if the key is a reserved attribute of the element named
2170// xml_element. Returns true if the property is valid.
2171bool TestResult::ValidateTestProperty(const std::string& xml_element,
2172 const TestProperty& test_property) {
2173 return ValidateTestPropertyName(test_property.key(),
2174 GetReservedAttributesForElement(xml_element));
2175}
2176
2177// Clears the object.
2178void TestResult::Clear() {
2179 test_part_results_.clear();
2180 test_properties_.clear();
2181 death_test_count_ = 0;
2182 elapsed_time_ = 0;
2183}
2184
2185// Returns true iff the test failed.
2187 for (int i = 0; i < total_part_count(); ++i) {
2188 if (GetTestPartResult(i).failed())
2189 return true;
2190 }
2191 return false;
2192}
2193
2194// Returns true iff the test part fatally failed.
2195static bool TestPartFatallyFailed(const TestPartResult& result) {
2196 return result.fatally_failed();
2197}
2198
2199// Returns true iff the test fatally failed.
2201 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
2202}
2203
2204// Returns true iff the test part non-fatally failed.
2205static bool TestPartNonfatallyFailed(const TestPartResult& result) {
2206 return result.nonfatally_failed();
2207}
2208
2209// Returns true iff the test has a non-fatal failure.
2211 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
2212}
2213
2214// Gets the number of all test parts. This is the sum of the number
2215// of successful test parts and the number of failed test parts.
2217 return static_cast<int>(test_part_results_.size());
2218}
2219
2220// Returns the number of the test properties.
2222 return static_cast<int>(test_properties_.size());
2223}
2224
2225// class Test
2226
2227// Creates a Test object.
2228
2229// The c'tor saves the states of all flags.
2231 : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
2232}
2233
2234// The d'tor restores the states of all flags. The actual work is
2235// done by the d'tor of the gtest_flag_saver_ field, and thus not
2236// visible here.
2238}
2239
2240// Sets up the test fixture.
2241//
2242// A sub-class may override this.
2244}
2245
2246// Tears down the test fixture.
2247//
2248// A sub-class may override this.
2250}
2251
2252// Allows user supplied key value pairs to be recorded for later output.
2253void Test::RecordProperty(const std::string& key, const std::string& value) {
2254 UnitTest::GetInstance()->RecordProperty(key, value);
2255}
2256
2257// Allows user supplied key value pairs to be recorded for later output.
2258void Test::RecordProperty(const std::string& key, int value) {
2259 Message value_message;
2260 value_message << value;
2261 RecordProperty(key, value_message.GetString().c_str());
2262}
2263
2264namespace internal {
2265
2267 const std::string& message) {
2268 // This function is a friend of UnitTest and as such has access to
2269 // AddTestPartResult.
2270 UnitTest::GetInstance()->AddTestPartResult(
2271 result_type,
2272 NULL, // No info about the source file where the exception occurred.
2273 -1, // We have no info on which line caused the exception.
2274 message,
2275 ""); // No stack trace, either.
2276}
2277
2278} // namespace internal
2279
2280// Google Test requires all tests in the same test case to use the same test
2281// fixture class. This function checks if the current test has the
2282// same fixture class as the first test in the current test case. If
2283// yes, it returns true; otherwise it generates a Google Test failure and
2284// returns false.
2285bool Test::HasSameFixtureClass() {
2286 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2287 const TestCase* const test_case = impl->current_test_case();
2288
2289 // Info about the first test in the current test case.
2290 const TestInfo* const first_test_info = test_case->test_info_list()[0];
2291 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2292 const char* const first_test_name = first_test_info->name();
2293
2294 // Info about the current test.
2295 const TestInfo* const this_test_info = impl->current_test_info();
2296 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2297 const char* const this_test_name = this_test_info->name();
2298
2299 if (this_fixture_id != first_fixture_id) {
2300 // Is the first test defined using TEST?
2301 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2302 // Is this test defined using TEST?
2303 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2304
2305 if (first_is_TEST || this_is_TEST) {
2306 // Both TEST and TEST_F appear in same test case, which is incorrect.
2307 // Tell the user how to fix this.
2308
2309 // Gets the name of the TEST and the name of the TEST_F. Note
2310 // that first_is_TEST and this_is_TEST cannot both be true, as
2311 // the fixture IDs are different for the two tests.
2312 const char* const TEST_name =
2313 first_is_TEST ? first_test_name : this_test_name;
2314 const char* const TEST_F_name =
2315 first_is_TEST ? this_test_name : first_test_name;
2316
2317 ADD_FAILURE()
2318 << "All tests in the same test case must use the same test fixture\n"
2319 << "class, so mixing TEST_F and TEST in the same test case is\n"
2320 << "illegal. In test case " << this_test_info->test_case_name()
2321 << ",\n"
2322 << "test " << TEST_F_name << " is defined using TEST_F but\n"
2323 << "test " << TEST_name << " is defined using TEST. You probably\n"
2324 << "want to change the TEST to TEST_F or move it to another test\n"
2325 << "case.";
2326 } else {
2327 // Two fixture classes with the same name appear in two different
2328 // namespaces, which is not allowed. Tell the user how to fix this.
2329 ADD_FAILURE()
2330 << "All tests in the same test case must use the same test fixture\n"
2331 << "class. However, in test case "
2332 << this_test_info->test_case_name() << ",\n"
2333 << "you defined test " << first_test_name
2334 << " and test " << this_test_name << "\n"
2335 << "using two different test fixture classes. This can happen if\n"
2336 << "the two classes are from different namespaces or translation\n"
2337 << "units and have the same name. You should probably rename one\n"
2338 << "of the classes to put the tests into different test cases.";
2339 }
2340 return false;
2341 }
2342
2343 return true;
2344}
2345
2346#if GTEST_HAS_SEH
2347
2348// Adds an "exception thrown" fatal failure to the current test. This
2349// function returns its result via an output parameter pointer because VC++
2350// prohibits creation of objects with destructors on stack in functions
2351// using __try (see error C2712).
2352static std::string* FormatSehExceptionMessage(DWORD exception_code,
2353 const char* location) {
2354 Message message;
2355 message << "SEH exception with code 0x" << std::setbase(16) <<
2356 exception_code << std::setbase(10) << " thrown in " << location << ".";
2357
2358 return new std::string(message.GetString());
2359}
2360
2361#endif // GTEST_HAS_SEH
2362
2363namespace internal {
2364
2365#if GTEST_HAS_EXCEPTIONS
2366
2367// Adds an "exception thrown" fatal failure to the current test.
2368static std::string FormatCxxExceptionMessage(const char* description,
2369 const char* location) {
2370 Message message;
2371 if (description != NULL) {
2372 message << "C++ exception with description \"" << description << "\"";
2373 } else {
2374 message << "Unknown C++ exception";
2375 }
2376 message << " thrown in " << location << ".";
2377
2378 return message.GetString();
2379}
2380
2381static std::string PrintTestPartResultToString(
2382 const TestPartResult& test_part_result);
2383
2384GoogleTestFailureException::GoogleTestFailureException(
2385 const TestPartResult& failure)
2386 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
2387
2388#endif // GTEST_HAS_EXCEPTIONS
2389
2390// We put these helper functions in the internal namespace as IBM's xlC
2391// compiler rejects the code if they were declared static.
2392
2393// Runs the given method and handles SEH exceptions it throws, when
2394// SEH is supported; returns the 0-value for type Result in case of an
2395// SEH exception. (Microsoft compilers cannot handle SEH and C++
2396// exceptions in the same function. Therefore, we provide a separate
2397// wrapper function for handling SEH exceptions.)
2398template <class T, typename Result>
2400 T* object, Result (T::*method)(), const char* location) {
2401#if GTEST_HAS_SEH
2402 __try {
2403 return (object->*method)();
2404 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
2405 GetExceptionCode())) {
2406 // We create the exception message on the heap because VC++ prohibits
2407 // creation of objects with destructors on stack in functions using __try
2408 // (see error C2712).
2409 std::string* exception_message = FormatSehExceptionMessage(
2410 GetExceptionCode(), location);
2412 *exception_message);
2413 delete exception_message;
2414 return static_cast<Result>(0);
2415 }
2416#else
2417 (void)location;
2418 return (object->*method)();
2419#endif // GTEST_HAS_SEH
2420}
2421
2422// Runs the given method and catches and reports C++ and/or SEH-style
2423// exceptions, if they are supported; returns the 0-value for type
2424// Result in case of an SEH exception.
2425template <class T, typename Result>
2427 T* object, Result (T::*method)(), const char* location) {
2428 // NOTE: The user code can affect the way in which Google Test handles
2429 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2430 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
2431 // after the exception is caught and either report or re-throw the
2432 // exception based on the flag's value:
2433 //
2434 // try {
2435 // // Perform the test method.
2436 // } catch (...) {
2437 // if (GTEST_FLAG(catch_exceptions))
2438 // // Report the exception as failure.
2439 // else
2440 // throw; // Re-throws the original exception.
2441 // }
2442 //
2443 // However, the purpose of this flag is to allow the program to drop into
2444 // the debugger when the exception is thrown. On most platforms, once the
2445 // control enters the catch block, the exception origin information is
2446 // lost and the debugger will stop the program at the point of the
2447 // re-throw in this function -- instead of at the point of the original
2448 // throw statement in the code under test. For this reason, we perform
2449 // the check early, sacrificing the ability to affect Google Test's
2450 // exception handling in the method where the exception is thrown.
2451 if (internal::GetUnitTestImpl()->catch_exceptions()) {
2452#if GTEST_HAS_EXCEPTIONS
2453 try {
2454 return HandleSehExceptionsInMethodIfSupported(object, method, location);
2455 } catch (const AssertionException&) { // NOLINT
2456 // This failure was reported already.
2457 } catch (const internal::GoogleTestFailureException&) { // NOLINT
2458 // This exception type can only be thrown by a failed Google
2459 // Test assertion with the intention of letting another testing
2460 // framework catch it. Therefore we just re-throw it.
2461 throw;
2462 } catch (const std::exception& e) { // NOLINT
2465 FormatCxxExceptionMessage(e.what(), location));
2466 } catch (...) { // NOLINT
2469 FormatCxxExceptionMessage(NULL, location));
2470 }
2471 return static_cast<Result>(0);
2472#else
2473 return HandleSehExceptionsInMethodIfSupported(object, method, location);
2474#endif // GTEST_HAS_EXCEPTIONS
2475 } else {
2476 return (object->*method)();
2477 }
2478}
2479
2480} // namespace internal
2481
2482// Runs the test and updates the test result.
2483void Test::Run() {
2484 if (!HasSameFixtureClass()) return;
2485
2486 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2487 impl->os_stack_trace_getter()->UponLeavingGTest();
2488 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2489 // We will run the test only if SetUp() was successful.
2490 if (!HasFatalFailure()) {
2491 impl->os_stack_trace_getter()->UponLeavingGTest();
2492 internal::HandleExceptionsInMethodIfSupported(
2493 this, &Test::TestBody, "the test body");
2494 }
2495
2496 // However, we want to clean up as much as possible. Hence we will
2497 // always call TearDown(), even if SetUp() or the test body has
2498 // failed.
2499 impl->os_stack_trace_getter()->UponLeavingGTest();
2500 internal::HandleExceptionsInMethodIfSupported(
2501 this, &Test::TearDown, "TearDown()");
2502}
2503
2504// Returns true iff the current test has a fatal failure.
2505bool Test::HasFatalFailure() {
2506 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2507}
2508
2509// Returns true iff the current test has a non-fatal failure.
2510bool Test::HasNonfatalFailure() {
2511 return internal::GetUnitTestImpl()->current_test_result()->
2512 HasNonfatalFailure();
2513}
2514
2515// class TestInfo
2516
2517// Constructs a TestInfo object. It assumes ownership of the test factory
2518// object.
2519TestInfo::TestInfo(const std::string& a_test_case_name,
2520 const std::string& a_name,
2521 const char* a_type_param,
2522 const char* a_value_param,
2523 internal::CodeLocation a_code_location,
2524 internal::TypeId fixture_class_id,
2526 : test_case_name_(a_test_case_name),
2527 name_(a_name),
2528 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2529 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
2530 location_(a_code_location),
2531 fixture_class_id_(fixture_class_id),
2532 should_run_(false),
2533 is_disabled_(false),
2534 matches_filter_(false),
2535 factory_(factory),
2536 result_() {}
2537
2538// Destructs a TestInfo object.
2539TestInfo::~TestInfo() { delete factory_; }
2540
2541namespace internal {
2542
2543// Creates a new TestInfo object and registers it with Google Test;
2544// returns the created object.
2545//
2546// Arguments:
2547//
2548// test_case_name: name of the test case
2549// name: name of the test
2550// type_param: the name of the test's type parameter, or NULL if
2551// this is not a typed or a type-parameterized test.
2552// value_param: text representation of the test's value parameter,
2553// or NULL if this is not a value-parameterized test.
2554// code_location: code location where the test is defined
2555// fixture_class_id: ID of the test fixture class
2556// set_up_tc: pointer to the function that sets up the test case
2557// tear_down_tc: pointer to the function that tears down the test case
2558// factory: pointer to the factory that creates a test object.
2559// The newly created TestInfo instance will assume
2560// ownership of the factory object.
2562 const char* test_case_name,
2563 const char* name,
2564 const char* type_param,
2565 const char* value_param,
2566 CodeLocation code_location,
2567 TypeId fixture_class_id,
2568 SetUpTestCaseFunc set_up_tc,
2569 TearDownTestCaseFunc tear_down_tc,
2570 TestFactoryBase* factory) {
2571 TestInfo* const test_info =
2572 new TestInfo(test_case_name, name, type_param, value_param,
2573 code_location, fixture_class_id, factory);
2574 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2575 return test_info;
2576}
2577
2578void ReportInvalidTestCaseType(const char* test_case_name,
2579 CodeLocation code_location) {
2580 Message errors;
2581 errors
2582 << "Attempted redefinition of test case " << test_case_name << ".\n"
2583 << "All tests in the same test case must use the same test fixture\n"
2584 << "class. However, in test case " << test_case_name << ", you tried\n"
2585 << "to define a test using a fixture class different from the one\n"
2586 << "used earlier. This can happen if the two fixture classes are\n"
2587 << "from different namespaces and have the same name. You should\n"
2588 << "probably rename one of the classes to put the tests into different\n"
2589 << "test cases.";
2590
2591 GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
2592 code_location.line)
2593 << " " << errors.GetString();
2594}
2595} // namespace internal
2596
2597namespace {
2598
2599// A predicate that checks the test name of a TestInfo against a known
2600// value.
2601//
2602// This is used for implementation of the TestCase class only. We put
2603// it in the anonymous namespace to prevent polluting the outer
2604// namespace.
2605//
2606// TestNameIs is copyable.
2607class TestNameIs {
2608 public:
2609 // Constructor.
2610 //
2611 // TestNameIs has NO default constructor.
2612 explicit TestNameIs(const char* name)
2613 : name_(name) {}
2614
2615 // Returns true iff the test name of test_info matches name_.
2616 bool operator()(const TestInfo * test_info) const {
2617 return test_info && test_info->name() == name_;
2618 }
2619
2620 private:
2621 std::string name_;
2622};
2623
2624} // namespace
2625
2626namespace internal {
2627
2628// This method expands all parameterized tests registered with macros TEST_P
2629// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2630// This will be done just once during the program runtime.
2632 if (!parameterized_tests_registered_) {
2633 parameterized_test_registry_.RegisterTests();
2634 parameterized_tests_registered_ = true;
2635 }
2636}
2637
2638} // namespace internal
2639
2640// Creates the test object, runs it, records its result, and then
2641// deletes it.
2642void TestInfo::Run() {
2643 if (!should_run_) return;
2644
2645 // Tells UnitTest where to store test result.
2647 impl->set_current_test_info(this);
2648
2649 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2650
2651 // Notifies the unit test event listeners that a test is about to start.
2652 repeater->OnTestStart(*this);
2653
2655
2657
2658 // Creates the test object.
2661 "the test fixture's constructor");
2662
2663 // Runs the test only if the test object was created and its
2664 // constructor didn't generate a fatal failure.
2665 if ((test != NULL) && !Test::HasFatalFailure()) {
2666 // This doesn't throw as all user code that can throw are wrapped into
2667 // exception handling code.
2668 test->Run();
2669 }
2670
2671 // Deletes the test object.
2674 test, &Test::DeleteSelf_, "the test fixture's destructor");
2675
2676 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
2677
2678 // Notifies the unit test event listener that a test has just finished.
2679 repeater->OnTestEnd(*this);
2680
2681 // Tells UnitTest to stop associating assertion results to this
2682 // test.
2683 impl->set_current_test_info(NULL);
2684}
2685
2686// class TestCase
2687
2688// Gets the number of successful tests in this test case.
2690 return CountIf(test_info_list_, TestPassed);
2691}
2692
2693// Gets the number of failed tests in this test case.
2695 return CountIf(test_info_list_, TestFailed);
2696}
2697
2698// Gets the number of disabled tests that will be reported in the XML report.
2700 return CountIf(test_info_list_, TestReportableDisabled);
2701}
2702
2703// Gets the number of disabled tests in this test case.
2705 return CountIf(test_info_list_, TestDisabled);
2706}
2707
2708// Gets the number of tests to be printed in the XML report.
2710 return CountIf(test_info_list_, TestReportable);
2711}
2712
2713// Get the number of tests in this test case that should run.
2715 return CountIf(test_info_list_, ShouldRunTest);
2716}
2717
2718// Gets the number of all tests.
2720 return static_cast<int>(test_info_list_.size());
2721}
2722
2723// Creates a TestCase with the given name.
2724//
2725// Arguments:
2726//
2727// name: name of the test case
2728// a_type_param: the name of the test case's type parameter, or NULL if
2729// this is not a typed or a type-parameterized test case.
2730// set_up_tc: pointer to the function that sets up the test case
2731// tear_down_tc: pointer to the function that tears down the test case
2732TestCase::TestCase(const char* a_name, const char* a_type_param,
2733 Test::SetUpTestCaseFunc set_up_tc,
2734 Test::TearDownTestCaseFunc tear_down_tc)
2735 : name_(a_name),
2736 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2737 set_up_tc_(set_up_tc),
2738 tear_down_tc_(tear_down_tc),
2739 should_run_(false),
2740 elapsed_time_(0) {
2741}
2742
2743// Destructor of TestCase.
2745 // Deletes every Test in the collection.
2746 ForEach(test_info_list_, internal::Delete<TestInfo>);
2747}
2748
2749// Returns the i-th test among all the tests. i can range from 0 to
2750// total_test_count() - 1. If i is not in that range, returns NULL.
2751const TestInfo* TestCase::GetTestInfo(int i) const {
2752 const int index = GetElementOr(test_indices_, i, -1);
2753 return index < 0 ? NULL : test_info_list_[index];
2754}
2755
2756// Returns the i-th test among all the tests. i can range from 0 to
2757// total_test_count() - 1. If i is not in that range, returns NULL.
2758TestInfo* TestCase::GetMutableTestInfo(int i) {
2759 const int index = GetElementOr(test_indices_, i, -1);
2760 return index < 0 ? NULL : test_info_list_[index];
2761}
2762
2763// Adds a test to this test case. Will delete the test upon
2764// destruction of the TestCase object.
2765void TestCase::AddTestInfo(TestInfo * test_info) {
2766 test_info_list_.push_back(test_info);
2767 test_indices_.push_back(static_cast<int>(test_indices_.size()));
2768}
2769
2770// Runs every test in this TestCase.
2771void TestCase::Run() {
2772 if (!should_run_) return;
2773
2775 impl->set_current_test_case(this);
2776
2777 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2778
2779 repeater->OnTestCaseStart(*this);
2780 impl->os_stack_trace_getter()->UponLeavingGTest();
2782 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
2783
2785 for (int i = 0; i < total_test_count(); i++) {
2786 GetMutableTestInfo(i)->Run();
2787 }
2788 elapsed_time_ = internal::GetTimeInMillis() - start;
2789
2790 impl->os_stack_trace_getter()->UponLeavingGTest();
2792 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
2793
2794 repeater->OnTestCaseEnd(*this);
2795 impl->set_current_test_case(NULL);
2796}
2797
2798// Clears the results of all tests in this test case.
2799void TestCase::ClearResult() {
2800 ad_hoc_test_result_.Clear();
2801 ForEach(test_info_list_, TestInfo::ClearTestResult);
2802}
2803
2804// Shuffles the tests in this test case.
2805void TestCase::ShuffleTests(internal::Random* random) {
2806 Shuffle(random, &test_indices_);
2807}
2808
2809// Restores the test order to before the first shuffle.
2810void TestCase::UnshuffleTests() {
2811 for (size_t i = 0; i < test_indices_.size(); i++) {
2812 test_indices_[i] = static_cast<int>(i);
2813 }
2814}
2815
2816// Formats a countable noun. Depending on its quantity, either the
2817// singular form or the plural form is used. e.g.
2818//
2819// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2820// FormatCountableNoun(5, "book", "books") returns "5 books".
2821static std::string FormatCountableNoun(int count,
2822 const char * singular_form,
2823 const char * plural_form) {
2824 return internal::StreamableToString(count) + " " +
2825 (count == 1 ? singular_form : plural_form);
2826}
2827
2828// Formats the count of tests.
2829static std::string FormatTestCount(int test_count) {
2830 return FormatCountableNoun(test_count, "test", "tests");
2831}
2832
2833// Formats the count of test cases.
2834static std::string FormatTestCaseCount(int test_case_count) {
2835 return FormatCountableNoun(test_case_count, "test case", "test cases");
2836}
2837
2838// Converts a TestPartResult::Type enum to human-friendly string
2839// representation. Both kNonFatalFailure and kFatalFailure are translated
2840// to "Failure", as the user usually doesn't care about the difference
2841// between the two when viewing the test result.
2842static const char * TestPartResultTypeToString(TestPartResult::Type type) {
2843 switch (type) {
2845 return "Success";
2846
2849#ifdef _MSC_VER
2850 return "error: ";
2851#else
2852 return "Failure\n";
2853#endif
2854 default:
2855 return "Unknown result type";
2856 }
2857}
2858
2859namespace internal {
2860
2861// Prints a TestPartResult to an std::string.
2862static std::string PrintTestPartResultToString(
2863 const TestPartResult& test_part_result) {
2864 return (Message()
2865 << internal::FormatFileLocation(test_part_result.file_name(),
2866 test_part_result.line_number())
2867 << " " << TestPartResultTypeToString(test_part_result.type())
2868 << test_part_result.message()).GetString();
2869}
2870
2871// Prints a TestPartResult.
2872static void PrintTestPartResult(const TestPartResult& test_part_result) {
2873 const std::string& result =
2874 PrintTestPartResultToString(test_part_result);
2875 printf("%s\n", result.c_str());
2876 fflush(stdout);
2877 // If the test program runs in Visual Studio or a debugger, the
2878 // following statements add the test part result message to the Output
2879 // window such that the user can double-click on it to jump to the
2880 // corresponding source code location; otherwise they do nothing.
2881#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2882 // We don't call OutputDebugString*() on Windows Mobile, as printing
2883 // to stdout is done by OutputDebugString() there already - we don't
2884 // want the same message printed twice.
2885 ::OutputDebugStringA(result.c_str());
2886 ::OutputDebugStringA("\n");
2887#endif
2888}
2889
2890// class PrettyUnitTestResultPrinter
2891
2898
2899#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
2900 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
2901
2902// Returns the character attribute for the given color.
2903static WORD GetColorAttribute(GTestColor color) {
2904 switch (color) {
2905 case COLOR_RED: return FOREGROUND_RED;
2906 case COLOR_GREEN: return FOREGROUND_GREEN;
2907 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2908 default: return 0;
2909 }
2910}
2911
2912static int GetBitOffset(WORD color_mask) {
2913 if (color_mask == 0) return 0;
2914
2915 int bitOffset = 0;
2916 while ((color_mask & 1) == 0) {
2917 color_mask >>= 1;
2918 ++bitOffset;
2919 }
2920 return bitOffset;
2921}
2922
2923static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
2924 // Let's reuse the BG
2925 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
2926 BACKGROUND_RED | BACKGROUND_INTENSITY;
2927 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
2928 FOREGROUND_RED | FOREGROUND_INTENSITY;
2929 const WORD existing_bg = old_color_attrs & background_mask;
2930
2931 WORD new_color =
2932 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
2933 static const int bg_bitOffset = GetBitOffset(background_mask);
2934 static const int fg_bitOffset = GetBitOffset(foreground_mask);
2935
2936 if (((new_color & background_mask) >> bg_bitOffset) ==
2937 ((new_color & foreground_mask) >> fg_bitOffset)) {
2938 new_color ^= FOREGROUND_INTENSITY; // invert intensity
2939 }
2940 return new_color;
2941}
2942
2943#else
2944
2945// Returns the ANSI color code for the given color. COLOR_DEFAULT is
2946// an invalid input.
2947static const char* GetAnsiColorCode(GTestColor color) {
2948 switch (color) {
2949 case COLOR_RED: return "1";
2950 case COLOR_GREEN: return "2";
2951 case COLOR_YELLOW: return "3";
2952 default: return NULL;
2953 };
2954}
2955
2956#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2957
2958// Returns true iff Google Test should use colors in the output.
2959bool ShouldUseColor(bool stdout_is_tty) {
2960 const char* const gtest_color = GTEST_FLAG(color).c_str();
2961
2962 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2963#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2964 // On Windows the TERM variable is usually not set, but the
2965 // console there does support colors.
2966 return stdout_is_tty;
2967#else
2968 // On non-Windows platforms, we rely on the TERM variable.
2969 const char* const term = posix::GetEnv("TERM");
2970 const bool term_supports_color =
2971 String::CStringEquals(term, "xterm") ||
2972 String::CStringEquals(term, "xterm-color") ||
2973 String::CStringEquals(term, "xterm-256color") ||
2974 String::CStringEquals(term, "screen") ||
2975 String::CStringEquals(term, "screen-256color") ||
2976 String::CStringEquals(term, "tmux") ||
2977 String::CStringEquals(term, "tmux-256color") ||
2978 String::CStringEquals(term, "rxvt-unicode") ||
2979 String::CStringEquals(term, "rxvt-unicode-256color") ||
2980 String::CStringEquals(term, "linux") ||
2981 String::CStringEquals(term, "cygwin");
2982 return stdout_is_tty && term_supports_color;
2983#endif // GTEST_OS_WINDOWS
2984 }
2985
2986 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2987 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2988 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2989 String::CStringEquals(gtest_color, "1");
2990 // We take "yes", "true", "t", and "1" as meaning "yes". If the
2991 // value is neither one of these nor "auto", we treat it as "no" to
2992 // be conservative.
2993}
2994
2995// Helpers for printing colored strings to stdout. Note that on Windows, we
2996// cannot simply emit special characters and have the terminal change colors.
2997// This routine must actually emit the characters rather than return a string
2998// that would be colored when printed, as can be done on Linux.
2999static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3000 va_list args;
3001 va_start(args, fmt);
3002
3003#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
3004 GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
3005 const bool use_color = AlwaysFalse();
3006#else
3007 static const bool in_color_mode =
3009 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3010#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3011 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
3012
3013 if (!use_color) {
3014 vprintf(fmt, args);
3015 va_end(args);
3016 return;
3017 }
3018
3019#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
3020 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3021 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3022
3023 // Gets the current text color.
3024 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3025 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3026 const WORD old_color_attrs = buffer_info.wAttributes;
3027 const WORD new_color = GetNewColor(color, old_color_attrs);
3028
3029 // We need to flush the stream buffers into the console before each
3030 // SetConsoleTextAttribute call lest it affect the text that is already
3031 // printed but has not yet reached the console.
3032 fflush(stdout);
3033 SetConsoleTextAttribute(stdout_handle, new_color);
3034
3035 vprintf(fmt, args);
3036
3037 fflush(stdout);
3038 // Restores the text color.
3039 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3040#else
3041 printf("\033[0;3%sm", GetAnsiColorCode(color));
3042 vprintf(fmt, args);
3043 printf("\033[m"); // Resets the terminal to default.
3044#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3045 va_end(args);
3046}
3047
3048// Text printed in Google Test's text output and --gtest_list_tests
3049// output to label the type parameter and value parameter for a test.
3050static const char kTypeParamLabel[] = "TypeParam";
3051static const char kValueParamLabel[] = "GetParam()";
3052
3053static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3054 const char* const type_param = test_info.type_param();
3055 const char* const value_param = test_info.value_param();
3056
3057 if (type_param != NULL || value_param != NULL) {
3058 printf(", where ");
3059 if (type_param != NULL) {
3060 printf("%s = %s", kTypeParamLabel, type_param);
3061 if (value_param != NULL)
3062 printf(" and ");
3063 }
3064 if (value_param != NULL) {
3065 printf("%s = %s", kValueParamLabel, value_param);
3066 }
3067 }
3068}
3069
3070// This class implements the TestEventListener interface.
3071//
3072// Class PrettyUnitTestResultPrinter is copyable.
3074 public:
3076 static void PrintTestName(const char * test_case, const char * test) {
3077 printf("%s.%s", test_case, test);
3078 }
3079
3080 // The following methods override what's in the TestEventListener class.
3081 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
3082 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
3083 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
3084 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
3085 virtual void OnTestCaseStart(const TestCase& test_case);
3086 virtual void OnTestStart(const TestInfo& test_info);
3087 virtual void OnTestPartResult(const TestPartResult& result);
3088 virtual void OnTestEnd(const TestInfo& test_info);
3089 virtual void OnTestCaseEnd(const TestCase& test_case);
3090 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
3091 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
3092 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3093 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
3094
3095 private:
3096 static void PrintFailedTests(const UnitTest& unit_test);
3097};
3098
3099 // Fired before each iteration of tests starts.
3101 const UnitTest& unit_test, int iteration) {
3102 if (GTEST_FLAG(repeat) != 1)
3103 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3104
3105 const char* const filter = GTEST_FLAG(filter).c_str();
3106
3107 // Prints the filter if it's not *. This reminds the user that some
3108 // tests may be skipped.
3109 if (!String::CStringEquals(filter, kUniversalFilter)) {
3110 ColoredPrintf(COLOR_YELLOW,
3111 "Note: %s filter = %s\n", GTEST_NAME_, filter);
3112 }
3113
3114 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
3115 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
3116 ColoredPrintf(COLOR_YELLOW,
3117 "Note: This is test shard %d of %s.\n",
3118 static_cast<int>(shard_index) + 1,
3119 internal::posix::GetEnv(kTestTotalShards));
3120 }
3121
3122 if (GTEST_FLAG(shuffle)) {
3123 ColoredPrintf(COLOR_YELLOW,
3124 "Note: Randomizing tests' orders with a seed of %d .\n",
3125 unit_test.random_seed());
3126 }
3127 ColoredPrintf(COLOR_GREEN, "[==========] ");
3128 printf("Running %s from %s.\n",
3129 FormatTestCount(unit_test.test_to_run_count()).c_str(),
3130 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
3131 fflush(stdout);
3132}
3133
3135 const UnitTest& /*unit_test*/) {
3136 ColoredPrintf(COLOR_GREEN, "[----------] ");
3137 printf("Global test environment set-up.\n");
3138 fflush(stdout);
3139}
3140
3142 const std::string counts =
3143 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3144 ColoredPrintf(COLOR_GREEN, "[----------] ");
3145 printf("%s from %s", counts.c_str(), test_case.name());
3146 if (test_case.type_param() == NULL) {
3147 printf("\n");
3148 } else {
3149 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
3150 }
3151 fflush(stdout);
3152}
3153
3155 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
3156 PrintTestName(test_info.test_case_name(), test_info.name());
3157 printf("\n");
3158 fflush(stdout);
3159}
3160
3161// Called after an assertion failure.
3163 const TestPartResult& result) {
3164 // If the test part succeeded, we don't need to do anything.
3165 if (result.type() == TestPartResult::kSuccess)
3166 return;
3167
3168 // Print failure message from the assertion (e.g. expected this and got that).
3169 PrintTestPartResult(result);
3170 fflush(stdout);
3171}
3172
3174 if (test_info.result()->Passed()) {
3175 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
3176 } else {
3177 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
3178 }
3179 PrintTestName(test_info.test_case_name(), test_info.name());
3180 if (test_info.result()->Failed())
3181 PrintFullTestCommentIfPresent(test_info);
3182
3183 if (GTEST_FLAG(print_time)) {
3184 printf(" (%s ms)\n", internal::StreamableToString(
3185 test_info.result()->elapsed_time()).c_str());
3186 } else {
3187 printf("\n");
3188 }
3189 fflush(stdout);
3190}
3191
3193 if (!GTEST_FLAG(print_time)) return;
3194
3195 const std::string counts =
3196 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3197 ColoredPrintf(COLOR_GREEN, "[----------] ");
3198 printf("%s from %s (%s ms total)\n\n",
3199 counts.c_str(), test_case.name(),
3200 internal::StreamableToString(test_case.elapsed_time()).c_str());
3201 fflush(stdout);
3202}
3203
3205 const UnitTest& /*unit_test*/) {
3206 ColoredPrintf(COLOR_GREEN, "[----------] ");
3207 printf("Global test environment tear-down\n");
3208 fflush(stdout);
3209}
3210
3211// Internal helper for printing the list of failed tests.
3212void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
3213 const int failed_test_count = unit_test.failed_test_count();
3214 if (failed_test_count == 0) {
3215 return;
3216 }
3217
3218 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
3219 const TestCase& test_case = *unit_test.GetTestCase(i);
3220 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
3221 continue;
3222 }
3223 for (int j = 0; j < test_case.total_test_count(); ++j) {
3224 const TestInfo& test_info = *test_case.GetTestInfo(j);
3225 if (!test_info.should_run() || test_info.result()->Passed()) {
3226 continue;
3227 }
3228 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
3229 printf("%s.%s", test_case.name(), test_info.name());
3230 PrintFullTestCommentIfPresent(test_info);
3231 printf("\n");
3232 }
3233 }
3234}
3235
3237 int /*iteration*/) {
3238 ColoredPrintf(COLOR_GREEN, "[==========] ");
3239 printf("%s from %s ran.",
3240 FormatTestCount(unit_test.test_to_run_count()).c_str(),
3241 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
3242 if (GTEST_FLAG(print_time)) {
3243 printf(" (%s ms total)",
3244 internal::StreamableToString(unit_test.elapsed_time()).c_str());
3245 }
3246 printf("\n");
3247 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
3248 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3249
3250 int num_failures = unit_test.failed_test_count();
3251 if (!unit_test.Passed()) {
3252 const int failed_test_count = unit_test.failed_test_count();
3253 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
3254 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
3255 PrintFailedTests(unit_test);
3256 printf("\n%2d FAILED %s\n", num_failures,
3257 num_failures == 1 ? "TEST" : "TESTS");
3258 }
3259
3260 int num_disabled = unit_test.reportable_disabled_test_count();
3261 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
3262 if (!num_failures) {
3263 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
3264 }
3265 ColoredPrintf(COLOR_YELLOW,
3266 " YOU HAVE %d DISABLED %s\n\n",
3267 num_disabled,
3268 num_disabled == 1 ? "TEST" : "TESTS");
3269 }
3270 // Ensure that Google Test output is printed before, e.g., heapchecker output.
3271 fflush(stdout);
3272}
3273
3274// End PrettyUnitTestResultPrinter
3275
3276// class TestEventRepeater
3277//
3278// This class forwards events to other event listeners.
3280 public:
3281 TestEventRepeater() : forwarding_enabled_(true) {}
3282 virtual ~TestEventRepeater();
3283 void Append(TestEventListener *listener);
3285
3286 // Controls whether events will be forwarded to listeners_. Set to false
3287 // in death test child processes.
3288 bool forwarding_enabled() const { return forwarding_enabled_; }
3289 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
3290
3291 virtual void OnTestProgramStart(const UnitTest& unit_test);
3292 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
3293 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
3294 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
3295 virtual void OnTestCaseStart(const TestCase& test_case);
3296 virtual void OnTestStart(const TestInfo& test_info);
3297 virtual void OnTestPartResult(const TestPartResult& result);
3298 virtual void OnTestEnd(const TestInfo& test_info);
3299 virtual void OnTestCaseEnd(const TestCase& test_case);
3300 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
3301 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
3302 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3303 virtual void OnTestProgramEnd(const UnitTest& unit_test);
3304
3305 private:
3306 // Controls whether events will be forwarded to listeners_. Set to false
3307 // in death test child processes.
3308 bool forwarding_enabled_;
3309 // The list of listeners that receive events.
3310 std::vector<TestEventListener*> listeners_;
3311
3313};
3314
3316 ForEach(listeners_, Delete<TestEventListener>);
3317}
3318
3320 listeners_.push_back(listener);
3321}
3322
3323// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
3325 for (size_t i = 0; i < listeners_.size(); ++i) {
3326 if (listeners_[i] == listener) {
3327 listeners_.erase(listeners_.begin() + i);
3328 return listener;
3329 }
3330 }
3331
3332 return NULL;
3333}
3334
3335// Since most methods are very similar, use macros to reduce boilerplate.
3336// This defines a member that forwards the call to all listeners.
3337#define GTEST_REPEATER_METHOD_(Name, Type) \
3338void TestEventRepeater::Name(const Type& parameter) { \
3339 if (forwarding_enabled_) { \
3340 for (size_t i = 0; i < listeners_.size(); i++) { \
3341 listeners_[i]->Name(parameter); \
3342 } \
3343 } \
3344}
3345// This defines a member that forwards the call to all listeners in reverse
3346// order.
3347#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3348void TestEventRepeater::Name(const Type& parameter) { \
3349 if (forwarding_enabled_) { \
3350 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
3351 listeners_[i]->Name(parameter); \
3352 } \
3353 } \
3354}
3355
3356GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
3357GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
3358GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
3359GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
3360GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
3361GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
3362GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
3363GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
3364GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
3365GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
3366GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
3367
3368#undef GTEST_REPEATER_METHOD_
3369#undef GTEST_REVERSE_REPEATER_METHOD_
3370
3372 int iteration) {
3373 if (forwarding_enabled_) {
3374 for (size_t i = 0; i < listeners_.size(); i++) {
3375 listeners_[i]->OnTestIterationStart(unit_test, iteration);
3376 }
3377 }
3378}
3379
3381 int iteration) {
3382 if (forwarding_enabled_) {
3383 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
3384 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
3385 }
3386 }
3387}
3388
3389// End TestEventRepeater
3390
3391// This class generates an XML output file.
3393 public:
3394 explicit XmlUnitTestResultPrinter(const char* output_file);
3395
3396 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3397
3398 private:
3399 // Is c a whitespace character that is normalized to a space character
3400 // when it appears in an XML attribute value?
3401 static bool IsNormalizableWhitespace(char c) {
3402 return c == 0x9 || c == 0xA || c == 0xD;
3403 }
3404
3405 // May c appear in a well-formed XML document?
3406 static bool IsValidXmlCharacter(char c) {
3407 return IsNormalizableWhitespace(c) || c >= 0x20;
3408 }
3409
3410 // Returns an XML-escaped copy of the input string str. If
3411 // is_attribute is true, the text is meant to appear as an attribute
3412 // value, and normalizable whitespace is preserved by replacing it
3413 // with character references.
3414 static std::string EscapeXml(const std::string& str, bool is_attribute);
3415
3416 // Returns the given string with all characters invalid in XML removed.
3417 static std::string RemoveInvalidXmlCharacters(const std::string& str);
3418
3419 // Convenience wrapper around EscapeXml when str is an attribute value.
3420 static std::string EscapeXmlAttribute(const std::string& str) {
3421 return EscapeXml(str, true);
3422 }
3423
3424 // Convenience wrapper around EscapeXml when str is not an attribute value.
3425 static std::string EscapeXmlText(const char* str) {
3426 return EscapeXml(str, false);
3427 }
3428
3429 // Verifies that the given attribute belongs to the given element and
3430 // streams the attribute as XML.
3431 static void OutputXmlAttribute(std::ostream* stream,
3432 const std::string& element_name,
3433 const std::string& name,
3434 const std::string& value);
3435
3436 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3437 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3438
3439 // Streams an XML representation of a TestInfo object.
3440 static void OutputXmlTestInfo(::std::ostream* stream,
3441 const char* test_case_name,
3442 const TestInfo& test_info);
3443
3444 // Prints an XML representation of a TestCase object
3445 static void PrintXmlTestCase(::std::ostream* stream,
3446 const TestCase& test_case);
3447
3448 // Prints an XML summary of unit_test to output stream out.
3449 static void PrintXmlUnitTest(::std::ostream* stream,
3450 const UnitTest& unit_test);
3451
3452 // Produces a string representing the test properties in a result as space
3453 // delimited XML attributes based on the property key="value" pairs.
3454 // When the std::string is not empty, it includes a space at the beginning,
3455 // to delimit this attribute from prior attributes.
3456 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
3457
3458 // Streams an XML representation of the test properties of a TestResult
3459 // object.
3460 static void OutputXmlTestProperties(std::ostream* stream,
3461 const TestResult& result);
3462
3463 // The output file.
3464 const std::string output_file_;
3465
3467};
3468
3469// Creates a new XmlUnitTestResultPrinter.
3471 : output_file_(output_file) {
3472 if (output_file_.c_str() == NULL || output_file_.empty()) {
3473 GTEST_LOG_(FATAL) << "XML output file may not be null";
3474 }
3475}
3476
3477// Called after the unit test ends.
3479 int /*iteration*/) {
3480 FILE* xmlout = NULL;
3481 FilePath output_file(output_file_);
3482 FilePath output_dir(output_file.RemoveFileName());
3483
3484 if (output_dir.CreateDirectoriesRecursively()) {
3485 xmlout = posix::FOpen(output_file_.c_str(), "w");
3486 }
3487 if (xmlout == NULL) {
3488 // TODO(wan): report the reason of the failure.
3489 //
3490 // We don't do it for now as:
3491 //
3492 // 1. There is no urgent need for it.
3493 // 2. It's a bit involved to make the errno variable thread-safe on
3494 // all three operating systems (Linux, Windows, and Mac OS).
3495 // 3. To interpret the meaning of errno in a thread-safe way,
3496 // we need the strerror_r() function, which is not available on
3497 // Windows.
3498
3499 GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file_ << "\"";
3500 }
3501 std::stringstream stream;
3502 PrintXmlUnitTest(&stream, unit_test);
3503 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
3504 fclose(xmlout);
3505}
3506
3507// Returns an XML-escaped copy of the input string str. If is_attribute
3508// is true, the text is meant to appear as an attribute value, and
3509// normalizable whitespace is preserved by replacing it with character
3510// references.
3511//
3512// Invalid XML characters in str, if any, are stripped from the output.
3513// It is expected that most, if not all, of the text processed by this
3514// module will consist of ordinary English text.
3515// If this module is ever modified to produce version 1.1 XML output,
3516// most invalid characters can be retained using character references.
3517// TODO(wan): It might be nice to have a minimally invasive, human-readable
3518// escaping scheme for invalid characters, rather than dropping them.
3519std::string XmlUnitTestResultPrinter::EscapeXml(
3520 const std::string& str, bool is_attribute) {
3521 Message m;
3522
3523 for (size_t i = 0; i < str.size(); ++i) {
3524 const char ch = str[i];
3525 switch (ch) {
3526 case '<':
3527 m << "&lt;";
3528 break;
3529 case '>':
3530 m << "&gt;";
3531 break;
3532 case '&':
3533 m << "&amp;";
3534 break;
3535 case '\'':
3536 if (is_attribute)
3537 m << "&apos;";
3538 else
3539 m << '\'';
3540 break;
3541 case '"':
3542 if (is_attribute)
3543 m << "&quot;";
3544 else
3545 m << '"';
3546 break;
3547 default:
3548 if (IsValidXmlCharacter(ch)) {
3549 if (is_attribute && IsNormalizableWhitespace(ch))
3550 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
3551 << ";";
3552 else
3553 m << ch;
3554 }
3555 break;
3556 }
3557 }
3558
3559 return m.GetString();
3560}
3561
3562// Returns the given string with all characters invalid in XML removed.
3563// Currently invalid characters are dropped from the string. An
3564// alternative is to replace them with certain characters such as . or ?.
3565std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
3566 const std::string& str) {
3567 std::string output;
3568 output.reserve(str.size());
3569 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
3570 if (IsValidXmlCharacter(*it))
3571 output.push_back(*it);
3572
3573 return output;
3574}
3575
3576// The following routines generate an XML representation of a UnitTest
3577// object.
3578//
3579// This is how Google Test concepts map to the DTD:
3580//
3581// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
3582// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
3583// <testcase name="test-name"> <-- corresponds to a TestInfo object
3584// <failure message="...">...</failure>
3585// <failure message="...">...</failure>
3586// <failure message="...">...</failure>
3587// <-- individual assertion failures
3588// </testcase>
3589// </testsuite>
3590// </testsuites>
3591
3592// Formats the given time in milliseconds as seconds.
3594 ::std::stringstream ss;
3595 ss << (static_cast<double>(ms) * 1e-3);
3596 return ss.str();
3597}
3598
3599static bool PortableLocaltime(time_t seconds, struct tm* out) {
3600#if defined(_MSC_VER)
3601 return localtime_s(out, &seconds) == 0;
3602#elif defined(__MINGW32__) || defined(__MINGW64__)
3603 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
3604 // Windows' localtime(), which has a thread-local tm buffer.
3605 struct tm* tm_ptr = localtime(&seconds); // NOLINT
3606 if (tm_ptr == NULL)
3607 return false;
3608 *out = *tm_ptr;
3609 return true;
3610#else
3611 return localtime_r(&seconds, out) != NULL;
3612#endif
3613}
3614
3615// Converts the given epoch time in milliseconds to a date string in the ISO
3616// 8601 format, without the timezone information.
3618 struct tm time_struct;
3619 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
3620 return "";
3621 // YYYY-MM-DDThh:mm:ss
3622 return StreamableToString(time_struct.tm_year + 1900) + "-" +
3623 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
3624 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
3625 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
3626 String::FormatIntWidth2(time_struct.tm_min) + ":" +
3627 String::FormatIntWidth2(time_struct.tm_sec);
3628}
3629
3630// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3631void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3632 const char* data) {
3633 const char* segment = data;
3634 *stream << "<![CDATA[";
3635 for (;;) {
3636 const char* const next_segment = strstr(segment, "]]>");
3637 if (next_segment != NULL) {
3638 stream->write(
3639 segment, static_cast<std::streamsize>(next_segment - segment));
3640 *stream << "]]>]]&gt;<![CDATA[";
3641 segment = next_segment + strlen("]]>");
3642 } else {
3643 *stream << segment;
3644 break;
3645 }
3646 }
3647 *stream << "]]>";
3648}
3649
3650void XmlUnitTestResultPrinter::OutputXmlAttribute(
3651 std::ostream* stream,
3652 const std::string& element_name,
3653 const std::string& name,
3654 const std::string& value) {
3655 const std::vector<std::string>& allowed_names =
3656 GetReservedAttributesForElement(element_name);
3657
3658 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
3659 allowed_names.end())
3660 << "Attribute " << name << " is not allowed for element <" << element_name
3661 << ">.";
3662
3663 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
3664}
3665
3666// Prints an XML representation of a TestInfo object.
3667// TODO(wan): There is also value in printing properties with the plain printer.
3668void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3669 const char* test_case_name,
3670 const TestInfo& test_info) {
3671 const TestResult& result = *test_info.result();
3672 const std::string kTestcase = "testcase";
3673
3674 if (test_info.is_in_another_shard()) {
3675 return;
3676 }
3677
3678 *stream << " <testcase";
3679 OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
3680
3681 if (test_info.value_param() != NULL) {
3682 OutputXmlAttribute(stream, kTestcase, "value_param",
3683 test_info.value_param());
3684 }
3685 if (test_info.type_param() != NULL) {
3686 OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
3687 }
3688
3689 OutputXmlAttribute(stream, kTestcase, "status",
3690 test_info.should_run() ? "run" : "notrun");
3691 OutputXmlAttribute(stream, kTestcase, "time",
3692 FormatTimeInMillisAsSeconds(result.elapsed_time()));
3693 OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
3694
3695 int failures = 0;
3696 for (int i = 0; i < result.total_part_count(); ++i) {
3697 const TestPartResult& part = result.GetTestPartResult(i);
3698 if (part.failed()) {
3699 if (++failures == 1) {
3700 *stream << ">\n";
3701 }
3702 const std::string location =
3704 part.line_number());
3705 const std::string summary = location + "\n" + part.summary();
3706 *stream << " <failure message=\""
3707 << EscapeXmlAttribute(summary.c_str())
3708 << "\" type=\"\">";
3709 const std::string detail = location + "\n" + part.message();
3710 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
3711 *stream << "</failure>\n";
3712 }
3713 }
3714
3715 if (failures == 0 && result.test_property_count() == 0) {
3716 *stream << " />\n";
3717 } else {
3718 if (failures == 0) {
3719 *stream << ">\n";
3720 }
3721 OutputXmlTestProperties(stream, result);
3722 *stream << " </testcase>\n";
3723 }
3724}
3725
3726// Prints an XML representation of a TestCase object
3727void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
3728 const TestCase& test_case) {
3729 const std::string kTestsuite = "testsuite";
3730 *stream << " <" << kTestsuite;
3731 OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
3732 OutputXmlAttribute(stream, kTestsuite, "tests",
3733 StreamableToString(test_case.reportable_test_count()));
3734 OutputXmlAttribute(stream, kTestsuite, "failures",
3735 StreamableToString(test_case.failed_test_count()));
3736 OutputXmlAttribute(
3737 stream, kTestsuite, "disabled",
3738 StreamableToString(test_case.reportable_disabled_test_count()));
3739 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
3740 OutputXmlAttribute(stream, kTestsuite, "time",
3741 FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
3742 *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
3743 << ">\n";
3744
3745 for (int i = 0; i < test_case.total_test_count(); ++i) {
3746 if (test_case.GetTestInfo(i)->is_reportable())
3747 OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
3748 }
3749 *stream << " </" << kTestsuite << ">\n";
3750}
3751
3752// Prints an XML summary of unit_test to output stream out.
3753void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
3754 const UnitTest& unit_test) {
3755 const std::string kTestsuites = "testsuites";
3756
3757 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3758 *stream << "<" << kTestsuites;
3759
3760 OutputXmlAttribute(stream, kTestsuites, "tests",
3761 StreamableToString(unit_test.reportable_test_count()));
3762 OutputXmlAttribute(stream, kTestsuites, "failures",
3763 StreamableToString(unit_test.failed_test_count()));
3764 OutputXmlAttribute(
3765 stream, kTestsuites, "disabled",
3766 StreamableToString(unit_test.reportable_disabled_test_count()));
3767 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
3768 OutputXmlAttribute(
3769 stream, kTestsuites, "timestamp",
3770 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
3771 OutputXmlAttribute(stream, kTestsuites, "time",
3772 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
3773
3774 if (GTEST_FLAG(shuffle)) {
3775 OutputXmlAttribute(stream, kTestsuites, "random_seed",
3776 StreamableToString(unit_test.random_seed()));
3777 }
3778 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
3779
3780 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
3781 *stream << ">\n";
3782
3783 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
3784 if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
3785 PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
3786 }
3787 *stream << "</" << kTestsuites << ">\n";
3788}
3789
3790// Produces a string representing the test properties in a result as space
3791// delimited XML attributes based on the property key="value" pairs.
3792std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3793 const TestResult& result) {
3794 Message attributes;
3795 for (int i = 0; i < result.test_property_count(); ++i) {
3796 const TestProperty& property = result.GetTestProperty(i);
3797 attributes << " " << property.key() << "="
3798 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3799 }
3800 return attributes.GetString();
3801}
3802
3803void XmlUnitTestResultPrinter::OutputXmlTestProperties(
3804 std::ostream* stream, const TestResult& result) {
3805 const std::string kProperties = "properties";
3806 const std::string kProperty = "property";
3807
3808 if (result.test_property_count() <= 0) {
3809 return;
3810 }
3811
3812 *stream << "<" << kProperties << ">\n";
3813 for (int i = 0; i < result.test_property_count(); ++i) {
3814 const TestProperty& property = result.GetTestProperty(i);
3815 *stream << "<" << kProperty;
3816 *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
3817 *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
3818 *stream << "/>\n";
3819 }
3820 *stream << "</" << kProperties << ">\n";
3821}
3822
3823// End XmlUnitTestResultPrinter
3824
3825
3826// This class generates an JSON output file.
3828 public:
3829 explicit JsonUnitTestResultPrinter(const char* output_file);
3830
3831 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3832
3833 private:
3834 // Returns an JSON-escaped copy of the input string str.
3835 static std::string EscapeJson(const std::string& str);
3836
3839 static void OutputJsonKey(std::ostream* stream,
3840 const std::string& element_name,
3841 const std::string& name,
3842 const std::string& value,
3843 const std::string& indent,
3844 bool comma = true);
3845 static void OutputJsonKey(std::ostream* stream,
3846 const std::string& element_name,
3847 const std::string& name,
3848 int value,
3849 const std::string& indent,
3850 bool comma = true);
3851
3852 // Streams a JSON representation of a TestInfo object.
3853 static void OutputJsonTestInfo(::std::ostream* stream,
3854 const char* test_case_name,
3855 const TestInfo& test_info);
3856
3857 // Prints a JSON representation of a TestCase object
3858 static void PrintJsonTestCase(::std::ostream* stream,
3859 const TestCase& test_case);
3860
3861 // Prints a JSON summary of unit_test to output stream out.
3862 static void PrintJsonUnitTest(::std::ostream* stream,
3863 const UnitTest& unit_test);
3864
3865 // Produces a string representing the test properties in a result as
3866 // a JSON dictionary.
3867 static std::string TestPropertiesAsJson(const TestResult& result,
3868 const std::string& indent);
3869
3870 // The output file.
3871 const std::string output_file_;
3872
3874};
3875
3876// Creates a new JsonUnitTestResultPrinter.
3878 : output_file_(output_file) {
3879 if (output_file_.empty()) {
3880 GTEST_LOG_(FATAL) << "JSON output file may not be null";
3881 }
3882}
3883
3885 int /*iteration*/) {
3886 FILE* jsonout = NULL;
3887 FilePath output_file(output_file_);
3888 FilePath output_dir(output_file.RemoveFileName());
3889
3890 if (output_dir.CreateDirectoriesRecursively()) {
3891 jsonout = posix::FOpen(output_file_.c_str(), "w");
3892 }
3893 if (jsonout == NULL) {
3894 // TODO(phosek): report the reason of the failure.
3895 //
3896 // We don't do it for now as:
3897 //
3898 // 1. There is no urgent need for it.
3899 // 2. It's a bit involved to make the errno variable thread-safe on
3900 // all three operating systems (Linux, Windows, and Mac OS).
3901 // 3. To interpret the meaning of errno in a thread-safe way,
3902 // we need the strerror_r() function, which is not available on
3903 // Windows.
3904 GTEST_LOG_(FATAL) << "Unable to open file \""
3905 << output_file_ << "\"";
3906 }
3907 std::stringstream stream;
3908 PrintJsonUnitTest(&stream, unit_test);
3909 fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
3910 fclose(jsonout);
3911}
3912
3913// Returns an JSON-escaped copy of the input string str.
3914std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
3915 Message m;
3916
3917 for (size_t i = 0; i < str.size(); ++i) {
3918 const char ch = str[i];
3919 switch (ch) {
3920 case '\\':
3921 case '"':
3922 case '/':
3923 m << '\\' << ch;
3924 break;
3925 case '\b':
3926 m << "\\b";
3927 break;
3928 case '\t':
3929 m << "\\t";
3930 break;
3931 case '\n':
3932 m << "\\n";
3933 break;
3934 case '\f':
3935 m << "\\f";
3936 break;
3937 case '\r':
3938 m << "\\r";
3939 break;
3940 default:
3941 if (ch < ' ') {
3942 m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
3943 } else {
3944 m << ch;
3945 }
3946 break;
3947 }
3948 }
3949
3950 return m.GetString();
3951}
3952
3953// The following routines generate an JSON representation of a UnitTest
3954// object.
3955
3956// Formats the given time in milliseconds as seconds.
3957static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
3958 ::std::stringstream ss;
3959 ss << (static_cast<double>(ms) * 1e-3) << "s";
3960 return ss.str();
3961}
3962
3963// Converts the given epoch time in milliseconds to a date string in the
3964// RFC3339 format, without the timezone information.
3965static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
3966 struct tm time_struct;
3967 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
3968 return "";
3969 // YYYY-MM-DDThh:mm:ss
3970 return StreamableToString(time_struct.tm_year + 1900) + "-" +
3971 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
3972 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
3973 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
3974 String::FormatIntWidth2(time_struct.tm_min) + ":" +
3975 String::FormatIntWidth2(time_struct.tm_sec) + "Z";
3976}
3977
3978static inline std::string Indent(int width) {
3979 return std::string(width, ' ');
3980}
3981
3982void JsonUnitTestResultPrinter::OutputJsonKey(
3983 std::ostream* stream,
3984 const std::string& element_name,
3985 const std::string& name,
3986 const std::string& value,
3987 const std::string& indent,
3988 bool comma) {
3989 const std::vector<std::string>& allowed_names =
3990 GetReservedAttributesForElement(element_name);
3991
3992 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
3993 allowed_names.end())
3994 << "Key \"" << name << "\" is not allowed for value \"" << element_name
3995 << "\".";
3996
3997 *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
3998 if (comma)
3999 *stream << ",\n";
4000}
4001
4002void JsonUnitTestResultPrinter::OutputJsonKey(
4003 std::ostream* stream,
4004 const std::string& element_name,
4005 const std::string& name,
4006 int value,
4007 const std::string& indent,
4008 bool comma) {
4009 const std::vector<std::string>& allowed_names =
4010 GetReservedAttributesForElement(element_name);
4011
4012 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4013 allowed_names.end())
4014 << "Key \"" << name << "\" is not allowed for value \"" << element_name
4015 << "\".";
4016
4017 *stream << indent << "\"" << name << "\": " << StreamableToString(value);
4018 if (comma)
4019 *stream << ",\n";
4020}
4021
4022// Prints a JSON representation of a TestInfo object.
4023void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4024 const char* test_case_name,
4025 const TestInfo& test_info) {
4026 const TestResult& result = *test_info.result();
4027 const std::string kTestcase = "testcase";
4028 const std::string kIndent = Indent(10);
4029
4030 *stream << Indent(8) << "{\n";
4031 OutputJsonKey(stream, kTestcase, "name", test_info.name(), kIndent);
4032
4033 if (test_info.value_param() != NULL) {
4034 OutputJsonKey(stream, kTestcase, "value_param",
4035 test_info.value_param(), kIndent);
4036 }
4037 if (test_info.type_param() != NULL) {
4038 OutputJsonKey(stream, kTestcase, "type_param", test_info.type_param(),
4039 kIndent);
4040 }
4041
4042 OutputJsonKey(stream, kTestcase, "status",
4043 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
4044 OutputJsonKey(stream, kTestcase, "time",
4045 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
4046 OutputJsonKey(stream, kTestcase, "classname", test_case_name, kIndent, false);
4047 *stream << TestPropertiesAsJson(result, kIndent);
4048
4049 int failures = 0;
4050 for (int i = 0; i < result.total_part_count(); ++i) {
4051 const TestPartResult& part = result.GetTestPartResult(i);
4052 if (part.failed()) {
4053 *stream << ",\n";
4054 if (++failures == 1) {
4055 *stream << kIndent << "\"" << "failures" << "\": [\n";
4056 }
4057 const std::string location =
4059 part.line_number());
4060 const std::string message = EscapeJson(location + "\n" + part.message());
4061 *stream << kIndent << " {\n"
4062 << kIndent << " \"failure\": \"" << message << "\",\n"
4063 << kIndent << " \"type\": \"\"\n"
4064 << kIndent << " }";
4065 }
4066 }
4067
4068 if (failures > 0)
4069 *stream << "\n" << kIndent << "]";
4070 *stream << "\n" << Indent(8) << "}";
4071}
4072
4073// Prints an JSON representation of a TestCase object
4074void JsonUnitTestResultPrinter::PrintJsonTestCase(std::ostream* stream,
4075 const TestCase& test_case) {
4076 const std::string kTestsuite = "testsuite";
4077 const std::string kIndent = Indent(6);
4078
4079 *stream << Indent(4) << "{\n";
4080 OutputJsonKey(stream, kTestsuite, "name", test_case.name(), kIndent);
4081 OutputJsonKey(stream, kTestsuite, "tests", test_case.reportable_test_count(),
4082 kIndent);
4083 OutputJsonKey(stream, kTestsuite, "failures", test_case.failed_test_count(),
4084 kIndent);
4085 OutputJsonKey(stream, kTestsuite, "disabled",
4086 test_case.reportable_disabled_test_count(), kIndent);
4087 OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
4088 OutputJsonKey(stream, kTestsuite, "time",
4089 FormatTimeInMillisAsDuration(test_case.elapsed_time()), kIndent,
4090 false);
4091 *stream << TestPropertiesAsJson(test_case.ad_hoc_test_result(), kIndent)
4092 << ",\n";
4093
4094 *stream << kIndent << "\"" << kTestsuite << "\": [\n";
4095
4096 bool comma = false;
4097 for (int i = 0; i < test_case.total_test_count(); ++i) {
4098 if (test_case.GetTestInfo(i)->is_reportable()) {
4099 if (comma) {
4100 *stream << ",\n";
4101 } else {
4102 comma = true;
4103 }
4104 OutputJsonTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
4105 }
4106 }
4107 *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
4108}
4109
4110// Prints a JSON summary of unit_test to output stream out.
4111void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4112 const UnitTest& unit_test) {
4113 const std::string kTestsuites = "testsuites";
4114 const std::string kIndent = Indent(2);
4115 *stream << "{\n";
4116
4117 OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
4118 kIndent);
4119 OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
4120 kIndent);
4121 OutputJsonKey(stream, kTestsuites, "disabled",
4122 unit_test.reportable_disabled_test_count(), kIndent);
4123 OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
4124 if (GTEST_FLAG(shuffle)) {
4125 OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
4126 kIndent);
4127 }
4128 OutputJsonKey(stream, kTestsuites, "timestamp",
4129 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
4130 kIndent);
4131 OutputJsonKey(stream, kTestsuites, "time",
4132 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
4133 false);
4134
4135 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4136 << ",\n";
4137
4138 OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4139 *stream << kIndent << "\"" << kTestsuites << "\": [\n";
4140
4141 bool comma = false;
4142 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4143 if (unit_test.GetTestCase(i)->reportable_test_count() > 0) {
4144 if (comma) {
4145 *stream << ",\n";
4146 } else {
4147 comma = true;
4148 }
4149 PrintJsonTestCase(stream, *unit_test.GetTestCase(i));
4150 }
4151 }
4152
4153 *stream << "\n" << kIndent << "]\n" << "}\n";
4154}
4155
4156// Produces a string representing the test properties in a result as
4157// a JSON dictionary.
4158std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4159 const TestResult& result, const std::string& indent) {
4160 Message attributes;
4161 for (int i = 0; i < result.test_property_count(); ++i) {
4162 const TestProperty& property = result.GetTestProperty(i);
4163 attributes << ",\n" << indent << "\"" << property.key() << "\": "
4164 << "\"" << EscapeJson(property.value()) << "\"";
4165 }
4166 return attributes.GetString();
4167}
4168
4169// End JsonUnitTestResultPrinter
4170
4171#if GTEST_CAN_STREAM_RESULTS_
4172
4173// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4174// replaces them by "%xx" where xx is their hexadecimal value. For
4175// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4176// in both time and space -- important as the input str may contain an
4177// arbitrarily long test failure message and stack trace.
4178std::string StreamingListener::UrlEncode(const char* str) {
4179 std::string result;
4180 result.reserve(strlen(str) + 1);
4181 for (char ch = *str; ch != '\0'; ch = *++str) {
4182 switch (ch) {
4183 case '%':
4184 case '=':
4185 case '&':
4186 case '\n':
4187 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
4188 break;
4189 default:
4190 result.push_back(ch);
4191 break;
4192 }
4193 }
4194 return result;
4195}
4196
4197void StreamingListener::SocketWriter::MakeConnection() {
4198 GTEST_CHECK_(sockfd_ == -1)
4199 << "MakeConnection() can't be called when there is already a connection.";
4200
4201 addrinfo hints;
4202 memset(&hints, 0, sizeof(hints));
4203 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4204 hints.ai_socktype = SOCK_STREAM;
4205 addrinfo* servinfo = NULL;
4206
4207 // Use the getaddrinfo() to get a linked list of IP addresses for
4208 // the given host name.
4209 const int error_num = getaddrinfo(
4210 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4211 if (error_num != 0) {
4212 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4213 << gai_strerror(error_num);
4214 }
4215
4216 // Loop through all the results and connect to the first we can.
4217 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4218 cur_addr = cur_addr->ai_next) {
4219 sockfd_ = socket(
4220 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4221 if (sockfd_ != -1) {
4222 // Connect the client socket to the server socket.
4223 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4224 close(sockfd_);
4225 sockfd_ = -1;
4226 }
4227 }
4228 }
4229
4230 freeaddrinfo(servinfo); // all done with this structure
4231
4232 if (sockfd_ == -1) {
4233 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4234 << host_name_ << ":" << port_num_;
4235 }
4236}
4237
4238// End of class Streaming Listener
4239#endif // GTEST_CAN_STREAM_RESULTS__
4240
4241// class OsStackTraceGetter
4242
4244 "... " GTEST_NAME_ " internal frames ...";
4245
4246std::string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/,
4247 int /*skip_count*/) {
4248 return "";
4249}
4250
4252
4253// A helper class that creates the premature-exit file in its
4254// constructor and deletes the file in its destructor.
4256 public:
4257 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
4258 : premature_exit_filepath_(premature_exit_filepath ?
4259 premature_exit_filepath : "") {
4260 // If a path to the premature-exit file is specified...
4261 if (!premature_exit_filepath_.empty()) {
4262 // create the file with a single "0" character in it. I/O
4263 // errors are ignored as there's nothing better we can do and we
4264 // don't want to fail the test because of this.
4265 FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
4266 fwrite("0", 1, 1, pfile);
4267 fclose(pfile);
4268 }
4269 }
4270
4272 if (!premature_exit_filepath_.empty()) {
4273 int retval = remove(premature_exit_filepath_.c_str());
4274 if (retval) {
4275 GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
4276 << premature_exit_filepath_ << "\" with error "
4277 << retval;
4278 }
4279 }
4280 }
4281
4282 private:
4283 const std::string premature_exit_filepath_;
4284
4286};
4287
4288} // namespace internal
4289
4290// class TestEventListeners
4291
4293 : repeater_(new internal::TestEventRepeater()),
4294 default_result_printer_(NULL),
4295 default_xml_generator_(NULL) {
4296}
4297
4299
4300// Returns the standard listener responsible for the default console
4301// output. Can be removed from the listeners list to shut down default
4302// console output. Note that removing this object from the listener list
4303// with Release transfers its ownership to the user.
4305 repeater_->Append(listener);
4306}
4307
4308// Removes the given event listener from the list and returns it. It then
4309// becomes the caller's responsibility to delete the listener. Returns
4310// NULL if the listener is not found in the list.
4312 if (listener == default_result_printer_)
4313 default_result_printer_ = NULL;
4314 else if (listener == default_xml_generator_)
4315 default_xml_generator_ = NULL;
4316 return repeater_->Release(listener);
4317}
4318
4319// Returns repeater that broadcasts the TestEventListener events to all
4320// subscribers.
4321TestEventListener* TestEventListeners::repeater() { return repeater_; }
4322
4323// Sets the default_result_printer attribute to the provided listener.
4324// The listener is also added to the listener list and previous
4325// default_result_printer is removed from it and deleted. The listener can
4326// also be NULL in which case it will not be added to the list. Does
4327// nothing if the previous and the current listener objects are the same.
4328void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4329 if (default_result_printer_ != listener) {
4330 // It is an error to pass this method a listener that is already in the
4331 // list.
4332 delete Release(default_result_printer_);
4333 default_result_printer_ = listener;
4334 if (listener != NULL)
4335 Append(listener);
4336 }
4337}
4338
4339// Sets the default_xml_generator attribute to the provided listener. The
4340// listener is also added to the listener list and previous
4341// default_xml_generator is removed from it and deleted. The listener can
4342// also be NULL in which case it will not be added to the list. Does
4343// nothing if the previous and the current listener objects are the same.
4344void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4345 if (default_xml_generator_ != listener) {
4346 // It is an error to pass this method a listener that is already in the
4347 // list.
4348 delete Release(default_xml_generator_);
4349 default_xml_generator_ = listener;
4350 if (listener != NULL)
4351 Append(listener);
4352 }
4353}
4354
4355// Controls whether events will be forwarded by the repeater to the
4356// listeners in the list.
4357bool TestEventListeners::EventForwardingEnabled() const {
4358 return repeater_->forwarding_enabled();
4359}
4360
4361void TestEventListeners::SuppressEventForwarding() {
4362 repeater_->set_forwarding_enabled(false);
4363}
4364
4365// class UnitTest
4366
4367// Gets the singleton UnitTest object. The first time this method is
4368// called, a UnitTest object is constructed and returned. Consecutive
4369// calls will return the same object.
4370//
4371// We don't protect this under mutex_ as a user is not supposed to
4372// call this before main() starts, from which point on the return
4373// value will never change.
4375 // When compiled with MSVC 7.1 in optimized mode, destroying the
4376 // UnitTest object upon exiting the program messes up the exit code,
4377 // causing successful tests to appear failed. We have to use a
4378 // different implementation in this case to bypass the compiler bug.
4379 // This implementation makes the compiler happy, at the cost of
4380 // leaking the UnitTest object.
4381
4382 // CodeGear C++Builder insists on a public destructor for the
4383 // default implementation. Use this implementation to keep good OO
4384 // design with private destructor.
4385
4386#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4387 static UnitTest* const instance = new UnitTest;
4388 return instance;
4389#else
4390 static UnitTest instance;
4391 return &instance;
4392#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4393}
4394
4395// Gets the number of successful test cases.
4397 return impl()->successful_test_case_count();
4398}
4399
4400// Gets the number of failed test cases.
4402 return impl()->failed_test_case_count();
4403}
4404
4405// Gets the number of all test cases.
4407 return impl()->total_test_case_count();
4408}
4409
4410// Gets the number of all test cases that contain at least one test
4411// that should run.
4413 return impl()->test_case_to_run_count();
4414}
4415
4416// Gets the number of successful tests.
4418 return impl()->successful_test_count();
4419}
4420
4421// Gets the number of failed tests.
4422int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4423
4424// Gets the number of disabled tests that will be reported in the XML report.
4426 return impl()->reportable_disabled_test_count();
4427}
4428
4429// Gets the number of disabled tests.
4431 return impl()->disabled_test_count();
4432}
4433
4434// Gets the number of tests to be printed in the XML report.
4436 return impl()->reportable_test_count();
4437}
4438
4439// Gets the number of all tests.
4440int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4441
4442// Gets the number of tests that should run.
4443int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4444
4445// Gets the time of the test program start, in ms from the start of the
4446// UNIX epoch.
4448 return impl()->start_timestamp();
4449}
4450
4451// Gets the elapsed time, in milliseconds.
4453 return impl()->elapsed_time();
4454}
4455
4456// Returns true iff the unit test passed (i.e. all test cases passed).
4457bool UnitTest::Passed() const { return impl()->Passed(); }
4458
4459// Returns true iff the unit test failed (i.e. some test case failed
4460// or something outside of all tests failed).
4461bool UnitTest::Failed() const { return impl()->Failed(); }
4462
4463// Gets the i-th test case among all the test cases. i can range from 0 to
4464// total_test_case_count() - 1. If i is not in that range, returns NULL.
4465const TestCase* UnitTest::GetTestCase(int i) const {
4466 return impl()->GetTestCase(i);
4467}
4468
4469// Returns the TestResult containing information on test failures and
4470// properties logged outside of individual test cases.
4472 return *impl()->ad_hoc_test_result();
4473}
4474
4475// Gets the i-th test case among all the test cases. i can range from 0 to
4476// total_test_case_count() - 1. If i is not in that range, returns NULL.
4477TestCase* UnitTest::GetMutableTestCase(int i) {
4478 return impl()->GetMutableTestCase(i);
4479}
4480
4481// Returns the list of event listeners that can be used to track events
4482// inside Google Test.
4484 return *impl()->listeners();
4485}
4486
4487// Registers and returns a global test environment. When a test
4488// program is run, all global test environments will be set-up in the
4489// order they were registered. After all tests in the program have
4490// finished, all global test environments will be torn-down in the
4491// *reverse* order they were registered.
4492//
4493// The UnitTest object takes ownership of the given environment.
4494//
4495// We don't protect this under mutex_, as we only support calling it
4496// from the main thread.
4497Environment* UnitTest::AddEnvironment(Environment* env) {
4498 if (env == NULL) {
4499 return NULL;
4500 }
4501
4502 impl_->environments().push_back(env);
4503 return env;
4504}
4505
4506// Adds a TestPartResult to the current TestResult object. All Google Test
4507// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
4508// this to report their results. The user code should use the
4509// assertion macros instead of calling this directly.
4510void UnitTest::AddTestPartResult(
4511 TestPartResult::Type result_type,
4512 const char* file_name,
4513 int line_number,
4514 const std::string& message,
4515 const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
4516 Message msg;
4517 msg << message;
4518
4519 internal::MutexLock lock(&mutex_);
4520 if (impl_->gtest_trace_stack().size() > 0) {
4521 msg << "\n" << GTEST_NAME_ << " trace:";
4522
4523 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
4524 i > 0; --i) {
4525 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
4526 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
4527 << " " << trace.message;
4528 }
4529 }
4530
4531 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
4532 msg << internal::kStackTraceMarker << os_stack_trace;
4533 }
4534
4535 const TestPartResult result =
4536 TestPartResult(result_type, file_name, line_number,
4537 msg.GetString().c_str());
4538 impl_->GetTestPartResultReporterForCurrentThread()->
4539 ReportTestPartResult(result);
4540
4541 if (result_type != TestPartResult::kSuccess) {
4542 // gtest_break_on_failure takes precedence over
4543 // gtest_throw_on_failure. This allows a user to set the latter
4544 // in the code (perhaps in order to use Google Test assertions
4545 // with another testing framework) and specify the former on the
4546 // command line for debugging.
4547 if (GTEST_FLAG(break_on_failure)) {
4548#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4549 // Using DebugBreak on Windows allows gtest to still break into a debugger
4550 // when a failure happens and both the --gtest_break_on_failure and
4551 // the --gtest_catch_exceptions flags are specified.
4552 DebugBreak();
4553#elif (!defined(__native_client__)) && \
4554 ((defined(__clang__) || defined(__GNUC__)) && \
4555 (defined(__x86_64__) || defined(__i386__)))
4556 // with clang/gcc we can achieve the same effect on x86 by invoking int3
4557 asm("int3");
4558#else
4559 // Dereference NULL through a volatile pointer to prevent the compiler
4560 // from removing. We use this rather than abort() or __builtin_trap() for
4561 // portability: Symbian doesn't implement abort() well, and some debuggers
4562 // don't correctly trap abort().
4563 *static_cast<volatile int*>(NULL) = 1;
4564#endif // GTEST_OS_WINDOWS
4565 } else if (GTEST_FLAG(throw_on_failure)) {
4566#if GTEST_HAS_EXCEPTIONS
4567 throw internal::GoogleTestFailureException(result);
4568#else
4569 // We cannot call abort() as it generates a pop-up in debug mode
4570 // that cannot be suppressed in VC 7.1 or below.
4571 exit(1);
4572#endif
4573 }
4574 }
4575}
4576
4577// Adds a TestProperty to the current TestResult object when invoked from
4578// inside a test, to current TestCase's ad_hoc_test_result_ when invoked
4579// from SetUpTestCase or TearDownTestCase, or to the global property set
4580// when invoked elsewhere. If the result already contains a property with
4581// the same key, the value will be updated.
4582void UnitTest::RecordProperty(const std::string& key,
4583 const std::string& value) {
4584 impl_->RecordProperty(TestProperty(key, value));
4585}
4586
4587// Runs all tests in this UnitTest object and prints the result.
4588// Returns 0 if successful, or 1 otherwise.
4589//
4590// We don't protect this under mutex_, as we only support calling it
4591// from the main thread.
4593 const bool in_death_test_child_process =
4594 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
4595
4596 // Google Test implements this protocol for catching that a test
4597 // program exits before returning control to Google Test:
4598 //
4599 // 1. Upon start, Google Test creates a file whose absolute path
4600 // is specified by the environment variable
4601 // TEST_PREMATURE_EXIT_FILE.
4602 // 2. When Google Test has finished its work, it deletes the file.
4603 //
4604 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
4605 // running a Google-Test-based test program and check the existence
4606 // of the file at the end of the test execution to see if it has
4607 // exited prematurely.
4608
4609 // If we are in the child process of a death test, don't
4610 // create/delete the premature exit file, as doing so is unnecessary
4611 // and will confuse the parent process. Otherwise, create/delete
4612 // the file upon entering/leaving this function. If the program
4613 // somehow exits before this function has a chance to return, the
4614 // premature-exit file will be left undeleted, causing a test runner
4615 // that understands the premature-exit-file protocol to report the
4616 // test as having failed.
4617 const internal::ScopedPrematureExitFile premature_exit_file(
4618 in_death_test_child_process ?
4619 NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
4620
4621 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
4622 // used for the duration of the program.
4623 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
4624
4625#if GTEST_HAS_SEH
4626 // Either the user wants Google Test to catch exceptions thrown by the
4627 // tests or this is executing in the context of death test child
4628 // process. In either case the user does not want to see pop-up dialogs
4629 // about crashes - they are expected.
4630 if (impl()->catch_exceptions() || in_death_test_child_process) {
4631# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4632 // SetErrorMode doesn't exist on CE.
4633 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
4634 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
4635# endif // !GTEST_OS_WINDOWS_MOBILE
4636
4637# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
4638 // Death test children can be terminated with _abort(). On Windows,
4639 // _abort() can show a dialog with a warning message. This forces the
4640 // abort message to go to stderr instead.
4641 _set_error_mode(_OUT_TO_STDERR);
4642# endif
4643
4644# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
4645 // In the debug version, Visual Studio pops up a separate dialog
4646 // offering a choice to debug the aborted program. We need to suppress
4647 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
4648 // executed. Google Test will notify the user of any unexpected
4649 // failure via stderr.
4650 //
4651 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
4652 // Users of prior VC versions shall suffer the agony and pain of
4653 // clicking through the countless debug dialogs.
4654 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
4655 // debug mode when compiled with VC 7.1 or lower.
4656 if (!GTEST_FLAG(break_on_failure))
4657 _set_abort_behavior(
4658 0x0, // Clear the following flags:
4659 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
4660# endif
4661 }
4662#endif // GTEST_HAS_SEH
4663
4665 impl(),
4667 "auxiliary test code (environments or event listeners)") ? 0 : 1;
4668}
4669
4670// Returns the working directory when the first TEST() or TEST_F() was
4671// executed.
4673 return impl_->original_working_dir_.c_str();
4674}
4675
4676// Returns the TestCase object for the test that's currently running,
4677// or NULL if no test is running.
4679 GTEST_LOCK_EXCLUDED_(mutex_) {
4680 internal::MutexLock lock(&mutex_);
4681 return impl_->current_test_case();
4682}
4683
4684// Returns the TestInfo object for the test that's currently running,
4685// or NULL if no test is running.
4687 GTEST_LOCK_EXCLUDED_(mutex_) {
4688 internal::MutexLock lock(&mutex_);
4689 return impl_->current_test_info();
4690}
4691
4692// Returns the random seed used at the start of the current test run.
4693int UnitTest::random_seed() const { return impl_->random_seed(); }
4694
4695// Returns ParameterizedTestCaseRegistry object used to keep track of
4696// value-parameterized tests and instantiate and register them.
4702
4703// Creates an empty UnitTest.
4704UnitTest::UnitTest() {
4705 impl_ = new internal::UnitTestImpl(this);
4706}
4707
4708// Destructor of UnitTest.
4709UnitTest::~UnitTest() {
4710 delete impl_;
4711}
4712
4713// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
4714// Google Test trace stack.
4715void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
4716 GTEST_LOCK_EXCLUDED_(mutex_) {
4717 internal::MutexLock lock(&mutex_);
4718 impl_->gtest_trace_stack().push_back(trace);
4719}
4720
4721// Pops a trace from the per-thread Google Test trace stack.
4722void UnitTest::PopGTestTrace()
4723 GTEST_LOCK_EXCLUDED_(mutex_) {
4724 internal::MutexLock lock(&mutex_);
4725 impl_->gtest_trace_stack().pop_back();
4726}
4727
4728namespace internal {
4729
4731 : parent_(parent),
4732 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
4733 default_global_test_part_result_reporter_(this),
4734 default_per_thread_test_part_result_reporter_(this),
4736 global_test_part_result_repoter_(
4737 &default_global_test_part_result_reporter_),
4738 per_thread_test_part_result_reporter_(
4739 &default_per_thread_test_part_result_reporter_),
4740 parameterized_test_registry_(),
4741 parameterized_tests_registered_(false),
4742 last_death_test_case_(-1),
4743 current_test_case_(NULL),
4744 current_test_info_(NULL),
4745 ad_hoc_test_result_(),
4746 os_stack_trace_getter_(NULL),
4747 post_flag_parse_init_performed_(false),
4748 random_seed_(0), // Will be overridden by the flag before first use.
4749 random_(0), // Will be reseeded before first use.
4750 start_timestamp_(0),
4751 elapsed_time_(0),
4752#if GTEST_HAS_DEATH_TEST
4753 death_test_factory_(new DefaultDeathTestFactory),
4754#endif
4755 // Will be overridden by the flag before first use.
4756 catch_exceptions_(false) {
4757 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
4758}
4759
4761 // Deletes every TestCase.
4762 ForEach(test_cases_, internal::Delete<TestCase>);
4763
4764 // Deletes every Environment.
4765 ForEach(environments_, internal::Delete<Environment>);
4766
4767 delete os_stack_trace_getter_;
4768}
4769
4770// Adds a TestProperty to the current TestResult object when invoked in a
4771// context of a test, to current test case's ad_hoc_test_result when invoke
4772// from SetUpTestCase/TearDownTestCase, or to the global property set
4773// otherwise. If the result already contains a property with the same key,
4774// the value will be updated.
4775void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
4776 std::string xml_element;
4777 TestResult* test_result; // TestResult appropriate for property recording.
4778
4779 if (current_test_info_ != NULL) {
4780 xml_element = "testcase";
4781 test_result = &(current_test_info_->result_);
4782 } else if (current_test_case_ != NULL) {
4783 xml_element = "testsuite";
4784 test_result = &(current_test_case_->ad_hoc_test_result_);
4785 } else {
4786 xml_element = "testsuites";
4787 test_result = &ad_hoc_test_result_;
4788 }
4789 test_result->RecordProperty(xml_element, test_property);
4790}
4791
4792#if GTEST_HAS_DEATH_TEST
4793// Disables event forwarding if the control is currently in a death test
4794// subprocess. Must not be called before InitGoogleTest.
4795void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
4796 if (internal_run_death_test_flag_.get() != NULL)
4797 listeners()->SuppressEventForwarding();
4798}
4799#endif // GTEST_HAS_DEATH_TEST
4800
4801// Initializes event listeners performing XML output as specified by
4802// UnitTestOptions. Must not be called before InitGoogleTest.
4804 const std::string& output_format = UnitTestOptions::GetOutputFormat();
4805 if (output_format == "xml") {
4806 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
4808 } else if (output_format == "json") {
4809 listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
4811 } else if (output_format != "") {
4812 GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
4813 << output_format << "\" ignored.";
4814 }
4815}
4816
4817#if GTEST_CAN_STREAM_RESULTS_
4818// Initializes event listeners for streaming test results in string form.
4819// Must not be called before InitGoogleTest.
4820void UnitTestImpl::ConfigureStreamingOutput() {
4821 const std::string& target = GTEST_FLAG(stream_result_to);
4822 if (!target.empty()) {
4823 const size_t pos = target.find(':');
4824 if (pos != std::string::npos) {
4825 listeners()->Append(new StreamingListener(target.substr(0, pos),
4826 target.substr(pos+1)));
4827 } else {
4828 GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
4829 << "\" ignored.";
4830 }
4831 }
4832}
4833#endif // GTEST_CAN_STREAM_RESULTS_
4834
4835// Performs initialization dependent upon flag values obtained in
4836// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
4837// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
4838// this function is also called from RunAllTests. Since this function can be
4839// called more than once, it has to be idempotent.
4841 // Ensures that this function does not execute more than once.
4842 if (!post_flag_parse_init_performed_) {
4843 post_flag_parse_init_performed_ = true;
4844
4845#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
4846 // Register to send notifications about key process state changes.
4847 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
4848#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
4849
4850#if GTEST_HAS_DEATH_TEST
4851 InitDeathTestSubprocessControlInfo();
4852 SuppressTestEventsIfInSubprocess();
4853#endif // GTEST_HAS_DEATH_TEST
4854
4855 // Registers parameterized tests. This makes parameterized tests
4856 // available to the UnitTest reflection API without running
4857 // RUN_ALL_TESTS.
4859
4860 // Configures listeners for XML output. This makes it possible for users
4861 // to shut down the default XML output before invoking RUN_ALL_TESTS.
4863
4864#if GTEST_CAN_STREAM_RESULTS_
4865 // Configures listeners for streaming test results to the specified server.
4866 ConfigureStreamingOutput();
4867#endif // GTEST_CAN_STREAM_RESULTS_
4868 }
4869}
4870
4871// A predicate that checks the name of a TestCase against a known
4872// value.
4873//
4874// This is used for implementation of the UnitTest class only. We put
4875// it in the anonymous namespace to prevent polluting the outer
4876// namespace.
4877//
4878// TestCaseNameIs is copyable.
4880 public:
4881 // Constructor.
4882 explicit TestCaseNameIs(const std::string& name)
4883 : name_(name) {}
4884
4885 // Returns true iff the name of test_case matches name_.
4886 bool operator()(const TestCase* test_case) const {
4887 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
4888 }
4889
4890 private:
4891 std::string name_;
4892};
4893
4894// Finds and returns a TestCase with the given name. If one doesn't
4895// exist, creates one and returns it. It's the CALLER'S
4896// RESPONSIBILITY to ensure that this function is only called WHEN THE
4897// TESTS ARE NOT SHUFFLED.
4898//
4899// Arguments:
4900//
4901// test_case_name: name of the test case
4902// type_param: the name of the test case's type parameter, or NULL if
4903// this is not a typed or a type-parameterized test case.
4904// set_up_tc: pointer to the function that sets up the test case
4905// tear_down_tc: pointer to the function that tears down the test case
4906TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
4907 const char* type_param,
4908 Test::SetUpTestCaseFunc set_up_tc,
4909 Test::TearDownTestCaseFunc tear_down_tc) {
4910 // Can we find a TestCase with the given name?
4911 const std::vector<TestCase*>::const_reverse_iterator test_case =
4912 std::find_if(test_cases_.rbegin(), test_cases_.rend(),
4913 TestCaseNameIs(test_case_name));
4914
4915 if (test_case != test_cases_.rend())
4916 return *test_case;
4917
4918 // No. Let's create one.
4919 TestCase* const new_test_case =
4920 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
4921
4922 // Is this a death test case?
4924 kDeathTestCaseFilter)) {
4925 // Yes. Inserts the test case after the last death test case
4926 // defined so far. This only works when the test cases haven't
4927 // been shuffled. Otherwise we may end up running a death test
4928 // after a non-death test.
4929 ++last_death_test_case_;
4930 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
4931 new_test_case);
4932 } else {
4933 // No. Appends to the end of the list.
4934 test_cases_.push_back(new_test_case);
4935 }
4936
4937 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
4938 return new_test_case;
4939}
4940
4941// Helpers for setting up / tearing down the given environment. They
4942// are for use in the ForEach() function.
4943static void SetUpEnvironment(Environment* env) { env->SetUp(); }
4944static void TearDownEnvironment(Environment* env) { env->TearDown(); }
4945
4946// Runs all tests in this UnitTest object, prints the result, and
4947// returns true if all tests are successful. If any exception is
4948// thrown during a test, the test is considered to be failed, but the
4949// rest of the tests will still be run.
4950//
4951// When parameterized tests are enabled, it expands and registers
4952// parameterized tests first in RegisterParameterizedTests().
4953// All other functions called from RunAllTests() may safely assume that
4954// parameterized tests are ready to be counted and run.
4956 // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
4957 const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
4958
4959 // Do not run any test if the --help flag was specified.
4960 if (g_help_flag)
4961 return true;
4962
4963 // Repeats the call to the post-flag parsing initialization in case the
4964 // user didn't call InitGoogleTest.
4966
4967 // Even if sharding is not on, test runners may want to use the
4968 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
4969 // protocol.
4971
4972 // True iff we are in a subprocess for running a thread-safe-style
4973 // death test.
4974 bool in_subprocess_for_death_test = false;
4975
4976#if GTEST_HAS_DEATH_TEST
4977 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
4978# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
4979 if (in_subprocess_for_death_test) {
4980 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
4981 }
4982# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
4983#endif // GTEST_HAS_DEATH_TEST
4984
4985 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
4986 in_subprocess_for_death_test);
4987
4988 // Compares the full test names with the filter to decide which
4989 // tests to run.
4990 const bool has_tests_to_run = FilterTests(should_shard
4993
4994 // Lists the tests and exits if the --gtest_list_tests flag was specified.
4995 if (GTEST_FLAG(list_tests)) {
4996 // This must be called *after* FilterTests() has been called.
4998 return true;
4999 }
5000
5001 random_seed_ = GTEST_FLAG(shuffle) ?
5002 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5003
5004 // True iff at least one test has failed.
5005 bool failed = false;
5006
5007 TestEventListener* repeater = listeners()->repeater();
5008
5009 start_timestamp_ = GetTimeInMillis();
5010 repeater->OnTestProgramStart(*parent_);
5011
5012 // How many times to repeat the tests? We don't want to repeat them
5013 // when we are inside the subprocess of a death test.
5014 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5015 // Repeats forever if the repeat count is negative.
5016 const bool forever = repeat < 0;
5017 for (int i = 0; forever || i != repeat; i++) {
5018 // We want to preserve failures generated by ad-hoc test
5019 // assertions executed before RUN_ALL_TESTS().
5021
5022 const TimeInMillis start = GetTimeInMillis();
5023
5024 // Shuffles test cases and tests if requested.
5025 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5026 random()->Reseed(random_seed_);
5027 // This should be done before calling OnTestIterationStart(),
5028 // such that a test event listener can see the actual test order
5029 // in the event.
5030 ShuffleTests();
5031 }
5032
5033 // Tells the unit test event listeners that the tests are about to start.
5034 repeater->OnTestIterationStart(*parent_, i);
5035
5036 // Runs each test case if there is at least one test to run.
5037 if (has_tests_to_run) {
5038 // Sets up all environments beforehand.
5039 repeater->OnEnvironmentsSetUpStart(*parent_);
5040 ForEach(environments_, SetUpEnvironment);
5041 repeater->OnEnvironmentsSetUpEnd(*parent_);
5042
5043 // Runs the tests only if there was no fatal failure during global
5044 // set-up.
5045 if (!Test::HasFatalFailure()) {
5046 for (int test_index = 0; test_index < total_test_case_count();
5047 test_index++) {
5048 GetMutableTestCase(test_index)->Run();
5049 }
5050 }
5051
5052 // Tears down all environments in reverse order afterwards.
5053 repeater->OnEnvironmentsTearDownStart(*parent_);
5054 std::for_each(environments_.rbegin(), environments_.rend(),
5055 TearDownEnvironment);
5056 repeater->OnEnvironmentsTearDownEnd(*parent_);
5057 }
5058
5059 elapsed_time_ = GetTimeInMillis() - start;
5060
5061 // Tells the unit test event listener that the tests have just finished.
5062 repeater->OnTestIterationEnd(*parent_, i);
5063
5064 // Gets the result and clears it.
5065 if (!Passed()) {
5066 failed = true;
5067 }
5068
5069 // Restores the original test order after the iteration. This
5070 // allows the user to quickly repro a failure that happens in the
5071 // N-th iteration without repeating the first (N - 1) iterations.
5072 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5073 // case the user somehow changes the value of the flag somewhere
5074 // (it's always safe to unshuffle the tests).
5076
5077 if (GTEST_FLAG(shuffle)) {
5078 // Picks a new random seed for each iteration.
5079 random_seed_ = GetNextRandomSeed(random_seed_);
5080 }
5081 }
5082
5083 repeater->OnTestProgramEnd(*parent_);
5084
5085 if (!gtest_is_initialized_before_run_all_tests) {
5086 ColoredPrintf(
5087 COLOR_RED,
5088 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5089 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
5090 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5091 " will start to enforce the valid usage. "
5092 "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
5093#if GTEST_FOR_GOOGLE_
5094 ColoredPrintf(COLOR_RED,
5095 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5096#endif // GTEST_FOR_GOOGLE_
5097 }
5098
5099 return !failed;
5100}
5101
5102// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5103// if the variable is present. If a file already exists at this location, this
5104// function will write over it. If the variable is present, but the file cannot
5105// be created, prints an error and exits.
5107 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5108 if (test_shard_file != NULL) {
5109 FILE* const file = posix::FOpen(test_shard_file, "w");
5110 if (file == NULL) {
5111 ColoredPrintf(COLOR_RED,
5112 "Could not write to the test shard status file \"%s\" "
5113 "specified by the %s environment variable.\n",
5114 test_shard_file, kTestShardStatusFile);
5115 fflush(stdout);
5116 exit(EXIT_FAILURE);
5117 }
5118 fclose(file);
5119 }
5120}
5121
5122// Checks whether sharding is enabled by examining the relevant
5123// environment variable values. If the variables are present,
5124// but inconsistent (i.e., shard_index >= total_shards), prints
5125// an error and exits. If in_subprocess_for_death_test, sharding is
5126// disabled because it must only be applied to the original test
5127// process. Otherwise, we could filter out death tests we intended to execute.
5128bool ShouldShard(const char* total_shards_env,
5129 const char* shard_index_env,
5130 bool in_subprocess_for_death_test) {
5131 if (in_subprocess_for_death_test) {
5132 return false;
5133 }
5134
5135 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5136 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5137
5138 if (total_shards == -1 && shard_index == -1) {
5139 return false;
5140 } else if (total_shards == -1 && shard_index != -1) {
5141 const Message msg = Message()
5142 << "Invalid environment variables: you have "
5143 << kTestShardIndex << " = " << shard_index
5144 << ", but have left " << kTestTotalShards << " unset.\n";
5145 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5146 fflush(stdout);
5147 exit(EXIT_FAILURE);
5148 } else if (total_shards != -1 && shard_index == -1) {
5149 const Message msg = Message()
5150 << "Invalid environment variables: you have "
5151 << kTestTotalShards << " = " << total_shards
5152 << ", but have left " << kTestShardIndex << " unset.\n";
5153 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5154 fflush(stdout);
5155 exit(EXIT_FAILURE);
5156 } else if (shard_index < 0 || shard_index >= total_shards) {
5157 const Message msg = Message()
5158 << "Invalid environment variables: we require 0 <= "
5159 << kTestShardIndex << " < " << kTestTotalShards
5160 << ", but you have " << kTestShardIndex << "=" << shard_index
5161 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5162 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5163 fflush(stdout);
5164 exit(EXIT_FAILURE);
5165 }
5166
5167 return total_shards > 1;
5168}
5169
5170// Parses the environment variable var as an Int32. If it is unset,
5171// returns default_val. If it is not an Int32, prints an error
5172// and aborts.
5173Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5174 const char* str_val = posix::GetEnv(var);
5175 if (str_val == NULL) {
5176 return default_val;
5177 }
5178
5179 Int32 result;
5180 if (!ParseInt32(Message() << "The value of environment variable " << var,
5181 str_val, &result)) {
5182 exit(EXIT_FAILURE);
5183 }
5184 return result;
5185}
5186
5187// Given the total number of shards, the shard index, and the test id,
5188// returns true iff the test should be run on this shard. The test id is
5189// some arbitrary but unique non-negative integer assigned to each test
5190// method. Assumes that 0 <= shard_index < total_shards.
5191bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5192 return (test_id % total_shards) == shard_index;
5193}
5194
5195// Compares the name of each test with the user-specified filter to
5196// decide whether the test should be run, then records the result in
5197// each TestCase and TestInfo object.
5198// If shard_tests == true, further filters tests based on sharding
5199// variables in the environment - see
5200// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
5201// . Returns the number of tests that should run.
5203 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5204 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5205 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5206 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5207
5208 // num_runnable_tests are the number of tests that will
5209 // run across all shards (i.e., match filter and are not disabled).
5210 // num_selected_tests are the number of tests to be run on
5211 // this shard.
5212 int num_runnable_tests = 0;
5213 int num_selected_tests = 0;
5214 for (size_t i = 0; i < test_cases_.size(); i++) {
5215 TestCase* const test_case = test_cases_[i];
5216 const std::string &test_case_name = test_case->name();
5217 test_case->set_should_run(false);
5218
5219 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5220 TestInfo* const test_info = test_case->test_info_list()[j];
5221 const std::string test_name(test_info->name());
5222 // A test is disabled if test case name or test name matches
5223 // kDisableTestFilter.
5224 const bool is_disabled =
5226 kDisableTestFilter) ||
5228 kDisableTestFilter);
5229 test_info->is_disabled_ = is_disabled;
5230
5231 const bool matches_filter =
5233 test_name);
5234 test_info->matches_filter_ = matches_filter;
5235
5236 const bool is_runnable =
5237 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5238 matches_filter;
5239
5240 const bool is_in_another_shard =
5241 shard_tests != IGNORE_SHARDING_PROTOCOL &&
5242 !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
5243 test_info->is_in_another_shard_ = is_in_another_shard;
5244 const bool is_selected = is_runnable && !is_in_another_shard;
5245
5246 num_runnable_tests += is_runnable;
5247 num_selected_tests += is_selected;
5248
5249 test_info->should_run_ = is_selected;
5250 test_case->set_should_run(test_case->should_run() || is_selected);
5251 }
5252 }
5253 return num_selected_tests;
5254}
5255
5256// Prints the given C-string on a single line by replacing all '\n'
5257// characters with string "\\n". If the output takes more than
5258// max_length characters, only prints the first max_length characters
5259// and "...".
5260static void PrintOnOneLine(const char* str, int max_length) {
5261 if (str != NULL) {
5262 for (int i = 0; *str != '\0'; ++str) {
5263 if (i >= max_length) {
5264 printf("...");
5265 break;
5266 }
5267 if (*str == '\n') {
5268 printf("\\n");
5269 i += 2;
5270 } else {
5271 printf("%c", *str);
5272 ++i;
5273 }
5274 }
5275 }
5276}
5277
5278// Prints the names of the tests matching the user-specified filter flag.
5280 // Print at most this many characters for each type/value parameter.
5281 const int kMaxParamLength = 250;
5282
5283 for (size_t i = 0; i < test_cases_.size(); i++) {
5284 const TestCase* const test_case = test_cases_[i];
5285 bool printed_test_case_name = false;
5286
5287 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5288 const TestInfo* const test_info =
5289 test_case->test_info_list()[j];
5290 if (test_info->matches_filter_) {
5291 if (!printed_test_case_name) {
5292 printed_test_case_name = true;
5293 printf("%s.", test_case->name());
5294 if (test_case->type_param() != NULL) {
5295 printf(" # %s = ", kTypeParamLabel);
5296 // We print the type parameter on a single line to make
5297 // the output easy to parse by a program.
5298 PrintOnOneLine(test_case->type_param(), kMaxParamLength);
5299 }
5300 printf("\n");
5301 }
5302 printf(" %s", test_info->name());
5303 if (test_info->value_param() != NULL) {
5304 printf(" # %s = ", kValueParamLabel);
5305 // We print the value parameter on a single line to make the
5306 // output easy to parse by a program.
5307 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
5308 }
5309 printf("\n");
5310 }
5311 }
5312 }
5313 fflush(stdout);
5314}
5315
5316// Sets the OS stack trace getter.
5317//
5318// Does nothing if the input and the current OS stack trace getter are
5319// the same; otherwise, deletes the old getter and makes the input the
5320// current getter.
5323 if (os_stack_trace_getter_ != getter) {
5324 delete os_stack_trace_getter_;
5325 os_stack_trace_getter_ = getter;
5326 }
5327}
5328
5329// Returns the current OS stack trace getter if it is not NULL;
5330// otherwise, creates an OsStackTraceGetter, makes it the current
5331// getter, and returns it.
5333 if (os_stack_trace_getter_ == NULL) {
5334#ifdef GTEST_OS_STACK_TRACE_GETTER_
5335 os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
5336#else
5337 os_stack_trace_getter_ = new OsStackTraceGetter;
5338#endif // GTEST_OS_STACK_TRACE_GETTER_
5339 }
5340
5341 return os_stack_trace_getter_;
5342}
5343
5344// Returns the most specific TestResult currently running.
5346 if (current_test_info_ != NULL) {
5347 return &current_test_info_->result_;
5348 }
5349 if (current_test_case_ != NULL) {
5350 return &current_test_case_->ad_hoc_test_result_;
5351 }
5352 return &ad_hoc_test_result_;
5353}
5354
5355// Shuffles all test cases, and the tests within each test case,
5356// making sure that death tests are still run first.
5358 // Shuffles the death test cases.
5359 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5360
5361 // Shuffles the non-death test cases.
5362 ShuffleRange(random(), last_death_test_case_ + 1,
5363 static_cast<int>(test_cases_.size()), &test_case_indices_);
5364
5365 // Shuffles the tests inside each test case.
5366 for (size_t i = 0; i < test_cases_.size(); i++) {
5367 test_cases_[i]->ShuffleTests(random());
5368 }
5369}
5370
5371// Restores the test cases and tests to their order before the first shuffle.
5373 for (size_t i = 0; i < test_cases_.size(); i++) {
5374 // Unshuffles the tests in each test case.
5375 test_cases_[i]->UnshuffleTests();
5376 // Resets the index of each test case.
5377 test_case_indices_[i] = static_cast<int>(i);
5378 }
5379}
5380
5381// Returns the current OS stack trace as an std::string.
5382//
5383// The maximum number of stack frames to be included is specified by
5384// the gtest_stack_trace_depth flag. The skip_count parameter
5385// specifies the number of top frames to be skipped, which doesn't
5386// count against the number of frames to be included.
5387//
5388// For example, if Foo() calls Bar(), which in turn calls
5389// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5390// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5392 int skip_count) {
5393 // We pass skip_count + 1 to skip this wrapper function in addition
5394 // to what the user really wants to skip.
5395 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5396}
5397
5398// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5399// suppress unreachable code warnings.
5400namespace {
5401class ClassUniqueToAlwaysTrue {};
5402}
5403
5404bool IsTrue(bool condition) { return condition; }
5405
5407#if GTEST_HAS_EXCEPTIONS
5408 // This condition is always false so AlwaysTrue() never actually throws,
5409 // but it makes the compiler think that it may throw.
5410 if (IsTrue(false))
5411 throw ClassUniqueToAlwaysTrue();
5412#endif // GTEST_HAS_EXCEPTIONS
5413 return true;
5414}
5415
5416// If *pstr starts with the given prefix, modifies *pstr to be right
5417// past the prefix and returns true; otherwise leaves *pstr unchanged
5418// and returns false. None of pstr, *pstr, and prefix can be NULL.
5419bool SkipPrefix(const char* prefix, const char** pstr) {
5420 const size_t prefix_len = strlen(prefix);
5421 if (strncmp(*pstr, prefix, prefix_len) == 0) {
5422 *pstr += prefix_len;
5423 return true;
5424 }
5425 return false;
5426}
5427
5428// Parses a string as a command line flag. The string should have
5429// the format "--flag=value". When def_optional is true, the "=value"
5430// part can be omitted.
5431//
5432// Returns the value of the flag, or NULL if the parsing failed.
5433static const char* ParseFlagValue(const char* str, const char* flag,
5434 bool def_optional) {
5435 // str and flag must not be NULL.
5436 if (str == NULL || flag == NULL) return NULL;
5437
5438 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5439 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
5440 const size_t flag_len = flag_str.length();
5441 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5442
5443 // Skips the flag name.
5444 const char* flag_end = str + flag_len;
5445
5446 // When def_optional is true, it's OK to not have a "=value" part.
5447 if (def_optional && (flag_end[0] == '\0')) {
5448 return flag_end;
5449 }
5450
5451 // If def_optional is true and there are more characters after the
5452 // flag name, or if def_optional is false, there must be a '=' after
5453 // the flag name.
5454 if (flag_end[0] != '=') return NULL;
5455
5456 // Returns the string after "=".
5457 return flag_end + 1;
5458}
5459
5460// Parses a string for a bool flag, in the form of either
5461// "--flag=value" or "--flag".
5462//
5463// In the former case, the value is taken as true as long as it does
5464// not start with '0', 'f', or 'F'.
5465//
5466// In the latter case, the value is taken as true.
5467//
5468// On success, stores the value of the flag in *value, and returns
5469// true. On failure, returns false without changing *value.
5470static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5471 // Gets the value of the flag as a string.
5472 const char* const value_str = ParseFlagValue(str, flag, true);
5473
5474 // Aborts if the parsing failed.
5475 if (value_str == NULL) return false;
5476
5477 // Converts the string value to a bool.
5478 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5479 return true;
5480}
5481
5482// Parses a string for an Int32 flag, in the form of
5483// "--flag=value".
5484//
5485// On success, stores the value of the flag in *value, and returns
5486// true. On failure, returns false without changing *value.
5487bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5488 // Gets the value of the flag as a string.
5489 const char* const value_str = ParseFlagValue(str, flag, false);
5490
5491 // Aborts if the parsing failed.
5492 if (value_str == NULL) return false;
5493
5494 // Sets *value to the value of the flag.
5495 return ParseInt32(Message() << "The value of flag --" << flag,
5496 value_str, value);
5497}
5498
5499// Parses a string for a string flag, in the form of
5500// "--flag=value".
5501//
5502// On success, stores the value of the flag in *value, and returns
5503// true. On failure, returns false without changing *value.
5504template <typename String>
5505static bool ParseStringFlag(const char* str, const char* flag, String* value) {
5506 // Gets the value of the flag as a string.
5507 const char* const value_str = ParseFlagValue(str, flag, false);
5508
5509 // Aborts if the parsing failed.
5510 if (value_str == NULL) return false;
5511
5512 // Sets *value to the value of the flag.
5513 *value = value_str;
5514 return true;
5515}
5516
5517// Determines whether a string has a prefix that Google Test uses for its
5518// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5519// If Google Test detects that a command line flag has its prefix but is not
5520// recognized, it will print its help message. Flags starting with
5521// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5522// internal flags and do not trigger the help message.
5523static bool HasGoogleTestFlagPrefix(const char* str) {
5524 return (SkipPrefix("--", &str) ||
5525 SkipPrefix("-", &str) ||
5526 SkipPrefix("/", &str)) &&
5527 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5530}
5531
5532// Prints a string containing code-encoded text. The following escape
5533// sequences can be used in the string to control the text color:
5534//
5535// @@ prints a single '@' character.
5536// @R changes the color to red.
5537// @G changes the color to green.
5538// @Y changes the color to yellow.
5539// @D changes to the default terminal text color.
5540//
5541// TODO(wan@google.com): Write tests for this once we add stdout
5542// capturing to Google Test.
5543static void PrintColorEncoded(const char* str) {
5544 GTestColor color = COLOR_DEFAULT; // The current color.
5545
5546 // Conceptually, we split the string into segments divided by escape
5547 // sequences. Then we print one segment at a time. At the end of
5548 // each iteration, the str pointer advances to the beginning of the
5549 // next segment.
5550 for (;;) {
5551 const char* p = strchr(str, '@');
5552 if (p == NULL) {
5553 ColoredPrintf(color, "%s", str);
5554 return;
5555 }
5556
5557 ColoredPrintf(color, "%s", std::string(str, p).c_str());
5558
5559 const char ch = p[1];
5560 str = p + 2;
5561 if (ch == '@') {
5562 ColoredPrintf(color, "@");
5563 } else if (ch == 'D') {
5564 color = COLOR_DEFAULT;
5565 } else if (ch == 'R') {
5566 color = COLOR_RED;
5567 } else if (ch == 'G') {
5568 color = COLOR_GREEN;
5569 } else if (ch == 'Y') {
5570 color = COLOR_YELLOW;
5571 } else {
5572 --str;
5573 }
5574 }
5575}
5576
5577static const char kColorEncodedHelpMessage[] =
5578"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
5579"following command line flags to control its behavior:\n"
5580"\n"
5581"Test Selection:\n"
5582" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
5583" List the names of all tests instead of running them. The name of\n"
5584" TEST(Foo, Bar) is \"Foo.Bar\".\n"
5585" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
5586 "[@G-@YNEGATIVE_PATTERNS]@D\n"
5587" Run only the tests whose name matches one of the positive patterns but\n"
5588" none of the negative patterns. '?' matches any single character; '*'\n"
5589" matches any substring; ':' separates two patterns.\n"
5590" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
5591" Run all disabled tests too.\n"
5592"\n"
5593"Test Execution:\n"
5594" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
5595" Run the tests repeatedly; use a negative count to repeat forever.\n"
5596" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
5597" Randomize tests' orders on every iteration.\n"
5598" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
5599" Random number seed to use for shuffling test orders (between 1 and\n"
5600" 99999, or 0 to use a seed based on the current time).\n"
5601"\n"
5602"Test Output:\n"
5603" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
5604" Enable/disable colored output. The default is @Gauto@D.\n"
5605" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
5606" Don't print the elapsed time of each test.\n"
5607" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
5608 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
5609" Generate a JSON or XML report in the given directory or with the given\n"
5610" file name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
5611# if GTEST_CAN_STREAM_RESULTS_
5612" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
5613" Stream test results to the given server.\n"
5614# endif // GTEST_CAN_STREAM_RESULTS_
5615"\n"
5616"Assertion Behavior:\n"
5617# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5618" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
5619" Set the default death test style.\n"
5620# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5621" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
5622" Turn assertion failures into debugger break-points.\n"
5623" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
5624" Turn assertion failures into C++ exceptions for use by an external\n"
5625" test framework.\n"
5626" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
5627" Do not report exceptions as test failures. Instead, allow them\n"
5628" to crash the program or throw a pop-up (on Windows).\n"
5629"\n"
5630"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
5631 "the corresponding\n"
5632"environment variable of a flag (all letters in upper-case). For example, to\n"
5633"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
5634 "color=no@D or set\n"
5635"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
5636"\n"
5637"For more information, please read the " GTEST_NAME_ " documentation at\n"
5638"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
5639"(not one in your own code or tests), please report it to\n"
5640"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
5641
5642static bool ParseGoogleTestFlag(const char* const arg) {
5643 return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
5644 &GTEST_FLAG(also_run_disabled_tests)) ||
5645 ParseBoolFlag(arg, kBreakOnFailureFlag,
5646 &GTEST_FLAG(break_on_failure)) ||
5647 ParseBoolFlag(arg, kCatchExceptionsFlag,
5648 &GTEST_FLAG(catch_exceptions)) ||
5649 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
5650 ParseStringFlag(arg, kDeathTestStyleFlag,
5651 &GTEST_FLAG(death_test_style)) ||
5652 ParseBoolFlag(arg, kDeathTestUseFork,
5653 &GTEST_FLAG(death_test_use_fork)) ||
5654 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
5655 ParseStringFlag(arg, kInternalRunDeathTestFlag,
5656 &GTEST_FLAG(internal_run_death_test)) ||
5657 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
5658 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
5659 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
5660 ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
5661 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
5662 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
5663 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
5665 &GTEST_FLAG(stack_trace_depth)) ||
5666 ParseStringFlag(arg, kStreamResultToFlag,
5667 &GTEST_FLAG(stream_result_to)) ||
5668 ParseBoolFlag(arg, kThrowOnFailureFlag,
5669 &GTEST_FLAG(throw_on_failure));
5670}
5671
5672#if GTEST_USE_OWN_FLAGFILE_FLAG_
5673static void LoadFlagsFromFile(const std::string& path) {
5674 FILE* flagfile = posix::FOpen(path.c_str(), "r");
5675 if (!flagfile) {
5676 GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
5677 << "\"";
5678 }
5679 std::string contents(ReadEntireFile(flagfile));
5680 posix::FClose(flagfile);
5681 std::vector<std::string> lines;
5682 SplitString(contents, '\n', &lines);
5683 for (size_t i = 0; i < lines.size(); ++i) {
5684 if (lines[i].empty())
5685 continue;
5686 if (!ParseGoogleTestFlag(lines[i].c_str()))
5687 g_help_flag = true;
5688 }
5689}
5690#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
5691
5692// Parses the command line for Google Test flags, without initializing
5693// other parts of Google Test. The type parameter CharType can be
5694// instantiated to either char or wchar_t.
5695template <typename CharType>
5696void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
5697 for (int i = 1; i < *argc; i++) {
5698 const std::string arg_string = StreamableToString(argv[i]);
5699 const char* const arg = arg_string.c_str();
5700
5701 using internal::ParseBoolFlag;
5703 using internal::ParseStringFlag;
5704
5705 bool remove_flag = false;
5706 if (ParseGoogleTestFlag(arg)) {
5707 remove_flag = true;
5708#if GTEST_USE_OWN_FLAGFILE_FLAG_
5709 } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
5710 LoadFlagsFromFile(GTEST_FLAG(flagfile));
5711 remove_flag = true;
5712#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
5713 } else if (arg_string == "--help" || arg_string == "-h" ||
5714 arg_string == "-?" || arg_string == "/?" ||
5715 HasGoogleTestFlagPrefix(arg)) {
5716 // Both help flag and unrecognized Google Test flags (excluding
5717 // internal ones) trigger help display.
5718 g_help_flag = true;
5719 }
5720
5721 if (remove_flag) {
5722 // Shift the remainder of the argv list left by one. Note
5723 // that argv has (*argc + 1) elements, the last one always being
5724 // NULL. The following loop moves the trailing NULL element as
5725 // well.
5726 for (int j = i; j != *argc; j++) {
5727 argv[j] = argv[j + 1];
5728 }
5729
5730 // Decrements the argument count.
5731 (*argc)--;
5732
5733 // We also need to decrement the iterator as we just removed
5734 // an element.
5735 i--;
5736 }
5737 }
5738
5739 if (g_help_flag) {
5740 // We print the help here instead of in RUN_ALL_TESTS(), as the
5741 // latter may not be called at all if the user is using Google
5742 // Test with another testing framework.
5743 PrintColorEncoded(kColorEncodedHelpMessage);
5744 }
5745}
5746
5747// Parses the command line for Google Test flags, without initializing
5748// other parts of Google Test.
5749void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
5751}
5752void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
5754}
5755
5756// The internal implementation of InitGoogleTest().
5757//
5758// The type parameter CharType can be instantiated to either char or
5759// wchar_t.
5760template <typename CharType>
5761void InitGoogleTestImpl(int* argc, CharType** argv) {
5762 // We don't want to run the initialization code twice.
5763 if (GTestIsInitialized()) return;
5764
5765 if (*argc <= 0) return;
5766
5767 g_argvs.clear();
5768 for (int i = 0; i != *argc; i++) {
5769 g_argvs.push_back(StreamableToString(argv[i]));
5770 }
5771
5774}
5775
5776} // namespace internal
5777
5778// Initializes Google Test. This must be called before calling
5779// RUN_ALL_TESTS(). In particular, it parses a command line for the
5780// flags that Google Test recognizes. Whenever a Google Test flag is
5781// seen, it is removed from argv, and *argc is decremented.
5782//
5783// No value is returned. Instead, the Google Test flag variables are
5784// updated.
5785//
5786// Calling the function for the second time has no user-visible effect.
5787void InitGoogleTest(int* argc, char** argv) {
5788#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5789 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5790#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5792#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5793}
5794
5795// This overloaded version can be used in Windows programs compiled in
5796// UNICODE mode.
5797void InitGoogleTest(int* argc, wchar_t** argv) {
5798#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5799 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5800#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5802#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5803}
5804
5805std::string TempDir() {
5806#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
5807 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
5808#endif
5809
5810#if GTEST_OS_WINDOWS_MOBILE
5811 return "\\temp\\";
5812#elif GTEST_OS_WINDOWS
5813 const char* temp_dir = internal::posix::GetEnv("TEMP");
5814 if (temp_dir == NULL || temp_dir[0] == '\0')
5815 return "\\temp\\";
5816 else if (temp_dir[strlen(temp_dir) - 1] == '\\')
5817 return temp_dir;
5818 else
5819 return std::string(temp_dir) + "\\";
5820#elif GTEST_OS_LINUX_ANDROID
5821 return "/sdcard/";
5822#else
5823 return "/tmp/";
5824#endif // GTEST_OS_WINDOWS_MOBILE
5825}
5826
5827// Class ScopedTrace
5828
5829// Pushes the given source file location and message onto a per-thread
5830// trace stack maintained by Google Test.
5831void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
5832 internal::TraceInfo trace;
5833 trace.file = file;
5834 trace.line = line;
5835 trace.message.swap(message);
5836
5837 UnitTest::GetInstance()->PushGTestTrace(trace);
5838}
5839
5840// Pops the info pushed by the c'tor.
5842 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
5843 UnitTest::GetInstance()->PopGTestTrace();
5844}
5845
5846} // namespace testing
Catch::Generators::GeneratorWrapper< std::string > lines(std::string)
const mie::Vuint & p
Definition bn.cpp:27
const mie::Vuint & r
Definition bn.cpp:28
std::string name
AssertionResult(const AssertionResult &other)
Definition gtest.cc:1001
AssertionResult operator!() const
Definition gtest.cc:1016
const char * message() const
Definition gtest.h:314
virtual void TearDown()
Definition gtest.h:1010
virtual void SetUp()
Definition gtest.h:1007
std::string GetString() const
Definition gtest.cc:995
Message & operator<<(const T &val)
virtual void ReportTestPartResult(const TestPartResult &result)
Definition gtest.cc:621
ScopedFakeTestPartResultReporter(TestPartResultArray *result)
Definition gtest.cc:580
const char * type_param() const
Definition gtest.h:833
const TestInfo * GetTestInfo(int i) const
Definition gtest.cc:2751
int test_to_run_count() const
Definition gtest.cc:2714
int failed_test_count() const
Definition gtest.cc:2694
const char * name() const
Definition gtest.h:829
bool should_run() const
Definition gtest.h:840
TestCase(const char *name, const char *a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc)
Definition gtest.cc:2732
int disabled_test_count() const
Definition gtest.cc:2704
virtual ~TestCase()
Definition gtest.cc:2744
int successful_test_count() const
Definition gtest.cc:2689
int total_test_count() const
Definition gtest.cc:2719
friend class internal::UnitTestImpl
Definition gtest.h:882
TimeInMillis elapsed_time() const
Definition gtest.h:870
int reportable_disabled_test_count() const
Definition gtest.cc:2699
int reportable_test_count() const
Definition gtest.cc:2709
virtual void OnTestPartResult(const TestPartResult &test_part_result)=0
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 OnTestCaseStart(const TestCase &test_case)=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:4311
void Append(TestEventListener *listener)
Definition gtest.cc:4304
static void RecordProperty(const std::string &key, const std::string &value)
Definition gtest.cc:2253
virtual void SetUp()
Definition gtest.cc:2243
virtual ~Test()
Definition gtest.cc:2237
internal::SetUpTestCaseFunc SetUpTestCaseFunc
Definition gtest.h:403
friend class TestInfo
Definition gtest.h:399
static bool HasFatalFailure()
Definition gtest.cc:2505
virtual void TearDown()
Definition gtest.cc:2249
internal::TearDownTestCaseFunc TearDownTestCaseFunc
Definition gtest.h:404
const char * value_param() const
Definition gtest.h:692
const char * name() const
Definition gtest.h:680
const TestResult * result() const
Definition gtest.h:733
const char * test_case_name() const
Definition gtest.h:677
void Append(const TestPartResult &result)
virtual void ReportTestPartResult(const TestPartResult &result)=0
bool HasFatalFailure() const
Definition gtest.cc:2200
bool HasNonfatalFailure() const
Definition gtest.cc:2210
int total_part_count() const
Definition gtest.cc:2216
const TestProperty & GetTestProperty(int i) const
Definition gtest.cc:2053
TimeInMillis elapsed_time() const
Definition gtest.h:577
const TestPartResult & GetTestPartResult(int i) const
Definition gtest.cc:2044
bool Passed() const
Definition gtest.h:565
bool Failed() const
Definition gtest.cc:2186
int test_property_count() const
Definition gtest.cc:2221
const TestInfo * current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_)
Definition gtest.cc:4686
static UnitTest * GetInstance()
Definition gtest.cc:4374
int reportable_disabled_test_count() const
Definition gtest.cc:4425
const TestCase * current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_)
Definition gtest.cc:4678
int Run() GTEST_MUST_USE_RESULT_
Definition gtest.cc:4592
TimeInMillis start_timestamp() const
Definition gtest.cc:4447
int reportable_test_count() const
Definition gtest.cc:4435
int test_to_run_count() const
Definition gtest.cc:4443
int successful_test_count() const
Definition gtest.cc:4417
bool Failed() const
Definition gtest.cc:4461
const TestCase * GetTestCase(int i) const
Definition gtest.cc:4465
bool Passed() const
Definition gtest.cc:4457
internal::ParameterizedTestCaseRegistry & parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_)
Definition gtest.cc:4698
int total_test_case_count() const
Definition gtest.cc:4406
int test_case_to_run_count() const
Definition gtest.cc:4412
const TestResult & ad_hoc_test_result() const
Definition gtest.cc:4471
TestEventListeners & listeners()
Definition gtest.cc:4483
int failed_test_case_count() const
Definition gtest.cc:4401
int successful_test_case_count() const
Definition gtest.cc:4396
int failed_test_count() const
Definition gtest.cc:4422
TimeInMillis elapsed_time() const
Definition gtest.cc:4452
int disabled_test_count() const
Definition gtest.cc:4430
int random_seed() const
Definition gtest.cc:4693
const char * original_working_dir() const
Definition gtest.cc:4672
int total_test_count() const
Definition gtest.cc:4440
void operator=(const Message &message) const
Definition gtest.cc:382
AssertHelper(TestPartResult::Type type, const char *file, int line, const char *message)
Definition gtest.cc:370
DefaultGlobalTestPartResultReporter(UnitTestImpl *unit_test)
Definition gtest.cc:700
virtual void ReportTestPartResult(const TestPartResult &result)
Definition gtest.cc:703
DefaultPerThreadTestPartResultReporter(UnitTestImpl *unit_test)
Definition gtest.cc:709
virtual void ReportTestPartResult(const TestPartResult &result)
Definition gtest.cc:712
static FilePath GenerateUniqueFileName(const FilePath &directory, const FilePath &base_name, const char *extension)
bool CreateDirectoriesRecursively() const
const std::string & string() const
const char * c_str() const
static FilePath MakeFileName(const FilePath &directory, const FilePath &base_name, int number, const char *extension)
static FilePath ConcatPaths(const FilePath &directory, const FilePath &relative_path)
JsonUnitTestResultPrinter(const char *output_file)
Definition gtest.cc:3877
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
Definition gtest.cc:3884
virtual std::string CurrentStackTrace(int max_depth, int skip_count)
Definition gtest.cc:4246
virtual std::string CurrentStackTrace(int max_depth, int skip_count)=0
virtual void OnTestEnd(const TestInfo &test_info)
Definition gtest.cc:3173
virtual void OnTestStart(const TestInfo &test_info)
Definition gtest.cc:3154
static void PrintTestName(const char *test_case, const char *test)
Definition gtest.cc:3076
virtual void OnTestPartResult(const TestPartResult &result)
Definition gtest.cc:3162
virtual void OnTestCaseEnd(const TestCase &test_case)
Definition gtest.cc:3192
virtual void OnTestProgramStart(const UnitTest &)
Definition gtest.cc:3081
virtual void OnEnvironmentsSetUpStart(const UnitTest &unit_test)
Definition gtest.cc:3134
virtual void OnTestProgramEnd(const UnitTest &)
Definition gtest.cc:3093
virtual void OnEnvironmentsSetUpEnd(const UnitTest &)
Definition gtest.cc:3084
virtual void OnEnvironmentsTearDownEnd(const UnitTest &)
Definition gtest.cc:3091
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)
Definition gtest.cc:3100
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
Definition gtest.cc:3236
virtual void OnTestCaseStart(const TestCase &test_case)
Definition gtest.cc:3141
virtual void OnEnvironmentsTearDownStart(const UnitTest &unit_test)
Definition gtest.cc:3204
UInt32 Generate(UInt32 range)
Definition gtest.cc:319
static const UInt32 kMaxRange
ScopedPrematureExitFile(const char *premature_exit_filepath)
Definition gtest.cc:4257
SingleFailureChecker(const TestPartResultArray *results, TestPartResult::Type type, const std::string &substr)
Definition gtest.cc:687
static bool CaseInsensitiveCStringEquals(const char *lhs, const char *rhs)
Definition gtest.cc:1920
static bool CaseInsensitiveWideCStringEquals(const wchar_t *lhs, const wchar_t *rhs)
Definition gtest.cc:1940
static bool CStringEquals(const char *lhs, const char *rhs)
Definition gtest.cc:908
static bool EndsWithCaseInsensitive(const std::string &str, const std::string &suffix)
Definition gtest.cc:1964
static std::string ShowWideCString(const wchar_t *wide_c_str)
Definition gtest.cc:1863
static bool WideCStringEquals(const wchar_t *lhs, const wchar_t *rhs)
Definition gtest.cc:1875
static std::string FormatIntWidth2(int value)
Definition gtest.cc:1974
static std::string FormatByte(unsigned char value)
Definition gtest.cc:1988
static std::string FormatHexInt(int value)
Definition gtest.cc:1981
TestCaseNameIs(const std::string &name)
Definition gtest.cc:4882
bool operator()(const TestCase *test_case) const
Definition gtest.cc:4886
virtual void OnTestCaseEnd(const TestCase &test_case)
virtual void OnTestProgramStart(const UnitTest &unit_test)
virtual void OnEnvironmentsTearDownStart(const UnitTest &unit_test)
virtual void OnEnvironmentsSetUpEnd(const UnitTest &unit_test)
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)
Definition gtest.cc:3371
virtual void OnTestProgramEnd(const UnitTest &unit_test)
virtual void OnTestCaseStart(const TestCase &test_case)
virtual void OnTestStart(const TestInfo &test_info)
virtual void OnEnvironmentsTearDownEnd(const UnitTest &unit_test)
void set_forwarding_enabled(bool enable)
Definition gtest.cc:3289
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
Definition gtest.cc:3380
virtual void OnTestEnd(const TestInfo &test_info)
TestEventListener * Release(TestEventListener *listener)
Definition gtest.cc:3324
virtual void OnTestPartResult(const TestPartResult &result)
void Append(TestEventListener *listener)
Definition gtest.cc:3319
virtual void OnEnvironmentsSetUpStart(const UnitTest &unit_test)
int reportable_disabled_test_count() const
Definition gtest.cc:775
void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface *reporter)
Definition gtest.cc:738
void RecordProperty(const TestProperty &test_property)
Definition gtest.cc:4775
void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo *test_info)
TestPartResultReporterInterface * GetGlobalTestPartResultReporter()
Definition gtest.cc:719
int successful_test_case_count() const
Definition gtest.cc:744
void set_os_stack_trace_getter(OsStackTraceGetterInterface *getter)
Definition gtest.cc:5321
TestPartResultReporterInterface * GetTestPartResultReporterForCurrentThread()
Definition gtest.cc:733
UnitTestImpl(UnitTest *parent)
Definition gtest.cc:4730
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_
Definition gtest.cc:810
OsStackTraceGetterInterface * os_stack_trace_getter()
Definition gtest.cc:5332
void SetGlobalTestPartResultReporter(TestPartResultReporterInterface *reporter)
Definition gtest.cc:725
void set_current_test_info(TestInfo *a_current_test_info)
TestResult * current_test_result()
Definition gtest.cc:5345
int FilterTests(ReactionToSharding shard_tests)
Definition gtest.cc:5202
const TestCase * GetTestCase(int i) const
std::vector< Environment * > & environments()
int total_test_case_count() const
Definition gtest.cc:754
int successful_test_count() const
Definition gtest.cc:765
std::vector< TraceInfo > & gtest_trace_stack()
internal::ParameterizedTestCaseRegistry & parameterized_test_registry()
int reportable_test_count() const
Definition gtest.cc:786
const TestCase * current_test_case() const
int failed_test_case_count() const
Definition gtest.cc:749
int test_case_to_run_count() const
Definition gtest.cc:760
static bool MatchesFilter(const std::string &name, const char *filter)
Definition gtest.cc:496
static std::string GetAbsolutePathToOutputFile()
Definition gtest.cc:438
static bool FilterMatchesTest(const std::string &test_case_name, const std::string &test_name)
Definition gtest.cc:519
static std::string GetOutputFormat()
Definition gtest.cc:426
static bool PatternMatchesString(const char *pattern, const char *str)
Definition gtest.cc:479
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
Definition gtest.cc:3478
XmlUnitTestResultPrinter(const char *output_file)
Definition gtest.cc:3470
uint64_t id
Definition code_cache.cpp:0
os_t os
int * count
#define GTEST_FLAG_PREFIX_
Definition gtest-port.h:293
#define GTEST_NAME_
Definition gtest-port.h:296
#define GTEST_DEV_EMAIL_
Definition gtest-port.h:292
#define GTEST_FLAG_SAVER_
#define GTEST_FLAG_PREFIX_UPPER_
Definition gtest-port.h:295
#define GTEST_FLAG_PREFIX_DASH_
Definition gtest-port.h:294
#define GTEST_DEFINE_bool_(name, default_val, doc)
#define GTEST_PROJECT_URL_
Definition gtest-port.h:297
#define GTEST_LOCK_EXCLUDED_(locks)
#define GTEST_FLAG(name)
#define GTEST_DEFINE_STATIC_MUTEX_(mutex)
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
Definition gtest-port.h:324
#define GTEST_DEFINE_string_(name, default_val, doc)
#define GTEST_DEFINE_int32_(name, default_val, doc)
#define GTEST_LOG_(severity)
#define GTEST_INIT_GOOGLE_TEST_NAME_
Definition gtest-port.h:301
#define GTEST_API_
Definition gtest-port.h:984
#define GTEST_DISABLE_MSC_WARNINGS_POP_()
Definition gtest-port.h:325
#define GTEST_CHECK_(condition)
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
Definition gtest-port.h:917
#define GTEST_PATH_SEP_
#define GTEST_REPEATER_METHOD_(Name, Type)
Definition gtest.cc:3337
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
Definition gtest.cc:3347
#define GTEST_IMPL_CMP_HELPER_(op_name, op)
Definition gtest.h:1545
#define ADD_FAILURE()
Definition gtest.h:1844
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3)
char ** argv
void close(T *e, websocketpp::connection_hdl hdl)
void diff(const std::string &a, const std::string &b)
Definition jmp.cpp:18
return str
Definition CLI11.hpp:1359
LOGGING_API void printf(Category category, const char *format,...)
Definition Logging.cpp:30
static const Reg8 ch(Operand::CH)
static const Segment ss(Segment::ss)
exception_code
Definition exception.hpp:18
Definition name.hpp:106
void swap(picojson::value &x, picojson::value &y)
GTEST_API_ std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
Definition gtest.cc:1042
GTEST_API_ std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context=2)
Definition gtest.cc:1217
int StrCaseCmp(const char *s1, const char *s2)
int FileNo(FILE *file)
const char * GetEnv(const char *name)
FILE * FOpen(const char *path, const char *mode)
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
Definition gtest.cc:1838
long long BiggestInt
void(* TearDownTestCaseFunc)()
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:1326
GTestMutexLock MutexLock
GTEST_API_ std::string CodePointToUtf8(UInt32 code_point)
Definition gtest.cc:1774
std::string OutputFlagAlsoCheckEnvVar()
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
GTEST_API_ Int32 Int32FromGTestEnv(const char *flag, Int32 default_val)
GTEST_API_ bool ShouldShard(const char *total_shards_str, const char *shard_index_str, bool in_subprocess_for_death_test)
Definition gtest.cc:5128
const UInt32 kMaxCodePoint1
Definition gtest.cc:1748
AssertionResult FloatingPointLE(const char *expr1, const char *expr2, RawType val1, RawType val2)
Definition gtest.cc:1399
void WriteToShardStatusFileIfNeeded()
Definition gtest.cc:5106
const char kListTestsFlag[]
::std::vector< std::string > g_argvs
Definition gtest.cc:396
int CountIf(const Container &c, Predicate predicate)
GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
GTEST_API_ bool SkipPrefix(const char *prefix, const char **pstr)
Definition gtest.cc:5419
UInt32 ChopLowBits(UInt32 *bits, int n)
Definition gtest.cc:1762
GTEST_API_ std::string ReadEntireFile(FILE *file)
void(* SetUpTestCaseFunc)()
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1518
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
TypeWithSize< 4 >::UInt UInt32
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
Definition gtest.cc:5191
AssertionResult CmpHelperEQ(const char *lhs_expression, const char *rhs_expression, const T1 &lhs, const T2 &rhs)
Definition gtest.h:1428
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
Definition gtest.cc:5749
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:1377
GTEST_API_ bool IsTrue(bool condition)
Definition gtest.cc:5404
void ForEach(const Container &c, Functor functor)
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
Definition gtest.cc:3617
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:1361
TypeWithSize< 8 >::Int TimeInMillis
bool BoolFromGTestEnv(const char *flag, bool default_val)
bool IsUtf16SurrogatePair(wchar_t first, wchar_t second)
Definition gtest.cc:1809
int GetNextRandomSeed(int seed)
GTEST_API_ AssertionResult CmpHelperSTREQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1502
E GetElementOr(const std::vector< E > &v, int i, E default_value)
GTEST_API_ FilePath GetCurrentExecutableName()
Definition gtest.cc:411
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1548
const char * StringFromGTestEnv(const char *flag, const char *default_val)
GTEST_API_ TestInfo * MakeAndRegisterTestInfo(const char *test_case_name, const char *name, const char *type_param, const char *value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase *factory)
Definition gtest.cc:2561
const char kBreakOnFailureFlag[]
const char kStreamResultToFlag[]
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string &message)
Definition gtest.cc:2266
void SplitString(const ::std::string &str, char delimiter, ::std::vector< ::std::string > *dest)
Definition gtest.cc:936
TypeWithSize< 4 >::Int Int32
void PrintTo(const ReferenceWrapper< T > &ref, ::std::ostream *os)
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
Definition gtest.cc:3593
void Shuffle(internal::Random *random, std::vector< E > *v)
std::string FormatForComparisonFailureMessage(const T1 &value, const T2 &)
GTEST_API_ bool AlwaysTrue()
Definition gtest.cc:5406
GTEST_API_ bool g_help_flag
Definition gtest.cc:183
GTEST_API_ std::vector< std::string > GetArgvs()
Definition gtest.cc:398
const char kRandomSeedFlag[]
class UnitTestImpl * GetUnitTestImpl()
const char kFlagfileFlag[]
const UInt32 kMaxCodePoint3
Definition gtest.cc:1754
const char kPrintTimeFlag[]
GTEST_API_ Int32 Int32FromEnvOrDie(const char *env_var, Int32 default_val)
Definition gtest.cc:5173
std::string StreamableToString(const T &streamable)
const char kPrintUTF8Flag[]
const void * TypeId
GTEST_API_ void ReportInvalidTestCaseType(const char *test_case_name, CodeLocation code_location)
Definition gtest.cc:2578
const UInt32 kMaxCodePoint2
Definition gtest.cc:1751
GTEST_API_ const char kStackTraceMarker[]
Definition gtest.cc:179
bool ParseInt32(const Message &src_text, const char *str, Int32 *value)
GTEST_API_ std::string StringStreamToString(::std::stringstream *stream)
Definition gtest.cc:1997
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty)
Definition gtest.cc:2959
void InitGoogleTestImpl(int *argc, CharType **argv)
Definition gtest.cc:5761
Result HandleSehExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
Definition gtest.cc:2399
UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second)
Definition gtest.cc:1815
const UInt32 kMaxCodePoint4
Definition gtest.cc:1757
GTEST_API_ TypeId GetTestTypeId()
Definition gtest.cc:637
const char kAlsoRunDisabledTestsFlag[]
const char kStackTraceDepthFlag[]
const char kThrowOnFailureFlag[]
Result HandleExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
Definition gtest.cc:2426
GTEST_API_ bool ParseInt32Flag(const char *str, const char *flag, Int32 *value)
Definition gtest.cc:5487
GTEST_API_ std::string AppendUserMessage(const std::string &gtest_msg, const Message &user_msg)
Definition gtest.cc:2016
void ParseGoogleTestFlagsOnlyImpl(int *argc, CharType **argv)
Definition gtest.cc:5696
GTEST_API_ TimeInMillis GetTimeInMillis()
Definition gtest.cc:820
int GetRandomSeedFromFlag(Int32 random_seed_flag)
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest *unit_test, int skip_count)
Definition gtest.cc:5391
GTEST_API_ AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
Definition gtest.cc:1534
bool IsSpace(char ch)
const char kCatchExceptionsFlag[]
const char kShuffleFlag[]
GTEST_API_ AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition gtest.cc:1633
GTEST_API_ AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
Definition gtest.cc:1436
GTEST_API_ AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition gtest.cc:1621
GTEST_API_ AssertionResult AssertionFailure()
Definition gtest.cc:1029
internal::TimeInMillis TimeInMillis
Definition gtest.h:506
::std::string PrintToString(const T &value)
GTEST_API_ std::string TempDir()
Definition gtest.cc:5805
std::vector< std::string > ArrayAsVector(const char *const (&array)[kSize])
Definition gtest.cc:2123
GTEST_API_ AssertionResult AssertionSuccess()
Definition gtest.cc:1024
GTEST_API_ AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
Definition gtest.cc:1443
GTEST_API_ void InitGoogleTest(int *argc, char **argv)
Definition gtest.cc:5787
#define value
Definition pkcs11.h:157
#define T(meth, val, expected)
uint32_t num_failures
int add(int a, int b)
Definition lib.h:54
account_query_db::get_accounts_by_authorizers_result results
void fabs()
void lock()
uint16_t random
Definition yubico_otp.c:47
cmd_format format
uint16_t j
if(ppFunctionList==NULL)
yh_object_descriptor object
memset(pInfo->slotDescription, ' ', 64)