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