llvm.org GIT mirror llvm / efbdf7f
Move all of the GoogleTest files back to the same locations they occupy externally to simplify our integration of GoogleTest into LLVM. Also, build the single source file gtest-all.cc instead of the individual source files as we don't expect these to change and thus gain nothing from increased incrementality in compiles. This makes our standard build of googletest exactly like upstream's recommended build and the sanitizer's build. It also simplifies the steps of importing a new version should we ever want one. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@194801 91177308-0d34-0410-b5e6-96231b3b80d8 Chandler Carruth 7 years ago
21 changed file(s) with 8894 addition(s) and 8910 deletion(s). Raw diff Collapse all Expand all
1313 # Where gtest's .h files can be found.
1414 include_directories(
1515 googletest/include
16 googletest
1617 )
1718
1819 if(WIN32)
3738 endif ()
3839
3940 add_llvm_library(gtest
40 googletest/gtest.cc
41 googletest/gtest-death-test.cc
42 googletest/gtest-filepath.cc
43 googletest/gtest-port.cc
44 googletest/gtest-printers.cc
45 googletest/gtest-test-part.cc
46 googletest/gtest-typed-test.cc
41 googletest/src/gtest-all.cc
4742 )
4843
4944 add_llvm_library(gtest_main
1818 # unittests/Makefile.unittest and ../UnitTestMain/Makefile; ensure that any
1919 # changes are made to both.
2020 CPP.Flags += -I$(LLVM_SRC_ROOT)/utils/unittest/googletest/include
21 CPP.Flags += -I$(LLVM_SRC_ROOT)/utils/unittest/googletest
2122 CPP.Flags += $(NO_MISSING_FIELD_INITIALIZERS) $(NO_VARIADIC_MACROS)
2223 CPP.Flags += -DGTEST_HAS_RTTI=0
2324 # libstdc++'s TR1 header depends on RTTI and uses C++'0x features not
3536
3637 NO_INSTALL = 1
3738
38 SOURCES = $(filter-out gtest-all.cc, $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cc)))
39 SOURCES = src/gtest-all.cc
3940
4041 include $(LEVEL)/Makefile.common
99 $ rm -f aclocal* CMakeLists.txt configure* Makefile* CHANGES CONTRIBUTORS README
1010 $ rm -rf build-aux cmake codegear fused-src m4 make msvc samples scripts test xcode
1111 $ rm -f `find . -name \*\.pump`
12 $ rm -f src/gtest_main.cc
1213
13 # Move all the source files to the current directory
14 $ mv src/* .
15 $ rmdir src
16
17 # Move extra headers into the already-existing internal headers dir
18 $ mv *.h include/gtest/internal/
19
20 # Update paths to the included files
21 $ perl -pi -e 's|^#include "src/|#include "|' gtest-all.cc
22 $ perl -pi -e 's|^#include "src/|#include "gtest/internal/|' *.cc
23
24 $ rm -f gtest_main.cc
25
14 # Put the license in the consistent place for LLVM.
2615 $ mv COPYING LICENSE.TXT
27
2816
2917 Modified as follows:
3018 * To GTestStreamToHelper in include/gtest/internal/gtest-internal.h,
+0
-48
utils/unittest/googletest/gtest-all.cc less more
None // Copyright 2008, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: mheule@google.com (Markus Heule)
30 //
31 // Google C++ Testing Framework (Google Test)
32 //
33 // Sometimes it's desirable to build Google Test by compiling a single file.
34 // This file serves this purpose.
35
36 // This line ensures that gtest.h can be compiled on its own, even
37 // when it's fused.
38 #include "gtest/gtest.h"
39
40 // The following lines pull in the real gtest *.cc files.
41 #include "gtest.cc"
42 #include "gtest-death-test.cc"
43 #include "gtest-filepath.cc"
44 #include "gtest-port.cc"
45 #include "gtest-printers.cc"
46 #include "gtest-test-part.cc"
47 #include "gtest-typed-test.cc"
+0
-1233
utils/unittest/googletest/gtest-death-test.cc less more
None // Copyright 2005, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
30 //
31 // This file implements death tests.
32
33 #include "gtest/gtest-death-test.h"
34 #include "gtest/internal/gtest-port.h"
35
36 #if GTEST_HAS_DEATH_TEST
37
38 # if GTEST_OS_MAC
39 # include
40 # endif // GTEST_OS_MAC
41
42 # include
43 # include
44 # include
45 # include
46
47 # if GTEST_OS_WINDOWS
48 # include
49 # else
50 # include
51 # include
52 # endif // GTEST_OS_WINDOWS
53
54 #endif // GTEST_HAS_DEATH_TEST
55
56 #include "gtest/gtest-message.h"
57 #include "gtest/internal/gtest-string.h"
58
59 // Indicates that this translation unit is part of Google Test's
60 // implementation. It must come before gtest-internal-inl.h is
61 // included, or there will be a compiler error. This trick is to
62 // prevent a user from accidentally including gtest-internal-inl.h in
63 // his code.
64 #define GTEST_IMPLEMENTATION_ 1
65 #include "gtest/internal/gtest-internal-inl.h"
66 #undef GTEST_IMPLEMENTATION_
67
68 namespace testing {
69
70 // Constants.
71
72 // The default death test style.
73 static const char kDefaultDeathTestStyle[] = "fast";
74
75 GTEST_DEFINE_string_(
76 death_test_style,
77 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
78 "Indicates how to run a death test in a forked child process: "
79 "\"threadsafe\" (child process re-executes the test binary "
80 "from the beginning, running only the specific death test) or "
81 "\"fast\" (child process runs the death test immediately "
82 "after forking).");
83
84 GTEST_DEFINE_bool_(
85 death_test_use_fork,
86 internal::BoolFromGTestEnv("death_test_use_fork", false),
87 "Instructs to use fork()/_exit() instead of clone() in death tests. "
88 "Ignored and always uses fork() on POSIX systems where clone() is not "
89 "implemented. Useful when running under valgrind or similar tools if "
90 "those do not support clone(). Valgrind 3.3.1 will just fail if "
91 "it sees an unsupported combination of clone() flags. "
92 "It is not recommended to use this flag w/o valgrind though it will "
93 "work in 99% of the cases. Once valgrind is fixed, this flag will "
94 "most likely be removed.");
95
96 namespace internal {
97 GTEST_DEFINE_string_(
98 internal_run_death_test, "",
99 "Indicates the file, line number, temporal index of "
100 "the single death test to run, and a file descriptor to "
101 "which a success code may be sent, all separated by "
102 "colons. This flag is specified if and only if the current "
103 "process is a sub-process launched for running a thread-safe "
104 "death test. FOR INTERNAL USE ONLY.");
105 } // namespace internal
106
107 #if GTEST_HAS_DEATH_TEST
108
109 // ExitedWithCode constructor.
110 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
111 }
112
113 // ExitedWithCode function-call operator.
114 bool ExitedWithCode::operator()(int exit_status) const {
115 # if GTEST_OS_WINDOWS
116
117 return exit_status == exit_code_;
118
119 # else
120
121 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
122
123 # endif // GTEST_OS_WINDOWS
124 }
125
126 # if !GTEST_OS_WINDOWS
127 // KilledBySignal constructor.
128 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
129 }
130
131 // KilledBySignal function-call operator.
132 bool KilledBySignal::operator()(int exit_status) const {
133 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
134 }
135 # endif // !GTEST_OS_WINDOWS
136
137 namespace internal {
138
139 // Utilities needed for death tests.
140
141 // Generates a textual description of a given exit code, in the format
142 // specified by wait(2).
143 static String ExitSummary(int exit_code) {
144 Message m;
145
146 # if GTEST_OS_WINDOWS
147
148 m << "Exited with exit status " << exit_code;
149
150 # else
151
152 if (WIFEXITED(exit_code)) {
153 m << "Exited with exit status " << WEXITSTATUS(exit_code);
154 } else if (WIFSIGNALED(exit_code)) {
155 m << "Terminated by signal " << WTERMSIG(exit_code);
156 }
157 # ifdef WCOREDUMP
158 if (WCOREDUMP(exit_code)) {
159 m << " (core dumped)";
160 }
161 # endif
162 # endif // GTEST_OS_WINDOWS
163
164 return m.GetString();
165 }
166
167 // Returns true if exit_status describes a process that was terminated
168 // by a signal, or exited normally with a nonzero exit code.
169 bool ExitedUnsuccessfully(int exit_status) {
170 return !ExitedWithCode(0)(exit_status);
171 }
172
173 # if !GTEST_OS_WINDOWS
174 // Generates a textual failure message when a death test finds more than
175 // one thread running, or cannot determine the number of threads, prior
176 // to executing the given statement. It is the responsibility of the
177 // caller not to pass a thread_count of 1.
178 static String DeathTestThreadWarning(size_t thread_count) {
179 Message msg;
180 msg << "Death tests use fork(), which is unsafe particularly"
181 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
182 if (thread_count == 0)
183 msg << "couldn't detect the number of threads.";
184 else
185 msg << "detected " << thread_count << " threads.";
186 return msg.GetString();
187 }
188 # endif // !GTEST_OS_WINDOWS
189
190 // Flag characters for reporting a death test that did not die.
191 static const char kDeathTestLived = 'L';
192 static const char kDeathTestReturned = 'R';
193 static const char kDeathTestThrew = 'T';
194 static const char kDeathTestInternalError = 'I';
195
196 // An enumeration describing all of the possible ways that a death test can
197 // conclude. DIED means that the process died while executing the test
198 // code; LIVED means that process lived beyond the end of the test code;
199 // RETURNED means that the test statement attempted to execute a return
200 // statement, which is not allowed; THREW means that the test statement
201 // returned control by throwing an exception. IN_PROGRESS means the test
202 // has not yet concluded.
203 // TODO(vladl@google.com): Unify names and possibly values for
204 // AbortReason, DeathTestOutcome, and flag characters above.
205 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
206
207 // Routine for aborting the program which is safe to call from an
208 // exec-style death test child process, in which case the error
209 // message is propagated back to the parent process. Otherwise, the
210 // message is simply printed to stderr. In either case, the program
211 // then exits with status 1.
212 void DeathTestAbort(const String& message) {
213 // On a POSIX system, this function may be called from a threadsafe-style
214 // death test child process, which operates on a very small stack. Use
215 // the heap for any additional non-minuscule memory requirements.
216 const InternalRunDeathTestFlag* const flag =
217 GetUnitTestImpl()->internal_run_death_test_flag();
218 if (flag != NULL) {
219 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
220 fputc(kDeathTestInternalError, parent);
221 fprintf(parent, "%s", message.c_str());
222 fflush(parent);
223 _exit(1);
224 } else {
225 fprintf(stderr, "%s", message.c_str());
226 fflush(stderr);
227 posix::Abort();
228 }
229 }
230
231 // A replacement for CHECK that calls DeathTestAbort if the assertion
232 // fails.
233 # define GTEST_DEATH_TEST_CHECK_(expression) \
234 do { \
235 if (!::testing::internal::IsTrue(expression)) { \
236 DeathTestAbort(::testing::internal::String::Format( \
237 "CHECK failed: File %s, line %d: %s", \
238 __FILE__, __LINE__, #expression)); \
239 } \
240 } while (::testing::internal::AlwaysFalse())
241
242 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
243 // evaluating any system call that fulfills two conditions: it must return
244 // -1 on failure, and set errno to EINTR when it is interrupted and
245 // should be tried again. The macro expands to a loop that repeatedly
246 // evaluates the expression as long as it evaluates to -1 and sets
247 // errno to EINTR. If the expression evaluates to -1 but errno is
248 // something other than EINTR, DeathTestAbort is called.
249 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
250 do { \
251 int gtest_retval; \
252 do { \
253 gtest_retval = (expression); \
254 } while (gtest_retval == -1 && errno == EINTR); \
255 if (gtest_retval == -1) { \
256 DeathTestAbort(::testing::internal::String::Format( \
257 "CHECK failed: File %s, line %d: %s != -1", \
258 __FILE__, __LINE__, #expression)); \
259 } \
260 } while (::testing::internal::AlwaysFalse())
261
262 // Returns the message describing the last system error in errno.
263 String GetLastErrnoDescription() {
264 return String(errno == 0 ? "" : posix::StrError(errno));
265 }
266
267 // This is called from a death test parent process to read a failure
268 // message from the death test child process and log it with the FATAL
269 // severity. On Windows, the message is read from a pipe handle. On other
270 // platforms, it is read from a file descriptor.
271 static void FailFromInternalError(int fd) {
272 Message error;
273 char buffer[256];
274 int num_read;
275
276 do {
277 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
278 buffer[num_read] = '\0';
279 error << buffer;
280 }
281 } while (num_read == -1 && errno == EINTR);
282
283 if (num_read == 0) {
284 GTEST_LOG_(FATAL) << error.GetString();
285 } else {
286 const int last_error = errno;
287 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
288 << GetLastErrnoDescription() << " [" << last_error << "]";
289 }
290 }
291
292 // Death test constructor. Increments the running death test count
293 // for the current test.
294 DeathTest::DeathTest() {
295 TestInfo* const info = GetUnitTestImpl()->current_test_info();
296 if (info == NULL) {
297 DeathTestAbort("Cannot run a death test outside of a TEST or "
298 "TEST_F construct");
299 }
300 }
301
302 // Creates and returns a death test by dispatching to the current
303 // death test factory.
304 bool DeathTest::Create(const char* statement, const RE* regex,
305 const char* file, int line, DeathTest** test) {
306 return GetUnitTestImpl()->death_test_factory()->Create(
307 statement, regex, file, line, test);
308 }
309
310 const char* DeathTest::LastMessage() {
311 return last_death_test_message_.c_str();
312 }
313
314 void DeathTest::set_last_death_test_message(const String& message) {
315 last_death_test_message_ = message;
316 }
317
318 String DeathTest::last_death_test_message_;
319
320 // Provides cross platform implementation for some death functionality.
321 class DeathTestImpl : public DeathTest {
322 protected:
323 DeathTestImpl(const char* a_statement, const RE* a_regex)
324 : statement_(a_statement),
325 regex_(a_regex),
326 spawned_(false),
327 status_(-1),
328 outcome_(IN_PROGRESS),
329 read_fd_(-1),
330 write_fd_(-1) {}
331
332 // read_fd_ is expected to be closed and cleared by a derived class.
333 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
334
335 void Abort(AbortReason reason);
336 virtual bool Passed(bool status_ok);
337
338 const char* statement() const { return statement_; }
339 const RE* regex() const { return regex_; }
340 bool spawned() const { return spawned_; }
341 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
342 int status() const { return status_; }
343 void set_status(int a_status) { status_ = a_status; }
344 DeathTestOutcome outcome() const { return outcome_; }
345 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
346 int read_fd() const { return read_fd_; }
347 void set_read_fd(int fd) { read_fd_ = fd; }
348 int write_fd() const { return write_fd_; }
349 void set_write_fd(int fd) { write_fd_ = fd; }
350
351 // Called in the parent process only. Reads the result code of the death
352 // test child process via a pipe, interprets it to set the outcome_
353 // member, and closes read_fd_. Outputs diagnostics and terminates in
354 // case of unexpected codes.
355 void ReadAndInterpretStatusByte();
356
357 private:
358 // The textual content of the code this object is testing. This class
359 // doesn't own this string and should not attempt to delete it.
360 const char* const statement_;
361 // The regular expression which test output must match. DeathTestImpl
362 // doesn't own this object and should not attempt to delete it.
363 const RE* const regex_;
364 // True if the death test child process has been successfully spawned.
365 bool spawned_;
366 // The exit status of the child process.
367 int status_;
368 // How the death test concluded.
369 DeathTestOutcome outcome_;
370 // Descriptor to the read end of the pipe to the child process. It is
371 // always -1 in the child process. The child keeps its write end of the
372 // pipe in write_fd_.
373 int read_fd_;
374 // Descriptor to the child's write end of the pipe to the parent process.
375 // It is always -1 in the parent process. The parent keeps its end of the
376 // pipe in read_fd_.
377 int write_fd_;
378 };
379
380 // Called in the parent process only. Reads the result code of the death
381 // test child process via a pipe, interprets it to set the outcome_
382 // member, and closes read_fd_. Outputs diagnostics and terminates in
383 // case of unexpected codes.
384 void DeathTestImpl::ReadAndInterpretStatusByte() {
385 char flag;
386 int bytes_read;
387
388 // The read() here blocks until data is available (signifying the
389 // failure of the death test) or until the pipe is closed (signifying
390 // its success), so it's okay to call this in the parent before
391 // the child process has exited.
392 do {
393 bytes_read = posix::Read(read_fd(), &flag, 1);
394 } while (bytes_read == -1 && errno == EINTR);
395
396 if (bytes_read == 0) {
397 set_outcome(DIED);
398 } else if (bytes_read == 1) {
399 switch (flag) {
400 case kDeathTestReturned:
401 set_outcome(RETURNED);
402 break;
403 case kDeathTestThrew:
404 set_outcome(THREW);
405 break;
406 case kDeathTestLived:
407 set_outcome(LIVED);
408 break;
409 case kDeathTestInternalError:
410 FailFromInternalError(read_fd()); // Does not return.
411 break;
412 default:
413 GTEST_LOG_(FATAL) << "Death test child process reported "
414 << "unexpected status byte ("
415 << static_cast(flag) << ")";
416 }
417 } else {
418 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
419 << GetLastErrnoDescription();
420 }
421 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
422 set_read_fd(-1);
423 }
424
425 // Signals that the death test code which should have exited, didn't.
426 // Should be called only in a death test child process.
427 // Writes a status byte to the child's status file descriptor, then
428 // calls _exit(1).
429 void DeathTestImpl::Abort(AbortReason reason) {
430 // The parent process considers the death test to be a failure if
431 // it finds any data in our pipe. So, here we write a single flag byte
432 // to the pipe, then exit.
433 const char status_ch =
434 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
435 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
436
437 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
438 // We are leaking the descriptor here because on some platforms (i.e.,
439 // when built as Windows DLL), destructors of global objects will still
440 // run after calling _exit(). On such systems, write_fd_ will be
441 // indirectly closed from the destructor of UnitTestImpl, causing double
442 // close if it is also closed here. On debug configurations, double close
443 // may assert. As there are no in-process buffers to flush here, we are
444 // relying on the OS to close the descriptor after the process terminates
445 // when the destructors are not run.
446 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
447 }
448
449 // Returns an indented copy of stderr output for a death test.
450 // This makes distinguishing death test output lines from regular log lines
451 // much easier.
452 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
453 ::std::string ret;
454 for (size_t at = 0; ; ) {
455 const size_t line_end = output.find('\n', at);
456 ret += "[ DEATH ] ";
457 if (line_end == ::std::string::npos) {
458 ret += output.substr(at);
459 break;
460 }
461 ret += output.substr(at, line_end + 1 - at);
462 at = line_end + 1;
463 }
464 return ret;
465 }
466
467 // Assesses the success or failure of a death test, using both private
468 // members which have previously been set, and one argument:
469 //
470 // Private data members:
471 // outcome: An enumeration describing how the death test
472 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
473 // fails in the latter three cases.
474 // status: The exit status of the child process. On *nix, it is in the
475 // in the format specified by wait(2). On Windows, this is the
476 // value supplied to the ExitProcess() API or a numeric code
477 // of the exception that terminated the program.
478 // regex: A regular expression object to be applied to
479 // the test's captured standard error output; the death test
480 // fails if it does not match.
481 //
482 // Argument:
483 // status_ok: true if exit_status is acceptable in the context of
484 // this particular death test, which fails if it is false
485 //
486 // Returns true iff all of the above conditions are met. Otherwise, the
487 // first failing condition, in the order given above, is the one that is
488 // reported. Also sets the last death test message string.
489 bool DeathTestImpl::Passed(bool status_ok) {
490 if (!spawned())
491 return false;
492
493 const String error_message = GetCapturedStderr();
494
495 bool success = false;
496 Message buffer;
497
498 buffer << "Death test: " << statement() << "\n";
499 switch (outcome()) {
500 case LIVED:
501 buffer << " Result: failed to die.\n"
502 << " Error msg:\n" << FormatDeathTestOutput(error_message);
503 break;
504 case THREW:
505 buffer << " Result: threw an exception.\n"
506 << " Error msg:\n" << FormatDeathTestOutput(error_message);
507 break;
508 case RETURNED:
509 buffer << " Result: illegal return in test statement.\n"
510 << " Error msg:\n" << FormatDeathTestOutput(error_message);
511 break;
512 case DIED:
513 if (status_ok) {
514 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
515 if (matched) {
516 success = true;
517 } else {
518 buffer << " Result: died but not with expected error.\n"
519 << " Expected: " << regex()->pattern() << "\n"
520 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
521 }
522 } else {
523 buffer << " Result: died but not with expected exit code:\n"
524 << " " << ExitSummary(status()) << "\n"
525 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
526 }
527 break;
528 case IN_PROGRESS:
529 GTEST_LOG_(FATAL)
530 << "DeathTest::Passed somehow called before conclusion of test";
531 }
532
533 DeathTest::set_last_death_test_message(buffer.GetString());
534 return success;
535 }
536
537 # if GTEST_OS_WINDOWS
538 // WindowsDeathTest implements death tests on Windows. Due to the
539 // specifics of starting new processes on Windows, death tests there are
540 // always threadsafe, and Google Test considers the
541 // --gtest_death_test_style=fast setting to be equivalent to
542 // --gtest_death_test_style=threadsafe there.
543 //
544 // A few implementation notes: Like the Linux version, the Windows
545 // implementation uses pipes for child-to-parent communication. But due to
546 // the specifics of pipes on Windows, some extra steps are required:
547 //
548 // 1. The parent creates a communication pipe and stores handles to both
549 // ends of it.
550 // 2. The parent starts the child and provides it with the information
551 // necessary to acquire the handle to the write end of the pipe.
552 // 3. The child acquires the write end of the pipe and signals the parent
553 // using a Windows event.
554 // 4. Now the parent can release the write end of the pipe on its side. If
555 // this is done before step 3, the object's reference count goes down to
556 // 0 and it is destroyed, preventing the child from acquiring it. The
557 // parent now has to release it, or read operations on the read end of
558 // the pipe will not return when the child terminates.
559 // 5. The parent reads child's output through the pipe (outcome code and
560 // any possible error messages) from the pipe, and its stderr and then
561 // determines whether to fail the test.
562 //
563 // Note: to distinguish Win32 API calls from the local method and function
564 // calls, the former are explicitly resolved in the global namespace.
565 //
566 class WindowsDeathTest : public DeathTestImpl {
567 public:
568 WindowsDeathTest(const char* a_statement,
569 const RE* a_regex,
570 const char* file,
571 int line)
572 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
573
574 // All of these virtual functions are inherited from DeathTest.
575 virtual int Wait();
576 virtual TestRole AssumeRole();
577
578 private:
579 // The name of the file in which the death test is located.
580 const char* const file_;
581 // The line number on which the death test is located.
582 const int line_;
583 // Handle to the write end of the pipe to the child process.
584 AutoHandle write_handle_;
585 // Child process handle.
586 AutoHandle child_handle_;
587 // Event the child process uses to signal the parent that it has
588 // acquired the handle to the write end of the pipe. After seeing this
589 // event the parent can release its own handles to make sure its
590 // ReadFile() calls return when the child terminates.
591 AutoHandle event_handle_;
592 };
593
594 // Waits for the child in a death test to exit, returning its exit
595 // status, or 0 if no child process exists. As a side effect, sets the
596 // outcome data member.
597 int WindowsDeathTest::Wait() {
598 if (!spawned())
599 return 0;
600
601 // Wait until the child either signals that it has acquired the write end
602 // of the pipe or it dies.
603 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
604 switch (::WaitForMultipleObjects(2,
605 wait_handles,
606 FALSE, // Waits for any of the handles.
607 INFINITE)) {
608 case WAIT_OBJECT_0:
609 case WAIT_OBJECT_0 + 1:
610 break;
611 default:
612 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
613 }
614
615 // The child has acquired the write end of the pipe or exited.
616 // We release the handle on our side and continue.
617 write_handle_.Reset();
618 event_handle_.Reset();
619
620 ReadAndInterpretStatusByte();
621
622 // Waits for the child process to exit if it haven't already. This
623 // returns immediately if the child has already exited, regardless of
624 // whether previous calls to WaitForMultipleObjects synchronized on this
625 // handle or not.
626 GTEST_DEATH_TEST_CHECK_(
627 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
628 INFINITE));
629 DWORD status_code;
630 GTEST_DEATH_TEST_CHECK_(
631 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
632 child_handle_.Reset();
633 set_status(static_cast(status_code));
634 return status();
635 }
636
637 // The AssumeRole process for a Windows death test. It creates a child
638 // process with the same executable as the current process to run the
639 // death test. The child process is given the --gtest_filter and
640 // --gtest_internal_run_death_test flags such that it knows to run the
641 // current death test only.
642 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
643 const UnitTestImpl* const impl = GetUnitTestImpl();
644 const InternalRunDeathTestFlag* const flag =
645 impl->internal_run_death_test_flag();
646 const TestInfo* const info = impl->current_test_info();
647 const int death_test_index = info->result()->death_test_count();
648
649 if (flag != NULL) {
650 // ParseInternalRunDeathTestFlag() has performed all the necessary
651 // processing.
652 set_write_fd(flag->write_fd());
653 return EXECUTE_TEST;
654 }
655
656 // WindowsDeathTest uses an anonymous pipe to communicate results of
657 // a death test.
658 SECURITY_ATTRIBUTES handles_are_inheritable = {
659 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
660 HANDLE read_handle, write_handle;
661 GTEST_DEATH_TEST_CHECK_(
662 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
663 0) // Default buffer size.
664 != FALSE);
665 set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle),
666 O_RDONLY));
667 write_handle_.Reset(write_handle);
668 event_handle_.Reset(::CreateEvent(
669 &handles_are_inheritable,
670 TRUE, // The event will automatically reset to non-signaled state.
671 FALSE, // The initial state is non-signalled.
672 NULL)); // The even is unnamed.
673 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
674 const String filter_flag = String::Format("--%s%s=%s.%s",
675 GTEST_FLAG_PREFIX_, kFilterFlag,
676 info->test_case_name(),
677 info->name());
678 const String internal_flag = String::Format(
679 "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
680 GTEST_FLAG_PREFIX_,
681 kInternalRunDeathTestFlag,
682 file_, line_,
683 death_test_index,
684 static_cast(::GetCurrentProcessId()),
685 // size_t has the same with as pointers on both 32-bit and 64-bit
686 // Windows platforms.
687 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
688 reinterpret_cast(write_handle),
689 reinterpret_cast(event_handle_.Get()));
690
691 char executable_path[_MAX_PATH + 1]; // NOLINT
692 GTEST_DEATH_TEST_CHECK_(
693 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
694 executable_path,
695 _MAX_PATH));
696
697 String command_line = String::Format("%s %s \"%s\"",
698 ::GetCommandLineA(),
699 filter_flag.c_str(),
700 internal_flag.c_str());
701
702 DeathTest::set_last_death_test_message("");
703
704 CaptureStderr();
705 // Flush the log buffers since the log streams are shared with the child.
706 FlushInfoLog();
707
708 // The child process will share the standard handles with the parent.
709 STARTUPINFOA startup_info;
710 memset(&startup_info, 0, sizeof(STARTUPINFO));
711 startup_info.dwFlags = STARTF_USESTDHANDLES;
712 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
713 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
714 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
715
716 PROCESS_INFORMATION process_info;
717 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
718 executable_path,
719 const_cast(command_line.c_str()),
720 NULL, // Retuned process handle is not inheritable.
721 NULL, // Retuned thread handle is not inheritable.
722 TRUE, // Child inherits all inheritable handles (for write_handle_).
723 0x0, // Default creation flags.
724 NULL, // Inherit the parent's environment.
725 UnitTest::GetInstance()->original_working_dir(),
726 &startup_info,
727 &process_info) != FALSE);
728 child_handle_.Reset(process_info.hProcess);
729 ::CloseHandle(process_info.hThread);
730 set_spawned(true);
731 return OVERSEE_TEST;
732 }
733 # else // We are not on Windows.
734
735 // ForkingDeathTest provides implementations for most of the abstract
736 // methods of the DeathTest interface. Only the AssumeRole method is
737 // left undefined.
738 class ForkingDeathTest : public DeathTestImpl {
739 public:
740 ForkingDeathTest(const char* statement, const RE* regex);
741
742 // All of these virtual functions are inherited from DeathTest.
743 virtual int Wait();
744
745 protected:
746 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
747
748 private:
749 // PID of child process during death test; 0 in the child process itself.
750 pid_t child_pid_;
751 };
752
753 // Constructs a ForkingDeathTest.
754 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
755 : DeathTestImpl(a_statement, a_regex),
756 child_pid_(-1) {}
757
758 // Waits for the child in a death test to exit, returning its exit
759 // status, or 0 if no child process exists. As a side effect, sets the
760 // outcome data member.
761 int ForkingDeathTest::Wait() {
762 if (!spawned())
763 return 0;
764
765 ReadAndInterpretStatusByte();
766
767 int status_value;
768 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
769 set_status(status_value);
770 return status_value;
771 }
772
773 // A concrete death test class that forks, then immediately runs the test
774 // in the child process.
775 class NoExecDeathTest : public ForkingDeathTest {
776 public:
777 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
778 ForkingDeathTest(a_statement, a_regex) { }
779 virtual TestRole AssumeRole();
780 };
781
782 // The AssumeRole process for a fork-and-run death test. It implements a
783 // straightforward fork, with a simple pipe to transmit the status byte.
784 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
785 const size_t thread_count = GetThreadCount();
786 if (thread_count != 1) {
787 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
788 }
789
790 int pipe_fd[2];
791 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
792
793 DeathTest::set_last_death_test_message("");
794 CaptureStderr();
795 // When we fork the process below, the log file buffers are copied, but the
796 // file descriptors are shared. We flush all log files here so that closing
797 // the file descriptors in the child process doesn't throw off the
798 // synchronization between descriptors and buffers in the parent process.
799 // This is as close to the fork as possible to avoid a race condition in case
800 // there are multiple threads running before the death test, and another
801 // thread writes to the log file.
802 FlushInfoLog();
803
804 const pid_t child_pid = fork();
805 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
806 set_child_pid(child_pid);
807 if (child_pid == 0) {
808 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
809 set_write_fd(pipe_fd[1]);
810 // Redirects all logging to stderr in the child process to prevent
811 // concurrent writes to the log files. We capture stderr in the parent
812 // process and append the child process' output to a log.
813 LogToStderr();
814 // Event forwarding to the listeners of event listener API mush be shut
815 // down in death test subprocesses.
816 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
817 return EXECUTE_TEST;
818 } else {
819 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
820 set_read_fd(pipe_fd[0]);
821 set_spawned(true);
822 return OVERSEE_TEST;
823 }
824 }
825
826 // A concrete death test class that forks and re-executes the main
827 // program from the beginning, with command-line flags set that cause
828 // only this specific death test to be run.
829 class ExecDeathTest : public ForkingDeathTest {
830 public:
831 ExecDeathTest(const char* a_statement, const RE* a_regex,
832 const char* file, int line) :
833 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
834 virtual TestRole AssumeRole();
835 private:
836 // The name of the file in which the death test is located.
837 const char* const file_;
838 // The line number on which the death test is located.
839 const int line_;
840 };
841
842 // Utility class for accumulating command-line arguments.
843 class Arguments {
844 public:
845 Arguments() {
846 args_.push_back(NULL);
847 }
848
849 ~Arguments() {
850 for (std::vector::iterator i = args_.begin(); i != args_.end();
851 ++i) {
852 free(*i);
853 }
854 }
855 void AddArgument(const char* argument) {
856 args_.insert(args_.end() - 1, posix::StrDup(argument));
857 }
858
859 template
860 void AddArguments(const ::std::vector& arguments) {
861 for (typename ::std::vector::const_iterator i = arguments.begin();
862 i != arguments.end();
863 ++i) {
864 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
865 }
866 }
867 char* const* Argv() {
868 return &args_[0];
869 }
870 private:
871 std::vector args_;
872 };
873
874 // A struct that encompasses the arguments to the child process of a
875 // threadsafe-style death test process.
876 struct ExecDeathTestArgs {
877 char* const* argv; // Command-line arguments for the child's call to exec
878 int close_fd; // File descriptor to close; the read end of a pipe
879 };
880
881 # if GTEST_OS_MAC
882 inline char** GetEnviron() {
883 // When Google Test is built as a framework on MacOS X, the environ variable
884 // is unavailable. Apple's documentation (man environ) recommends using
885 // _NSGetEnviron() instead.
886 return *_NSGetEnviron();
887 }
888 # else
889 // Some POSIX platforms expect you to declare environ. extern "C" makes
890 // it reside in the global namespace.
891 extern "C" char** environ;
892 inline char** GetEnviron() { return environ; }
893 # endif // GTEST_OS_MAC
894
895 // The main function for a threadsafe-style death test child process.
896 // This function is called in a clone()-ed process and thus must avoid
897 // any potentially unsafe operations like malloc or libc functions.
898 static int ExecDeathTestChildMain(void* child_arg) {
899 ExecDeathTestArgs* const args = static_cast(child_arg);
900 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
901
902 // We need to execute the test program in the same environment where
903 // it was originally invoked. Therefore we change to the original
904 // working directory first.
905 const char* const original_dir =
906 UnitTest::GetInstance()->original_working_dir();
907 // We can safely call chdir() as it's a direct system call.
908 if (chdir(original_dir) != 0) {
909 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
910 original_dir,
911 GetLastErrnoDescription().c_str()));
912 return EXIT_FAILURE;
913 }
914
915 // We can safely call execve() as it's a direct system call. We
916 // cannot use execvp() as it's a libc function and thus potentially
917 // unsafe. Since execve() doesn't search the PATH, the user must
918 // invoke the test program via a valid path that contains at least
919 // one path separator.
920 execve(args->argv[0], args->argv, GetEnviron());
921 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
922 args->argv[0],
923 original_dir,
924 GetLastErrnoDescription().c_str()));
925 return EXIT_FAILURE;
926 }
927
928 // Two utility routines that together determine the direction the stack
929 // grows.
930 // This could be accomplished more elegantly by a single recursive
931 // function, but we want to guard against the unlikely possibility of
932 // a smart compiler optimizing the recursion away.
933 //
934 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
935 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
936 // correct answer.
937 bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_;
938 bool StackLowerThanAddress(const void* ptr) {
939 int dummy;
940 return &dummy < ptr;
941 }
942
943 bool StackGrowsDown() {
944 int dummy;
945 return StackLowerThanAddress(&dummy);
946 }
947
948 // A threadsafe implementation of fork(2) for threadsafe-style death tests
949 // that uses clone(2). It dies with an error message if anything goes
950 // wrong.
951 static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
952 ExecDeathTestArgs args = { argv, close_fd };
953 pid_t child_pid = -1;
954
955 # if GTEST_HAS_CLONE
956 const bool use_fork = GTEST_FLAG(death_test_use_fork);
957
958 if (!use_fork) {
959 static const bool stack_grows_down = StackGrowsDown();
960 const size_t stack_size = getpagesize();
961 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
962 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
963 MAP_ANON | MAP_PRIVATE, -1, 0);
964 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
965 void* const stack_top =
966 static_cast(stack) + (stack_grows_down ? stack_size : 0);
967
968 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
969
970 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
971 }
972 # else
973 const bool use_fork = true;
974 # endif // GTEST_HAS_CLONE
975
976 if (use_fork && (child_pid = fork()) == 0) {
977 ExecDeathTestChildMain(&args);
978 _exit(0);
979 }
980
981 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
982 return child_pid;
983 }
984
985 // The AssumeRole process for a fork-and-exec death test. It re-executes the
986 // main program from the beginning, setting the --gtest_filter
987 // and --gtest_internal_run_death_test flags to cause only the current
988 // death test to be re-run.
989 DeathTest::TestRole ExecDeathTest::AssumeRole() {
990 const UnitTestImpl* const impl = GetUnitTestImpl();
991 const InternalRunDeathTestFlag* const flag =
992 impl->internal_run_death_test_flag();
993 const TestInfo* const info = impl->current_test_info();
994 const int death_test_index = info->result()->death_test_count();
995
996 if (flag != NULL) {
997 set_write_fd(flag->write_fd());
998 return EXECUTE_TEST;
999 }
1000
1001 int pipe_fd[2];
1002 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
1003 // Clear the close-on-exec flag on the write end of the pipe, lest
1004 // it be closed when the child process does an exec:
1005 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
1006
1007 const String filter_flag =
1008 String::Format("--%s%s=%s.%s",
1009 GTEST_FLAG_PREFIX_, kFilterFlag,
1010 info->test_case_name(), info->name());
1011 const String internal_flag =
1012 String::Format("--%s%s=%s|%d|%d|%d",
1013 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
1014 file_, line_, death_test_index, pipe_fd[1]);
1015 Arguments args;
1016 args.AddArguments(GetArgvs());
1017 args.AddArgument(filter_flag.c_str());
1018 args.AddArgument(internal_flag.c_str());
1019
1020 DeathTest::set_last_death_test_message("");
1021
1022 CaptureStderr();
1023 // See the comment in NoExecDeathTest::AssumeRole for why the next line
1024 // is necessary.
1025 FlushInfoLog();
1026
1027 const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
1028 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
1029 set_child_pid(child_pid);
1030 set_read_fd(pipe_fd[0]);
1031 set_spawned(true);
1032 return OVERSEE_TEST;
1033 }
1034
1035 # endif // !GTEST_OS_WINDOWS
1036
1037 // Creates a concrete DeathTest-derived class that depends on the
1038 // --gtest_death_test_style flag, and sets the pointer pointed to
1039 // by the "test" argument to its address. If the test should be
1040 // skipped, sets that pointer to NULL. Returns true, unless the
1041 // flag is set to an invalid value.
1042 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
1043 const char* file, int line,
1044 DeathTest** test) {
1045 UnitTestImpl* const impl = GetUnitTestImpl();
1046 const InternalRunDeathTestFlag* const flag =
1047 impl->internal_run_death_test_flag();
1048 const int death_test_index = impl->current_test_info()
1049 ->increment_death_test_count();
1050
1051 if (flag != NULL) {
1052 if (death_test_index > flag->index()) {
1053 DeathTest::set_last_death_test_message(String::Format(
1054 "Death test count (%d) somehow exceeded expected maximum (%d)",
1055 death_test_index, flag->index()));
1056 return false;
1057 }
1058
1059 if (!(flag->file() == file && flag->line() == line &&
1060 flag->index() == death_test_index)) {
1061 *test = NULL;
1062 return true;
1063 }
1064 }
1065
1066 # if GTEST_OS_WINDOWS
1067
1068 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
1069 GTEST_FLAG(death_test_style) == "fast") {
1070 *test = new WindowsDeathTest(statement, regex, file, line);
1071 }
1072
1073 # else
1074
1075 if (GTEST_FLAG(death_test_style) == "threadsafe") {
1076 *test = new ExecDeathTest(statement, regex, file, line);
1077 } else if (GTEST_FLAG(death_test_style) == "fast") {
1078 *test = new NoExecDeathTest(statement, regex);
1079 }
1080
1081 # endif // GTEST_OS_WINDOWS
1082
1083 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
1084 DeathTest::set_last_death_test_message(String::Format(
1085 "Unknown death test style \"%s\" encountered",
1086 GTEST_FLAG(death_test_style).c_str()));
1087 return false;
1088 }
1089
1090 return true;
1091 }
1092
1093 // Splits a given string on a given delimiter, populating a given
1094 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
1095 // ::std::string, so we can use it here.
1096 static void SplitString(const ::std::string& str, char delimiter,
1097 ::std::vector< ::std::string>* dest) {
1098 ::std::vector< ::std::string> parsed;
1099 ::std::string::size_type pos = 0;
1100 while (::testing::internal::AlwaysTrue()) {
1101 const ::std::string::size_type colon = str.find(delimiter, pos);
1102 if (colon == ::std::string::npos) {
1103 parsed.push_back(str.substr(pos));
1104 break;
1105 } else {
1106 parsed.push_back(str.substr(pos, colon - pos));
1107 pos = colon + 1;
1108 }
1109 }
1110 dest->swap(parsed);
1111 }
1112
1113 # if GTEST_OS_WINDOWS
1114 // Recreates the pipe and event handles from the provided parameters,
1115 // signals the event, and returns a file descriptor wrapped around the pipe
1116 // handle. This function is called in the child process only.
1117 int GetStatusFileDescriptor(unsigned int parent_process_id,
1118 size_t write_handle_as_size_t,
1119 size_t event_handle_as_size_t) {
1120 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
1121 FALSE, // Non-inheritable.
1122 parent_process_id));
1123 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
1124 DeathTestAbort(String::Format("Unable to open parent process %u",
1125 parent_process_id));
1126 }
1127
1128 // TODO(vladl@google.com): Replace the following check with a
1129 // compile-time assertion when available.
1130 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
1131
1132 const HANDLE write_handle =
1133 reinterpret_cast(write_handle_as_size_t);
1134 HANDLE dup_write_handle;
1135
1136 // The newly initialized handle is accessible only in in the parent
1137 // process. To obtain one accessible within the child, we need to use
1138 // DuplicateHandle.
1139 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
1140 ::GetCurrentProcess(), &dup_write_handle,
1141 0x0, // Requested privileges ignored since
1142 // DUPLICATE_SAME_ACCESS is used.
1143 FALSE, // Request non-inheritable handler.
1144 DUPLICATE_SAME_ACCESS)) {
1145 DeathTestAbort(String::Format(
1146 "Unable to duplicate the pipe handle %Iu from the parent process %u",
1147 write_handle_as_size_t, parent_process_id));
1148 }
1149
1150 const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t);
1151 HANDLE dup_event_handle;
1152
1153 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
1154 ::GetCurrentProcess(), &dup_event_handle,
1155 0x0,
1156 FALSE,
1157 DUPLICATE_SAME_ACCESS)) {
1158 DeathTestAbort(String::Format(
1159 "Unable to duplicate the event handle %Iu from the parent process %u",
1160 event_handle_as_size_t, parent_process_id));
1161 }
1162
1163 const int write_fd =
1164 ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND);
1165 if (write_fd == -1) {
1166 DeathTestAbort(String::Format(
1167 "Unable to convert pipe handle %Iu to a file descriptor",
1168 write_handle_as_size_t));
1169 }
1170
1171 // Signals the parent that the write end of the pipe has been acquired
1172 // so the parent can release its own write end.
1173 ::SetEvent(dup_event_handle);
1174
1175 return write_fd;
1176 }
1177 # endif // GTEST_OS_WINDOWS
1178
1179 // Returns a newly created InternalRunDeathTestFlag object with fields
1180 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
1181 // the flag is specified; otherwise returns NULL.
1182 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
1183 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
1184
1185 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
1186 // can use it here.
1187 int line = -1;
1188 int index = -1;
1189 ::std::vector< ::std::string> fields;
1190 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
1191 int write_fd = -1;
1192
1193 # if GTEST_OS_WINDOWS
1194
1195 unsigned int parent_process_id = 0;
1196 size_t write_handle_as_size_t = 0;
1197 size_t event_handle_as_size_t = 0;
1198
1199 if (fields.size() != 6
1200 || !ParseNaturalNumber(fields[1], &line)
1201 || !ParseNaturalNumber(fields[2], &index)
1202 || !ParseNaturalNumber(fields[3], &parent_process_id)
1203 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
1204 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
1205 DeathTestAbort(String::Format(
1206 "Bad --gtest_internal_run_death_test flag: %s",
1207 GTEST_FLAG(internal_run_death_test).c_str()));
1208 }
1209 write_fd = GetStatusFileDescriptor(parent_process_id,
1210 write_handle_as_size_t,
1211 event_handle_as_size_t);
1212 # else
1213
1214 if (fields.size() != 4
1215 || !ParseNaturalNumber(fields[1], &line)
1216 || !ParseNaturalNumber(fields[2], &index)
1217 || !ParseNaturalNumber(fields[3], &write_fd)) {
1218 DeathTestAbort(String::Format(
1219 "Bad --gtest_internal_run_death_test flag: %s",
1220 GTEST_FLAG(internal_run_death_test).c_str()));
1221 }
1222
1223 # endif // GTEST_OS_WINDOWS
1224
1225 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
1226 }
1227
1228 } // namespace internal
1229
1230 #endif // GTEST_HAS_DEATH_TEST
1231
1232 } // namespace testing
+0
-378
utils/unittest/googletest/gtest-filepath.cc less more
None // Copyright 2008, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Authors: keith.ray@gmail.com (Keith Ray)
30
31 #include "gtest/internal/gtest-filepath.h"
32 #include "gtest/internal/gtest-port.h"
33
34 #include
35
36 #if GTEST_OS_WINDOWS_MOBILE
37 # include
38 #elif GTEST_OS_WINDOWS
39 # include
40 # include
41 #elif GTEST_OS_SYMBIAN || GTEST_OS_NACL
42 // Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h
43 # include
44 #else
45 # include
46 # include // Some Linux distributions define PATH_MAX here.
47 #endif // GTEST_OS_WINDOWS_MOBILE
48
49 #if GTEST_OS_WINDOWS
50 # define GTEST_PATH_MAX_ _MAX_PATH
51 #elif defined(PATH_MAX)
52 # define GTEST_PATH_MAX_ PATH_MAX
53 #elif defined(_XOPEN_PATH_MAX)
54 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
55 #else
56 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
57 #endif // GTEST_OS_WINDOWS
58
59 #include "gtest/internal/gtest-string.h"
60
61 namespace testing {
62 namespace internal {
63
64 #if GTEST_OS_WINDOWS
65 // On Windows, '\\' is the standard path separator, but many tools and the
66 // Windows API also accept '/' as an alternate path separator. Unless otherwise
67 // noted, a file path can contain either kind of path separators, or a mixture
68 // of them.
69 const char kPathSeparator = '\\';
70 const char kAlternatePathSeparator = '/';
71 const char kAlternatePathSeparatorString[] = "/";
72 # if GTEST_OS_WINDOWS_MOBILE
73 // Windows CE doesn't have a current directory. You should not use
74 // the current directory in tests on Windows CE, but this at least
75 // provides a reasonable fallback.
76 const char kCurrentDirectoryString[] = "\\";
77 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
78 const DWORD kInvalidFileAttributes = 0xffffffff;
79 # else
80 const char kCurrentDirectoryString[] = ".\\";
81 # endif // GTEST_OS_WINDOWS_MOBILE
82 #else
83 const char kPathSeparator = '/';
84 const char kCurrentDirectoryString[] = "./";
85 #endif // GTEST_OS_WINDOWS
86
87 // Returns whether the given character is a valid path separator.
88 static bool IsPathSeparator(char c) {
89 #if GTEST_HAS_ALT_PATH_SEP_
90 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
91 #else
92 return c == kPathSeparator;
93 #endif
94 }
95
96 // Returns the current working directory, or "" if unsuccessful.
97 FilePath FilePath::GetCurrentDir() {
98 #if GTEST_OS_WINDOWS_MOBILE
99 // Windows CE doesn't have a current directory, so we just return
100 // something reasonable.
101 return FilePath(kCurrentDirectoryString);
102 #elif GTEST_OS_WINDOWS
103 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
104 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
105 #else
106 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
107 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
108 #endif // GTEST_OS_WINDOWS_MOBILE
109 }
110
111 // Returns a copy of the FilePath with the case-insensitive extension removed.
112 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
113 // FilePath("dir/file"). If a case-insensitive extension is not
114 // found, returns a copy of the original FilePath.
115 FilePath FilePath::RemoveExtension(const char* extension) const {
116 String dot_extension(String::Format(".%s", extension));
117 if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
118 return FilePath(String(pathname_.c_str(), pathname_.length() - 4));
119 }
120 return *this;
121 }
122
123 // Returns a pointer to the last occurrence of a valid path separator in
124 // the FilePath. On Windows, for example, both '/' and '\' are valid path
125 // separators. Returns NULL if no path separator was found.
126 const char* FilePath::FindLastPathSeparator() const {
127 const char* const last_sep = strrchr(c_str(), kPathSeparator);
128 #if GTEST_HAS_ALT_PATH_SEP_
129 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
130 // Comparing two pointers of which only one is NULL is undefined.
131 if (last_alt_sep != NULL &&
132 (last_sep == NULL || last_alt_sep > last_sep)) {
133 return last_alt_sep;
134 }
135 #endif
136 return last_sep;
137 }
138
139 // Returns a copy of the FilePath with the directory part removed.
140 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
141 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
142 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
143 // returns an empty FilePath ("").
144 // On Windows platform, '\' is the path separator, otherwise it is '/'.
145 FilePath FilePath::RemoveDirectoryName() const {
146 const char* const last_sep = FindLastPathSeparator();
147 return last_sep ? FilePath(String(last_sep + 1)) : *this;
148 }
149
150 // RemoveFileName returns the directory path with the filename removed.
151 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
152 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
153 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
154 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
155 // On Windows platform, '\' is the path separator, otherwise it is '/'.
156 FilePath FilePath::RemoveFileName() const {
157 const char* const last_sep = FindLastPathSeparator();
158 String dir;
159 if (last_sep) {
160 dir = String(c_str(), last_sep + 1 - c_str());
161 } else {
162 dir = kCurrentDirectoryString;
163 }
164 return FilePath(dir);
165 }
166
167 // Helper functions for naming files in a directory for xml output.
168
169 // Given directory = "dir", base_name = "test", number = 0,
170 // extension = "xml", returns "dir/test.xml". If number is greater
171 // than zero (e.g., 12), returns "dir/test_12.xml".
172 // On Windows platform, uses \ as the separator rather than /.
173 FilePath FilePath::MakeFileName(const FilePath& directory,
174 const FilePath& base_name,
175 int number,
176 const char* extension) {
177 String file;
178 if (number == 0) {
179 file = String::Format("%s.%s", base_name.c_str(), extension);
180 } else {
181 file = String::Format("%s_%d.%s", base_name.c_str(), number, extension);
182 }
183 return ConcatPaths(directory, FilePath(file));
184 }
185
186 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
187 // On Windows, uses \ as the separator rather than /.
188 FilePath FilePath::ConcatPaths(const FilePath& directory,
189 const FilePath& relative_path) {
190 if (directory.IsEmpty())
191 return relative_path;
192 const FilePath dir(directory.RemoveTrailingPathSeparator());
193 return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
194 relative_path.c_str()));
195 }
196
197 // Returns true if pathname describes something findable in the file-system,
198 // either a file, directory, or whatever.
199 bool FilePath::FileOrDirectoryExists() const {
200 #if GTEST_OS_WINDOWS_MOBILE
201 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
202 const DWORD attributes = GetFileAttributes(unicode);
203 delete [] unicode;
204 return attributes != kInvalidFileAttributes;
205 #else
206 posix::StatStruct file_stat;
207 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
208 #endif // GTEST_OS_WINDOWS_MOBILE
209 }
210
211 // Returns true if pathname describes a directory in the file-system
212 // that exists.
213 bool FilePath::DirectoryExists() const {
214 bool result = false;
215 #if GTEST_OS_WINDOWS
216 // Don't strip off trailing separator if path is a root directory on
217 // Windows (like "C:\\").
218 const FilePath& path(IsRootDirectory() ? *this :
219 RemoveTrailingPathSeparator());
220 #else
221 const FilePath& path(*this);
222 #endif
223
224 #if GTEST_OS_WINDOWS_MOBILE
225 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
226 const DWORD attributes = GetFileAttributes(unicode);
227 delete [] unicode;
228 if ((attributes != kInvalidFileAttributes) &&
229 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
230 result = true;
231 }
232 #else
233 posix::StatStruct file_stat;
234 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
235 posix::IsDir(file_stat);
236 #endif // GTEST_OS_WINDOWS_MOBILE
237
238 return result;
239 }
240
241 // Returns true if pathname describes a root directory. (Windows has one
242 // root directory per disk drive.)
243 bool FilePath::IsRootDirectory() const {
244 #if GTEST_OS_WINDOWS
245 // TODO(wan@google.com): on Windows a network share like
246 // \\server\share can be a root directory, although it cannot be the
247 // current directory. Handle this properly.
248 return pathname_.length() == 3 && IsAbsolutePath();
249 #else
250 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
251 #endif
252 }
253
254 // Returns true if pathname describes an absolute path.
255 bool FilePath::IsAbsolutePath() const {
256 const char* const name = pathname_.c_str();
257 #if GTEST_OS_WINDOWS
258 return pathname_.length() >= 3 &&
259 ((name[0] >= 'a' && name[0] <= 'z') ||
260 (name[0] >= 'A' && name[0] <= 'Z')) &&
261 name[1] == ':' &&
262 IsPathSeparator(name[2]);
263 #else
264 return IsPathSeparator(name[0]);
265 #endif
266 }
267
268 // Returns a pathname for a file that does not currently exist. The pathname
269 // will be directory/base_name.extension or
270 // directory/base_name_.extension if directory/base_name.extension
271 // already exists. The number will be incremented until a pathname is found
272 // that does not already exist.
273 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
274 // There could be a race condition if two or more processes are calling this
275 // function at the same time -- they could both pick the same filename.
276 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
277 const FilePath& base_name,
278 const char* extension) {
279 FilePath full_pathname;
280 int number = 0;
281 do {
282 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
283 } while (full_pathname.FileOrDirectoryExists());
284 return full_pathname;
285 }
286
287 // Returns true if FilePath ends with a path separator, which indicates that
288 // it is intended to represent a directory. Returns false otherwise.
289 // This does NOT check that a directory (or file) actually exists.
290 bool FilePath::IsDirectory() const {
291 return !pathname_.empty() &&
292 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
293 }
294
295 // Create directories so that path exists. Returns true if successful or if
296 // the directories already exist; returns false if unable to create directories
297 // for any reason.
298 bool FilePath::CreateDirectoriesRecursively() const {
299 if (!this->IsDirectory()) {
300 return false;
301 }
302
303 if (pathname_.length() == 0 || this->DirectoryExists()) {
304 return true;
305 }
306
307 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
308 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
309 }
310
311 // Create the directory so that path exists. Returns true if successful or
312 // if the directory already exists; returns false if unable to create the
313 // directory for any reason, including if the parent directory does not
314 // exist. Not named "CreateDirectory" because that's a macro on Windows.
315 bool FilePath::CreateFolder() const {
316 #if GTEST_OS_WINDOWS_MOBILE
317 FilePath removed_sep(this->RemoveTrailingPathSeparator());
318 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
319 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
320 delete [] unicode;
321 #elif GTEST_OS_WINDOWS
322 int result = _mkdir(pathname_.c_str());
323 #else
324 int result = mkdir(pathname_.c_str(), 0777);
325 #endif // GTEST_OS_WINDOWS_MOBILE
326
327 if (result == -1) {
328 return this->DirectoryExists(); // An error is OK if the directory exists.
329 }
330 return true; // No error.
331 }
332
333 // If input name has a trailing separator character, remove it and return the
334 // name, otherwise return the name string unmodified.
335 // On Windows platform, uses \ as the separator, other platforms use /.
336 FilePath FilePath::RemoveTrailingPathSeparator() const {
337 return IsDirectory()
338 ? FilePath(String(pathname_.c_str(), pathname_.length() - 1))
339 : *this;
340 }
341
342 // Removes any redundant separators that might be in the pathname.
343 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
344 // redundancies that might be in a pathname involving "." or "..".
345 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
346 void FilePath::Normalize() {
347 if (pathname_.c_str() == NULL) {
348 pathname_ = "";
349 return;
350 }
351 const char* src = pathname_.c_str();
352 char* const dest = new char[pathname_.length() + 1];
353 char* dest_ptr = dest;
354 memset(dest_ptr, 0, pathname_.length() + 1);
355
356 while (*src != '\0') {
357 *dest_ptr = *src;
358 if (!IsPathSeparator(*src)) {
359 src++;
360 } else {
361 #if GTEST_HAS_ALT_PATH_SEP_
362 if (*dest_ptr == kAlternatePathSeparator) {
363 *dest_ptr = kPathSeparator;
364 }
365 #endif
366 while (IsPathSeparator(*src))
367 src++;
368 }
369 dest_ptr++;
370 }
371 *dest_ptr = '\0';
372 pathname_ = dest;
373 delete[] dest;
374 }
375
376 } // namespace internal
377 } // namespace testing
+0
-750
utils/unittest/googletest/gtest-port.cc less more
None // Copyright 2008, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: wan@google.com (Zhanyong Wan)
30
31 #include "gtest/internal/gtest-port.h"
32
33 #include
34 #include
35 #include
36 #include
37
38 #if GTEST_OS_WINDOWS_MOBILE
39 # include // For TerminateProcess()
40 #elif GTEST_OS_WINDOWS
41 # include
42 # include
43 #else
44 # include
45 #endif // GTEST_OS_WINDOWS_MOBILE
46
47 #if GTEST_OS_MAC
48 # include
49 # include
50 # include
51 #endif // GTEST_OS_MAC
52
53 #include "gtest/gtest-spi.h"
54 #include "gtest/gtest-message.h"
55 #include "gtest/internal/gtest-internal.h"
56 #include "gtest/internal/gtest-string.h"
57
58 // Indicates that this translation unit is part of Google Test's
59 // implementation. It must come before gtest-internal-inl.h is
60 // included, or there will be a compiler error. This trick is to
61 // prevent a user from accidentally including gtest-internal-inl.h in
62 // his code.
63 #define GTEST_IMPLEMENTATION_ 1
64 #include "gtest/internal/gtest-internal-inl.h"
65 #undef GTEST_IMPLEMENTATION_
66
67 namespace testing {
68 namespace internal {
69
70 #if defined(_MSC_VER) || defined(__BORLANDC__)
71 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
72 const int kStdOutFileno = 1;
73 const int kStdErrFileno = 2;
74 #else
75 const int kStdOutFileno = STDOUT_FILENO;
76 const int kStdErrFileno = STDERR_FILENO;
77 #endif // _MSC_VER
78
79 #if GTEST_OS_MAC
80
81 // Returns the number of threads running in the process, or 0 to indicate that
82 // we cannot detect it.
83 size_t GetThreadCount() {
84 const task_t task = mach_task_self();
85 mach_msg_type_number_t thread_count;
86 thread_act_array_t thread_list;
87 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
88 if (status == KERN_SUCCESS) {
89 // task_threads allocates resources in thread_list and we need to free them
90 // to avoid leaks.
91 vm_deallocate(task,
92 reinterpret_cast(thread_list),
93 sizeof(thread_t) * thread_count);
94 return static_cast(thread_count);
95 } else {
96 return 0;
97 }
98 }
99
100 #else
101
102 size_t GetThreadCount() {
103 // There's no portable way to detect the number of threads, so we just
104 // return 0 to indicate that we cannot detect it.
105 return 0;
106 }
107
108 #endif // GTEST_OS_MAC
109
110 #if GTEST_USES_POSIX_RE
111
112 // Implements RE. Currently only needed for death tests.
113
114 RE::~RE() {
115 if (is_valid_) {
116 // regfree'ing an invalid regex might crash because the content
117 // of the regex is undefined. Since the regex's are essentially
118 // the same, one cannot be valid (or invalid) without the other
119 // being so too.
120 regfree(&partial_regex_);
121 regfree(&full_regex_);
122 }
123 free(const_cast(pattern_));
124 }
125
126 // Returns true iff regular expression re matches the entire str.
127 bool RE::FullMatch(const char* str, const RE& re) {
128 if (!re.is_valid_) return false;
129
130 regmatch_t match;
131 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
132 }
133
134 // Returns true iff regular expression re matches a substring of str
135 // (including str itself).
136 bool RE::PartialMatch(const char* str, const RE& re) {
137 if (!re.is_valid_) return false;
138
139 regmatch_t match;
140 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
141 }
142
143 // Initializes an RE from its string representation.
144 void RE::Init(const char* regex) {
145 pattern_ = posix::StrDup(regex);
146
147 // Reserves enough bytes to hold the regular expression used for a
148 // full match.
149 const size_t full_regex_len = strlen(regex) + 10;
150 char* const full_pattern = new char[full_regex_len];
151
152 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
153 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
154 // We want to call regcomp(&partial_regex_, ...) even if the
155 // previous expression returns false. Otherwise partial_regex_ may
156 // not be properly initialized can may cause trouble when it's
157 // freed.
158 //
159 // Some implementation of POSIX regex (e.g. on at least some
160 // versions of Cygwin) doesn't accept the empty string as a valid
161 // regex. We change it to an equivalent form "()" to be safe.
162 if (is_valid_) {
163 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
164 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
165 }
166 EXPECT_TRUE(is_valid_)
167 << "Regular expression \"" << regex
168 << "\" is not a valid POSIX Extended regular expression.";
169
170 delete[] full_pattern;
171 }
172
173 #elif GTEST_USES_SIMPLE_RE
174
175 // Returns true iff ch appears anywhere in str (excluding the
176 // terminating '\0' character).
177 bool IsInSet(char ch, const char* str) {
178 return ch != '\0' && strchr(str, ch) != NULL;
179 }
180
181 // Returns true iff ch belongs to the given classification. Unlike
182 // similar functions in , these aren't affected by the
183 // current locale.
184 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
185 bool IsAsciiPunct(char ch) {
186 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
187 }
188 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
189 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
190 bool IsAsciiWordChar(char ch) {
191 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
192 ('0' <= ch && ch <= '9') || ch == '_';
193 }
194
195 // Returns true iff "\\c" is a supported escape sequence.
196 bool IsValidEscape(char c) {
197 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
198 }
199
200 // Returns true iff the given atom (specified by escaped and pattern)
201 // matches ch. The result is undefined if the atom is invalid.
202 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
203 if (escaped) { // "\\p" where p is pattern_char.
204 switch (pattern_char) {
205 case 'd': return IsAsciiDigit(ch);
206 case 'D': return !IsAsciiDigit(ch);
207 case 'f': return ch == '\f';
208 case 'n': return ch == '\n';
209 case 'r': return ch == '\r';
210 case 's': return IsAsciiWhiteSpace(ch);
211 case 'S': return !IsAsciiWhiteSpace(ch);
212 case 't': return ch == '\t';
213 case 'v': return ch == '\v';
214 case 'w': return IsAsciiWordChar(ch);
215 case 'W': return !IsAsciiWordChar(ch);
216 }
217 return IsAsciiPunct(pattern_char) && pattern_char == ch;
218 }
219
220 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
221 }
222
223 // Helper function used by ValidateRegex() to format error messages.
224 String FormatRegexSyntaxError(const char* regex, int index) {
225 return (Message() << "Syntax error at index " << index
226 << " in simple regular expression \"" << regex << "\": ").GetString();
227 }
228
229 // Generates non-fatal failures and returns false if regex is invalid;
230 // otherwise returns true.
231 bool ValidateRegex(const char* regex) {
232 if (regex == NULL) {
233 // TODO(wan@google.com): fix the source file location in the
234 // assertion failures to match where the regex is used in user
235 // code.
236 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
237 return false;
238 }
239
240 bool is_valid = true;
241
242 // True iff ?, *, or + can follow the previous atom.
243 bool prev_repeatable = false;
244 for (int i = 0; regex[i]; i++) {
245 if (regex[i] == '\\') { // An escape sequence
246 i++;
247 if (regex[i] == '\0') {
248 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
249 << "'\\' cannot appear at the end.";
250 return false;
251 }
252
253 if (!IsValidEscape(regex[i])) {
254 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
255 << "invalid escape sequence \"\\" << regex[i] << "\".";
256 is_valid = false;
257 }
258 prev_repeatable = true;
259 } else { // Not an escape sequence.
260 const char ch = regex[i];
261
262 if (ch == '^' && i > 0) {
263 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
264 << "'^' can only appear at the beginning.";
265 is_valid = false;
266 } else if (ch == '$' && regex[i + 1] != '\0') {
267 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
268 << "'$' can only appear at the end.";
269 is_valid = false;
270 } else if (IsInSet(ch, "()[]{}|")) {
271 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
272 << "'" << ch << "' is unsupported.";
273 is_valid = false;
274 } else if (IsRepeat(ch) && !prev_repeatable) {
275 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
276 << "'" << ch << "' can only follow a repeatable token.";
277 is_valid = false;
278 }
279
280 prev_repeatable = !IsInSet(ch, "^$?*+");
281 }
282 }
283
284 return is_valid;
285 }
286
287 // Matches a repeated regex atom followed by a valid simple regular
288 // expression. The regex atom is defined as c if escaped is false,
289 // or \c otherwise. repeat is the repetition meta character (?, *,
290 // or +). The behavior is undefined if str contains too many
291 // characters to be indexable by size_t, in which case the test will
292 // probably time out anyway. We are fine with this limitation as
293 // std::string has it too.
294 bool MatchRepetitionAndRegexAtHead(
295 bool escaped, char c, char repeat, const char* regex,
296 const char* str) {
297 const size_t min_count = (repeat == '+') ? 1 : 0;
298 const size_t max_count = (repeat == '?') ? 1 :
299 static_cast(-1) - 1;
300 // We cannot call numeric_limits::max() as it conflicts with the
301 // max() macro on Windows.
302
303 for (size_t i = 0; i <= max_count; ++i) {
304 // We know that the atom matches each of the first i characters in str.
305 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
306 // We have enough matches at the head, and the tail matches too.
307 // Since we only care about *whether* the pattern matches str
308 // (as opposed to *how* it matches), there is no need to find a
309 // greedy match.
310 return true;
311 }
312 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
313 return false;
314 }
315 return false;
316 }
317
318 // Returns true iff regex matches a prefix of str. regex must be a
319 // valid simple regular expression and not start with "^", or the
320 // result is undefined.
321 bool MatchRegexAtHead(const char* regex, const char* str) {
322 if (*regex == '\0') // An empty regex matches a prefix of anything.
323 return true;
324
325 // "$" only matches the end of a string. Note that regex being
326 // valid guarantees that there's nothing after "$" in it.
327 if (*regex == '$')
328 return *str == '\0';
329
330 // Is the first thing in regex an escape sequence?
331 const bool escaped = *regex == '\\';
332 if (escaped)
333 ++regex;
334 if (IsRepeat(regex[1])) {
335 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
336 // here's an indirect recursion. It terminates as the regex gets
337 // shorter in each recursion.
338 return MatchRepetitionAndRegexAtHead(
339 escaped, regex[0], regex[1], regex + 2, str);
340 } else {
341 // regex isn't empty, isn't "$", and doesn't start with a
342 // repetition. We match the first atom of regex with the first
343 // character of str and recurse.
344 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
345 MatchRegexAtHead(regex + 1, str + 1);
346 }
347 }
348
349 // Returns true iff regex matches any substring of str. regex must be
350 // a valid simple regular expression, or the result is undefined.
351 //
352 // The algorithm is recursive, but the recursion depth doesn't exceed
353 // the regex length, so we won't need to worry about running out of
354 // stack space normally. In rare cases the time complexity can be
355 // exponential with respect to the regex length + the string length,
356 // but usually it's must faster (often close to linear).
357 bool MatchRegexAnywhere(const char* regex, const char* str) {
358 if (regex == NULL || str == NULL)
359 return false;
360
361 if (*regex == '^')
362 return MatchRegexAtHead(regex + 1, str);
363
364 // A successful match can be anywhere in str.
365 do {
366 if (MatchRegexAtHead(regex, str))
367 return true;
368 } while (*str++ != '\0');
369 return false;
370 }
371
372 // Implements the RE class.
373
374 RE::~RE() {
375 free(const_cast(pattern_));
376 free(const_cast(full_pattern_));
377 }
378
379 // Returns true iff regular expression re matches the entire str.
380 bool RE::FullMatch(const char* str, const RE& re) {
381 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
382 }
383
384 // Returns true iff regular expression re matches a substring of str
385 // (including str itself).
386 bool RE::PartialMatch(const char* str, const RE& re) {
387 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
388 }
389
390 // Initializes an RE from its string representation.
391 void RE::Init(const char* regex) {
392 pattern_ = full_pattern_ = NULL;
393 if (regex != NULL) {
394 pattern_ = posix::StrDup(regex);
395 }
396
397 is_valid_ = ValidateRegex(regex);
398 if (!is_valid_) {
399 // No need to calculate the full pattern when the regex is invalid.
400 return;
401 }
402
403 const size_t len = strlen(regex);
404 // Reserves enough bytes to hold the regular expression used for a
405 // full match: we need space to prepend a '^', append a '$', and
406 // terminate the string with '\0'.
407 char* buffer = static_cast(malloc(len + 3));
408 full_pattern_ = buffer;
409
410 if (*regex != '^')
411 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
412
413 // We don't use snprintf or strncpy, as they trigger a warning when
414 // compiled with VC++ 8.0.
415 memcpy(buffer, regex, len);
416 buffer += len;
417
418 if (len == 0 || regex[len - 1] != '$')
419 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
420
421 *buffer = '\0';
422 }
423
424 #endif // GTEST_USES_POSIX_RE
425
426 const char kUnknownFile[] = "unknown file";
427
428 // Formats a source file path and a line number as they would appear
429 // in an error message from the compiler used to compile this code.
430 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
431 const char* const file_name = file == NULL ? kUnknownFile : file;
432
433 if (line < 0) {
434 return String::Format("%s:", file_name).c_str();
435 }
436 #ifdef _MSC_VER
437 return String::Format("%s(%d):", file_name, line).c_str();
438 #else
439 return String::Format("%s:%d:", file_name, line).c_str();
440 #endif // _MSC_VER
441 }
442
443 // Formats a file location for compiler-independent XML output.
444 // Although this function is not platform dependent, we put it next to
445 // FormatFileLocation in order to contrast the two functions.
446 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
447 // to the file location it produces, unlike FormatFileLocation().
448 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
449 const char* file, int line) {
450 const char* const file_name = file == NULL ? kUnknownFile : file;
451
452 if (line < 0)
453 return file_name;
454 else
455 return String::Format("%s:%d", file_name, line).c_str();
456 }
457
458
459 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
460 : severity_(severity) {
461 const char* const marker =
462 severity == GTEST_INFO ? "[ INFO ]" :
463 severity == GTEST_WARNING ? "[WARNING]" :
464 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
465 GetStream() << ::std::endl << marker << " "
466 << FormatFileLocation(file, line).c_str() << ": ";
467 }
468
469 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
470 GTestLog::~GTestLog() {
471 GetStream() << ::std::endl;
472 if (severity_ == GTEST_FATAL) {
473 fflush(stderr);
474 posix::Abort();
475 }
476 }
477 // Disable Microsoft deprecation warnings for POSIX functions called from
478 // this class (creat, dup, dup2, and close)
479 #ifdef _MSC_VER
480 # pragma warning(push)
481 # pragma warning(disable: 4996)
482 #endif // _MSC_VER
483
484 #if GTEST_HAS_STREAM_REDIRECTION
485
486 // Object that captures an output stream (stdout/stderr).
487 class CapturedStream {
488 public:
489 // The ctor redirects the stream to a temporary file.
490 CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
491
492 # if GTEST_OS_WINDOWS
493 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
494 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
495
496 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
497 const UINT success = ::GetTempFileNameA(temp_dir_path,
498 "gtest_redir",
499 0, // Generate unique file name.
500 temp_file_path);
501 GTEST_CHECK_(success != 0)
502 << "Unable to create a temporary file in " << temp_dir_path;
503 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
504 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
505 << temp_file_path;
506 filename_ = temp_file_path;
507 #elif GTEST_OS_LINUX_ANDROID
508 char name_template[] = "/sdcard/captured_stderr.XXXXXX";
509 const int captured_fd = mkstemp(name_template);
510 filename_ = name_template;
511 # else
512 // There's no guarantee that a test has write access to the
513 // current directory, so we create the temporary file in the /tmp
514 // directory instead.
515 char name_template[] = "/tmp/captured_stream.XXXXXX";
516 const int captured_fd = mkstemp(name_template);
517 filename_ = name_template;
518 # endif // GTEST_OS_WINDOWS
519 fflush(NULL);
520 dup2(captured_fd, fd_);
521 close(captured_fd);
522 }
523
524 ~CapturedStream() {
525 remove(filename_.c_str());
526 }
527
528 String GetCapturedString() {
529 if (uncaptured_fd_ != -1) {
530 // Restores the original stream.
531 fflush(NULL);
532 dup2(uncaptured_fd_, fd_);
533 close(uncaptured_fd_);
534 uncaptured_fd_ = -1;
535 }
536
537 FILE* const file = posix::FOpen(filename_.c_str(), "r");
538 const String content = ReadEntireFile(file);
539 posix::FClose(file);
540 return content;
541 }
542
543 private:
544 // Reads the entire content of a file as a String.
545 static String ReadEntireFile(FILE* file);
546
547 // Returns the size (in bytes) of a file.
548 static size_t GetFileSize(FILE* file);
549
550 const int fd_; // A stream to capture.
551 int uncaptured_fd_;
552 // Name of the temporary file holding the stderr output.
553 ::std::string filename_;
554
555 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
556 };
557
558 // Returns the size (in bytes) of a file.
559 size_t CapturedStream::GetFileSize(FILE* file) {
560 fseek(file, 0, SEEK_END);
561 return static_cast(ftell(file));
562 }
563
564 // Reads the entire content of a file as a string.
565 String CapturedStream::ReadEntireFile(FILE* file) {
566 const size_t file_size = GetFileSize(file);
567 char* const buffer = new char[file_size];
568
569 size_t bytes_last_read = 0; // # of bytes read in the last fread()
570 size_t bytes_read = 0; // # of bytes read so far
571
572 fseek(file, 0, SEEK_SET);
573
574 // Keeps reading the file until we cannot read further or the
575 // pre-determined file size is reached.
576 do {
577 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
578 bytes_read += bytes_last_read;
579 } while (bytes_last_read > 0 && bytes_read < file_size);
580
581 const String content(buffer, bytes_read);
582 delete[] buffer;
583
584 return content;
585 }
586
587 # ifdef _MSC_VER
588 # pragma warning(pop)
589 # endif // _MSC_VER
590
591 static CapturedStream* g_captured_stderr = NULL;
592 static CapturedStream* g_captured_stdout = NULL;
593
594 // Starts capturing an output stream (stdout/stderr).
595 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
596 if (*stream != NULL) {
597 GTEST_LOG_(FATAL) << "Only one " << stream_name
598 << " capturer can exist at a time.";
599 }
600 *stream = new CapturedStream(fd);
601 }
602
603 // Stops capturing the output stream and returns the captured string.
604 String GetCapturedStream(CapturedStream** captured_stream) {
605 const String content = (*captured_stream)->GetCapturedString();
606
607 delete *captured_stream;
608 *captured_stream = NULL;
609
610 return content;
611 }
612
613 // Starts capturing stdout.
614 void CaptureStdout() {
615 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
616 }
617
618 // Starts capturing stderr.
619 void CaptureStderr() {
620 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
621 }
622
623 // Stops capturing stdout and returns the captured string.
624 String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
625
626 // Stops capturing stderr and returns the captured string.
627 String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
628
629 #endif // GTEST_HAS_STREAM_REDIRECTION
630
631 #if GTEST_HAS_DEATH_TEST
632
633 // A copy of all command line arguments. Set by InitGoogleTest().
634 ::std::vector g_argvs;
635
636 // Returns the command line as a vector of strings.
637 const ::std::vector& GetArgvs() { return g_argvs; }
638
639 #endif // GTEST_HAS_DEATH_TEST
640
641 #if GTEST_OS_WINDOWS_MOBILE
642 namespace posix {
643 void Abort() {
644 DebugBreak();
645 TerminateProcess(GetCurrentProcess(), 1);
646 }
647 } // namespace posix
648 #endif // GTEST_OS_WINDOWS_MOBILE
649
650 // Returns the name of the environment variable corresponding to the
651 // given flag. For example, FlagToEnvVar("foo") will return
652 // "GTEST_FOO" in the open-source version.
653 static String FlagToEnvVar(const char* flag) {
654 const String full_flag =
655 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
656
657 Message env_var;
658 for (size_t i = 0; i != full_flag.length(); i++) {
659 env_var << ToUpper(full_flag.c_str()[i]);
660 }
661
662 return env_var.GetString();
663 }
664
665 // Parses 'str' for a 32-bit signed integer. If successful, writes
666 // the result to *value and returns true; otherwise leaves *value
667 // unchanged and returns false.
668 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
669 // Parses the environment variable as a decimal integer.
670 char* end = NULL;
671 const long long_value = strtol(str, &end, 10); // NOLINT
672
673 // Has strtol() consumed all characters in the string?
674 if (*end != '\0') {
675 // No - an invalid character was encountered.
676 Message msg;
677 msg << "WARNING: " << src_text
678 << " is expected to be a 32-bit integer, but actually"
679 << " has value \"" << str << "\".\n";
680 printf("%s", msg.GetString().c_str());
681 fflush(stdout);
682 return false;
683 }
684
685 // Is the parsed value in the range of an Int32?
686 const Int32 result = static_cast(long_value);
687 if (long_value == LONG_MAX || long_value == LONG_MIN ||
688 // The parsed value overflows as a long. (strtol() returns
689 // LONG_MAX or LONG_MIN when the input overflows.)
690 result != long_value
691 // The parsed value overflows as an Int32.
692 ) {
693 Message msg;
694 msg << "WARNING: " << src_text
695 << " is expected to be a 32-bit integer, but actually"
696 << " has value " << str << ", which overflows.\n";
697 printf("%s", msg.GetString().c_str());
698 fflush(stdout);
699 return false;
700 }
701
702 *value = result;
703 return true;
704 }
705
706 // Reads and returns the Boolean environment variable corresponding to
707 // the given flag; if it's not set, returns default_value.
708 //
709 // The value is considered true iff it's not "0".
710 bool BoolFromGTestEnv(const char* flag, bool default_value) {
711 const String env_var = FlagToEnvVar(flag);
712 const char* const string_value = posix::GetEnv(env_var.c_str());
713 return string_value == NULL ?
714 default_value : strcmp(string_value, "0") != 0;
715 }
716
717 // Reads and returns a 32-bit integer stored in the environment
718 // variable corresponding to the given flag; if it isn't set or
719 // doesn't represent a valid 32-bit integer, returns default_value.
720 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
721 const String env_var = FlagToEnvVar(flag);
722 const char* const string_value = posix::GetEnv(env_var.c_str());
723 if (string_value == NULL) {
724 // The environment variable is not set.
725 return default_value;
726 }
727
728 Int32 result = default_value;
729 if (!ParseInt32(Message() << "Environment variable " << env_var,
730 string_value, &result)) {
731 printf("The default value %s is used.\n",
732 (Message() << default_value).GetString().c_str());
733 fflush(stdout);
734 return default_value;
735 }
736
737 return result;
738 }
739
740 // Reads and returns the string environment variable corresponding to
741 // the given flag; if it's not set, returns default_value.
742 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
743 const String env_var = FlagToEnvVar(flag);
744 const char* const value = posix::GetEnv(env_var.c_str());
745 return value == NULL ? default_value : value;
746 }
747
748 } // namespace internal
749 } // namespace testing
+0
-356
utils/unittest/googletest/gtest-printers.cc less more
None // Copyright 2007, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: wan@google.com (Zhanyong Wan)
30
31 // Google Test - The Google C++ Testing Framework
32 //
33 // This file implements a universal value printer that can print a
34 // value of any type T:
35 //
36 // void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr);
37 //
38 // It uses the << operator when possible, and prints the bytes in the
39 // object otherwise. A user can override its behavior for a class
40 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
41 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
42 // defines Foo.
43
44 #include "gtest/gtest-printers.h"
45 #include
46 #include
47 #include // NOLINT
48 #include
49 #include "gtest/internal/gtest-port.h"
50
51 namespace testing {
52
53 namespace {
54
55 using ::std::ostream;
56
57 #if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
58 # define snprintf _snprintf
59 #elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
60 # define snprintf _snprintf_s
61 #elif _MSC_VER
62 # define snprintf _snprintf
63 #endif // GTEST_OS_WINDOWS_MOBILE
64
65 // Prints a segment of bytes in the given object.
66 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
67 size_t count, ostream* os) {
68 char text[5] = "";
69 for (size_t i = 0; i != count; i++) {
70 const size_t j = start + i;
71 if (i != 0) {
72 // Organizes the bytes into groups of 2 for easy parsing by
73 // human.
74 if ((j % 2) == 0)
75 *os << ' ';
76 else
77 *os << '-';
78 }
79 snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
80 *os << text;
81 }
82 }
83
84 // Prints the bytes in the given value to the given ostream.
85 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
86 ostream* os) {
87 // Tells the user how big the object is.
88 *os << count << "-byte object <";
89
90 const size_t kThreshold = 132;
91 const size_t kChunkSize = 64;
92 // If the object size is bigger than kThreshold, we'll have to omit
93 // some details by printing only the first and the last kChunkSize
94 // bytes.
95 // TODO(wan): let the user control the threshold using a flag.
96 if (count < kThreshold) {
97 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
98 } else {
99 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
100 *os << " ... ";
101 // Rounds up to 2-byte boundary.
102 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
103 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
104 }
105 *os << ">";
106 }
107
108 } // namespace
109
110 namespace internal2 {
111
112 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
113 // given object. The delegation simplifies the implementation, which
114 // uses the << operator and thus is easier done outside of the
115 // ::testing::internal namespace, which contains a << operator that
116 // sometimes conflicts with the one in STL.
117 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
118 ostream* os) {
119 PrintBytesInObjectToImpl(obj_bytes, count, os);
120 }
121
122 } // namespace internal2
123
124 namespace internal {
125
126 // Depending on the value of a char (or wchar_t), we print it in one
127 // of three formats:
128 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
129 // - as a hexadecimal escape sequence (e.g. '\x7F'), or
130 // - as a special escape sequence (e.g. '\r', '\n').
131 enum CharFormat {
132 kAsIs,
133 kHexEscape,
134 kSpecialEscape
135 };
136
137 // Returns true if c is a printable ASCII character. We test the
138 // value of c directly instead of calling isprint(), which is buggy on
139 // Windows Mobile.
140 inline bool IsPrintableAscii(wchar_t c) {
141 return 0x20 <= c && c <= 0x7E;
142 }
143
144 // Prints a wide or narrow char c as a character literal without the
145 // quotes, escaping it when necessary; returns how c was formatted.
146 // The template argument UnsignedChar is the unsigned version of Char,
147 // which is the type of c.
148 template
149 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
150 switch (static_cast(c)) {
151 case L'\0':
152 *os << "\\0";
153 break;
154 case L'\'':
155 *os << "\\'";
156 break;
157 case L'\\':
158 *os << "\\\\";
159 break;
160 case L'\a':
161 *os << "\\a";
162 break;
163 case L'\b':
164 *os << "\\b";
165 break;
166 case L'\f':
167 *os << "\\f";
168 break;
169 case L'\n':
170 *os << "\\n";
171 break;
172 case L'\r':
173 *os << "\\r";
174 break;
175 case L'\t':
176 *os << "\\t";
177 break;
178 case L'\v':
179 *os << "\\v";
180 break;
181 default:
182 if (IsPrintableAscii(c)) {
183 *os << static_cast(c);
184 return kAsIs;
185 } else {
186 *os << String::Format("\\x%X", static_cast(c));
187 return kHexEscape;
188 }
189 }
190 return kSpecialEscape;
191 }
192
193 // Prints a char c as if it's part of a string literal, escaping it when
194 // necessary; returns how c was formatted.
195 static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
196 switch (c) {
197 case L'\'':
198 *os << "'";
199 return kAsIs;
200 case L'"':
201 *os << "\\\"";
202 return kSpecialEscape;
203 default:
204 return PrintAsCharLiteralTo(c, os);
205 }
206 }
207
208 // Prints a char c as if it's part of a string literal, escaping it when
209 // necessary; returns how c was formatted.
210 static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) {
211 return PrintAsWideStringLiteralTo(static_cast(c), os);
212 }
213
214 // Prints a wide or narrow character c and its code. '\0' is printed
215 // as "'\\0'", other unprintable characters are also properly escaped
216 // using the standard C++ escape sequence. The template argument
217 // UnsignedChar is the unsigned version of Char, which is the type of c.
218 template
219 void PrintCharAndCodeTo(Char c, ostream* os) {
220 // First, print c as a literal in the most readable form we can find.
221 *os << ((sizeof(c) > 1) ? "L'" : "'");
222 const CharFormat format = PrintAsCharLiteralTo(c, os);
223 *os << "'";
224
225 // To aid user debugging, we also print c's code in decimal, unless
226 // it's 0 (in which case c was printed as '\\0', making the code
227 // obvious).
228 if (c == 0)
229 return;
230 *os << " (" << String::Format("%d", c).c_str();
231
232 // For more convenience, we print c's code again in hexadecimal,
233 // unless c was already printed in the form '\x##' or the code is in
234 // [1, 9].
235 if (format == kHexEscape || (1 <= c && c <= 9)) {
236 // Do nothing.
237 } else {
238 *os << String::Format(", 0x%X",
239 static_cast(c)).c_str();
240 }
241 *os << ")";
242 }
243
244 void PrintTo(unsigned char c, ::std::ostream* os) {
245 PrintCharAndCodeTo(c, os);
246 }
247 void PrintTo(signed char c, ::std::ostream* os) {
248 PrintCharAndCodeTo(c, os);
249 }
250
251 // Prints a wchar_t as a symbol if it is printable or as its internal
252 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
253 void PrintTo(wchar_t wc, ostream* os) {
254 PrintCharAndCodeTo(wc, os);
255 }
256
257 // Prints the given array of characters to the ostream.
258 // The array starts at *begin, the length is len, it may include '\0' characters
259 // and may not be null-terminated.
260 static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
261 *os << "\"";
262 bool is_previous_hex = false;
263 for (size_t index = 0; index < len; ++index) {
264 const char cur = begin[index];
265 if (is_previous_hex && IsXDigit(cur)) {
266 // Previous character is of '\x..' form and this character can be
267 // interpreted as another hexadecimal digit in its number. Break string to
268 // disambiguate.
269 *os << "\" \"";
270 }
271 is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape;
272 }
273 *os << "\"";
274 }
275
276 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
277 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
278 PrintCharsAsStringTo(begin, len, os);
279 }
280
281 // Prints the given array of wide characters to the ostream.
282 // The array starts at *begin, the length is len, it may include L'\0'
283 // characters and may not be null-terminated.
284 static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
285 ostream* os) {
286 *os << "L\"";
287 bool is_previous_hex = false;
288 for (size_t index = 0; index < len; ++index) {
289 const wchar_t cur = begin[index];
290 if (is_previous_hex && isascii(cur) && IsXDigit(static_cast(cur))) {
291 // Previous character is of '\x..' form and this character can be
292 // interpreted as another hexadecimal digit in its number. Break string to
293 // disambiguate.
294 *os << "\" L\"";
295 }
296 is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
297 }
298 *os << "\"";
299 }
300
301 // Prints the given C string to the ostream.
302 void PrintTo(const char* s, ostream* os) {
303 if (s == NULL) {
304 *os << "NULL";
305 } else {
306 *os << ImplicitCast_(s) << " pointing to ";
307 PrintCharsAsStringTo(s, strlen(s), os);
308 }
309 }
310
311 // MSVC compiler can be configured to define whar_t as a typedef
312 // of unsigned short. Defining an overload for const wchar_t* in that case
313 // would cause pointers to unsigned shorts be printed as wide strings,
314 // possibly accessing more memory than intended and causing invalid
315 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
316 // wchar_t is implemented as a native type.
317 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
318 // Prints the given wide C string to the ostream.
319 void PrintTo(const wchar_t* s, ostream* os) {
320 if (s == NULL) {
321 *os << "NULL";
322 } else {
323 *os << ImplicitCast_(s) << " pointing to ";
324 PrintWideCharsAsStringTo(s, wcslen(s), os);
325 }
326 }
327 #endif // wchar_t is native
328
329 // Prints a ::string object.
330 #if GTEST_HAS_GLOBAL_STRING
331 void PrintStringTo(const ::string& s, ostream* os) {
332 PrintCharsAsStringTo(s.data(), s.size(), os);
333 }
334 #endif // GTEST_HAS_GLOBAL_STRING
335
336 void PrintStringTo(const ::std::string& s, ostream* os) {
337 PrintCharsAsStringTo(s.data(), s.size(), os);
338 }
339
340 // Prints a ::wstring object.
341 #if GTEST_HAS_GLOBAL_WSTRING
342 void PrintWideStringTo(const ::wstring& s, ostream* os) {
343 PrintWideCharsAsStringTo(s.data(), s.size(), os);
344 }
345 #endif // GTEST_HAS_GLOBAL_WSTRING
346
347 #if GTEST_HAS_STD_WSTRING
348 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
349 PrintWideCharsAsStringTo(s.data(), s.size(), os);
350 }
351 #endif // GTEST_HAS_STD_WSTRING
352
353 } // namespace internal
354
355 } // namespace testing
+0
-110
utils/unittest/googletest/gtest-test-part.cc less more
None // Copyright 2008, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: mheule@google.com (Markus Heule)
30 //
31 // The Google C++ Testing Framework (Google Test)
32
33 #include "gtest/gtest-test-part.h"
34
35 // Indicates that this translation unit is part of Google Test's
36 // implementation. It must come before gtest-internal-inl.h is
37 // included, or there will be a compiler error. This trick is to
38 // prevent a user from accidentally including gtest-internal-inl.h in
39 // his code.
40 #define GTEST_IMPLEMENTATION_ 1
41 #include "gtest/internal/gtest-internal-inl.h"
42 #undef GTEST_IMPLEMENTATION_
43
44 namespace testing {
45
46 using internal::GetUnitTestImpl;
47
48 // Gets the summary of the failure message by omitting the stack trace
49 // in it.
50 internal::String TestPartResult::ExtractSummary(const char* message) {
51 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
52 return stack_trace == NULL ? internal::String(message) :
53 internal::String(message, stack_trace - message);
54 }
55
56 // Prints a TestPartResult object.
57 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
58 return os
59 << result.file_name() << ":" << result.line_number() << ": "
60 << (result.type() == TestPartResult::kSuccess ? "Success" :
61 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
62 "Non-fatal failure") << ":\n"
63 << result.message() << std::endl;
64 }
65
66 // Appends a TestPartResult to the array.
67 void TestPartResultArray::Append(const TestPartResult& result) {
68 array_.push_back(result);
69 }
70
71 // Returns the TestPartResult at the given index (0-based).
72 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
73 if (index < 0 || index >= size()) {
74 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
75 internal::posix::Abort();
76 }
77
78 return array_[index];
79 }
80
81 // Returns the number of TestPartResult objects in the array.
82 int TestPartResultArray::size() const {
83 return static_cast(array_.size());
84 }
85
86 namespace internal {
87
88 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
89 : has_new_fatal_failure_(false),
90 original_reporter_(GetUnitTestImpl()->
91 GetTestPartResultReporterForCurrentThread()) {
92 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
93 }
94
95 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
96 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
97 original_reporter_);
98 }
99
100 void HasNewFatalFailureHelper::ReportTestPartResult(
101 const TestPartResult& result) {
102 if (result.fatally_failed())
103 has_new_fatal_failure_ = true;
104 original_reporter_->ReportTestPartResult(result);
105 }
106
107 } // namespace internal
108
109 } // namespace testing
+0
-110
utils/unittest/googletest/gtest-typed-test.cc less more
None // Copyright 2008 Google Inc.
1 // All Rights Reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: wan@google.com (Zhanyong Wan)
30
31 #include "gtest/gtest-typed-test.h"
32 #include "gtest/gtest.h"
33
34 namespace testing {
35 namespace internal {
36
37 #if GTEST_HAS_TYPED_TEST_P
38
39 // Skips to the first non-space char in str. Returns an empty string if str
40 // contains only whitespace characters.
41 static const char* SkipSpaces(const char* str) {
42 while (IsSpace(*str))
43 str++;
44 return str;
45 }
46
47 // Verifies that registered_tests match the test names in
48 // defined_test_names_; returns registered_tests if successful, or
49 // aborts the program otherwise.
50 const char* TypedTestCasePState::VerifyRegisteredTestNames(
51 const char* file, int line, const char* registered_tests) {
52 typedef ::std::set::const_iterator DefinedTestIter;
53 registered_ = true;
54
55 // Skip initial whitespace in registered_tests since some
56 // preprocessors prefix stringizied literals with whitespace.
57 registered_tests = SkipSpaces(registered_tests);
58
59 Message errors;
60 ::std::set tests;
61 for (const char* names = registered_tests; names != NULL;
62 names = SkipComma(names)) {
63 const String name = GetPrefixUntilComma(names);
64 if (tests.count(name) != 0) {
65 errors << "Test " << name << " is listed more than once.\n";
66 continue;
67 }
68
69 bool found = false;
70 for (DefinedTestIter it = defined_test_names_.begin();
71 it != defined_test_names_.end();
72 ++it) {
73 if (name == *it) {
74 found = true;
75 break;
76 }
77 }
78
79 if (found) {
80 tests.insert(name);
81 } else {
82 errors << "No test named " << name
83 << " can be found in this test case.\n";
84 }
85 }
86
87 for (DefinedTestIter it = defined_test_names_.begin();
88 it != defined_test_names_.end();
89 ++it) {
90 if (tests.count(*it) == 0) {
91 errors << "You forgot to list test " << *it << ".\n";
92 }
93 }
94
95 const String& errors_str = errors.GetString();
96 if (errors_str != "") {
97 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
98 errors_str.c_str());
99 fflush(stderr);
100 posix::Abort();
101 }
102
103 return registered_tests;
104 }
105
106 #endif // GTEST_HAS_TYPED_TEST_P
107
108 } // namespace internal
109 } // namespace testing
+0
-4866
utils/unittest/googletest/gtest.cc less more
None // Copyright 2005, Google Inc.
1 // All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: wan@google.com (Zhanyong Wan)
30 //
31 // The Google C++ Testing Framework (Google Test)
32
33 #include "gtest/gtest.h"
34 #include "gtest/gtest-spi.h"
35
36 #include
37 #include
38 #include
39 #include
40 #include
41 #include
42 #include
43
44 #include
45 #include // NOLINT
46 #include
47 #include
48
49 #if GTEST_OS_LINUX
50
51 // TODO(kenton@google.com): Use autoconf to detect availability of
52 // gettimeofday().
53 # define GTEST_HAS_GETTIMEOFDAY_ 1
54
55 # include // NOLINT
56 # include // NOLINT
57 # include // NOLINT
58 // Declares vsnprintf(). This header is not available on Windows.
59 # include // NOLINT
60 # include // NOLINT
61 # include // NOLINT
62 # include // NOLINT
63 # include
64
65 #elif GTEST_OS_SYMBIAN
66 # define GTEST_HAS_GETTIMEOFDAY_ 1
67 # include // NOLINT
68
69 #elif GTEST_OS_ZOS
70 # define GTEST_HAS_GETTIMEOFDAY_ 1
71 # include // NOLINT
72
73 // On z/OS we additionally need strings.h for strcasecmp.
74 # include // NOLINT
75
76 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
77
78 # include // NOLINT
79
80 #elif GTEST_OS_WINDOWS // We are on Windows proper.
81
82 # include // NOLINT
83 # include // NOLINT
84 # include // NOLINT
85 # include // NOLINT
86
87 # if GTEST_OS_WINDOWS_MINGW
88 // MinGW has gettimeofday() but not _ftime64().
89 // TODO(kenton@google.com): Use autoconf to detect availability of
90 // gettimeofday().
91 // TODO(kenton@google.com): There are other ways to get the time on
92 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
93 // supports these. consider using them instead.
94 # define GTEST_HAS_GETTIMEOFDAY_ 1
95 # include // NOLINT
96 # endif // GTEST_OS_WINDOWS_MINGW
97
98 // cpplint thinks that the header is already included, so we want to
99 // silence it.
100 # include // NOLINT
101
102 #else
103
104 // Assume other platforms have gettimeofday().
105 // TODO(kenton@google.com): Use autoconf to detect availability of
106 // gettimeofday().
107 # define GTEST_HAS_GETTIMEOFDAY_ 1
108
109 // cpplint thinks that the header is already included, so we want to
110 // silence it.
111 # include // NOLINT
112 # include // NOLINT
113
114 #endif // GTEST_OS_LINUX
115
116 #if GTEST_HAS_EXCEPTIONS
117 # include
118 #endif
119
120 #if GTEST_CAN_STREAM_RESULTS_
121 # include // NOLINT
122 # include // NOLINT
123 #endif
124
125 // Indicates that this translation unit is part of Google Test's
126 // implementation. It must come before gtest-internal-inl.h is
127 // included, or there will be a compiler error. This trick is to
128 // prevent a user from accidentally including gtest-internal-inl.h in
129 // his code.
130 #define GTEST_IMPLEMENTATION_ 1
131 #include "gtest/internal/gtest-internal-inl.h"
132 #undef GTEST_IMPLEMENTATION_
133
134 #if GTEST_OS_WINDOWS
135 # define vsnprintf _vsnprintf
136 #endif // GTEST_OS_WINDOWS
137
138 namespace testing {
139
140 using internal::CountIf;
141 using internal::ForEach;
142 using internal::GetElementOr;
143 using internal::Shuffle;
144
145 // Constants.
146
147 // A test whose test case name or test name matches this filter is
148 // disabled and not run.
149 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
150
151 // A test case whose name matches this filter is considered a death
152 // test case and will be run before test cases whose name doesn't
153 // match this filter.
154 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
155
156 // A test filter that matches everything.
157 static const char kUniversalFilter[] = "*";
158
159 // The default output file for XML output.
160 static const char kDefaultOutputFile[] = "test_detail.xml";
161
162 // The environment variable name for the test shard index.
163 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
164 // The environment variable name for the total number of test shards.
165 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
166 // The environment variable name for the test shard status file.
167 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
168
169 namespace internal {
170
171 // The text used in failure messages to indicate the start of the
172 // stack trace.
173 const char kStackTraceMarker[] = "\nStack trace:\n";
174
175 // g_help_flag is true iff the --help flag or an equivalent form is
176 // specified on the command line.
177 bool g_help_flag = false;
178
179 } // namespace internal
180
181 GTEST_DEFINE_bool_(
182 also_run_disabled_tests,
183 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
184 "Run disabled tests too, in addition to the tests normally being run.");
185
186 GTEST_DEFINE_bool_(
187 break_on_failure,
188 internal::BoolFromGTestEnv("break_on_failure", false),
189 "True iff a failed assertion should be a debugger break-point.");
190
191 GTEST_DEFINE_bool_(
192 catch_exceptions,
193 internal::BoolFromGTestEnv("catch_exceptions", true),
194 "True iff " GTEST_NAME_
195 " should catch exceptions and treat them as test failures.");
196
197 GTEST_DEFINE_string_(
198 color,
199 internal::StringFromGTestEnv("color", "auto"),
200 "Whether to use colors in the output. Valid values: yes, no, "
201 "and auto. 'auto' means to use colors if the output is "
202 "being sent to a terminal and the TERM environment variable "
203 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
204
205 GTEST_DEFINE_string_(
206 filter,
207 internal::StringFromGTestEnv("filter", kUniversalFilter),
208 "A colon-separated list of glob (not regex) patterns "
209 "for filtering the tests to run, optionally followed by a "
210 "'-' and a : separated list of negative patterns (tests to "
211 "exclude). A test is run if it matches one of the positive "
212 "patterns and does not match any of the negative patterns.");
213
214 GTEST_DEFINE_bool_(list_tests, false,
215 "List all tests without running them.");
216
217 GTEST_DEFINE_string_(
218 output,
219 internal::StringFromGTestEnv("output", ""),
220 "A format (currently must be \"xml\"), optionally followed "
221 "by a colon and an output file name or directory. A directory "
222 "is indicated by a trailing pathname separator. "
223 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
224 "If a directory is specified, output files will be created "
225 "within that directory, with file-names based on the test "
226 "executable's name and, if necessary, made unique by adding "
227 "digits.");
228
229 GTEST_DEFINE_bool_(
230 print_time,
231 internal::BoolFromGTestEnv("print_time", true),
232 "True iff " GTEST_NAME_
233 " should display elapsed time in text output.");
234
235 GTEST_DEFINE_int32_(
236 random_seed,
237 internal::Int32FromGTestEnv("random_seed", 0),
238 "Random number seed to use when shuffling test orders. Must be in range "
239 "[1, 99999], or 0 to use a seed based on the current time.");
240
241 GTEST_DEFINE_int32_(
242 repeat,
243 internal::Int32FromGTestEnv("repeat", 1),
244 "How many times to repeat each test. Specify a negative number "
245 "for repeating forever. Useful for shaking out flaky tests.");
246
247 GTEST_DEFINE_bool_(
248 show_internal_stack_frames, false,
249 "True iff " GTEST_NAME_ " should include internal stack frames when "
250 "printing test failure stack traces.");
251
252 GTEST_DEFINE_bool_(
253 shuffle,
254 internal::BoolFromGTestEnv("shuffle", false),
255 "True iff " GTEST_NAME_
256 " should randomize tests' order on every run.");
257
258 GTEST_DEFINE_int32_(
259 stack_trace_depth,
260 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
261 "The maximum number of stack frames to print when an "
262 "assertion fails. The valid range is 0 through 100, inclusive.");
263
264 GTEST_DEFINE_string_(
265 stream_result_to,
266 internal::StringFromGTestEnv("stream_result_to", ""),
267 "This flag specifies the host name and the port number on which to stream "
268 "test results. Example: \"localhost:555\". The flag is effective only on "
269 "Linux.");
270
271 GTEST_DEFINE_bool_(
272 throw_on_failure,
273 internal::BoolFromGTestEnv("throw_on_failure", false),
274 "When this flag is specified, a failed assertion will throw an exception "
275 "if exceptions are enabled or exit the program with a non-zero code "
276 "otherwise.");
277
278 namespace internal {
279
280 // Generates a random number from [0, range), using a Linear
281 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
282 // than kMaxRange.
283 UInt32 Random::Generate(UInt32 range) {
284 // These constants are the same as are used in glibc's rand(3).
285 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
286
287 GTEST_CHECK_(range > 0)
288 << "Cannot generate a number in the range [0, 0).";
289 GTEST_CHECK_(range <= kMaxRange)
290 << "Generation of a number in [0, " << range << ") was requested, "
291 << "but this can only generate numbers in [0, " << kMaxRange << ").";
292
293 // Converting via modulus introduces a bit of downward bias, but
294 // it's simple, and a linear congruential generator isn't too good
295 // to begin with.
296 return state_ % range;
297 }
298
299 // GTestIsInitialized() returns true iff the user has initialized
300 // Google Test. Useful for catching the user mistake of not initializing
301 // Google Test before calling RUN_ALL_TESTS().
302 //
303 // A user must call testing::InitGoogleTest() to initialize Google
304 // Test. g_init_gtest_count is set to the number of times
305 // InitGoogleTest() has been called. We don't protect this variable
306 // under a mutex as it is only accessed in the main thread.
307 int g_init_gtest_count = 0;
308 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
309
310 // Iterates over a vector of TestCases, keeping a running sum of the
311 // results of calling a given int-returning method on each.
312 // Returns the sum.
313 static int SumOverTestCaseList(const std::vector& case_list,
314 int (TestCase::*method)() const) {
315 int sum = 0;
316 for (size_t i = 0; i < case_list.size(); i++) {
317 sum += (case_list[i]->*method)();
318 }
319 return sum;
320 }
321
322 // Returns true iff the test case passed.
323 static bool TestCasePassed(const TestCase* test_case) {
324 return test_case->should_run() && test_case->Passed();
325 }
326
327 // Returns true iff the test case failed.
328 static bool TestCaseFailed(const TestCase* test_case) {
329 return test_case->should_run() && test_case->Failed();
330 }
331
332 // Returns true iff test_case contains at least one test that should
333 // run.
334 static bool ShouldRunTestCase(const TestCase* test_case) {
335 return test_case->should_run();
336 }
337
338 // AssertHelper constructor.
339 AssertHelper::AssertHelper(TestPartResult::Type type,
340 const char* file,
341 int line,
342 const char* message)
343 : data_(new AssertHelperData(type, file, line, message)) {
344 }
345
346 AssertHelper::~AssertHelper() {
347 delete data_;
348 }
349
350 // Message assignment, for assertion streaming support.
351 void AssertHelper::operator=(const Message& message) const {
352 UnitTest::GetInstance()->
353 AddTestPartResult(data_->type, data_->file, data_->line,
354 AppendUserMessage(data_->message, message),
355 UnitTest::GetInstance()->impl()
356 ->CurrentOsStackTraceExceptTop(1)
357 // Skips the stack frame for this function itself.
358 ); // NOLINT
359 }
360
361 // Mutex for linked pointers.
362 GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
363
364 // Application pathname gotten in InitGoogleTest.
365 String g_executable_path;
366
367 // Returns the current application's name, removing directory path if that
368 // is present.
369 FilePath GetCurrentExecutableName() {
370 FilePath result;
371
372 #if GTEST_OS_WINDOWS
373 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
374 #else
375 result.Set(FilePath(g_executable_path));
376 #endif // GTEST_OS_WINDOWS
377
378 return result.RemoveDirectoryName();
379 }
380
381 // Functions for processing the gtest_output flag.
382
383 // Returns the output format, or "" for normal printed output.
384 String UnitTestOptions::GetOutputFormat() {
385 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
386 if (gtest_output_flag == NULL) return String("");
387
388 const char* const colon = strchr(gtest_output_flag, ':');
389 return (colon == NULL) ?
390 String(gtest_output_flag) :
391 String(gtest_output_flag, colon - gtest_output_flag);
392 }
393
394 // Returns the name of the requested output file, or the default if none
395 // was explicitly specified.
396 String UnitTestOptions::GetAbsolutePathToOutputFile() {
397 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
398 if (gtest_output_flag == NULL)
399 return String("");
400
401 const char* const colon = strchr(gtest_output_flag, ':');
402 if (colon == NULL)
403 return String(internal::FilePath::ConcatPaths(
404 internal::FilePath(
405 UnitTest::GetInstance()->original_working_dir()),
406 internal::FilePath(kDefaultOutputFile)).ToString() );
407
408 internal::FilePath output_name(colon + 1);
409 if (!output_name.IsAbsolutePath())
410 // TODO(wan@google.com): on Windows \some\path is not an absolute
411 // path (as its meaning depends on the current drive), yet the
412 // following logic for turning it into an absolute path is wrong.
413 // Fix it.
414 output_name = internal::FilePath::ConcatPaths(
415 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
416 internal::FilePath(colon + 1));
417
418 if (!output_name.IsDirectory())
419 return output_name.ToString();
420
421 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
422 output_name, internal::GetCurrentExecutableName(),
423 GetOutputFormat().c_str()));
424 return result.ToString();
425 }
426
427 // Returns true iff the wildcard pattern matches the string. The
428 // first ':' or '\0' character in pattern marks the end of it.
429 //
430 // This recursive algorithm isn't very efficient, but is clear and
431 // works well enough for matching test names, which are short.
432 bool UnitTestOptions::PatternMatchesString(const char *pattern,
433 const char *str) {
434 switch (*pattern) {
435 case '\0':
436 case ':': // Either ':' or '\0' marks the end of the pattern.
437 return *str == '\0';
438 case '?': // Matches any single character.
439 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
440 case '*': // Matches any string (possibly empty) of characters.
441 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
442 PatternMatchesString(pattern + 1, str);
443 default: // Non-special character. Matches itself.
444 return *pattern == *str &&
445 PatternMatchesString(pattern + 1, str + 1);
446 }
447 }
448
449 bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
450 const char *cur_pattern = filter;
451 for (;;) {
452 if (PatternMatchesString(cur_pattern, name.c_str())) {
453 return true;
454 }
455
456 // Finds the next pattern in the filter.
457 cur_pattern = strchr(cur_pattern, ':');
458
459 // Returns if no more pattern can be found.
460 if (cur_pattern == NULL) {
461 return false;
462 }
463
464 // Skips the pattern separater (the ':' character).
465 cur_pattern++;
466 }
467 }
468
469 // TODO(keithray): move String function implementations to gtest-string.cc.
470
471 // Returns true iff the user-specified filter matches the test case
472 // name and the test name.
473 bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
474 const String &test_name) {
475 const String& full_name = String::Format("%s.%s",
476 test_case_name.c_str(),
477 test_name.c_str());
478
479 // Split --gtest_filter at '-', if there is one, to separate into
480 // positive filter and negative filter portions
481 const char* const p = GTEST_FLAG(filter).c_str();
482 const char* const dash = strchr(p, '-');
483 String positive;
484 String negative;
485 if (dash == NULL) {
486 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
487 negative = String("");
488 } else {
489 positive = String(p, dash - p); // Everything up to the dash
490 negative = String(dash+1); // Everything after the dash
491 if (positive.empty()) {
492 // Treat '-test1' as the same as '*-test1'
493 positive = kUniversalFilter;
494 }
495 }
496
497 // A filter is a colon-separated list of patterns. It matches a
498 // test if any pattern in it matches the test.
499 return (MatchesFilter(full_name, positive.c_str()) &&
500 !MatchesFilter(full_name, negative.c_str()));
501 }
502
503 #if GTEST_HAS_SEH
504 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
505 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
506 // This function is useful as an __except condition.
507 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
508 // Google Test should handle a SEH exception if:
509 // 1. the user wants it to, AND
510 // 2. this is not a breakpoint exception, AND
511 // 3. this is not a C++ exception (VC++ implements them via SEH,
512 // apparently).
513 //
514 // SEH exception code for C++ exceptions.
515 // (see http://support.microsoft.com/kb/185294 for more information).
516 const DWORD kCxxExceptionCode = 0xe06d7363;
517
518 bool should_handle = true;
519
520 if (!GTEST_FLAG(catch_exceptions))
521 should_handle = false;
522 else if (exception_code == EXCEPTION_BREAKPOINT)
523 should_handle = false;
524 else if (exception_code == kCxxExceptionCode)
525 should_handle = false;
526
527 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
528 }
529 #endif // GTEST_HAS_SEH
530
531 } // namespace internal
532
533 // The c'tor sets this object as the test part result reporter used by
534 // Google Test. The 'result' parameter specifies where to report the
535 // results. Intercepts only failures from the current thread.
536 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
537 TestPartResultArray* result)
538 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
539 result_(result) {
540 Init();
541 }
542
543 // The c'tor sets this object as the test part result reporter used by
544 // Google Test. The 'result' parameter specifies where to report the
545 // results.
546 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
547 InterceptMode intercept_mode, TestPartResultArray* result)
548 : intercept_mode_(intercept_mode),
549 result_(result) {
550 Init();
551 }
552
553 void ScopedFakeTestPartResultReporter::Init() {
554 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
555 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
556 old_reporter_ = impl->GetGlobalTestPartResultReporter();
557 impl->SetGlobalTestPartResultReporter(this);
558 } else {
559 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
560 impl->SetTestPartResultReporterForCurrentThread(this);
561 }
562 }
563
564 // The d'tor restores the test part result reporter used by Google Test
565 // before.
566 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
567 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
568 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
569 impl->SetGlobalTestPartResultReporter(old_reporter_);
570 } else {
571 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
572 }
573 }
574
575 // Increments the test part result count and remembers the result.
576 // This method is from the TestPartResultReporterInterface interface.
577 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
578 const TestPartResult& result) {
579 result_->Append(result);
580 }
581
582 namespace internal {
583
584 // Returns the type ID of ::testing::Test. We should always call this
585 // instead of GetTypeId< ::testing::Test>() to get the type ID of
586 // testing::Test. This is to work around a suspected linker bug when
587 // using Google Test as a framework on Mac OS X. The bug causes
588 // GetTypeId< ::testing::Test>() to return different values depending
589 // on whether the call is from the Google Test framework itself or
590 // from user test code. GetTestTypeId() is guaranteed to always
591 // return the same value, as it always calls GetTypeId<>() from the
592 // gtest.cc, which is within the Google Test framework.
593 TypeId GetTestTypeId() {
594 return GetTypeId();
595 }
596
597 // The value of GetTestTypeId() as seen from within the Google Test
598 // library. This is solely for testing GetTestTypeId().
599 const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
600
601 // This predicate-formatter checks that 'results' contains a test part
602 // failure of the given type and that the failure message contains the
603 // given substring.
604 AssertionResult HasOneFailure(const char* /* results_expr */,
605 const char* /* type_expr */,
606 const char* /* substr_expr */,
607 const TestPartResultArray& results,
608 TestPartResult::Type type,
609 const string& substr) {
610 const String expected(type == TestPartResult::kFatalFailure ?
611 "1 fatal failure" :
612 "1 non-fatal failure");
613 Message msg;
614 if (results.size() != 1) {
615 msg << "Expected: " << expected << "\n"
616 << " Actual: " << results.size() << " failures";
617 for (int i = 0; i < results.size(); i++) {
618 msg << "\n" << results.GetTestPartResult(i);
619 }
620 return AssertionFailure() << msg;
621 }
622
623 const TestPartResult& r = results.GetTestPartResult(0);
624 if (r.type() != type) {
625 return AssertionFailure() << "Expected: " << expected << "\n"
626 << " Actual:\n"
627 << r;
628 }
629
630 if (strstr(r.message(), substr.c_str()) == NULL) {
631 return AssertionFailure() << "Expected: " << expected << " containing \""
632 << substr << "\"\n"
633 << " Actual:\n"
634 << r;
635 }
636
637 return AssertionSuccess();
638 }
639
640 // The constructor of SingleFailureChecker remembers where to look up