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