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