Initial windows support. Now we don't have the stacktrace and several unittests.
[platform/upstream/glog.git] / src / googletest.h
1 #ifdef GOOGLETEST_H__
2 #error You must not include this file twice.
3 #endif
4 #define GOOGLETEST_H__
5
6 #include <ctype.h>
7 #include <setjmp.h>
8 #include <time.h>
9
10 #include <map>
11 #include <sstream>
12 #include <string>
13 #include <vector>
14
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #ifdef HAVE_UNISTD_H
19 # include <unistd.h>
20 #endif
21
22 #include "base/commandlineflags.h"
23
24 using std::map;
25 using std::string;
26 using std::vector;
27
28 _START_GOOGLE_NAMESPACE_
29
30 extern GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)();
31
32 _END_GOOGLE_NAMESPACE_
33
34 #undef GOOGLE_GLOG_DLL_DECL
35 #define GOOGLE_GLOG_DLL_DECL
36
37 static string GetTempDir() {
38 #ifndef OS_WINDOWS
39   return "/tmp";
40 #else
41   char tmp[MAX_PATH];
42   GetTempPathA(MAX_PATH, tmp);
43   return tmp;
44 #endif
45 }
46
47 #ifdef OS_WINDOWS
48 // The test will run in glog/vsproject/<project name>
49 // (e.g., glog/vsproject/logging_unittest).
50 static const char TEST_SRC_DIR[] = "../..";
51 #else
52 static const char TEST_SRC_DIR[] = ".";
53 #endif
54
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");
58 #ifdef NDEBUG
59 DEFINE_int32(benchmark_iters, 100000000, "Number of iterations per benchmark");
60 #else
61 DEFINE_int32(benchmark_iters, 1000000, "Number of iterations per benchmark");
62 #endif
63
64 _START_GOOGLE_NAMESPACE_
65
66 // The following is some bare-bones testing infrastructure
67
68 #define EXPECT_TRUE(cond)                               \
69   do {                                                  \
70     if (!(cond)) {                                      \
71       fprintf(stderr, "Check failed: %s\n", #cond);     \
72       exit(1);                                          \
73     }                                                   \
74   } while (0)
75
76 #define EXPECT_FALSE(cond)  EXPECT_TRUE(!(cond))
77
78 #define EXPECT_OP(op, val1, val2)                                       \
79   do {                                                                  \
80     if (!((val1) op (val2))) {                                          \
81       fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2);   \
82       exit(1);                                                          \
83     }                                                                   \
84   } while (0)
85
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)
90
91 #define EXPECT_NAN(arg)                                         \
92   do {                                                          \
93     if (!isnan(arg)) {                                          \
94       fprintf(stderr, "Check failed: isnan(%s)\n", #arg);       \
95       exit(1);                                                  \
96     }                                                           \
97   } while (0)
98
99 #define EXPECT_INF(arg)                                         \
100   do {                                                          \
101     if (!isinf(arg)) {                                          \
102       fprintf(stderr, "Check failed: isinf(%s)\n", #arg);       \
103       exit(1);                                                  \
104     }                                                           \
105   } while (0)
106
107 #define EXPECT_DOUBLE_EQ(val1, val2)                                    \
108   do {                                                                  \
109     if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) {         \
110       fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2);        \
111       exit(1);                                                          \
112     }                                                                   \
113   } while (0)
114
115 #define EXPECT_STREQ(val1, val2)                                        \
116   do {                                                                  \
117     if (strcmp((val1), (val2)) != 0) {                                  \
118       fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2);   \
119       exit(1);                                                          \
120     }                                                                   \
121   } while (0)
122
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);
128 }
129
130 #ifdef OS_WINDOWS
131 // TODO(hamaji): Death test somehow doesn't work in Windows.
132 #define ASSERT_DEATH(fn, msg)
133 #else
134 #define ASSERT_DEATH(fn, msg)                                           \
135   do {                                                                  \
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);      \
145       exit(1);                                                          \
146     }                                                                   \
147   } while (0)
148 #endif
149
150 #ifdef NDEBUG
151 #define ASSERT_DEBUG_DEATH(fn, msg)
152 #else
153 #define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg)
154 #endif  // NDEBUG
155
156 vector<void (*)()> g_testlist;  // the tests to run
157
158 #define TEST(a, b)                                      \
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();                              \
163   };                                                    \
164   static Test_##a##_##b g_test_##a##_##b;               \
165   void Test_##a##_##b::RunTest()
166
167
168 static int RUN_ALL_TESTS() {
169   vector<void (*)()>::const_iterator it;
170   for (it = g_testlist.begin(); it != g_testlist.end(); ++it) {
171     (*it)();
172   }
173   fprintf(stderr, "Passed %d tests\n\nPASS\n", (int)g_testlist.size());
174   return 0;
175 }
176
177 // Benchmark tools.
178
179 #define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n);
180
181 map<string, void (*)(int)> g_benchlist;  // the benchmarks to run
182
183 class BenchmarkRegisterer {
184  public:
185   BenchmarkRegisterer(const char* name, void (*function)(int iters)) {
186     EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second);
187   }
188 };
189
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();
195        ++iter) {
196     clock_t start = clock();
197     iter->second(iter_cnt);
198     double elapsed_ns =
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);
202   }
203   puts("");
204 }
205
206 // ----------------------------------------------------------------------
207 // Golden file functions
208 // ----------------------------------------------------------------------
209
210 class CapturedStream {
211  public:
212   CapturedStream(int fd, const string & filename) :
213     fd_(fd),
214     uncaptured_fd_(-1),
215     filename_(filename) {
216     Capture();
217   }
218
219   ~CapturedStream() {
220     if (uncaptured_fd_ != -1) {
221       CHECK(close(uncaptured_fd_) != -1);
222     }
223   }
224
225   // Start redirecting output to a file
226   void Capture() {
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);
231
232     // Open file to save stream to
233     int cap_fd = open(filename_.c_str(),
234                       O_CREAT | O_TRUNC | O_WRONLY,
235                       S_IRUSR | S_IWUSR);
236     CHECK(cap_fd != -1);
237
238     // Send stdout/stderr to this file
239     fflush(NULL);
240     CHECK(dup2(cap_fd, fd_) != -1);
241     CHECK(close(cap_fd) != -1);
242   }
243
244   // Remove output redirection
245   void StopCapture() {
246     // Restore original stream
247     if (uncaptured_fd_ != -1) {
248       fflush(NULL);
249       CHECK(dup2(uncaptured_fd_, fd_) != -1);
250     }
251   }
252
253   const string & filename() const { return filename_; }
254
255  private:
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
259 };
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);
268 }
269 static void CaptureTestStderr() {
270   CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err");
271 }
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));
276 }
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];
281
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
284
285   fseek(file, 0, SEEK_SET);
286
287   // Keep reading the file until we cannot read further or the
288   // pre-determined file size is reached.
289   do {
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);
293
294   const string content = string(buffer, buffer+bytes_read);
295   delete[] buffer;
296
297   return content;
298 }
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];
304   CHECK(cap)
305     << ": did you forget CaptureTestStdout() or CaptureTestStderr()?";
306
307   // Make sure everything is flushed.
308   cap->StopCapture();
309
310   // Read the captured file.
311   FILE * const file = fopen(cap->filename().c_str(), "r");
312   const string content = ReadEntireFile(file);
313   fclose(file);
314
315   delete cap;
316   s_captured_streams[fd] = NULL;
317
318   return content;
319 }
320 // Get the captured stderr of a test as a string.
321 static string GetCapturedTestStderr() {
322   return GetCapturedTestOutput(STDERR_FILENO);
323 }
324
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;
331   }
332   return true;
333 }
334
335 // Convert log output into normalized form.
336 //
337 // Example:
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;
343   iss >> logcode_date;
344   while (!IsLoggingPrefix(logcode_date)) {
345     before += " " + logcode_date;
346     if (!(iss >> logcode_date)) {
347       // We cannot find the header of log output.
348       return before;
349     }
350   }
351   if (!before.empty()) before += " ";
352   iss >> time;
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.
358     string tmp;
359     iss >> tmp;
360     CHECK(!tmp.empty());
361     CHECK_EQ(']', tmp[tmp.size() - 1]);
362     thread_lineinfo = "THREADID " + tmp;
363   }
364   size_t index = thread_lineinfo.find(':');
365   CHECK_NE(string::npos, index);
366   thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]";
367   string rest;
368   std::getline(iss, rest);
369   return (before + logcode_date[0] + "DATE TIME__ " + thread_lineinfo +
370           MungeLine(rest));
371 }
372
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());
379   }
380 }
381
382 static string Munge(const string& filename) {
383   FILE* fp = fopen(filename.c_str(), "rb");
384   CHECK(fp != NULL) << filename << ": couldn't open";
385   char buf[4096];
386   string result;
387   while (fgets(buf, 4095, fp)) {
388     string line = MungeLine(buf);
389     char null_str[256];
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", " ");
394
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__ ", "");
401     } else {
402       StringReplace(&line, "__SUCCESS__", errmsg_buf);
403     }
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";
409   }
410   fclose(fp);
411   return result;
412 }
413
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);
417   fclose(fp);
418 }
419
420 static bool MungeAndDiffTestStderr(const string& golden_filename) {
421   CapturedStream* cap = s_captured_streams[STDERR_FILENO];
422   CHECK(cap) << ": did you forget CaptureTestStderr()?";
423
424   cap->StopCapture();
425
426   // Run munge
427   const string captured = Munge(cap->filename());
428   const string golden = Munge(golden_filename);
429   if (captured != golden) {
430     fprintf(stderr,
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");
439     }
440     unlink(munged_golden.c_str());
441     unlink(munged_captured.c_str());
442     return false;
443   }
444   LOG(INFO) << "Diff was successful";
445   return true;
446 }
447
448 // Save flags used from logging_unittest.cc.
449 #ifndef HAVE_LIB_GFLAGS
450 struct FlagSaver {
451   FlagSaver()
452       : v_(FLAGS_v),
453         stderrthreshold_(FLAGS_stderrthreshold),
454         logtostderr_(FLAGS_logtostderr),
455         alsologtostderr_(FLAGS_alsologtostderr) {}
456   ~FlagSaver() {
457     FLAGS_v = v_;
458     FLAGS_stderrthreshold = stderrthreshold_;
459     FLAGS_logtostderr = logtostderr_;
460     FLAGS_alsologtostderr = alsologtostderr_;
461   }
462   int v_;
463   int stderrthreshold_;
464   bool logtostderr_;
465   bool alsologtostderr_;
466 };
467 #endif
468
469 class Thread {
470  public:
471   void SetJoinable(bool joinable) {}
472 #if defined(HAVE_PTHREAD)
473   void Start() {
474     pthread_create(&th_, NULL, &Thread::InvokeThread, this);
475   }
476   void Join() {
477     pthread_join(th_, NULL);
478   }
479 #elif defined(OS_WINDOWS)
480   void Start() {
481     handle_ = CreateThread(NULL,
482                            0,
483                            (LPTHREAD_START_ROUTINE)&Thread::InvokeThread,
484                            (LPVOID)this,
485                            0,
486                            &th_);
487     CHECK(handle_) << "CreateThread";
488   }
489   void Join() {
490     WaitForSingleObject(handle_, INFINITE);
491   }
492 #else
493 # error No thread implementation.
494 #endif
495
496  protected:
497   virtual void Run() = 0;
498
499  private:
500   static void* InvokeThread(void* self) {
501     ((Thread*)self)->Run();
502     return NULL;
503   }
504
505   pthread_t th_;
506 #ifdef OS_WINDOWS
507   HANDLE handle_;
508 #endif
509 };
510
511 static void SleepForMilliseconds(int t) {
512 #ifndef OS_WINDOWS
513   usleep(t * 1000);
514 #else
515   Sleep(t);
516 #endif
517 }
518
519 // Add hook for operator new to ensure there are no memory allocation.
520
521 void (*g_new_hook)() = NULL;
522
523 _END_GOOGLE_NAMESPACE_
524
525 void* operator new(size_t size) {
526   if (GOOGLE_NAMESPACE::g_new_hook) {
527     GOOGLE_NAMESPACE::g_new_hook();
528   }
529   return malloc(size);
530 }
531
532 void* operator new[](size_t size) {
533   return ::operator new(size);
534 }
535
536 void operator delete(void* p) {
537   free(p);
538 }
539
540 void operator delete[](void* p) {
541   ::operator delete(p);
542 }