Make sure stderr is not buffered.
[platform/upstream/glog.git] / src / logging_unittest.cc
1 // Copyright (c) 2002, 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: Ray Sidney
31
32 #include "config_for_unittests.h"
33 #include "utilities.h"
34
35 #include <fcntl.h>
36 #ifdef HAVE_GLOB_H
37 # include <glob.h>
38 #endif
39 #include <sys/stat.h>
40 #ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 #endif
43
44 #include <iomanip>
45 #include <iostream>
46 #include <memory>
47 #include <queue>
48 #include <sstream>
49 #include <string>
50 #include <vector>
51
52 #include <stdio.h>
53 #include <stdlib.h>
54
55 #include "base/commandlineflags.h"
56 #include "glog/logging.h"
57 #include "glog/raw_logging.h"
58 #include "googletest.h"
59
60 DECLARE_string(log_backtrace_at);  // logging.cc
61
62 #ifdef HAVE_LIB_GFLAGS
63 #include <gflags/gflags.h>
64 #endif
65
66 #ifdef HAVE_LIB_GMOCK
67 #include <gmock/gmock.h>
68 #include "mock-log.h"
69 // Introduce several symbols from gmock.
70 using testing::_;
71 using testing::AnyNumber;
72 using testing::HasSubstr;
73 using testing::AllOf;
74 using testing::StrNe;
75 using testing::StrictMock;
76 using testing::InitGoogleMock;
77 using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog;
78 #endif
79
80 using namespace std;
81 using namespace GOOGLE_NAMESPACE;
82
83 // Some non-advertised functions that we want to test or use.
84 _START_GOOGLE_NAMESPACE_
85 namespace base {
86 namespace internal {
87 bool GetExitOnDFatal();
88 void SetExitOnDFatal(bool value);
89 }  // namespace internal
90 }  // namespace base
91 _END_GOOGLE_NAMESPACE_
92
93 static void TestLogging(bool check_counts);
94 static void TestRawLogging();
95 static void LogWithLevels(int v, int severity, bool err, bool alsoerr);
96 static void TestLoggingLevels();
97 static void TestLogString();
98 static void TestLogSink();
99 static void TestLogToString();
100 static void TestLogSinkWaitTillSent();
101 static void TestCHECK();
102 static void TestDCHECK();
103 static void TestSTREQ();
104 static void TestBasename();
105 static void TestSymlink();
106 static void TestExtension();
107 static void TestWrapper();
108 static void TestErrno();
109 static void TestTruncate();
110
111 static int x = -1;
112 static void BM_Check1(int n) {
113   while (n-- > 0) {
114     CHECK_GE(n, x);
115     CHECK_GE(n, x);
116     CHECK_GE(n, x);
117     CHECK_GE(n, x);
118     CHECK_GE(n, x);
119     CHECK_GE(n, x);
120     CHECK_GE(n, x);
121     CHECK_GE(n, x);
122   }
123 }
124 BENCHMARK(BM_Check1);
125
126 static void CheckFailure(int a, int b, const char* file, int line, const char* msg);
127 static void BM_Check3(int n) {
128   while (n-- > 0) {
129     if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x");
130     if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x");
131     if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x");
132     if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x");
133     if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x");
134     if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x");
135     if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x");
136     if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x");
137   }
138 }
139 BENCHMARK(BM_Check3);
140
141 static void BM_Check2(int n) {
142   if (n == 17) {
143     x = 5;
144   }
145   while (n-- > 0) {
146     CHECK(n >= x);
147     CHECK(n >= x);
148     CHECK(n >= x);
149     CHECK(n >= x);
150     CHECK(n >= x);
151     CHECK(n >= x);
152     CHECK(n >= x);
153     CHECK(n >= x);
154   }
155 }
156 BENCHMARK(BM_Check2);
157
158 static void CheckFailure(int, int, const char* /* file */, int /* line */,
159                          const char* /* msg */) {
160 }
161
162 static void BM_logspeed(int n) {
163   while (n-- > 0) {
164     LOG(INFO) << "test message";
165   }
166 }
167 BENCHMARK(BM_logspeed);
168
169 static void BM_vlog(int n) {
170   while (n-- > 0) {
171     VLOG(1) << "test message";
172   }
173 }
174 BENCHMARK(BM_vlog);
175
176 int main(int argc, char **argv) {
177   FLAGS_colorlogtostderr = false;
178 #ifdef HAVE_LIB_GFLAGS
179   ParseCommandLineFlags(&argc, &argv, true);
180 #endif
181   // Make sure stderr is not buffered as stderr seems to be buffered
182   // on recent windows.
183   setbuf(stderr, NULL);
184
185   // Test some basics before InitGoogleLogging:
186   CaptureTestStderr();
187   LogWithLevels(FLAGS_v, FLAGS_stderrthreshold,
188                 FLAGS_logtostderr, FLAGS_alsologtostderr);
189   LogWithLevels(0, 0, 0, 0);  // simulate "before global c-tors"
190   const string early_stderr = GetCapturedTestStderr();
191
192   InitGoogleLogging(argv[0]);
193
194   RunSpecifiedBenchmarks();
195
196   FLAGS_logtostderr = true;
197
198   InitGoogleTest(&argc, argv);
199 #ifdef HAVE_LIB_GMOCK
200   InitGoogleMock(&argc, argv);
201 #endif
202
203   // so that death tests run before we use threads
204   CHECK_EQ(RUN_ALL_TESTS(), 0);
205
206   CaptureTestStderr();
207
208   // re-emit early_stderr
209   LogMessage("dummy", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << early_stderr;
210
211   TestLogging(true);
212   TestRawLogging();
213   TestLoggingLevels();
214   TestLogString();
215   TestLogSink();
216   TestLogToString();
217   TestLogSinkWaitTillSent();
218   TestCHECK();
219   TestDCHECK();
220   TestSTREQ();
221
222   // TODO: The golden test portion of this test is very flakey.
223   EXPECT_TRUE(
224       MungeAndDiffTestStderr(FLAGS_test_srcdir + "/src/logging_unittest.err"));
225
226   FLAGS_logtostderr = false;
227
228   TestBasename();
229   TestSymlink();
230   TestExtension();
231   TestWrapper();
232   TestErrno();
233   TestTruncate();
234
235   ShutdownGoogleLogging();
236
237   fprintf(stdout, "PASS\n");
238   return 0;
239 }
240
241 void TestLogging(bool check_counts) {
242   int64 base_num_infos   = LogMessage::num_messages(GLOG_INFO);
243   int64 base_num_warning = LogMessage::num_messages(GLOG_WARNING);
244   int64 base_num_errors  = LogMessage::num_messages(GLOG_ERROR);
245
246   LOG(INFO) << string("foo ") << "bar " << 10 << ' ' << 3.4;
247   for ( int i = 0; i < 10; ++i ) {
248     int old_errno = errno;
249     errno = i;
250     PLOG_EVERY_N(ERROR, 2) << "Plog every 2, iteration " << COUNTER;
251     errno = old_errno;
252
253     LOG_EVERY_N(ERROR, 3) << "Log every 3, iteration " << COUNTER << endl;
254     LOG_EVERY_N(ERROR, 4) << "Log every 4, iteration " << COUNTER << endl;
255
256     LOG_IF_EVERY_N(WARNING, true, 5) << "Log if every 5, iteration " << COUNTER;
257     LOG_IF_EVERY_N(WARNING, false, 3)
258         << "Log if every 3, iteration " << COUNTER;
259     LOG_IF_EVERY_N(INFO, true, 1) << "Log if every 1, iteration " << COUNTER;
260     LOG_IF_EVERY_N(ERROR, (i < 3), 2)
261         << "Log if less than 3 every 2, iteration " << COUNTER;
262   }
263   LOG_IF(WARNING, true) << "log_if this";
264   LOG_IF(WARNING, false) << "don't log_if this";
265
266   char s[] = "array";
267   LOG(INFO) << s;
268   const char const_s[] = "const array";
269   LOG(INFO) << const_s;
270   int j = 1000;
271   LOG(ERROR) << string("foo") << ' '<< j << ' ' << setw(10) << j << " "
272              << setw(1) << hex << j;
273
274   LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << "no prefix";
275
276   if (check_counts) {
277     CHECK_EQ(base_num_infos   + 14, LogMessage::num_messages(GLOG_INFO));
278     CHECK_EQ(base_num_warning + 3,  LogMessage::num_messages(GLOG_WARNING));
279     CHECK_EQ(base_num_errors  + 15, LogMessage::num_messages(GLOG_ERROR));
280   }
281 }
282
283 static void NoAllocNewHook() {
284   CHECK(false) << "unexpected new";
285 }
286
287 struct NewHook {
288   NewHook() {
289     g_new_hook = &NoAllocNewHook;
290   }
291   ~NewHook() {
292     g_new_hook = NULL;
293   }
294 };
295
296 TEST(DeathNoAllocNewHook, logging) {
297   // tests that NewHook used below works
298   NewHook new_hook;
299   ASSERT_DEATH({
300     new int;
301   }, "unexpected new");
302 }
303
304 void TestRawLogging() {
305   string* foo = new string("foo ");
306   string huge_str(50000, 'a');
307
308   FlagSaver saver;
309
310   // Check that RAW loggging does not use mallocs.
311   NewHook new_hook;
312
313   RAW_LOG(INFO, "%s%s%d%c%f", foo->c_str(), "bar ", 10, ' ', 3.4);
314   char s[] = "array";
315   RAW_LOG(WARNING, "%s", s);
316   const char const_s[] = "const array";
317   RAW_LOG(INFO, "%s", const_s);
318   void* p = reinterpret_cast<void*>(0x12345678);
319   RAW_LOG(INFO, "ptr %p", p);
320   p = NULL;
321   RAW_LOG(INFO, "ptr %p", p);
322   int j = 1000;
323   RAW_LOG(ERROR, "%s%d%c%010d%s%1x", foo->c_str(), j, ' ', j, " ", j);
324   RAW_VLOG(0, "foo %d", j);
325
326 #ifdef NDEBUG
327   RAW_LOG(INFO, "foo %d", j);  // so that have same stderr to compare
328 #else
329   RAW_DLOG(INFO, "foo %d", j);  // test RAW_DLOG in debug mode
330 #endif
331
332   // test how long messages are chopped:
333   RAW_LOG(WARNING, "Huge string: %s", huge_str.c_str());
334   RAW_VLOG(0, "Huge string: %s", huge_str.c_str());
335
336   FLAGS_v = 0;
337   RAW_LOG(INFO, "log");
338   RAW_VLOG(0, "vlog 0 on");
339   RAW_VLOG(1, "vlog 1 off");
340   RAW_VLOG(2, "vlog 2 off");
341   RAW_VLOG(3, "vlog 3 off");
342   FLAGS_v = 2;
343   RAW_LOG(INFO, "log");
344   RAW_VLOG(1, "vlog 1 on");
345   RAW_VLOG(2, "vlog 2 on");
346   RAW_VLOG(3, "vlog 3 off");
347
348 #ifdef NDEBUG
349   RAW_DCHECK(1 == 2, " RAW_DCHECK's shouldn't be compiled in normal mode");
350 #endif
351
352   RAW_CHECK(1 == 1, "should be ok");
353   RAW_DCHECK(true, "should be ok");
354
355   delete foo;
356 }
357
358 void LogWithLevels(int v, int severity, bool err, bool alsoerr) {
359   RAW_LOG(INFO,
360           "Test: v=%d stderrthreshold=%d logtostderr=%d alsologtostderr=%d",
361           v, severity, err, alsoerr);
362
363   FlagSaver saver;
364
365   FLAGS_v = v;
366   FLAGS_stderrthreshold = severity;
367   FLAGS_logtostderr = err;
368   FLAGS_alsologtostderr = alsoerr;
369
370   RAW_VLOG(-1, "vlog -1");
371   RAW_VLOG(0, "vlog 0");
372   RAW_VLOG(1, "vlog 1");
373   RAW_LOG(INFO, "log info");
374   RAW_LOG(WARNING, "log warning");
375   RAW_LOG(ERROR, "log error");
376
377   VLOG(-1) << "vlog -1";
378   VLOG(0) << "vlog 0";
379   VLOG(1) << "vlog 1";
380   LOG(INFO) << "log info";
381   LOG(WARNING) << "log warning";
382   LOG(ERROR) << "log error";
383
384   VLOG_IF(-1, true) << "vlog_if -1";
385   VLOG_IF(-1, false) << "don't vlog_if -1";
386   VLOG_IF(0, true) << "vlog_if 0";
387   VLOG_IF(0, false) << "don't vlog_if 0";
388   VLOG_IF(1, true) << "vlog_if 1";
389   VLOG_IF(1, false) << "don't vlog_if 1";
390   LOG_IF(INFO, true) << "log_if info";
391   LOG_IF(INFO, false) << "don't log_if info";
392   LOG_IF(WARNING, true) << "log_if warning";
393   LOG_IF(WARNING, false) << "don't log_if warning";
394   LOG_IF(ERROR, true) << "log_if error";
395   LOG_IF(ERROR, false) << "don't log_if error";
396
397   int c;
398   c = 1; VLOG_IF(100, c -= 2) << "vlog_if 100 expr"; EXPECT_EQ(c, -1);
399   c = 1; VLOG_IF(0, c -= 2) << "vlog_if 0 expr"; EXPECT_EQ(c, -1);
400   c = 1; LOG_IF(INFO, c -= 2) << "log_if info expr"; EXPECT_EQ(c, -1);
401   c = 1; LOG_IF(ERROR, c -= 2) << "log_if error expr"; EXPECT_EQ(c, -1);
402   c = 2; VLOG_IF(0, c -= 2) << "don't vlog_if 0 expr"; EXPECT_EQ(c, 0);
403   c = 2; LOG_IF(ERROR, c -= 2) << "don't log_if error expr"; EXPECT_EQ(c, 0);
404
405   c = 3; LOG_IF_EVERY_N(INFO, c -= 4, 1) << "log_if info every 1 expr";
406   EXPECT_EQ(c, -1);
407   c = 3; LOG_IF_EVERY_N(ERROR, c -= 4, 1) << "log_if error every 1 expr";
408   EXPECT_EQ(c, -1);
409   c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if info every 3 expr";
410   EXPECT_EQ(c, 0);
411   c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if error every 3 expr";
412   EXPECT_EQ(c, 0);
413   c = 5; VLOG_IF_EVERY_N(0, c -= 4, 1) << "vlog_if 0 every 1 expr";
414   EXPECT_EQ(c, 1);
415   c = 5; VLOG_IF_EVERY_N(100, c -= 4, 3) << "vlog_if 100 every 3 expr";
416   EXPECT_EQ(c, 1);
417   c = 6; VLOG_IF_EVERY_N(0, c -= 6, 1) << "don't vlog_if 0 every 1 expr";
418   EXPECT_EQ(c, 0);
419   c = 6; VLOG_IF_EVERY_N(100, c -= 6, 3) << "don't vlog_if 100 every 1 expr";
420   EXPECT_EQ(c, 0);
421 }
422
423 void TestLoggingLevels() {
424   LogWithLevels(0, GLOG_INFO, false, false);
425   LogWithLevels(1, GLOG_INFO, false, false);
426   LogWithLevels(-1, GLOG_INFO, false, false);
427   LogWithLevels(0, GLOG_WARNING, false, false);
428   LogWithLevels(0, GLOG_ERROR, false, false);
429   LogWithLevels(0, GLOG_FATAL, false, false);
430   LogWithLevels(0, GLOG_FATAL, true, false);
431   LogWithLevels(0, GLOG_FATAL, false, true);
432   LogWithLevels(1, GLOG_WARNING, false, false);
433   LogWithLevels(1, GLOG_FATAL, false, true);
434 }
435
436 TEST(DeathRawCHECK, logging) {
437   ASSERT_DEATH(RAW_CHECK(false, "failure 1"),
438                "RAW: Check false failed: failure 1");
439   ASSERT_DEBUG_DEATH(RAW_DCHECK(1 == 2, "failure 2"),
440                "RAW: Check 1 == 2 failed: failure 2");
441 }
442
443 void TestLogString() {
444   vector<string> errors;
445   vector<string> *no_errors = NULL;
446
447   LOG_STRING(INFO, &errors) << "LOG_STRING: " << "collected info";
448   LOG_STRING(WARNING, &errors) << "LOG_STRING: " << "collected warning";
449   LOG_STRING(ERROR, &errors) << "LOG_STRING: " << "collected error";
450
451   LOG_STRING(INFO, no_errors) << "LOG_STRING: " << "reported info";
452   LOG_STRING(WARNING, no_errors) << "LOG_STRING: " << "reported warning";
453   LOG_STRING(ERROR, NULL) << "LOG_STRING: " << "reported error";
454
455   for (size_t i = 0; i < errors.size(); ++i) {
456     LOG(INFO) << "Captured by LOG_STRING:  " << errors[i];
457   }
458 }
459
460 void TestLogToString() {
461   string error;
462   string* no_error = NULL;
463
464   LOG_TO_STRING(INFO, &error) << "LOG_TO_STRING: " << "collected info";
465   LOG(INFO) << "Captured by LOG_TO_STRING:  " << error;
466   LOG_TO_STRING(WARNING, &error) << "LOG_TO_STRING: " << "collected warning";
467   LOG(INFO) << "Captured by LOG_TO_STRING:  " << error;
468   LOG_TO_STRING(ERROR, &error) << "LOG_TO_STRING: " << "collected error";
469   LOG(INFO) << "Captured by LOG_TO_STRING:  " << error;
470
471   LOG_TO_STRING(INFO, no_error) << "LOG_TO_STRING: " << "reported info";
472   LOG_TO_STRING(WARNING, no_error) << "LOG_TO_STRING: " << "reported warning";
473   LOG_TO_STRING(ERROR, NULL) << "LOG_TO_STRING: " << "reported error";
474 }
475
476 class TestLogSinkImpl : public LogSink {
477  public:
478   vector<string> errors;
479   virtual void send(LogSeverity severity, const char* /* full_filename */,
480                     const char* base_filename, int line,
481                     const struct tm* tm_time,
482                     const char* message, size_t message_len) {
483     errors.push_back(
484       ToString(severity, base_filename, line, tm_time, message, message_len));
485   }
486 };
487
488 void TestLogSink() {
489   TestLogSinkImpl sink;
490   LogSink *no_sink = NULL;
491
492   LOG_TO_SINK(&sink, INFO) << "LOG_TO_SINK: " << "collected info";
493   LOG_TO_SINK(&sink, WARNING) << "LOG_TO_SINK: " << "collected warning";
494   LOG_TO_SINK(&sink, ERROR) << "LOG_TO_SINK: " << "collected error";
495
496   LOG_TO_SINK(no_sink, INFO) << "LOG_TO_SINK: " << "reported info";
497   LOG_TO_SINK(no_sink, WARNING) << "LOG_TO_SINK: " << "reported warning";
498   LOG_TO_SINK(NULL, ERROR) << "LOG_TO_SINK: " << "reported error";
499
500   LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, INFO)
501       << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected info";
502   LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, WARNING)
503       << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected warning";
504   LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, ERROR)
505       << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected error";
506
507   LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, INFO)
508       << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed info";
509   LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, WARNING)
510       << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed warning";
511   LOG_TO_SINK_BUT_NOT_TO_LOGFILE(NULL, ERROR)
512       << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed error";
513
514   LOG(INFO) << "Captured by LOG_TO_SINK:";
515   for (size_t i = 0; i < sink.errors.size(); ++i) {
516     LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream()
517       << sink.errors[i];
518   }
519 }
520
521 // For testing using CHECK*() on anonymous enums.
522 enum {
523   CASE_A,
524   CASE_B
525 };
526
527 void TestCHECK() {
528   // Tests using CHECK*() on int values.
529   CHECK(1 == 1);
530   CHECK_EQ(1, 1);
531   CHECK_NE(1, 2);
532   CHECK_GE(1, 1);
533   CHECK_GE(2, 1);
534   CHECK_LE(1, 1);
535   CHECK_LE(1, 2);
536   CHECK_GT(2, 1);
537   CHECK_LT(1, 2);
538
539   // Tests using CHECK*() on anonymous enums.
540   // Apple's GCC doesn't like this.
541 #if !defined(OS_MACOSX)
542   CHECK_EQ(CASE_A, CASE_A);
543   CHECK_NE(CASE_A, CASE_B);
544   CHECK_GE(CASE_A, CASE_A);
545   CHECK_GE(CASE_B, CASE_A);
546   CHECK_LE(CASE_A, CASE_A);
547   CHECK_LE(CASE_A, CASE_B);
548   CHECK_GT(CASE_B, CASE_A);
549   CHECK_LT(CASE_A, CASE_B);
550 #endif
551 }
552
553 void TestDCHECK() {
554 #ifdef NDEBUG
555   DCHECK( 1 == 2 ) << " DCHECK's shouldn't be compiled in normal mode";
556 #endif
557   DCHECK( 1 == 1 );
558   DCHECK_EQ(1, 1);
559   DCHECK_NE(1, 2);
560   DCHECK_GE(1, 1);
561   DCHECK_GE(2, 1);
562   DCHECK_LE(1, 1);
563   DCHECK_LE(1, 2);
564   DCHECK_GT(2, 1);
565   DCHECK_LT(1, 2);
566
567   auto_ptr<int64> sptr(new int64);
568   int64* ptr = DCHECK_NOTNULL(sptr.get());
569   CHECK_EQ(ptr, sptr.get());
570 }
571
572 void TestSTREQ() {
573   CHECK_STREQ("this", "this");
574   CHECK_STREQ(NULL, NULL);
575   CHECK_STRCASEEQ("this", "tHiS");
576   CHECK_STRCASEEQ(NULL, NULL);
577   CHECK_STRNE("this", "tHiS");
578   CHECK_STRNE("this", NULL);
579   CHECK_STRCASENE("this", "that");
580   CHECK_STRCASENE(NULL, "that");
581   CHECK_STREQ((string("a")+"b").c_str(), "ab");
582   CHECK_STREQ(string("test").c_str(),
583               (string("te") + string("st")).c_str());
584 }
585
586 TEST(DeathSTREQ, logging) {
587   ASSERT_DEATH(CHECK_STREQ(NULL, "this"), "");
588   ASSERT_DEATH(CHECK_STREQ("this", "siht"), "");
589   ASSERT_DEATH(CHECK_STRCASEEQ(NULL, "siht"), "");
590   ASSERT_DEATH(CHECK_STRCASEEQ("this", "siht"), "");
591   ASSERT_DEATH(CHECK_STRNE(NULL, NULL), "");
592   ASSERT_DEATH(CHECK_STRNE("this", "this"), "");
593   ASSERT_DEATH(CHECK_STREQ((string("a")+"b").c_str(), "abc"), "");
594 }
595
596 TEST(CheckNOTNULL, Simple) {
597   int64 t;
598   void *ptr = static_cast<void *>(&t);
599   void *ref = CHECK_NOTNULL(ptr);
600   EXPECT_EQ(ptr, ref);
601   CHECK_NOTNULL(reinterpret_cast<char *>(ptr));
602   CHECK_NOTNULL(reinterpret_cast<unsigned char *>(ptr));
603   CHECK_NOTNULL(reinterpret_cast<int *>(ptr));
604   CHECK_NOTNULL(reinterpret_cast<int64 *>(ptr));
605 }
606
607 TEST(DeathCheckNN, Simple) {
608   ASSERT_DEATH(CHECK_NOTNULL(static_cast<void *>(NULL)), "");
609 }
610
611 // Get list of file names that match pattern
612 static void GetFiles(const string& pattern, vector<string>* files) {
613   files->clear();
614 #if defined(HAVE_GLOB_H)
615   glob_t g;
616   const int r = glob(pattern.c_str(), 0, NULL, &g);
617   CHECK((r == 0) || (r == GLOB_NOMATCH)) << ": error matching " << pattern;
618   for (size_t i = 0; i < g.gl_pathc; i++) {
619     files->push_back(string(g.gl_pathv[i]));
620   }
621   globfree(&g);
622 #elif defined(OS_WINDOWS)
623   WIN32_FIND_DATAA data;
624   HANDLE handle = FindFirstFileA(pattern.c_str(), &data);
625   size_t index = pattern.rfind('\\');
626   if (index == string::npos) {
627     LOG(FATAL) << "No directory separator.";
628   }
629   const string dirname = pattern.substr(0, index + 1);
630   if (FAILED(handle)) {
631     // Finding no files is OK.
632     return;
633   }
634   do {
635     files->push_back(dirname + data.cFileName);
636   } while (FindNextFileA(handle, &data));
637   LOG_SYSRESULT(FindClose(handle));
638 #else
639 # error There is no way to do glob.
640 #endif
641 }
642
643 // Delete files patching pattern
644 static void DeleteFiles(const string& pattern) {
645   vector<string> files;
646   GetFiles(pattern, &files);
647   for (size_t i = 0; i < files.size(); i++) {
648     CHECK(unlink(files[i].c_str()) == 0) << ": " << strerror(errno);
649   }
650 }
651
652 static void CheckFile(const string& name, const string& expected_string) {
653   vector<string> files;
654   GetFiles(name + "*", &files);
655   CHECK_EQ(files.size(), 1UL);
656
657   FILE* file = fopen(files[0].c_str(), "r");
658   CHECK(file != NULL) << ": could not open " << files[0];
659   char buf[1000];
660   while (fgets(buf, sizeof(buf), file) != NULL) {
661     if (strstr(buf, expected_string.c_str()) != NULL) {
662       fclose(file);
663       return;
664     }
665   }
666   fclose(file);
667   LOG(FATAL) << "Did not find " << expected_string << " in " << files[0];
668 }
669
670 static void TestBasename() {
671   fprintf(stderr, "==== Test setting log file basename\n");
672   const string dest = FLAGS_test_tmpdir + "/logging_test_basename";
673   DeleteFiles(dest + "*");
674
675   SetLogDestination(GLOG_INFO, dest.c_str());
676   LOG(INFO) << "message to new base";
677   FlushLogFiles(GLOG_INFO);
678
679   CheckFile(dest, "message to new base");
680
681   // Release file handle for the destination file to unlock the file in Windows.
682   LogToStderr();
683   DeleteFiles(dest + "*");
684 }
685
686 static void TestSymlink() {
687 #ifndef OS_WINDOWS
688   fprintf(stderr, "==== Test setting log file symlink\n");
689   string dest = FLAGS_test_tmpdir + "/logging_test_symlink";
690   string sym = FLAGS_test_tmpdir + "/symlinkbase";
691   DeleteFiles(dest + "*");
692   DeleteFiles(sym + "*");
693
694   SetLogSymlink(GLOG_INFO, "symlinkbase");
695   SetLogDestination(GLOG_INFO, dest.c_str());
696   LOG(INFO) << "message to new symlink";
697   FlushLogFiles(GLOG_INFO);
698   CheckFile(sym, "message to new symlink");
699
700   DeleteFiles(dest + "*");
701   DeleteFiles(sym + "*");
702 #endif
703 }
704
705 static void TestExtension() {
706   fprintf(stderr, "==== Test setting log file extension\n");
707   string dest = FLAGS_test_tmpdir + "/logging_test_extension";
708   DeleteFiles(dest + "*");
709
710   SetLogDestination(GLOG_INFO, dest.c_str());
711   SetLogFilenameExtension("specialextension");
712   LOG(INFO) << "message to new extension";
713   FlushLogFiles(GLOG_INFO);
714   CheckFile(dest, "message to new extension");
715
716   // Check that file name ends with extension
717   vector<string> filenames;
718   GetFiles(dest + "*", &filenames);
719   CHECK_EQ(filenames.size(), 1UL);
720   CHECK(strstr(filenames[0].c_str(), "specialextension") != NULL);
721
722   // Release file handle for the destination file to unlock the file in Windows.
723   LogToStderr();
724   DeleteFiles(dest + "*");
725 }
726
727 struct MyLogger : public base::Logger {
728   string data;
729
730   virtual void Write(bool /* should_flush */,
731                      time_t /* timestamp */,
732                      const char* message,
733                      int length) {
734     data.append(message, length);
735   }
736
737   virtual void Flush() { }
738
739   virtual uint32 LogSize() { return data.length(); }
740 };
741
742 static void TestWrapper() {
743   fprintf(stderr, "==== Test log wrapper\n");
744
745   MyLogger my_logger;
746   base::Logger* old_logger = base::GetLogger(GLOG_INFO);
747   base::SetLogger(GLOG_INFO, &my_logger);
748   LOG(INFO) << "Send to wrapped logger";
749   FlushLogFiles(GLOG_INFO);
750   base::SetLogger(GLOG_INFO, old_logger);
751
752   CHECK(strstr(my_logger.data.c_str(), "Send to wrapped logger") != NULL);
753 }
754
755 static void TestErrno() {
756   fprintf(stderr, "==== Test errno preservation\n");
757
758   errno = ENOENT;
759   TestLogging(false);
760   CHECK_EQ(errno, ENOENT);
761 }
762
763 static void TestOneTruncate(const char *path, int64 limit, int64 keep,
764                             int64 dsize, int64 ksize, int64 expect) {
765   int fd;
766   CHECK_ERR(fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600));
767
768   const char *discardstr = "DISCARDME!", *keepstr = "KEEPME!";
769
770   // Fill the file with the requested data; first discard data, then kept data
771   int64 written = 0;
772   while (written < dsize) {
773     int bytes = min<int64>(dsize - written, strlen(discardstr));
774     CHECK_ERR(write(fd, discardstr, bytes));
775     written += bytes;
776   }
777   written = 0;
778   while (written < ksize) {
779     int bytes = min<int64>(ksize - written, strlen(keepstr));
780     CHECK_ERR(write(fd, keepstr, bytes));
781     written += bytes;
782   }
783
784   TruncateLogFile(path, limit, keep);
785
786   // File should now be shorter
787   struct stat statbuf;
788   CHECK_ERR(fstat(fd, &statbuf));
789   CHECK_EQ(statbuf.st_size, expect);
790   CHECK_ERR(lseek(fd, 0, SEEK_SET));
791
792   // File should contain the suffix of the original file
793   const size_t buf_size = statbuf.st_size + 1;
794   char* buf = new char[buf_size];
795   memset(buf, 0, buf_size);
796   CHECK_ERR(read(fd, buf, buf_size));
797
798   const char *p = buf;
799   int64 checked = 0;
800   while (checked < expect) {
801     int bytes = min<int64>(expect - checked, strlen(keepstr));
802     CHECK(!memcmp(p, keepstr, bytes));
803     checked += bytes;
804   }
805   close(fd);
806   delete[] buf;
807 }
808
809 static void TestTruncate() {
810 #ifdef HAVE_UNISTD_H
811   fprintf(stderr, "==== Test log truncation\n");
812   string path = FLAGS_test_tmpdir + "/truncatefile";
813
814   // Test on a small file
815   TestOneTruncate(path.c_str(), 10, 10, 10, 10, 10);
816
817   // And a big file (multiple blocks to copy)
818   TestOneTruncate(path.c_str(), 2<<20, 4<<10, 3<<20, 4<<10, 4<<10);
819
820   // Check edge-case limits
821   TestOneTruncate(path.c_str(), 10, 20, 0, 20, 20);
822   TestOneTruncate(path.c_str(), 10, 0, 0, 0, 0);
823   TestOneTruncate(path.c_str(), 10, 50, 0, 10, 10);
824   TestOneTruncate(path.c_str(), 50, 100, 0, 30, 30);
825
826   // MacOSX 10.4 doesn't fail in this case.
827   // Windows doesn't have symlink.
828   // Let's just ignore this test for these cases.
829 #if !defined(OS_MACOSX) && !defined(OS_WINDOWS)
830   // Through a symlink should fail to truncate
831   string linkname = path + ".link";
832   unlink(linkname.c_str());
833   CHECK_ERR(symlink(path.c_str(), linkname.c_str()));
834   TestOneTruncate(linkname.c_str(), 10, 10, 0, 30, 30);
835 #endif
836
837   // The /proc/self path makes sense only for linux.
838 #if defined(OS_LINUX)
839   // Through an open fd symlink should work
840   int fd;
841   CHECK_ERR(fd = open(path.c_str(), O_APPEND | O_WRONLY));
842   char fdpath[64];
843   snprintf(fdpath, sizeof(fdpath), "/proc/self/fd/%d", fd);
844   TestOneTruncate(fdpath, 10, 10, 10, 10, 10);
845 #endif
846
847 #endif
848 }
849
850 _START_GOOGLE_NAMESPACE_
851 namespace glog_internal_namespace_ {
852 extern  // in logging.cc
853 bool SafeFNMatch_(const char* pattern, size_t patt_len,
854                   const char* str, size_t str_len);
855 } // namespace glog_internal_namespace_
856 using glog_internal_namespace_::SafeFNMatch_;
857 _END_GOOGLE_NAMESPACE_
858
859 static bool WrapSafeFNMatch(string pattern, string str) {
860   pattern += "abc";
861   str += "defgh";
862   return SafeFNMatch_(pattern.data(), pattern.size() - 3,
863                       str.data(), str.size() - 5);
864 }
865
866 TEST(SafeFNMatch, logging) {
867   CHECK(WrapSafeFNMatch("foo", "foo"));
868   CHECK(!WrapSafeFNMatch("foo", "bar"));
869   CHECK(!WrapSafeFNMatch("foo", "fo"));
870   CHECK(!WrapSafeFNMatch("foo", "foo2"));
871   CHECK(WrapSafeFNMatch("bar/foo.ext", "bar/foo.ext"));
872   CHECK(WrapSafeFNMatch("*ba*r/fo*o.ext*", "bar/foo.ext"));
873   CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/baz.ext"));
874   CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/foo"));
875   CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/foo.ext.zip"));
876   CHECK(WrapSafeFNMatch("ba?/*.ext", "bar/foo.ext"));
877   CHECK(WrapSafeFNMatch("ba?/*.ext", "baZ/FOO.ext"));
878   CHECK(!WrapSafeFNMatch("ba?/*.ext", "barr/foo.ext"));
879   CHECK(!WrapSafeFNMatch("ba?/*.ext", "bar/foo.ext2"));
880   CHECK(WrapSafeFNMatch("ba?/*", "bar/foo.ext2"));
881   CHECK(WrapSafeFNMatch("ba?/*", "bar/"));
882   CHECK(!WrapSafeFNMatch("ba?/?", "bar/"));
883   CHECK(!WrapSafeFNMatch("ba?/*", "bar"));
884 }
885
886 // TestWaitingLogSink will save messages here
887 // No lock: Accessed only by TestLogSinkWriter thread
888 // and after its demise by its creator.
889 static vector<string> global_messages;
890
891 // helper for TestWaitingLogSink below.
892 // Thread that does the logic of TestWaitingLogSink
893 // It's free to use LOG() itself.
894 class TestLogSinkWriter : public Thread {
895  public:
896
897   TestLogSinkWriter() : should_exit_(false) {
898     SetJoinable(true);
899     Start();
900   }
901
902   // Just buffer it (can't use LOG() here).
903   void Buffer(const string& message) {
904     mutex_.Lock();
905     RAW_LOG(INFO, "Buffering");
906     messages_.push(message);
907     mutex_.Unlock();
908     RAW_LOG(INFO, "Buffered");
909   }
910
911   // Wait for the buffer to clear (can't use LOG() here).
912   void Wait() {
913     RAW_LOG(INFO, "Waiting");
914     mutex_.Lock();
915     while (!NoWork()) {
916       mutex_.Unlock();
917       SleepForMilliseconds(1);
918       mutex_.Lock();
919     }
920     RAW_LOG(INFO, "Waited");
921     mutex_.Unlock();
922   }
923
924   // Trigger thread exit.
925   void Stop() {
926     MutexLock l(&mutex_);
927     should_exit_ = true;
928   }
929
930  private:
931
932   // helpers ---------------
933
934   // For creating a "Condition".
935   bool NoWork() { return messages_.empty(); }
936   bool HaveWork() { return !messages_.empty() || should_exit_; }
937
938   // Thread body; CAN use LOG() here!
939   virtual void Run() {
940     while (1) {
941       mutex_.Lock();
942       while (!HaveWork()) {
943         mutex_.Unlock();
944         SleepForMilliseconds(1);
945         mutex_.Lock();
946       }
947       if (should_exit_ && messages_.empty()) {
948         mutex_.Unlock();
949         break;
950       }
951       // Give the main thread time to log its message,
952       // so that we get a reliable log capture to compare to golden file.
953       // Same for the other sleep below.
954       SleepForMilliseconds(20);
955       RAW_LOG(INFO, "Sink got a messages");  // only RAW_LOG under mutex_ here
956       string message = messages_.front();
957       messages_.pop();
958       // Normally this would be some more real/involved logging logic
959       // where LOG() usage can't be eliminated,
960       // e.g. pushing the message over with an RPC:
961       int messages_left = messages_.size();
962       mutex_.Unlock();
963       SleepForMilliseconds(20);
964       // May not use LOG while holding mutex_, because Buffer()
965       // acquires mutex_, and Buffer is called from LOG(),
966       // which has its own internal mutex:
967       // LOG()->LogToSinks()->TestWaitingLogSink::send()->Buffer()
968       LOG(INFO) << "Sink is sending out a message: " << message;
969       LOG(INFO) << "Have " << messages_left << " left";
970       global_messages.push_back(message);
971     }
972   }
973
974   // data ---------------
975
976   Mutex mutex_;
977   bool should_exit_;
978   queue<string> messages_;  // messages to be logged
979 };
980
981 // A log sink that exercises WaitTillSent:
982 // it pushes data to a buffer and wakes up another thread to do the logging
983 // (that other thread can than use LOG() itself),
984 class TestWaitingLogSink : public LogSink {
985  public:
986
987   TestWaitingLogSink() {
988     tid_ = pthread_self();  // for thread-specific behavior
989     AddLogSink(this);
990   }
991   ~TestWaitingLogSink() {
992     RemoveLogSink(this);
993     writer_.Stop();
994     writer_.Join();
995   }
996
997   // (re)define LogSink interface
998
999   virtual void send(LogSeverity severity, const char* /* full_filename */,
1000                     const char* base_filename, int line,
1001                     const struct tm* tm_time,
1002                     const char* message, size_t message_len) {
1003     // Push it to Writer thread if we are the original logging thread.
1004     // Note: Something like ThreadLocalLogSink is a better choice
1005     //       to do thread-specific LogSink logic for real.
1006     if (pthread_equal(tid_, pthread_self())) {
1007       writer_.Buffer(ToString(severity, base_filename, line,
1008                               tm_time, message, message_len));
1009     }
1010   }
1011   virtual void WaitTillSent() {
1012     // Wait for Writer thread if we are the original logging thread.
1013     if (pthread_equal(tid_, pthread_self()))  writer_.Wait();
1014   }
1015
1016  private:
1017
1018   pthread_t tid_;
1019   TestLogSinkWriter writer_;
1020 };
1021
1022 // Check that LogSink::WaitTillSent can be used in the advertised way.
1023 // We also do golden-stderr comparison.
1024 static void TestLogSinkWaitTillSent() {
1025   { TestWaitingLogSink sink;
1026     // Sleeps give the sink threads time to do all their work,
1027     // so that we get a reliable log capture to compare to the golden file.
1028     LOG(INFO) << "Message 1";
1029     SleepForMilliseconds(60);
1030     LOG(ERROR) << "Message 2";
1031     SleepForMilliseconds(60);
1032     LOG(WARNING) << "Message 3";
1033     SleepForMilliseconds(60);
1034   }
1035   for (size_t i = 0; i < global_messages.size(); ++i) {
1036     LOG(INFO) << "Sink capture: " << global_messages[i];
1037   }
1038   CHECK_EQ(global_messages.size(), 3UL);
1039 }
1040
1041 TEST(Strerror, logging) {
1042   int errcode = EINTR;
1043   char *msg = strdup(strerror(errcode));
1044   const size_t buf_size = strlen(msg) + 1;
1045   char *buf = new char[buf_size];
1046   CHECK_EQ(posix_strerror_r(errcode, NULL, 0), -1);
1047   buf[0] = 'A';
1048   CHECK_EQ(posix_strerror_r(errcode, buf, 0), -1);
1049   CHECK_EQ(buf[0], 'A');
1050   CHECK_EQ(posix_strerror_r(errcode, NULL, buf_size), -1);
1051 #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)
1052   // MacOSX or FreeBSD considers this case is an error since there is
1053   // no enough space.
1054   CHECK_EQ(posix_strerror_r(errcode, buf, 1), -1);
1055 #else
1056   CHECK_EQ(posix_strerror_r(errcode, buf, 1), 0);
1057 #endif
1058   CHECK_STREQ(buf, "");
1059   CHECK_EQ(posix_strerror_r(errcode, buf, buf_size), 0);
1060   CHECK_STREQ(buf, msg);
1061   free(msg);
1062   delete[] buf;
1063 }
1064
1065 // Simple routines to look at the sizes of generated code for LOG(FATAL) and
1066 // CHECK(..) via objdump
1067 void MyFatal() {
1068   LOG(FATAL) << "Failed";
1069 }
1070 void MyCheck(bool a, bool b) {
1071   CHECK_EQ(a, b);
1072 }
1073
1074 #ifdef HAVE_LIB_GMOCK
1075
1076 TEST(DVLog, Basic) {
1077   ScopedMockLog log;
1078
1079 #if NDEBUG
1080   // We are expecting that nothing is logged.
1081   EXPECT_CALL(log, Log(_, _, _)).Times(0);
1082 #else
1083   EXPECT_CALL(log, Log(INFO, __FILE__, "debug log"));
1084 #endif
1085
1086   FLAGS_v = 1;
1087   DVLOG(1) << "debug log";
1088 }
1089
1090 TEST(DVLog, V0) {
1091   ScopedMockLog log;
1092
1093   // We are expecting that nothing is logged.
1094   EXPECT_CALL(log, Log(_, _, _)).Times(0);
1095
1096   FLAGS_v = 0;
1097   DVLOG(1) << "debug log";
1098 }
1099
1100 TEST(LogAtLevel, Basic) {
1101   ScopedMockLog log;
1102
1103   // The function version outputs "logging.h" as a file name.
1104   EXPECT_CALL(log, Log(WARNING, StrNe(__FILE__), "function version"));
1105   EXPECT_CALL(log, Log(INFO, __FILE__, "macro version"));
1106
1107   int severity = WARNING;
1108   LogAtLevel(severity, "function version");
1109
1110   severity = INFO;
1111   // We can use the macro version as a C++ stream.
1112   LOG_AT_LEVEL(severity) << "macro" << ' ' << "version";
1113 }
1114
1115 TEST(TestExitOnDFatal, ToBeOrNotToBe) {
1116   // Check the default setting...
1117   EXPECT_TRUE(base::internal::GetExitOnDFatal());
1118
1119   // Turn off...
1120   base::internal::SetExitOnDFatal(false);
1121   EXPECT_FALSE(base::internal::GetExitOnDFatal());
1122
1123   // We don't die.
1124   {
1125     ScopedMockLog log;
1126     //EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
1127     // LOG(DFATAL) has severity FATAL if debugging, but is
1128     // downgraded to ERROR if not debugging.
1129     const LogSeverity severity =
1130 #ifdef NDEBUG
1131         ERROR;
1132 #else
1133         FATAL;
1134 #endif
1135     EXPECT_CALL(log, Log(severity, __FILE__, "This should not be fatal"));
1136     LOG(DFATAL) << "This should not be fatal";
1137   }
1138
1139   // Turn back on...
1140   base::internal::SetExitOnDFatal(true);
1141   EXPECT_TRUE(base::internal::GetExitOnDFatal());
1142
1143 #ifdef GTEST_HAS_DEATH_TEST
1144   // Death comes on little cats' feet.
1145   EXPECT_DEBUG_DEATH({
1146       LOG(DFATAL) << "This should be fatal in debug mode";
1147     }, "This should be fatal in debug mode");
1148 #endif
1149 }
1150
1151 #ifdef HAVE_STACKTRACE
1152
1153 static void BacktraceAtHelper() {
1154   LOG(INFO) << "Not me";
1155
1156 // The vertical spacing of the next 3 lines is significant.
1157   LOG(INFO) << "Backtrace me";
1158 }
1159 static int kBacktraceAtLine = __LINE__ - 2;  // The line of the LOG(INFO) above
1160
1161 TEST(LogBacktraceAt, DoesNotBacktraceWhenDisabled) {
1162   StrictMock<ScopedMockLog> log;
1163
1164   FLAGS_log_backtrace_at = "";
1165
1166   EXPECT_CALL(log, Log(_, _, "Backtrace me"));
1167   EXPECT_CALL(log, Log(_, _, "Not me"));
1168
1169   BacktraceAtHelper();
1170 }
1171
1172 TEST(LogBacktraceAt, DoesBacktraceAtRightLineWhenEnabled) {
1173   StrictMock<ScopedMockLog> log;
1174
1175   char where[100];
1176   snprintf(where, 100, "%s:%d", const_basename(__FILE__), kBacktraceAtLine);
1177   FLAGS_log_backtrace_at = where;
1178
1179   // The LOG at the specified line should include a stacktrace which includes
1180   // the name of the containing function, followed by the log message.
1181   // We use HasSubstr()s instead of ContainsRegex() for environments
1182   // which don't have regexp.
1183   EXPECT_CALL(log, Log(_, _, AllOf(HasSubstr("stacktrace:"),
1184                                    HasSubstr("BacktraceAtHelper"),
1185                                    HasSubstr("main"),
1186                                    HasSubstr("Backtrace me"))));
1187   // Other LOGs should not include a backtrace.
1188   EXPECT_CALL(log, Log(_, _, "Not me"));
1189
1190   BacktraceAtHelper();
1191 }
1192
1193 #endif // HAVE_STACKTRACE
1194
1195 #endif // HAVE_LIB_GMOCK
1196
1197 struct UserDefinedClass {
1198   bool operator==(const UserDefinedClass&) const { return true; }
1199 };
1200
1201 inline ostream& operator<<(ostream& out, const UserDefinedClass&) {
1202   out << "OK";
1203   return out;
1204 }
1205
1206 TEST(UserDefinedClass, logging) {
1207   UserDefinedClass u;
1208   vector<string> buf;
1209   LOG_STRING(INFO, &buf) << u;
1210   CHECK_EQ(1UL, buf.size());
1211   CHECK(buf[0].find("OK") != string::npos);
1212
1213   // We must be able to compile this.
1214   CHECK_EQ(u, u);
1215 }