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"
52 #include <sys/types.h>
59 #include "base/commandlineflags.h"
65 _START_GOOGLE_NAMESPACE_
67 extern GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)();
69 _END_GOOGLE_NAMESPACE_
71 #undef GOOGLE_GLOG_DLL_DECL
72 #define GOOGLE_GLOG_DLL_DECL
74 static string GetTempDir() {
79 GetTempPathA(MAX_PATH, tmp);
85 // The test will run in glog/vsproject/<project name>
86 // (e.g., glog/vsproject/logging_unittest).
87 static const char TEST_SRC_DIR[] = "../..";
89 static const char TEST_SRC_DIR[] = ".";
92 DEFINE_string(test_tmpdir, GetTempDir(), "Dir we use for temp files");
93 DEFINE_string(test_srcdir, TEST_SRC_DIR,
94 "Source-dir root, needed to find glog_unittest_flagfile");
96 DEFINE_int32(benchmark_iters, 100000000, "Number of iterations per benchmark");
98 DEFINE_int32(benchmark_iters, 100000, "Number of iterations per benchmark");
101 #ifdef HAVE_LIB_GTEST
102 # include <gtest/gtest.h>
103 // Use our ASSERT_DEATH implementation.
105 # undef ASSERT_DEBUG_DEATH
106 using testing::InitGoogleTest;
109 _START_GOOGLE_NAMESPACE_
111 void InitGoogleTest(int* argc, char** argv) {}
113 // The following is some bare-bones testing infrastructure
115 #define EXPECT_TRUE(cond) \
118 fprintf(stderr, "Check failed: %s\n", #cond); \
123 #define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond))
125 #define EXPECT_OP(op, val1, val2) \
127 if (!((val1) op (val2))) { \
128 fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \
133 #define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2)
134 #define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2)
135 #define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2)
136 #define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2)
138 #define EXPECT_NAN(arg) \
141 fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \
146 #define EXPECT_INF(arg) \
149 fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \
154 #define EXPECT_DOUBLE_EQ(val1, val2) \
156 if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \
157 fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \
162 #define EXPECT_STREQ(val1, val2) \
164 if (strcmp((val1), (val2)) != 0) { \
165 fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \
170 vector<void (*)()> g_testlist; // the tests to run
173 struct Test_##a##_##b { \
174 Test_##a##_##b() { g_testlist.push_back(&Run); } \
175 static void Run() { FlagSaver fs; RunTest(); } \
176 static void RunTest(); \
178 static Test_##a##_##b g_test_##a##_##b; \
179 void Test_##a##_##b::RunTest()
182 static int RUN_ALL_TESTS() {
183 vector<void (*)()>::const_iterator it;
184 for (it = g_testlist.begin(); it != g_testlist.end(); ++it) {
187 fprintf(stderr, "Passed %d tests\n\nPASS\n", (int)g_testlist.size());
191 _END_GOOGLE_NAMESPACE_
193 #endif // ! HAVE_LIB_GTEST
195 _START_GOOGLE_NAMESPACE_
197 static bool g_called_abort;
198 static jmp_buf g_jmp_buf;
199 static void CalledAbort() {
200 g_called_abort = true;
201 longjmp(g_jmp_buf, 1);
205 // TODO(hamaji): Death test somehow doesn't work in Windows.
206 #define ASSERT_DEATH(fn, msg)
208 #define ASSERT_DEATH(fn, msg) \
210 g_called_abort = false; \
211 /* in logging.cc */ \
212 void (*original_logging_fail_func)() = g_logging_fail_func; \
213 g_logging_fail_func = &CalledAbort; \
214 if (!setjmp(g_jmp_buf)) fn; \
215 /* set back to their default */ \
216 g_logging_fail_func = original_logging_fail_func; \
217 if (!g_called_abort) { \
218 fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \
225 #define ASSERT_DEBUG_DEATH(fn, msg)
227 #define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg)
232 #define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n);
234 map<string, void (*)(int)> g_benchlist; // the benchmarks to run
236 class BenchmarkRegisterer {
238 BenchmarkRegisterer(const char* name, void (*function)(int iters)) {
239 EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second);
243 static void RunSpecifiedBenchmarks() {
244 int iter_cnt = FLAGS_benchmark_iters;
245 puts("Benchmark\tTime(ns)\tIterations");
246 for (map<string, void (*)(int)>::const_iterator iter = g_benchlist.begin();
247 iter != g_benchlist.end();
249 clock_t start = clock();
250 iter->second(iter_cnt);
252 ((double)clock() - start) / CLOCKS_PER_SEC * 1000*1000*1000;
253 printf("%s\t%8.2lf\t%10d\n",
254 iter->first.c_str(), elapsed_ns / iter_cnt, iter_cnt);
259 // ----------------------------------------------------------------------
260 // Golden file functions
261 // ----------------------------------------------------------------------
263 class CapturedStream {
265 CapturedStream(int fd, const string & filename) :
268 filename_(filename) {
273 if (uncaptured_fd_ != -1) {
274 CHECK(close(uncaptured_fd_) != -1);
278 // Start redirecting output to a file
280 // Keep original stream for later
281 CHECK(uncaptured_fd_ == -1) << ", Stream " << fd_ << " already captured!";
282 uncaptured_fd_ = dup(fd_);
283 CHECK(uncaptured_fd_ != -1);
285 // Open file to save stream to
286 int cap_fd = open(filename_.c_str(),
287 O_CREAT | O_TRUNC | O_WRONLY,
291 // Send stdout/stderr to this file
293 CHECK(dup2(cap_fd, fd_) != -1);
294 CHECK(close(cap_fd) != -1);
297 // Remove output redirection
299 // Restore original stream
300 if (uncaptured_fd_ != -1) {
302 CHECK(dup2(uncaptured_fd_, fd_) != -1);
306 const string & filename() const { return filename_; }
309 int fd_; // file descriptor being captured
310 int uncaptured_fd_; // where the stream was originally being sent to
311 string filename_; // file where stream is being saved
313 static CapturedStream * s_captured_streams[STDERR_FILENO+1];
314 // Redirect a file descriptor to a file.
315 // fd - Should be STDOUT_FILENO or STDERR_FILENO
316 // filename - File where output should be stored
317 static void CaptureTestOutput(int fd, const string & filename) {
318 CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO));
319 CHECK(s_captured_streams[fd] == NULL);
320 s_captured_streams[fd] = new CapturedStream(fd, filename);
322 static void CaptureTestStderr() {
323 CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err");
325 // Return the size (in bytes) of a file
326 static size_t GetFileSize(FILE * file) {
327 fseek(file, 0, SEEK_END);
328 return static_cast<size_t>(ftell(file));
330 // Read the entire content of a file as a string
331 static string ReadEntireFile(FILE * file) {
332 const size_t file_size = GetFileSize(file);
333 char * const buffer = new char[file_size];
335 size_t bytes_last_read = 0; // # of bytes read in the last fread()
336 size_t bytes_read = 0; // # of bytes read so far
338 fseek(file, 0, SEEK_SET);
340 // Keep reading the file until we cannot read further or the
341 // pre-determined file size is reached.
343 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
344 bytes_read += bytes_last_read;
345 } while (bytes_last_read > 0 && bytes_read < file_size);
347 const string content = string(buffer, buffer+bytes_read);
352 // Get the captured stdout (when fd is STDOUT_FILENO) or stderr (when
353 // fd is STDERR_FILENO) as a string
354 static string GetCapturedTestOutput(int fd) {
355 CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO);
356 CapturedStream * const cap = s_captured_streams[fd];
358 << ": did you forget CaptureTestStdout() or CaptureTestStderr()?";
360 // Make sure everything is flushed.
363 // Read the captured file.
364 FILE * const file = fopen(cap->filename().c_str(), "r");
365 const string content = ReadEntireFile(file);
369 s_captured_streams[fd] = NULL;
373 // Get the captured stderr of a test as a string.
374 static string GetCapturedTestStderr() {
375 return GetCapturedTestOutput(STDERR_FILENO);
378 // Check if the string is [IWEF](\d{4}|DATE)
379 static bool IsLoggingPrefix(const string& s) {
380 if (s.size() != 5) return false;
381 if (!strchr("IWEF", s[0])) return false;
382 for (int i = 1; i <= 4; ++i) {
383 if (!isdigit(s[i]) && s[i] != "DATE"[i-1]) return false;
388 // Convert log output into normalized form.
391 // I0102 030405 logging_unittest.cc:345] RAW: vlog -1
392 // => IDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1
393 static string MungeLine(const string& line) {
394 std::istringstream iss(line);
395 string before, logcode_date, time, thread_lineinfo;
397 while (!IsLoggingPrefix(logcode_date)) {
398 before += " " + logcode_date;
399 if (!(iss >> logcode_date)) {
400 // We cannot find the header of log output.
404 if (!before.empty()) before += " ";
406 iss >> thread_lineinfo;
407 CHECK(!thread_lineinfo.empty());
408 if (thread_lineinfo[thread_lineinfo.size() - 1] != ']') {
409 // We found thread ID.
413 CHECK_EQ(']', tmp[tmp.size() - 1]);
414 thread_lineinfo = "THREADID " + tmp;
416 size_t index = thread_lineinfo.find(':');
417 CHECK_NE(string::npos, index);
418 thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]";
420 std::getline(iss, rest);
421 return (before + logcode_date[0] + "DATE TIME__ " + thread_lineinfo +
425 static void StringReplace(string* str,
426 const string& oldsub,
427 const string& newsub) {
428 size_t pos = str->find(oldsub);
429 if (pos != string::npos) {
430 str->replace(pos, oldsub.size(), newsub.c_str());
434 static string Munge(const string& filename) {
435 FILE* fp = fopen(filename.c_str(), "rb");
436 CHECK(fp != NULL) << filename << ": couldn't open";
439 while (fgets(buf, 4095, fp)) {
440 string line = MungeLine(buf);
442 sprintf(null_str, "%p", NULL);
443 StringReplace(&line, "__NULLP__", null_str);
444 // Remove 0x prefix produced by %p. VC++ doesn't put the prefix.
445 StringReplace(&line, " 0x", " ");
447 char errmsg_buf[100];
448 posix_strerror_r(0, errmsg_buf, sizeof(errmsg_buf));
449 if (*errmsg_buf == '\0') {
450 // MacOSX 10.4 and FreeBSD return empty string for errno=0.
451 // In such case, the we need to remove an extra space.
452 StringReplace(&line, "__SUCCESS__ ", "");
454 StringReplace(&line, "__SUCCESS__", errmsg_buf);
456 StringReplace(&line, "__ENOENT__", strerror(ENOENT));
457 StringReplace(&line, "__EINTR__", strerror(EINTR));
458 StringReplace(&line, "__ENXIO__", strerror(ENXIO));
459 StringReplace(&line, "__ENOEXEC__", strerror(ENOEXEC));
460 result += line + "\n";
466 static void WriteToFile(const string& body, const string& file) {
467 FILE* fp = fopen(file.c_str(), "wb");
468 fwrite(body.data(), 1, body.size(), fp);
472 static bool MungeAndDiffTestStderr(const string& golden_filename) {
473 CapturedStream* cap = s_captured_streams[STDERR_FILENO];
474 CHECK(cap) << ": did you forget CaptureTestStderr()?";
479 const string captured = Munge(cap->filename());
480 const string golden = Munge(golden_filename);
481 if (captured != golden) {
483 "Test with golden file failed. We'll try to show the diff:\n");
484 string munged_golden = golden_filename + ".munged";
485 WriteToFile(golden, munged_golden);
486 string munged_captured = cap->filename() + ".munged";
487 WriteToFile(captured, munged_captured);
488 string diffcmd("diff -u " + munged_golden + " " + munged_captured);
489 if (system(diffcmd.c_str()) != 0) {
490 fprintf(stderr, "diff command was failed.\n");
492 unlink(munged_golden.c_str());
493 unlink(munged_captured.c_str());
496 LOG(INFO) << "Diff was successful";
500 // Save flags used from logging_unittest.cc.
501 #ifndef HAVE_LIB_GFLAGS
505 stderrthreshold_(FLAGS_stderrthreshold),
506 logtostderr_(FLAGS_logtostderr),
507 alsologtostderr_(FLAGS_alsologtostderr) {}
510 FLAGS_stderrthreshold = stderrthreshold_;
511 FLAGS_logtostderr = logtostderr_;
512 FLAGS_alsologtostderr = alsologtostderr_;
515 int stderrthreshold_;
517 bool alsologtostderr_;
523 void SetJoinable(bool joinable) {}
524 #if defined(HAVE_PTHREAD)
526 pthread_create(&th_, NULL, &Thread::InvokeThread, this);
529 pthread_join(th_, NULL);
531 #elif defined(OS_WINDOWS) || defined(OS_CYGWIN)
533 handle_ = CreateThread(NULL,
535 (LPTHREAD_START_ROUTINE)&Thread::InvokeThread,
539 CHECK(handle_) << "CreateThread";
542 WaitForSingleObject(handle_, INFINITE);
545 # error No thread implementation.
549 virtual void Run() = 0;
552 static void* InvokeThread(void* self) {
553 ((Thread*)self)->Run();
557 #if defined(OS_WINDOWS) || defined(OS_CYGWIN)
565 static void SleepForMilliseconds(int t) {
573 // Add hook for operator new to ensure there are no memory allocation.
575 void (*g_new_hook)() = NULL;
577 _END_GOOGLE_NAMESPACE_
579 void* operator new(size_t size) {
580 if (GOOGLE_NAMESPACE::g_new_hook) {
581 GOOGLE_NAMESPACE::g_new_hook();
586 void* operator new[](size_t size) {
587 return ::operator new(size);
590 void operator delete(void* p) {
594 void operator delete[](void* p) {
595 ::operator delete(p);