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