2 #error You must not include this file twice.
15 #include <sys/types.h>
22 #include "base/commandlineflags.h"
28 _START_GOOGLE_NAMESPACE_
30 extern GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)();
32 _END_GOOGLE_NAMESPACE_
34 #undef GOOGLE_GLOG_DLL_DECL
35 #define GOOGLE_GLOG_DLL_DECL
37 static string GetTempDir() {
42 GetTempPathA(MAX_PATH, tmp);
48 // The test will run in glog/vsproject/<project name>
49 // (e.g., glog/vsproject/logging_unittest).
50 static const char TEST_SRC_DIR[] = "../..";
52 static const char TEST_SRC_DIR[] = ".";
55 DEFINE_string(test_tmpdir, GetTempDir(), "Dir we use for temp files");
56 DEFINE_string(test_srcdir, TEST_SRC_DIR,
57 "Source-dir root, needed to find glog_unittest_flagfile");
59 DEFINE_int32(benchmark_iters, 100000000, "Number of iterations per benchmark");
61 DEFINE_int32(benchmark_iters, 1000000, "Number of iterations per benchmark");
65 # include <gtest/gtest.h>
66 // Use our ASSERT_DEATH implementation.
68 # undef ASSERT_DEBUG_DEATH
69 using testing::InitGoogleTest;
72 _START_GOOGLE_NAMESPACE_
74 void InitGoogleTest(int* argc, char** argv) {}
76 // The following is some bare-bones testing infrastructure
78 #define EXPECT_TRUE(cond) \
81 fprintf(stderr, "Check failed: %s\n", #cond); \
86 #define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond))
88 #define EXPECT_OP(op, val1, val2) \
90 if (!((val1) op (val2))) { \
91 fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \
96 #define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2)
97 #define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2)
98 #define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2)
99 #define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2)
101 #define EXPECT_NAN(arg) \
104 fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \
109 #define EXPECT_INF(arg) \
112 fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \
117 #define EXPECT_DOUBLE_EQ(val1, val2) \
119 if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \
120 fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \
125 #define EXPECT_STREQ(val1, val2) \
127 if (strcmp((val1), (val2)) != 0) { \
128 fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \
133 vector<void (*)()> g_testlist; // the tests to run
136 struct Test_##a##_##b { \
137 Test_##a##_##b() { g_testlist.push_back(&Run); } \
138 static void Run() { FlagSaver fs; RunTest(); } \
139 static void RunTest(); \
141 static Test_##a##_##b g_test_##a##_##b; \
142 void Test_##a##_##b::RunTest()
145 static int RUN_ALL_TESTS() {
146 vector<void (*)()>::const_iterator it;
147 for (it = g_testlist.begin(); it != g_testlist.end(); ++it) {
150 fprintf(stderr, "Passed %d tests\n\nPASS\n", (int)g_testlist.size());
154 _END_GOOGLE_NAMESPACE_
158 _START_GOOGLE_NAMESPACE_
160 static bool g_called_abort;
161 static jmp_buf g_jmp_buf;
162 static void CalledAbort() {
163 g_called_abort = true;
164 longjmp(g_jmp_buf, 1);
168 // TODO(hamaji): Death test somehow doesn't work in Windows.
169 #define ASSERT_DEATH(fn, msg)
171 #define ASSERT_DEATH(fn, msg) \
173 g_called_abort = false; \
174 /* in logging.cc */ \
175 void (*original_logging_fail_func)() = g_logging_fail_func; \
176 g_logging_fail_func = &CalledAbort; \
177 if (!setjmp(g_jmp_buf)) fn; \
178 /* set back to their default */ \
179 g_logging_fail_func = original_logging_fail_func; \
180 if (!g_called_abort) { \
181 fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \
188 #define ASSERT_DEBUG_DEATH(fn, msg)
190 #define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg)
195 #define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n);
197 map<string, void (*)(int)> g_benchlist; // the benchmarks to run
199 class BenchmarkRegisterer {
201 BenchmarkRegisterer(const char* name, void (*function)(int iters)) {
202 EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second);
206 static void RunSpecifiedBenchmarks() {
207 int iter_cnt = FLAGS_benchmark_iters;
208 puts("Benchmark\tTime(ns)\tIterations");
209 for (map<string, void (*)(int)>::const_iterator iter = g_benchlist.begin();
210 iter != g_benchlist.end();
212 clock_t start = clock();
213 iter->second(iter_cnt);
215 ((double)clock() - start) / CLOCKS_PER_SEC * 1000*1000*1000;
216 printf("%s\t%8.2lf\t%10d\n",
217 iter->first.c_str(), elapsed_ns / iter_cnt, iter_cnt);
222 // ----------------------------------------------------------------------
223 // Golden file functions
224 // ----------------------------------------------------------------------
226 class CapturedStream {
228 CapturedStream(int fd, const string & filename) :
231 filename_(filename) {
236 if (uncaptured_fd_ != -1) {
237 CHECK(close(uncaptured_fd_) != -1);
241 // Start redirecting output to a file
243 // Keep original stream for later
244 CHECK(uncaptured_fd_ == -1) << ", Stream " << fd_ << " already captured!";
245 uncaptured_fd_ = dup(fd_);
246 CHECK(uncaptured_fd_ != -1);
248 // Open file to save stream to
249 int cap_fd = open(filename_.c_str(),
250 O_CREAT | O_TRUNC | O_WRONLY,
254 // Send stdout/stderr to this file
256 CHECK(dup2(cap_fd, fd_) != -1);
257 CHECK(close(cap_fd) != -1);
260 // Remove output redirection
262 // Restore original stream
263 if (uncaptured_fd_ != -1) {
265 CHECK(dup2(uncaptured_fd_, fd_) != -1);
269 const string & filename() const { return filename_; }
272 int fd_; // file descriptor being captured
273 int uncaptured_fd_; // where the stream was originally being sent to
274 string filename_; // file where stream is being saved
276 static CapturedStream * s_captured_streams[STDERR_FILENO+1];
277 // Redirect a file descriptor to a file.
278 // fd - Should be STDOUT_FILENO or STDERR_FILENO
279 // filename - File where output should be stored
280 static void CaptureTestOutput(int fd, const string & filename) {
281 CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO));
282 CHECK(s_captured_streams[fd] == NULL);
283 s_captured_streams[fd] = new CapturedStream(fd, filename);
285 static void CaptureTestStderr() {
286 CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err");
288 // Return the size (in bytes) of a file
289 static size_t GetFileSize(FILE * file) {
290 fseek(file, 0, SEEK_END);
291 return static_cast<size_t>(ftell(file));
293 // Read the entire content of a file as a string
294 static string ReadEntireFile(FILE * file) {
295 const size_t file_size = GetFileSize(file);
296 char * const buffer = new char[file_size];
298 size_t bytes_last_read = 0; // # of bytes read in the last fread()
299 size_t bytes_read = 0; // # of bytes read so far
301 fseek(file, 0, SEEK_SET);
303 // Keep reading the file until we cannot read further or the
304 // pre-determined file size is reached.
306 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
307 bytes_read += bytes_last_read;
308 } while (bytes_last_read > 0 && bytes_read < file_size);
310 const string content = string(buffer, buffer+bytes_read);
315 // Get the captured stdout (when fd is STDOUT_FILENO) or stderr (when
316 // fd is STDERR_FILENO) as a string
317 static string GetCapturedTestOutput(int fd) {
318 CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO);
319 CapturedStream * const cap = s_captured_streams[fd];
321 << ": did you forget CaptureTestStdout() or CaptureTestStderr()?";
323 // Make sure everything is flushed.
326 // Read the captured file.
327 FILE * const file = fopen(cap->filename().c_str(), "r");
328 const string content = ReadEntireFile(file);
332 s_captured_streams[fd] = NULL;
336 // Get the captured stderr of a test as a string.
337 static string GetCapturedTestStderr() {
338 return GetCapturedTestOutput(STDERR_FILENO);
341 // Check if the string is [IWEF](\d{4}|DATE)
342 static bool IsLoggingPrefix(const string& s) {
343 if (s.size() != 5) return false;
344 if (!strchr("IWEF", s[0])) return false;
345 for (int i = 1; i <= 4; ++i) {
346 if (!isdigit(s[i]) && s[i] != "DATE"[i-1]) return false;
351 // Convert log output into normalized form.
354 // I0102 030405 logging_unittest.cc:345] RAW: vlog -1
355 // => IDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1
356 static string MungeLine(const string& line) {
357 std::istringstream iss(line);
358 string before, logcode_date, time, thread_lineinfo;
360 while (!IsLoggingPrefix(logcode_date)) {
361 before += " " + logcode_date;
362 if (!(iss >> logcode_date)) {
363 // We cannot find the header of log output.
367 if (!before.empty()) before += " ";
369 CHECK_EQ(6, time.size());
370 iss >> thread_lineinfo;
371 CHECK(!thread_lineinfo.empty());
372 if (thread_lineinfo[thread_lineinfo.size() - 1] != ']') {
373 // We found thread ID.
377 CHECK_EQ(']', tmp[tmp.size() - 1]);
378 thread_lineinfo = "THREADID " + tmp;
380 size_t index = thread_lineinfo.find(':');
381 CHECK_NE(string::npos, index);
382 thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]";
384 std::getline(iss, rest);
385 return (before + logcode_date[0] + "DATE TIME__ " + thread_lineinfo +
389 static void StringReplace(string* str,
390 const string& oldsub,
391 const string& newsub) {
392 size_t pos = str->find(oldsub);
393 if (pos != string::npos) {
394 str->replace(pos, oldsub.size(), newsub.c_str());
398 static string Munge(const string& filename) {
399 FILE* fp = fopen(filename.c_str(), "rb");
400 CHECK(fp != NULL) << filename << ": couldn't open";
403 while (fgets(buf, 4095, fp)) {
404 string line = MungeLine(buf);
406 sprintf(null_str, "%p", NULL);
407 StringReplace(&line, "__NULLP__", null_str);
408 // Remove 0x prefix produced by %p. VC++ doesn't put the prefix.
409 StringReplace(&line, " 0x", " ");
411 char errmsg_buf[100];
412 posix_strerror_r(0, errmsg_buf, sizeof(errmsg_buf));
413 if (*errmsg_buf == '\0') {
414 // MacOSX 10.4 and FreeBSD return empty string for errno=0.
415 // In such case, the we need to remove an extra space.
416 StringReplace(&line, "__SUCCESS__ ", "");
418 StringReplace(&line, "__SUCCESS__", errmsg_buf);
420 StringReplace(&line, "__ENOENT__", strerror(ENOENT));
421 StringReplace(&line, "__EINTR__", strerror(EINTR));
422 StringReplace(&line, "__ENXIO__", strerror(ENXIO));
423 StringReplace(&line, "__ENOEXEC__", strerror(ENOEXEC));
424 result += line + "\n";
430 static void WriteToFile(const string& body, const string& file) {
431 FILE* fp = fopen(file.c_str(), "wb");
432 fwrite(body.data(), 1, body.size(), fp);
436 static bool MungeAndDiffTestStderr(const string& golden_filename) {
437 CapturedStream* cap = s_captured_streams[STDERR_FILENO];
438 CHECK(cap) << ": did you forget CaptureTestStderr()?";
443 const string captured = Munge(cap->filename());
444 const string golden = Munge(golden_filename);
445 if (captured != golden) {
447 "Test with golden file failed. We'll try to show the diff:\n");
448 string munged_golden = golden_filename + ".munged";
449 WriteToFile(golden, munged_golden);
450 string munged_captured = cap->filename() + ".munged";
451 WriteToFile(captured, munged_captured);
452 string diffcmd("diff -u " + munged_golden + " " + munged_captured);
453 if (system(diffcmd.c_str()) != 0) {
454 fprintf(stderr, "diff command was failed.\n");
456 unlink(munged_golden.c_str());
457 unlink(munged_captured.c_str());
460 LOG(INFO) << "Diff was successful";
464 // Save flags used from logging_unittest.cc.
465 #ifndef HAVE_LIB_GFLAGS
469 stderrthreshold_(FLAGS_stderrthreshold),
470 logtostderr_(FLAGS_logtostderr),
471 alsologtostderr_(FLAGS_alsologtostderr) {}
474 FLAGS_stderrthreshold = stderrthreshold_;
475 FLAGS_logtostderr = logtostderr_;
476 FLAGS_alsologtostderr = alsologtostderr_;
479 int stderrthreshold_;
481 bool alsologtostderr_;
487 void SetJoinable(bool joinable) {}
488 #if defined(HAVE_PTHREAD)
490 pthread_create(&th_, NULL, &Thread::InvokeThread, this);
493 pthread_join(th_, NULL);
495 #elif defined(OS_WINDOWS)
497 handle_ = CreateThread(NULL,
499 (LPTHREAD_START_ROUTINE)&Thread::InvokeThread,
503 CHECK(handle_) << "CreateThread";
506 WaitForSingleObject(handle_, INFINITE);
509 # error No thread implementation.
513 virtual void Run() = 0;
516 static void* InvokeThread(void* self) {
517 ((Thread*)self)->Run();
527 static void SleepForMilliseconds(int t) {
535 // Add hook for operator new to ensure there are no memory allocation.
537 void (*g_new_hook)() = NULL;
539 _END_GOOGLE_NAMESPACE_
541 void* operator new(size_t size) {
542 if (GOOGLE_NAMESPACE::g_new_hook) {
543 GOOGLE_NAMESPACE::g_new_hook();
548 void* operator new[](size_t size) {
549 return ::operator new(size);
552 void operator delete(void* p) {
556 void operator delete[](void* p) {
557 ::operator delete(p);