2 #error You must not include this file twice.
17 #include <sys/types.h>
24 #include "base/commandlineflags.h"
30 _START_GOOGLE_NAMESPACE_
32 extern GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)();
34 _END_GOOGLE_NAMESPACE_
36 #undef GOOGLE_GLOG_DLL_DECL
37 #define GOOGLE_GLOG_DLL_DECL
39 static string GetTempDir() {
44 GetTempPathA(MAX_PATH, tmp);
50 // The test will run in glog/vsproject/<project name>
51 // (e.g., glog/vsproject/logging_unittest).
52 static const char TEST_SRC_DIR[] = "../..";
54 static const char TEST_SRC_DIR[] = ".";
57 DEFINE_string(test_tmpdir, GetTempDir(), "Dir we use for temp files");
58 DEFINE_string(test_srcdir, TEST_SRC_DIR,
59 "Source-dir root, needed to find glog_unittest_flagfile");
61 DEFINE_int32(benchmark_iters, 100000000, "Number of iterations per benchmark");
63 DEFINE_int32(benchmark_iters, 100000, "Number of iterations per benchmark");
67 # include <gtest/gtest.h>
68 // Use our ASSERT_DEATH implementation.
70 # undef ASSERT_DEBUG_DEATH
71 using testing::InitGoogleTest;
74 _START_GOOGLE_NAMESPACE_
76 void InitGoogleTest(int* argc, char** argv) {}
78 // The following is some bare-bones testing infrastructure
80 #define EXPECT_TRUE(cond) \
83 fprintf(stderr, "Check failed: %s\n", #cond); \
88 #define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond))
90 #define EXPECT_OP(op, val1, val2) \
92 if (!((val1) op (val2))) { \
93 fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \
98 #define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2)
99 #define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2)
100 #define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2)
101 #define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2)
103 #define EXPECT_NAN(arg) \
106 fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \
111 #define EXPECT_INF(arg) \
114 fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \
119 #define EXPECT_DOUBLE_EQ(val1, val2) \
121 if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \
122 fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \
127 #define EXPECT_STREQ(val1, val2) \
129 if (strcmp((val1), (val2)) != 0) { \
130 fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \
135 vector<void (*)()> g_testlist; // the tests to run
138 struct Test_##a##_##b { \
139 Test_##a##_##b() { g_testlist.push_back(&Run); } \
140 static void Run() { FlagSaver fs; RunTest(); } \
141 static void RunTest(); \
143 static Test_##a##_##b g_test_##a##_##b; \
144 void Test_##a##_##b::RunTest()
147 static int RUN_ALL_TESTS() {
148 vector<void (*)()>::const_iterator it;
149 for (it = g_testlist.begin(); it != g_testlist.end(); ++it) {
152 fprintf(stderr, "Passed %d tests\n\nPASS\n", (int)g_testlist.size());
156 _END_GOOGLE_NAMESPACE_
158 #endif // ! HAVE_LIB_GTEST
160 _START_GOOGLE_NAMESPACE_
162 static bool g_called_abort;
163 static jmp_buf g_jmp_buf;
164 static void CalledAbort() {
165 g_called_abort = true;
166 longjmp(g_jmp_buf, 1);
170 // TODO(hamaji): Death test somehow doesn't work in Windows.
171 #define ASSERT_DEATH(fn, msg)
173 #define ASSERT_DEATH(fn, msg) \
175 g_called_abort = false; \
176 /* in logging.cc */ \
177 void (*original_logging_fail_func)() = g_logging_fail_func; \
178 g_logging_fail_func = &CalledAbort; \
179 if (!setjmp(g_jmp_buf)) fn; \
180 /* set back to their default */ \
181 g_logging_fail_func = original_logging_fail_func; \
182 if (!g_called_abort) { \
183 fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \
190 #define ASSERT_DEBUG_DEATH(fn, msg)
192 #define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg)
197 #define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n);
199 map<string, void (*)(int)> g_benchlist; // the benchmarks to run
201 class BenchmarkRegisterer {
203 BenchmarkRegisterer(const char* name, void (*function)(int iters)) {
204 EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second);
208 static void RunSpecifiedBenchmarks() {
209 int iter_cnt = FLAGS_benchmark_iters;
210 puts("Benchmark\tTime(ns)\tIterations");
211 for (map<string, void (*)(int)>::const_iterator iter = g_benchlist.begin();
212 iter != g_benchlist.end();
214 clock_t start = clock();
215 iter->second(iter_cnt);
217 ((double)clock() - start) / CLOCKS_PER_SEC * 1000*1000*1000;
218 printf("%s\t%8.2lf\t%10d\n",
219 iter->first.c_str(), elapsed_ns / iter_cnt, iter_cnt);
224 // ----------------------------------------------------------------------
225 // Golden file functions
226 // ----------------------------------------------------------------------
228 class CapturedStream {
230 CapturedStream(int fd, const string & filename) :
233 filename_(filename) {
238 if (uncaptured_fd_ != -1) {
239 CHECK(close(uncaptured_fd_) != -1);
243 // Start redirecting output to a file
245 // Keep original stream for later
246 CHECK(uncaptured_fd_ == -1) << ", Stream " << fd_ << " already captured!";
247 uncaptured_fd_ = dup(fd_);
248 CHECK(uncaptured_fd_ != -1);
250 // Open file to save stream to
251 int cap_fd = open(filename_.c_str(),
252 O_CREAT | O_TRUNC | O_WRONLY,
256 // Send stdout/stderr to this file
258 CHECK(dup2(cap_fd, fd_) != -1);
259 CHECK(close(cap_fd) != -1);
262 // Remove output redirection
264 // Restore original stream
265 if (uncaptured_fd_ != -1) {
267 CHECK(dup2(uncaptured_fd_, fd_) != -1);
271 const string & filename() const { return filename_; }
274 int fd_; // file descriptor being captured
275 int uncaptured_fd_; // where the stream was originally being sent to
276 string filename_; // file where stream is being saved
278 static CapturedStream * s_captured_streams[STDERR_FILENO+1];
279 // Redirect a file descriptor to a file.
280 // fd - Should be STDOUT_FILENO or STDERR_FILENO
281 // filename - File where output should be stored
282 static void CaptureTestOutput(int fd, const string & filename) {
283 CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO));
284 CHECK(s_captured_streams[fd] == NULL);
285 s_captured_streams[fd] = new CapturedStream(fd, filename);
287 static void CaptureTestStderr() {
288 CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err");
290 // Return the size (in bytes) of a file
291 static size_t GetFileSize(FILE * file) {
292 fseek(file, 0, SEEK_END);
293 return static_cast<size_t>(ftell(file));
295 // Read the entire content of a file as a string
296 static string ReadEntireFile(FILE * file) {
297 const size_t file_size = GetFileSize(file);
298 char * const buffer = new char[file_size];
300 size_t bytes_last_read = 0; // # of bytes read in the last fread()
301 size_t bytes_read = 0; // # of bytes read so far
303 fseek(file, 0, SEEK_SET);
305 // Keep reading the file until we cannot read further or the
306 // pre-determined file size is reached.
308 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
309 bytes_read += bytes_last_read;
310 } while (bytes_last_read > 0 && bytes_read < file_size);
312 const string content = string(buffer, buffer+bytes_read);
317 // Get the captured stdout (when fd is STDOUT_FILENO) or stderr (when
318 // fd is STDERR_FILENO) as a string
319 static string GetCapturedTestOutput(int fd) {
320 CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO);
321 CapturedStream * const cap = s_captured_streams[fd];
323 << ": did you forget CaptureTestStdout() or CaptureTestStderr()?";
325 // Make sure everything is flushed.
328 // Read the captured file.
329 FILE * const file = fopen(cap->filename().c_str(), "r");
330 const string content = ReadEntireFile(file);
334 s_captured_streams[fd] = NULL;
338 // Get the captured stderr of a test as a string.
339 static string GetCapturedTestStderr() {
340 return GetCapturedTestOutput(STDERR_FILENO);
343 // Check if the string is [IWEF](\d{4}|DATE)
344 static bool IsLoggingPrefix(const string& s) {
345 if (s.size() != 5) return false;
346 if (!strchr("IWEF", s[0])) return false;
347 for (int i = 1; i <= 4; ++i) {
348 if (!isdigit(s[i]) && s[i] != "DATE"[i-1]) return false;
353 // Convert log output into normalized form.
356 // I0102 030405 logging_unittest.cc:345] RAW: vlog -1
357 // => IDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1
358 static string MungeLine(const string& line) {
359 std::istringstream iss(line);
360 string before, logcode_date, time, thread_lineinfo;
362 while (!IsLoggingPrefix(logcode_date)) {
363 before += " " + logcode_date;
364 if (!(iss >> logcode_date)) {
365 // We cannot find the header of log output.
369 if (!before.empty()) before += " ";
371 iss >> thread_lineinfo;
372 CHECK(!thread_lineinfo.empty());
373 if (thread_lineinfo[thread_lineinfo.size() - 1] != ']') {
374 // We found thread ID.
378 CHECK_EQ(']', tmp[tmp.size() - 1]);
379 thread_lineinfo = "THREADID " + tmp;
381 size_t index = thread_lineinfo.find(':');
382 CHECK_NE(string::npos, index);
383 thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]";
385 std::getline(iss, rest);
386 return (before + logcode_date[0] + "DATE TIME__ " + thread_lineinfo +
390 static void StringReplace(string* str,
391 const string& oldsub,
392 const string& newsub) {
393 size_t pos = str->find(oldsub);
394 if (pos != string::npos) {
395 str->replace(pos, oldsub.size(), newsub.c_str());
399 static string Munge(const string& filename) {
400 FILE* fp = fopen(filename.c_str(), "rb");
401 CHECK(fp != NULL) << filename << ": couldn't open";
404 while (fgets(buf, 4095, fp)) {
405 string line = MungeLine(buf);
407 sprintf(null_str, "%p", NULL);
408 StringReplace(&line, "__NULLP__", null_str);
409 // Remove 0x prefix produced by %p. VC++ doesn't put the prefix.
410 StringReplace(&line, " 0x", " ");
412 char errmsg_buf[100];
413 posix_strerror_r(0, errmsg_buf, sizeof(errmsg_buf));
414 if (*errmsg_buf == '\0') {
415 // MacOSX 10.4 and FreeBSD return empty string for errno=0.
416 // In such case, the we need to remove an extra space.
417 StringReplace(&line, "__SUCCESS__ ", "");
419 StringReplace(&line, "__SUCCESS__", errmsg_buf);
421 StringReplace(&line, "__ENOENT__", strerror(ENOENT));
422 StringReplace(&line, "__EINTR__", strerror(EINTR));
423 StringReplace(&line, "__ENXIO__", strerror(ENXIO));
424 StringReplace(&line, "__ENOEXEC__", strerror(ENOEXEC));
425 result += line + "\n";
431 static void WriteToFile(const string& body, const string& file) {
432 FILE* fp = fopen(file.c_str(), "wb");
433 fwrite(body.data(), 1, body.size(), fp);
437 static bool MungeAndDiffTestStderr(const string& golden_filename) {
438 CapturedStream* cap = s_captured_streams[STDERR_FILENO];
439 CHECK(cap) << ": did you forget CaptureTestStderr()?";
444 const string captured = Munge(cap->filename());
445 const string golden = Munge(golden_filename);
446 if (captured != golden) {
448 "Test with golden file failed. We'll try to show the diff:\n");
449 string munged_golden = golden_filename + ".munged";
450 WriteToFile(golden, munged_golden);
451 string munged_captured = cap->filename() + ".munged";
452 WriteToFile(captured, munged_captured);
453 string diffcmd("diff -u " + munged_golden + " " + munged_captured);
454 if (system(diffcmd.c_str()) != 0) {
455 fprintf(stderr, "diff command was failed.\n");
457 unlink(munged_golden.c_str());
458 unlink(munged_captured.c_str());
461 LOG(INFO) << "Diff was successful";
465 // Save flags used from logging_unittest.cc.
466 #ifndef HAVE_LIB_GFLAGS
470 stderrthreshold_(FLAGS_stderrthreshold),
471 logtostderr_(FLAGS_logtostderr),
472 alsologtostderr_(FLAGS_alsologtostderr) {}
475 FLAGS_stderrthreshold = stderrthreshold_;
476 FLAGS_logtostderr = logtostderr_;
477 FLAGS_alsologtostderr = alsologtostderr_;
480 int stderrthreshold_;
482 bool alsologtostderr_;
488 void SetJoinable(bool joinable) {}
489 #if defined(HAVE_PTHREAD)
491 pthread_create(&th_, NULL, &Thread::InvokeThread, this);
494 pthread_join(th_, NULL);
496 #elif defined(OS_WINDOWS) || defined(OS_CYGWIN)
498 handle_ = CreateThread(NULL,
500 (LPTHREAD_START_ROUTINE)&Thread::InvokeThread,
504 CHECK(handle_) << "CreateThread";
507 WaitForSingleObject(handle_, INFINITE);
510 # error No thread implementation.
514 virtual void Run() = 0;
517 static void* InvokeThread(void* self) {
518 ((Thread*)self)->Run();
522 #if defined(OS_WINDOWS) || defined(OS_CYGWIN)
530 static void SleepForMilliseconds(int t) {
538 // Add hook for operator new to ensure there are no memory allocation.
540 void (*g_new_hook)() = NULL;
542 _END_GOOGLE_NAMESPACE_
544 void* operator new(size_t size) {
545 if (GOOGLE_NAMESPACE::g_new_hook) {
546 GOOGLE_NAMESPACE::g_new_hook();
551 void* operator new[](size_t size) {
552 return ::operator new(size);
555 void operator delete(void* p) {
559 void operator delete[](void* p) {
560 ::operator delete(p);