Style fixes for consistency
[platform/upstream/glog.git] / src / googletest.h
1 // Copyright (c) 2009, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
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
13 // distribution.
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.
17 //
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.
29 //
30 // Author: Shinichiro Hamaji
31 //   (based on googletest: http://code.google.com/p/googletest/)
32
33 #ifdef GOOGLETEST_H__
34 #error You must not include this file twice.
35 #endif
36 #define GOOGLETEST_H__
37
38 #include "utilities.h"
39
40 #include <ctype.h>
41 #include <setjmp.h>
42 #include <time.h>
43
44 #include <map>
45 #include <sstream>
46 #include <string>
47 #include <vector>
48
49 #include <stdio.h>
50 #include <stdlib.h>
51
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <fcntl.h>
55 #ifdef HAVE_UNISTD_H
56 # include <unistd.h>
57 #endif
58
59 #include "base/commandlineflags.h"
60
61 using std::map;
62 using std::string;
63 using std::vector;
64
65 _START_GOOGLE_NAMESPACE_
66
67 extern GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)();
68
69 _END_GOOGLE_NAMESPACE_
70
71 #undef GOOGLE_GLOG_DLL_DECL
72 #define GOOGLE_GLOG_DLL_DECL
73
74 static inline string GetTempDir() {
75 #ifndef OS_WINDOWS
76   return "/tmp";
77 #else
78   char tmp[MAX_PATH];
79   GetTempPathA(MAX_PATH, tmp);
80   return tmp;
81 #endif
82 }
83
84 #if defined(OS_WINDOWS) && defined(_MSC_VER) && !defined(TEST_SRC_DIR)
85 // The test will run in glog/vsproject/<project name>
86 // (e.g., glog/vsproject/logging_unittest).
87 static const char TEST_SRC_DIR[] = "../..";
88 #elif !defined(TEST_SRC_DIR)
89 # warning TEST_SRC_DIR should be defined in config.h
90 static const char TEST_SRC_DIR[] = ".";
91 #endif
92
93 DEFINE_string(test_tmpdir, GetTempDir(), "Dir we use for temp files");
94 DEFINE_string(test_srcdir, TEST_SRC_DIR,
95               "Source-dir root, needed to find glog_unittest_flagfile");
96 DEFINE_bool(run_benchmark, false, "If true, run benchmarks");
97 #ifdef NDEBUG
98 DEFINE_int32(benchmark_iters, 100000000, "Number of iterations per benchmark");
99 #else
100 DEFINE_int32(benchmark_iters, 100000, "Number of iterations per benchmark");
101 #endif
102
103 #ifdef HAVE_LIB_GTEST
104 # include <gtest/gtest.h>
105 // Use our ASSERT_DEATH implementation.
106 # undef ASSERT_DEATH
107 # undef ASSERT_DEBUG_DEATH
108 using testing::InitGoogleTest;
109 #else
110
111 _START_GOOGLE_NAMESPACE_
112
113 void InitGoogleTest(int*, char**) {}
114
115 // The following is some bare-bones testing infrastructure
116
117 #define EXPECT_TRUE(cond)                               \
118   do {                                                  \
119     if (!(cond)) {                                      \
120       fprintf(stderr, "Check failed: %s\n", #cond);     \
121       exit(1);                                          \
122     }                                                   \
123   } while (0)
124
125 #define EXPECT_FALSE(cond)  EXPECT_TRUE(!(cond))
126
127 #define EXPECT_OP(op, val1, val2)                                       \
128   do {                                                                  \
129     if (!((val1) op (val2))) {                                          \
130       fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2);   \
131       exit(1);                                                          \
132     }                                                                   \
133   } while (0)
134
135 #define EXPECT_EQ(val1, val2)  EXPECT_OP(==, val1, val2)
136 #define EXPECT_NE(val1, val2)  EXPECT_OP(!=, val1, val2)
137 #define EXPECT_GT(val1, val2)  EXPECT_OP(>, val1, val2)
138 #define EXPECT_LT(val1, val2)  EXPECT_OP(<, val1, val2)
139
140 #define EXPECT_NAN(arg)                                         \
141   do {                                                          \
142     if (!isnan(arg)) {                                          \
143       fprintf(stderr, "Check failed: isnan(%s)\n", #arg);       \
144       exit(1);                                                  \
145     }                                                           \
146   } while (0)
147
148 #define EXPECT_INF(arg)                                         \
149   do {                                                          \
150     if (!isinf(arg)) {                                          \
151       fprintf(stderr, "Check failed: isinf(%s)\n", #arg);       \
152       exit(1);                                                  \
153     }                                                           \
154   } while (0)
155
156 #define EXPECT_DOUBLE_EQ(val1, val2)                                    \
157   do {                                                                  \
158     if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) {         \
159       fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2);        \
160       exit(1);                                                          \
161     }                                                                   \
162   } while (0)
163
164 #define EXPECT_STREQ(val1, val2)                                        \
165   do {                                                                  \
166     if (strcmp((val1), (val2)) != 0) {                                  \
167       fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2);   \
168       exit(1);                                                          \
169     }                                                                   \
170   } while (0)
171
172 vector<void (*)()> g_testlist;  // the tests to run
173
174 #define TEST(a, b)                                      \
175   struct Test_##a##_##b {                               \
176     Test_##a##_##b() { g_testlist.push_back(&Run); }    \
177     static void Run() { FlagSaver fs; RunTest(); }      \
178     static void RunTest();                              \
179   };                                                    \
180   static Test_##a##_##b g_test_##a##_##b;               \
181   void Test_##a##_##b::RunTest()
182
183
184 static inline int RUN_ALL_TESTS() {
185   vector<void (*)()>::const_iterator it;
186   for (it = g_testlist.begin(); it != g_testlist.end(); ++it) {
187     (*it)();
188   }
189   fprintf(stderr, "Passed %d tests\n\nPASS\n", (int)g_testlist.size());
190   return 0;
191 }
192
193 _END_GOOGLE_NAMESPACE_
194
195 #endif  // ! HAVE_LIB_GTEST
196
197 _START_GOOGLE_NAMESPACE_
198
199 static bool g_called_abort;
200 static jmp_buf g_jmp_buf;
201 static inline void CalledAbort() {
202   g_called_abort = true;
203   longjmp(g_jmp_buf, 1);
204 }
205
206 #ifdef OS_WINDOWS
207 // TODO(hamaji): Death test somehow doesn't work in Windows.
208 #define ASSERT_DEATH(fn, msg)
209 #else
210 #define ASSERT_DEATH(fn, msg)                                           \
211   do {                                                                  \
212     g_called_abort = false;                                             \
213     /* in logging.cc */                                                 \
214     void (*original_logging_fail_func)() = g_logging_fail_func;         \
215     g_logging_fail_func = &CalledAbort;                                 \
216     if (!setjmp(g_jmp_buf)) fn;                                         \
217     /* set back to their default */                                     \
218     g_logging_fail_func = original_logging_fail_func;                   \
219     if (!g_called_abort) {                                              \
220       fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn);      \
221       exit(1);                                                          \
222     }                                                                   \
223   } while (0)
224 #endif
225
226 #ifdef NDEBUG
227 #define ASSERT_DEBUG_DEATH(fn, msg)
228 #else
229 #define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg)
230 #endif  // NDEBUG
231
232 // Benchmark tools.
233
234 #define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n);
235
236 map<string, void (*)(int)> g_benchlist;  // the benchmarks to run
237
238 class BenchmarkRegisterer {
239  public:
240   BenchmarkRegisterer(const char* name, void (*function)(int iters)) {
241     EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second);
242   }
243 };
244
245 static inline void RunSpecifiedBenchmarks() {
246   if (!FLAGS_run_benchmark) {
247     return;
248   }
249
250   int iter_cnt = FLAGS_benchmark_iters;
251   puts("Benchmark\tTime(ns)\tIterations");
252   for (map<string, void (*)(int)>::const_iterator iter = g_benchlist.begin();
253        iter != g_benchlist.end();
254        ++iter) {
255     clock_t start = clock();
256     iter->second(iter_cnt);
257     double elapsed_ns =
258         ((double)clock() - start) / CLOCKS_PER_SEC * 1000*1000*1000;
259     printf("%s\t%8.2lf\t%10d\n",
260            iter->first.c_str(), elapsed_ns / iter_cnt, iter_cnt);
261   }
262   puts("");
263 }
264
265 // ----------------------------------------------------------------------
266 // Golden file functions
267 // ----------------------------------------------------------------------
268
269 class CapturedStream {
270  public:
271   CapturedStream(int fd, const string & filename) :
272     fd_(fd),
273     uncaptured_fd_(-1),
274     filename_(filename) {
275     Capture();
276   }
277
278   ~CapturedStream() {
279     if (uncaptured_fd_ != -1) {
280       CHECK(close(uncaptured_fd_) != -1);
281     }
282   }
283
284   // Start redirecting output to a file
285   void Capture() {
286     // Keep original stream for later
287     CHECK(uncaptured_fd_ == -1) << ", Stream " << fd_ << " already captured!";
288     uncaptured_fd_ = dup(fd_);
289     CHECK(uncaptured_fd_ != -1);
290
291     // Open file to save stream to
292     int cap_fd = open(filename_.c_str(),
293                       O_CREAT | O_TRUNC | O_WRONLY,
294                       S_IRUSR | S_IWUSR);
295     CHECK(cap_fd != -1);
296
297     // Send stdout/stderr to this file
298     fflush(NULL);
299     CHECK(dup2(cap_fd, fd_) != -1);
300     CHECK(close(cap_fd) != -1);
301   }
302
303   // Remove output redirection
304   void StopCapture() {
305     // Restore original stream
306     if (uncaptured_fd_ != -1) {
307       fflush(NULL);
308       CHECK(dup2(uncaptured_fd_, fd_) != -1);
309     }
310   }
311
312   const string & filename() const { return filename_; }
313
314  private:
315   int fd_;             // file descriptor being captured
316   int uncaptured_fd_;  // where the stream was originally being sent to
317   string filename_;    // file where stream is being saved
318 };
319 static CapturedStream * s_captured_streams[STDERR_FILENO+1];
320 // Redirect a file descriptor to a file.
321 //   fd       - Should be STDOUT_FILENO or STDERR_FILENO
322 //   filename - File where output should be stored
323 static inline void CaptureTestOutput(int fd, const string & filename) {
324   CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO));
325   CHECK(s_captured_streams[fd] == NULL);
326   s_captured_streams[fd] = new CapturedStream(fd, filename);
327 }
328 static inline void CaptureTestStderr() {
329   CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err");
330 }
331 // Return the size (in bytes) of a file
332 static inline size_t GetFileSize(FILE * file) {
333   fseek(file, 0, SEEK_END);
334   return static_cast<size_t>(ftell(file));
335 }
336 // Read the entire content of a file as a string
337 static inline string ReadEntireFile(FILE * file) {
338   const size_t file_size = GetFileSize(file);
339   char * const buffer = new char[file_size];
340
341   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
342   size_t bytes_read = 0;       // # of bytes read so far
343
344   fseek(file, 0, SEEK_SET);
345
346   // Keep reading the file until we cannot read further or the
347   // pre-determined file size is reached.
348   do {
349     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
350     bytes_read += bytes_last_read;
351   } while (bytes_last_read > 0 && bytes_read < file_size);
352
353   const string content = string(buffer, buffer+bytes_read);
354   delete[] buffer;
355
356   return content;
357 }
358 // Get the captured stdout (when fd is STDOUT_FILENO) or stderr (when
359 // fd is STDERR_FILENO) as a string
360 static inline string GetCapturedTestOutput(int fd) {
361   CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO);
362   CapturedStream * const cap = s_captured_streams[fd];
363   CHECK(cap)
364     << ": did you forget CaptureTestStdout() or CaptureTestStderr()?";
365
366   // Make sure everything is flushed.
367   cap->StopCapture();
368
369   // Read the captured file.
370   FILE * const file = fopen(cap->filename().c_str(), "r");
371   const string content = ReadEntireFile(file);
372   fclose(file);
373
374   delete cap;
375   s_captured_streams[fd] = NULL;
376
377   return content;
378 }
379 // Get the captured stderr of a test as a string.
380 static inline string GetCapturedTestStderr() {
381   return GetCapturedTestOutput(STDERR_FILENO);
382 }
383
384 // Check if the string is [IWEF](\d{4}|DATE)
385 static inline bool IsLoggingPrefix(const string& s) {
386   if (s.size() != 5) return false;
387   if (!strchr("IWEF", s[0])) return false;
388   for (int i = 1; i <= 4; ++i) {
389     if (!isdigit(s[i]) && s[i] != "DATE"[i-1]) return false;
390   }
391   return true;
392 }
393
394 // Convert log output into normalized form.
395 //
396 // Example:
397 //     I0102 030405 logging_unittest.cc:345] RAW: vlog -1
398 //  => IDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1
399 static inline string MungeLine(const string& line) {
400   std::istringstream iss(line);
401   string before, logcode_date, time, thread_lineinfo;
402   iss >> logcode_date;
403   while (!IsLoggingPrefix(logcode_date)) {
404     before += " " + logcode_date;
405     if (!(iss >> logcode_date)) {
406       // We cannot find the header of log output.
407       return before;
408     }
409   }
410   if (!before.empty()) before += " ";
411   iss >> time;
412   iss >> thread_lineinfo;
413   CHECK(!thread_lineinfo.empty());
414   if (thread_lineinfo[thread_lineinfo.size() - 1] != ']') {
415     // We found thread ID.
416     string tmp;
417     iss >> tmp;
418     CHECK(!tmp.empty());
419     CHECK_EQ(']', tmp[tmp.size() - 1]);
420     thread_lineinfo = "THREADID " + tmp;
421   }
422   size_t index = thread_lineinfo.find(':');
423   CHECK_NE(string::npos, index);
424   thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]";
425   string rest;
426   std::getline(iss, rest);
427   return (before + logcode_date[0] + "DATE TIME__ " + thread_lineinfo +
428           MungeLine(rest));
429 }
430
431 static inline void StringReplace(string* str,
432                           const string& oldsub,
433                           const string& newsub) {
434   size_t pos = str->find(oldsub);
435   if (pos != string::npos) {
436     str->replace(pos, oldsub.size(), newsub.c_str());
437   }
438 }
439
440 static inline string Munge(const string& filename) {
441   FILE* fp = fopen(filename.c_str(), "rb");
442   CHECK(fp != NULL) << filename << ": couldn't open";
443   char buf[4096];
444   string result;
445   while (fgets(buf, 4095, fp)) {
446     string line = MungeLine(buf);
447     char null_str[256];
448     sprintf(null_str, "%p", static_cast<void*>(NULL));
449     StringReplace(&line, "__NULLP__", null_str);
450     // Remove 0x prefix produced by %p. VC++ doesn't put the prefix.
451     StringReplace(&line, " 0x", " ");
452
453     StringReplace(&line, "__SUCCESS__", StrError(0));
454     StringReplace(&line, "__ENOENT__", StrError(ENOENT));
455     StringReplace(&line, "__EINTR__", StrError(EINTR));
456     StringReplace(&line, "__ENXIO__", StrError(ENXIO));
457     StringReplace(&line, "__ENOEXEC__", StrError(ENOEXEC));
458     result += line + "\n";
459   }
460   fclose(fp);
461   return result;
462 }
463
464 static inline void WriteToFile(const string& body, const string& file) {
465   FILE* fp = fopen(file.c_str(), "wb");
466   fwrite(body.data(), 1, body.size(), fp);
467   fclose(fp);
468 }
469
470 static inline bool MungeAndDiffTestStderr(const string& golden_filename) {
471   CapturedStream* cap = s_captured_streams[STDERR_FILENO];
472   CHECK(cap) << ": did you forget CaptureTestStderr()?";
473
474   cap->StopCapture();
475
476   // Run munge
477   const string captured = Munge(cap->filename());
478   const string golden = Munge(golden_filename);
479   if (captured != golden) {
480     fprintf(stderr,
481             "Test with golden file failed. We'll try to show the diff:\n");
482     string munged_golden = golden_filename + ".munged";
483     WriteToFile(golden, munged_golden);
484     string munged_captured = cap->filename() + ".munged";
485     WriteToFile(captured, munged_captured);
486     string diffcmd("diff -u " + munged_golden + " " + munged_captured);
487     if (system(diffcmd.c_str()) != 0) {
488       fprintf(stderr, "diff command was failed.\n");
489     }
490     unlink(munged_golden.c_str());
491     unlink(munged_captured.c_str());
492     return false;
493   }
494   LOG(INFO) << "Diff was successful";
495   return true;
496 }
497
498 // Save flags used from logging_unittest.cc.
499 #ifndef HAVE_LIB_GFLAGS
500 struct FlagSaver {
501   FlagSaver()
502       : v_(FLAGS_v),
503         stderrthreshold_(FLAGS_stderrthreshold),
504         logtostderr_(FLAGS_logtostderr),
505         alsologtostderr_(FLAGS_alsologtostderr) {}
506   ~FlagSaver() {
507     FLAGS_v = v_;
508     FLAGS_stderrthreshold = stderrthreshold_;
509     FLAGS_logtostderr = logtostderr_;
510     FLAGS_alsologtostderr = alsologtostderr_;
511   }
512   int v_;
513   int stderrthreshold_;
514   bool logtostderr_;
515   bool alsologtostderr_;
516 };
517 #endif
518
519 class Thread {
520  public:
521   virtual ~Thread() {}
522
523   void SetJoinable(bool) {}
524 #if defined(OS_WINDOWS) && !defined(OS_CYGWIN)
525   void Start() {
526     handle_ = CreateThread(NULL,
527                            0,
528                            (LPTHREAD_START_ROUTINE)&Thread::InvokeThread,
529                            (LPVOID)this,
530                            0,
531                            &th_);
532     CHECK(handle_) << "CreateThread";
533   }
534   void Join() {
535     WaitForSingleObject(handle_, INFINITE);
536   }
537 #elif defined(HAVE_PTHREAD)
538   void Start() {
539     pthread_create(&th_, NULL, &Thread::InvokeThread, this);
540   }
541   void Join() {
542     pthread_join(th_, NULL);
543   }
544 #else
545 # error No thread implementation.
546 #endif
547
548  protected:
549   virtual void Run() = 0;
550
551  private:
552   static void* InvokeThread(void* self) {
553     ((Thread*)self)->Run();
554     return NULL;
555   }
556
557 #if defined(OS_WINDOWS) && !defined(OS_CYGWIN)
558   HANDLE handle_;
559   DWORD th_;
560 #else
561   pthread_t th_;
562 #endif
563 };
564
565 static inline void SleepForMilliseconds(int t) {
566 #ifndef OS_WINDOWS
567   usleep(t * 1000);
568 #else
569   Sleep(t);
570 #endif
571 }
572
573 // Add hook for operator new to ensure there are no memory allocation.
574
575 void (*g_new_hook)() = NULL;
576
577 _END_GOOGLE_NAMESPACE_
578
579 void* operator new(size_t size) throw(std::bad_alloc) {
580   if (GOOGLE_NAMESPACE::g_new_hook) {
581     GOOGLE_NAMESPACE::g_new_hook();
582   }
583   return malloc(size);
584 }
585
586 void* operator new[](size_t size) throw(std::bad_alloc) {
587   return ::operator new(size);
588 }
589
590 void operator delete(void* p) throw() {
591   free(p);
592 }
593
594 void operator delete[](void* p) throw() {
595   ::operator delete(p);
596 }