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