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");
64 _START_GOOGLE_NAMESPACE_
66 // The following is some bare-bones testing infrastructure
68 #define EXPECT_TRUE(cond) \
71 fprintf(stderr, "Check failed: %s\n", #cond); \
76 #define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond))
78 #define EXPECT_OP(op, val1, val2) \
80 if (!((val1) op (val2))) { \
81 fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \
86 #define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2)
87 #define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2)
88 #define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2)
89 #define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2)
91 #define EXPECT_NAN(arg) \
94 fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \
99 #define EXPECT_INF(arg) \
102 fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \
107 #define EXPECT_DOUBLE_EQ(val1, val2) \
109 if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \
110 fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \
115 #define EXPECT_STREQ(val1, val2) \
117 if (strcmp((val1), (val2)) != 0) { \
118 fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \
123 static bool g_called_abort;
124 static jmp_buf g_jmp_buf;
125 static void CalledAbort() {
126 g_called_abort = true;
127 longjmp(g_jmp_buf, 1);
131 // TODO(hamaji): Death test somehow doesn't work in Windows.
132 #define ASSERT_DEATH(fn, msg)
134 #define ASSERT_DEATH(fn, msg) \
136 g_called_abort = false; \
137 /* in logging.cc */ \
138 void (*original_logging_fail_func)() = g_logging_fail_func; \
139 g_logging_fail_func = &CalledAbort; \
140 if (!setjmp(g_jmp_buf)) fn; \
141 /* set back to their default */ \
142 g_logging_fail_func = original_logging_fail_func; \
143 if (!g_called_abort) { \
144 fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \
151 #define ASSERT_DEBUG_DEATH(fn, msg)
153 #define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg)
156 vector<void (*)()> g_testlist; // the tests to run
159 struct Test_##a##_##b { \
160 Test_##a##_##b() { g_testlist.push_back(&Run); } \
161 static void Run() { FlagSaver fs; RunTest(); } \
162 static void RunTest(); \
164 static Test_##a##_##b g_test_##a##_##b; \
165 void Test_##a##_##b::RunTest()
168 static int RUN_ALL_TESTS() {
169 vector<void (*)()>::const_iterator it;
170 for (it = g_testlist.begin(); it != g_testlist.end(); ++it) {
173 fprintf(stderr, "Passed %d tests\n\nPASS\n", (int)g_testlist.size());
179 #define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n);
181 map<string, void (*)(int)> g_benchlist; // the benchmarks to run
183 class BenchmarkRegisterer {
185 BenchmarkRegisterer(const char* name, void (*function)(int iters)) {
186 EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second);
190 static void RunSpecifiedBenchmarks() {
191 int iter_cnt = FLAGS_benchmark_iters;
192 puts("Benchmark\tTime(ns)\tIterations");
193 for (map<string, void (*)(int)>::const_iterator iter = g_benchlist.begin();
194 iter != g_benchlist.end();
196 clock_t start = clock();
197 iter->second(iter_cnt);
199 ((double)clock() - start) / CLOCKS_PER_SEC * 1000*1000*1000;
200 printf("%s\t%8.2lf\t%10d\n",
201 iter->first.c_str(), elapsed_ns / iter_cnt, iter_cnt);
206 // ----------------------------------------------------------------------
207 // Golden file functions
208 // ----------------------------------------------------------------------
210 class CapturedStream {
212 CapturedStream(int fd, const string & filename) :
215 filename_(filename) {
220 if (uncaptured_fd_ != -1) {
221 CHECK(close(uncaptured_fd_) != -1);
225 // Start redirecting output to a file
227 // Keep original stream for later
228 CHECK(uncaptured_fd_ == -1) << ", Stream " << fd_ << " already captured!";
229 uncaptured_fd_ = dup(fd_);
230 CHECK(uncaptured_fd_ != -1);
232 // Open file to save stream to
233 int cap_fd = open(filename_.c_str(),
234 O_CREAT | O_TRUNC | O_WRONLY,
238 // Send stdout/stderr to this file
240 CHECK(dup2(cap_fd, fd_) != -1);
241 CHECK(close(cap_fd) != -1);
244 // Remove output redirection
246 // Restore original stream
247 if (uncaptured_fd_ != -1) {
249 CHECK(dup2(uncaptured_fd_, fd_) != -1);
253 const string & filename() const { return filename_; }
256 int fd_; // file descriptor being captured
257 int uncaptured_fd_; // where the stream was originally being sent to
258 string filename_; // file where stream is being saved
260 static CapturedStream * s_captured_streams[STDERR_FILENO+1];
261 // Redirect a file descriptor to a file.
262 // fd - Should be STDOUT_FILENO or STDERR_FILENO
263 // filename - File where output should be stored
264 static void CaptureTestOutput(int fd, const string & filename) {
265 CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO));
266 CHECK(s_captured_streams[fd] == NULL);
267 s_captured_streams[fd] = new CapturedStream(fd, filename);
269 static void CaptureTestStderr() {
270 CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err");
272 // Return the size (in bytes) of a file
273 static size_t GetFileSize(FILE * file) {
274 fseek(file, 0, SEEK_END);
275 return static_cast<size_t>(ftell(file));
277 // Read the entire content of a file as a string
278 static string ReadEntireFile(FILE * file) {
279 const size_t file_size = GetFileSize(file);
280 char * const buffer = new char[file_size];
282 size_t bytes_last_read = 0; // # of bytes read in the last fread()
283 size_t bytes_read = 0; // # of bytes read so far
285 fseek(file, 0, SEEK_SET);
287 // Keep reading the file until we cannot read further or the
288 // pre-determined file size is reached.
290 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
291 bytes_read += bytes_last_read;
292 } while (bytes_last_read > 0 && bytes_read < file_size);
294 const string content = string(buffer, buffer+bytes_read);
299 // Get the captured stdout (when fd is STDOUT_FILENO) or stderr (when
300 // fd is STDERR_FILENO) as a string
301 static string GetCapturedTestOutput(int fd) {
302 CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO);
303 CapturedStream * const cap = s_captured_streams[fd];
305 << ": did you forget CaptureTestStdout() or CaptureTestStderr()?";
307 // Make sure everything is flushed.
310 // Read the captured file.
311 FILE * const file = fopen(cap->filename().c_str(), "r");
312 const string content = ReadEntireFile(file);
316 s_captured_streams[fd] = NULL;
320 // Get the captured stderr of a test as a string.
321 static string GetCapturedTestStderr() {
322 return GetCapturedTestOutput(STDERR_FILENO);
325 // Check if the string is [IWEF](\d{4}|DATE)
326 static bool IsLoggingPrefix(const string& s) {
327 if (s.size() != 5) return false;
328 if (!strchr("IWEF", s[0])) return false;
329 for (int i = 1; i <= 4; ++i) {
330 if (!isdigit(s[i]) && s[i] != "DATE"[i-1]) return false;
335 // Convert log output into normalized form.
338 // I0102 030405 logging_unittest.cc:345] RAW: vlog -1
339 // => IDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1
340 static string MungeLine(const string& line) {
341 std::istringstream iss(line);
342 string before, logcode_date, time, thread_lineinfo;
344 while (!IsLoggingPrefix(logcode_date)) {
345 before += " " + logcode_date;
346 if (!(iss >> logcode_date)) {
347 // We cannot find the header of log output.
351 if (!before.empty()) before += " ";
353 CHECK_EQ(6, time.size());
354 iss >> thread_lineinfo;
355 CHECK(!thread_lineinfo.empty());
356 if (thread_lineinfo[thread_lineinfo.size() - 1] != ']') {
357 // We found thread ID.
361 CHECK_EQ(']', tmp[tmp.size() - 1]);
362 thread_lineinfo = "THREADID " + tmp;
364 size_t index = thread_lineinfo.find(':');
365 CHECK_NE(string::npos, index);
366 thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]";
368 std::getline(iss, rest);
369 return (before + logcode_date[0] + "DATE TIME__ " + thread_lineinfo +
373 static void StringReplace(string* str,
374 const string& oldsub,
375 const string& newsub) {
376 size_t pos = str->find(oldsub);
377 if (pos != string::npos) {
378 str->replace(pos, oldsub.size(), newsub.c_str());
382 static string Munge(const string& filename) {
383 FILE* fp = fopen(filename.c_str(), "rb");
384 CHECK(fp != NULL) << filename << ": couldn't open";
387 while (fgets(buf, 4095, fp)) {
388 string line = MungeLine(buf);
390 sprintf(null_str, "%p", NULL);
391 StringReplace(&line, "__NULLP__", null_str);
392 // Remove 0x prefix produced by %p. VC++ doesn't put the prefix.
393 StringReplace(&line, " 0x", " ");
395 char errmsg_buf[100];
396 posix_strerror_r(0, errmsg_buf, sizeof(errmsg_buf));
397 if (*errmsg_buf == '\0') {
398 // MacOSX 10.4 and FreeBSD return empty string for errno=0.
399 // In such case, the we need to remove an extra space.
400 StringReplace(&line, "__SUCCESS__ ", "");
402 StringReplace(&line, "__SUCCESS__", errmsg_buf);
404 StringReplace(&line, "__ENOENT__", strerror(ENOENT));
405 StringReplace(&line, "__EINTR__", strerror(EINTR));
406 StringReplace(&line, "__ENXIO__", strerror(ENXIO));
407 StringReplace(&line, "__ENOEXEC__", strerror(ENOEXEC));
408 result += line + "\n";
414 static void WriteToFile(const string& body, const string& file) {
415 FILE* fp = fopen(file.c_str(), "wb");
416 fwrite(body.data(), 1, body.size(), fp);
420 static bool MungeAndDiffTestStderr(const string& golden_filename) {
421 CapturedStream* cap = s_captured_streams[STDERR_FILENO];
422 CHECK(cap) << ": did you forget CaptureTestStderr()?";
427 const string captured = Munge(cap->filename());
428 const string golden = Munge(golden_filename);
429 if (captured != golden) {
431 "Test with golden file failed. We'll try to show the diff:\n");
432 string munged_golden = golden_filename + ".munged";
433 WriteToFile(golden, munged_golden);
434 string munged_captured = cap->filename() + ".munged";
435 WriteToFile(captured, munged_captured);
436 string diffcmd("diff -u " + munged_golden + " " + munged_captured);
437 if (system(diffcmd.c_str()) != 0) {
438 fprintf(stderr, "diff command was failed.\n");
440 unlink(munged_golden.c_str());
441 unlink(munged_captured.c_str());
444 LOG(INFO) << "Diff was successful";
448 // Save flags used from logging_unittest.cc.
449 #ifndef HAVE_LIB_GFLAGS
453 stderrthreshold_(FLAGS_stderrthreshold),
454 logtostderr_(FLAGS_logtostderr),
455 alsologtostderr_(FLAGS_alsologtostderr) {}
458 FLAGS_stderrthreshold = stderrthreshold_;
459 FLAGS_logtostderr = logtostderr_;
460 FLAGS_alsologtostderr = alsologtostderr_;
463 int stderrthreshold_;
465 bool alsologtostderr_;
471 void SetJoinable(bool joinable) {}
472 #if defined(HAVE_PTHREAD)
474 pthread_create(&th_, NULL, &Thread::InvokeThread, this);
477 pthread_join(th_, NULL);
479 #elif defined(OS_WINDOWS)
481 handle_ = CreateThread(NULL,
483 (LPTHREAD_START_ROUTINE)&Thread::InvokeThread,
487 CHECK(handle_) << "CreateThread";
490 WaitForSingleObject(handle_, INFINITE);
493 # error No thread implementation.
497 virtual void Run() = 0;
500 static void* InvokeThread(void* self) {
501 ((Thread*)self)->Run();
511 static void SleepForMilliseconds(int t) {
519 // Add hook for operator new to ensure there are no memory allocation.
521 void (*g_new_hook)() = NULL;
523 _END_GOOGLE_NAMESPACE_
525 void* operator new(size_t size) {
526 if (GOOGLE_NAMESPACE::g_new_hook) {
527 GOOGLE_NAMESPACE::g_new_hook();
532 void* operator new[](size_t size) {
533 return ::operator new(size);
536 void operator delete(void* p) {
540 void operator delete[](void* p) {
541 ::operator delete(p);