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