1 // Copyright (c) 2009, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: Shinichiro Hamaji
31 // (based on googletest: http://code.google.com/p/googletest/)
34 #error You must not include this file twice.
36 #define GOOGLETEST_H__
38 #include "utilities.h"
49 #include <sys/types.h>
56 #include "base/commandlineflags.h"
62 _START_GOOGLE_NAMESPACE_
64 extern GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)();
66 _END_GOOGLE_NAMESPACE_
68 #undef GOOGLE_GLOG_DLL_DECL
69 #define GOOGLE_GLOG_DLL_DECL
71 static string GetTempDir() {
76 GetTempPathA(MAX_PATH, tmp);
82 // The test will run in glog/vsproject/<project name>
83 // (e.g., glog/vsproject/logging_unittest).
84 static const char TEST_SRC_DIR[] = "../..";
86 static const char TEST_SRC_DIR[] = ".";
89 DEFINE_string(test_tmpdir, GetTempDir(), "Dir we use for temp files");
90 DEFINE_string(test_srcdir, TEST_SRC_DIR,
91 "Source-dir root, needed to find glog_unittest_flagfile");
93 DEFINE_int32(benchmark_iters, 100000000, "Number of iterations per benchmark");
95 DEFINE_int32(benchmark_iters, 100000, "Number of iterations per benchmark");
99 # include <gtest/gtest.h>
100 // Use our ASSERT_DEATH implementation.
102 # undef ASSERT_DEBUG_DEATH
103 using testing::InitGoogleTest;
106 _START_GOOGLE_NAMESPACE_
108 void InitGoogleTest(int* argc, char** argv) {}
110 // The following is some bare-bones testing infrastructure
112 #define EXPECT_TRUE(cond) \
115 fprintf(stderr, "Check failed: %s\n", #cond); \
120 #define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond))
122 #define EXPECT_OP(op, val1, val2) \
124 if (!((val1) op (val2))) { \
125 fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \
130 #define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2)
131 #define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2)
132 #define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2)
133 #define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2)
135 #define EXPECT_NAN(arg) \
138 fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \
143 #define EXPECT_INF(arg) \
146 fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \
151 #define EXPECT_DOUBLE_EQ(val1, val2) \
153 if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \
154 fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \
159 #define EXPECT_STREQ(val1, val2) \
161 if (strcmp((val1), (val2)) != 0) { \
162 fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \
167 vector<void (*)()> g_testlist; // the tests to run
170 struct Test_##a##_##b { \
171 Test_##a##_##b() { g_testlist.push_back(&Run); } \
172 static void Run() { FlagSaver fs; RunTest(); } \
173 static void RunTest(); \
175 static Test_##a##_##b g_test_##a##_##b; \
176 void Test_##a##_##b::RunTest()
179 static int RUN_ALL_TESTS() {
180 vector<void (*)()>::const_iterator it;
181 for (it = g_testlist.begin(); it != g_testlist.end(); ++it) {
184 fprintf(stderr, "Passed %d tests\n\nPASS\n", (int)g_testlist.size());
188 _END_GOOGLE_NAMESPACE_
190 #endif // ! HAVE_LIB_GTEST
192 _START_GOOGLE_NAMESPACE_
194 static bool g_called_abort;
195 static jmp_buf g_jmp_buf;
196 static void CalledAbort() {
197 g_called_abort = true;
198 longjmp(g_jmp_buf, 1);
202 // TODO(hamaji): Death test somehow doesn't work in Windows.
203 #define ASSERT_DEATH(fn, msg)
205 #define ASSERT_DEATH(fn, msg) \
207 g_called_abort = false; \
208 /* in logging.cc */ \
209 void (*original_logging_fail_func)() = g_logging_fail_func; \
210 g_logging_fail_func = &CalledAbort; \
211 if (!setjmp(g_jmp_buf)) fn; \
212 /* set back to their default */ \
213 g_logging_fail_func = original_logging_fail_func; \
214 if (!g_called_abort) { \
215 fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \
222 #define ASSERT_DEBUG_DEATH(fn, msg)
224 #define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg)
229 #define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n);
231 map<string, void (*)(int)> g_benchlist; // the benchmarks to run
233 class BenchmarkRegisterer {
235 BenchmarkRegisterer(const char* name, void (*function)(int iters)) {
236 EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second);
240 static void RunSpecifiedBenchmarks() {
241 int iter_cnt = FLAGS_benchmark_iters;
242 puts("Benchmark\tTime(ns)\tIterations");
243 for (map<string, void (*)(int)>::const_iterator iter = g_benchlist.begin();
244 iter != g_benchlist.end();
246 clock_t start = clock();
247 iter->second(iter_cnt);
249 ((double)clock() - start) / CLOCKS_PER_SEC * 1000*1000*1000;
250 printf("%s\t%8.2lf\t%10d\n",
251 iter->first.c_str(), elapsed_ns / iter_cnt, iter_cnt);
256 // ----------------------------------------------------------------------
257 // Golden file functions
258 // ----------------------------------------------------------------------
260 class CapturedStream {
262 CapturedStream(int fd, const string & filename) :
265 filename_(filename) {
270 if (uncaptured_fd_ != -1) {
271 CHECK(close(uncaptured_fd_) != -1);
275 // Start redirecting output to a file
277 // Keep original stream for later
278 CHECK(uncaptured_fd_ == -1) << ", Stream " << fd_ << " already captured!";
279 uncaptured_fd_ = dup(fd_);
280 CHECK(uncaptured_fd_ != -1);
282 // Open file to save stream to
283 int cap_fd = open(filename_.c_str(),
284 O_CREAT | O_TRUNC | O_WRONLY,
288 // Send stdout/stderr to this file
290 CHECK(dup2(cap_fd, fd_) != -1);
291 CHECK(close(cap_fd) != -1);
294 // Remove output redirection
296 // Restore original stream
297 if (uncaptured_fd_ != -1) {
299 CHECK(dup2(uncaptured_fd_, fd_) != -1);
303 const string & filename() const { return filename_; }
306 int fd_; // file descriptor being captured
307 int uncaptured_fd_; // where the stream was originally being sent to
308 string filename_; // file where stream is being saved
310 static CapturedStream * s_captured_streams[STDERR_FILENO+1];
311 // Redirect a file descriptor to a file.
312 // fd - Should be STDOUT_FILENO or STDERR_FILENO
313 // filename - File where output should be stored
314 static void CaptureTestOutput(int fd, const string & filename) {
315 CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO));
316 CHECK(s_captured_streams[fd] == NULL);
317 s_captured_streams[fd] = new CapturedStream(fd, filename);
319 static void CaptureTestStderr() {
320 CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err");
322 // Return the size (in bytes) of a file
323 static size_t GetFileSize(FILE * file) {
324 fseek(file, 0, SEEK_END);
325 return static_cast<size_t>(ftell(file));
327 // Read the entire content of a file as a string
328 static string ReadEntireFile(FILE * file) {
329 const size_t file_size = GetFileSize(file);
330 char * const buffer = new char[file_size];
332 size_t bytes_last_read = 0; // # of bytes read in the last fread()
333 size_t bytes_read = 0; // # of bytes read so far
335 fseek(file, 0, SEEK_SET);
337 // Keep reading the file until we cannot read further or the
338 // pre-determined file size is reached.
340 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
341 bytes_read += bytes_last_read;
342 } while (bytes_last_read > 0 && bytes_read < file_size);
344 const string content = string(buffer, buffer+bytes_read);
349 // Get the captured stdout (when fd is STDOUT_FILENO) or stderr (when
350 // fd is STDERR_FILENO) as a string
351 static string GetCapturedTestOutput(int fd) {
352 CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO);
353 CapturedStream * const cap = s_captured_streams[fd];
355 << ": did you forget CaptureTestStdout() or CaptureTestStderr()?";
357 // Make sure everything is flushed.
360 // Read the captured file.
361 FILE * const file = fopen(cap->filename().c_str(), "r");
362 const string content = ReadEntireFile(file);
366 s_captured_streams[fd] = NULL;
370 // Get the captured stderr of a test as a string.
371 static string GetCapturedTestStderr() {
372 return GetCapturedTestOutput(STDERR_FILENO);
375 // Check if the string is [IWEF](\d{4}|DATE)
376 static bool IsLoggingPrefix(const string& s) {
377 if (s.size() != 5) return false;
378 if (!strchr("IWEF", s[0])) return false;
379 for (int i = 1; i <= 4; ++i) {
380 if (!isdigit(s[i]) && s[i] != "DATE"[i-1]) return false;
385 // Convert log output into normalized form.
388 // I0102 030405 logging_unittest.cc:345] RAW: vlog -1
389 // => IDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1
390 static string MungeLine(const string& line) {
391 std::istringstream iss(line);
392 string before, logcode_date, time, thread_lineinfo;
394 while (!IsLoggingPrefix(logcode_date)) {
395 before += " " + logcode_date;
396 if (!(iss >> logcode_date)) {
397 // We cannot find the header of log output.
401 if (!before.empty()) before += " ";
403 iss >> thread_lineinfo;
404 CHECK(!thread_lineinfo.empty());
405 if (thread_lineinfo[thread_lineinfo.size() - 1] != ']') {
406 // We found thread ID.
410 CHECK_EQ(']', tmp[tmp.size() - 1]);
411 thread_lineinfo = "THREADID " + tmp;
413 size_t index = thread_lineinfo.find(':');
414 CHECK_NE(string::npos, index);
415 thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]";
417 std::getline(iss, rest);
418 return (before + logcode_date[0] + "DATE TIME__ " + thread_lineinfo +
422 static void StringReplace(string* str,
423 const string& oldsub,
424 const string& newsub) {
425 size_t pos = str->find(oldsub);
426 if (pos != string::npos) {
427 str->replace(pos, oldsub.size(), newsub.c_str());
431 static string Munge(const string& filename) {
432 FILE* fp = fopen(filename.c_str(), "rb");
433 CHECK(fp != NULL) << filename << ": couldn't open";
436 while (fgets(buf, 4095, fp)) {
437 string line = MungeLine(buf);
439 sprintf(null_str, "%p", NULL);
440 StringReplace(&line, "__NULLP__", null_str);
441 // Remove 0x prefix produced by %p. VC++ doesn't put the prefix.
442 StringReplace(&line, " 0x", " ");
444 char errmsg_buf[100];
445 posix_strerror_r(0, errmsg_buf, sizeof(errmsg_buf));
446 if (*errmsg_buf == '\0') {
447 // MacOSX 10.4 and FreeBSD return empty string for errno=0.
448 // In such case, the we need to remove an extra space.
449 StringReplace(&line, "__SUCCESS__ ", "");
451 StringReplace(&line, "__SUCCESS__", errmsg_buf);
453 StringReplace(&line, "__ENOENT__", strerror(ENOENT));
454 StringReplace(&line, "__EINTR__", strerror(EINTR));
455 StringReplace(&line, "__ENXIO__", strerror(ENXIO));
456 StringReplace(&line, "__ENOEXEC__", strerror(ENOEXEC));
457 result += line + "\n";
463 static void WriteToFile(const string& body, const string& file) {
464 FILE* fp = fopen(file.c_str(), "wb");
465 fwrite(body.data(), 1, body.size(), fp);
469 static bool MungeAndDiffTestStderr(const string& golden_filename) {
470 CapturedStream* cap = s_captured_streams[STDERR_FILENO];
471 CHECK(cap) << ": did you forget CaptureTestStderr()?";
476 const string captured = Munge(cap->filename());
477 const string golden = Munge(golden_filename);
478 if (captured != golden) {
480 "Test with golden file failed. We'll try to show the diff:\n");
481 string munged_golden = golden_filename + ".munged";
482 WriteToFile(golden, munged_golden);
483 string munged_captured = cap->filename() + ".munged";
484 WriteToFile(captured, munged_captured);
485 string diffcmd("diff -u " + munged_golden + " " + munged_captured);
486 if (system(diffcmd.c_str()) != 0) {
487 fprintf(stderr, "diff command was failed.\n");
489 unlink(munged_golden.c_str());
490 unlink(munged_captured.c_str());
493 LOG(INFO) << "Diff was successful";
497 // Save flags used from logging_unittest.cc.
498 #ifndef HAVE_LIB_GFLAGS
502 stderrthreshold_(FLAGS_stderrthreshold),
503 logtostderr_(FLAGS_logtostderr),
504 alsologtostderr_(FLAGS_alsologtostderr) {}
507 FLAGS_stderrthreshold = stderrthreshold_;
508 FLAGS_logtostderr = logtostderr_;
509 FLAGS_alsologtostderr = alsologtostderr_;
512 int stderrthreshold_;
514 bool alsologtostderr_;
520 void SetJoinable(bool joinable) {}
521 #if defined(HAVE_PTHREAD)
523 pthread_create(&th_, NULL, &Thread::InvokeThread, this);
526 pthread_join(th_, NULL);
528 #elif defined(OS_WINDOWS) || defined(OS_CYGWIN)
530 handle_ = CreateThread(NULL,
532 (LPTHREAD_START_ROUTINE)&Thread::InvokeThread,
536 CHECK(handle_) << "CreateThread";
539 WaitForSingleObject(handle_, INFINITE);
542 # error No thread implementation.
546 virtual void Run() = 0;
549 static void* InvokeThread(void* self) {
550 ((Thread*)self)->Run();
554 #if defined(OS_WINDOWS) || defined(OS_CYGWIN)
562 static void SleepForMilliseconds(int t) {
570 // Add hook for operator new to ensure there are no memory allocation.
572 void (*g_new_hook)() = NULL;
574 _END_GOOGLE_NAMESPACE_
576 void* operator new(size_t size) {
577 if (GOOGLE_NAMESPACE::g_new_hook) {
578 GOOGLE_NAMESPACE::g_new_hook();
583 void* operator new[](size_t size) {
584 return ::operator new(size);
587 void operator delete(void* p) {
591 void operator delete[](void* p) {
592 ::operator delete(p);