1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <tuple>
6
7 #include "base/check_deref.h"
8 #include "base/debug/dump_without_crashing.h"
9 #include "base/features.h"
10 #include "base/functional/bind.h"
11 #include "base/functional/callback.h"
12 #include "base/logging.h"
13 #include "base/strings/string_piece.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/test/gtest_util.h"
16 #include "base/test/scoped_feature_list.h"
17 #include "build/build_config.h"
18 #include "testing/gmock/include/gmock/gmock.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20
21 namespace {
22
23 int g_dump_without_crashing_count = 0;
24
25 class ScopedExpectDumpWithoutCrashing {
26 public:
ScopedExpectDumpWithoutCrashing()27 ScopedExpectDumpWithoutCrashing() {
28 g_dump_without_crashing_count = 0;
29 base::debug::SetDumpWithoutCrashingFunction(&DumpWithoutCrashing);
30 }
31
~ScopedExpectDumpWithoutCrashing()32 ~ScopedExpectDumpWithoutCrashing() {
33 EXPECT_EQ(1, g_dump_without_crashing_count);
34 base::debug::SetDumpWithoutCrashingFunction(nullptr);
35 }
36
37 private:
DumpWithoutCrashing()38 static void DumpWithoutCrashing() { ++g_dump_without_crashing_count; }
39 };
40
41 MATCHER_P2(LogErrorMatches, line, expected_msg, "") {
42 EXPECT_THAT(arg, testing::HasSubstr(
43 base::StringPrintf("check_unittest.cc(%d)] ", line)));
44 if (std::string(expected_msg).find("=~") == 0) {
45 EXPECT_THAT(std::string(arg),
46 testing::ContainsRegex(std::string(expected_msg).substr(2)));
47 } else {
48 EXPECT_THAT(std::string(arg), testing::HasSubstr(expected_msg));
49 }
50 return true;
51 }
52
53 // TODO(pbos): Upstream support for ignoring matchers in gtest when death
54 // testing is not available.
55 // Without this we get a compile failure on iOS because
56 // GTEST_UNSUPPORTED_DEATH_TEST does not compile with a MATCHER as parameter.
57 #if GTEST_HAS_DEATH_TEST
58 #define CHECK_MATCHER(line, msg) LogErrorMatches(line, msg)
59 #else
60 #define CHECK_MATCHER(line, msg) msg
61 #endif
62
63 // Macro which expects a CHECK to fire with a certain message. If msg starts
64 // with "=~", it's interpreted as a regular expression.
65 // Example: EXPECT_CHECK("Check failed: false.", CHECK(false));
66 //
67 // Note: Please use the `CheckDeathTest` fixture when using this check.
68 #if !CHECK_WILL_STREAM()
69 #define EXPECT_CHECK(msg, check_expr) \
70 do { \
71 EXPECT_CHECK_DEATH(check_expr); \
72 } while (0)
73 #else
74 #define EXPECT_CHECK(msg, check_expr) \
75 EXPECT_DEATH_IF_SUPPORTED(check_expr, CHECK_MATCHER(__LINE__, msg))
76 #endif // !CHECK_WILL_STREAM()
77
78 // Macro which expects a DCHECK to fire if DCHECKs are enabled.
79 //
80 // Note: Please use the `CheckDeathTest` fixture when using this check.
81 // TODO(crbug.com/1505315) Port test to iOS if possible.
82 #define EXPECT_DCHECK(msg, check_expr) \
83 do { \
84 if (DCHECK_IS_ON() && \
85 (logging::LOGGING_DCHECK == logging::LOGGING_FATAL || \
86 BUILDFLAG(IS_IOS))) { \
87 EXPECT_DEATH_IF_SUPPORTED(check_expr, CHECK_MATCHER(__LINE__, msg)); \
88 } else if (DCHECK_IS_ON()) { \
89 ScopedExpectDumpWithoutCrashing expect_dump; \
90 check_expr; \
91 } else { \
92 check_expr; \
93 } \
94 } while (0)
95
96 #define EXPECT_LOG_ERROR_WITH_FILENAME(expected_file, expected_line, expr, \
97 msg) \
98 do { \
99 static bool got_log_message = false; \
100 ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \
101 logging::SetLogMessageHandler([](int severity, const char* file, int line, \
102 size_t message_start, \
103 const std::string& str) { \
104 EXPECT_FALSE(got_log_message); \
105 got_log_message = true; \
106 EXPECT_EQ(severity, logging::LOG_ERROR); \
107 EXPECT_EQ(str.substr(message_start), (msg)); \
108 if (base::StringPiece(expected_file) != "") { \
109 EXPECT_STREQ(expected_file, file); \
110 } \
111 if (expected_line != -1) { \
112 EXPECT_EQ(expected_line, line); \
113 } \
114 return true; \
115 }); \
116 expr; \
117 EXPECT_TRUE(got_log_message); \
118 logging::SetLogMessageHandler(nullptr); \
119 } while (0)
120
121 #define EXPECT_LOG_ERROR(expected_line, expr, msg) \
122 EXPECT_LOG_ERROR_WITH_FILENAME(__FILE__, expected_line, expr, msg)
123
124 #define EXPECT_NO_LOG(expr) \
125 do { \
126 ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \
127 logging::SetLogMessageHandler([](int severity, const char* file, int line, \
128 size_t message_start, \
129 const std::string& str) { \
130 EXPECT_TRUE(false) << "Unexpected log: " << str; \
131 return true; \
132 }); \
133 expr; \
134 logging::SetLogMessageHandler(nullptr); \
135 } while (0)
136
137 // TODO(crbug.com/1505315) Port test to iOS if possible.
138 #if DCHECK_IS_ON() || BUILDFLAG(IS_IOS)
139 #define EXPECT_DUMP_WILL_BE_CHECK EXPECT_DCHECK
140 #else
141 #define EXPECT_DUMP_WILL_BE_CHECK(expected_string, statement) \
142 do { \
143 ScopedExpectDumpWithoutCrashing expect_dump; \
144 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(), \
145 base::Location::Current().line_number(), \
146 statement, expected_string "\n"); \
147 } while (0)
148 #endif // DCHECK_IS_ON()
149
TEST(CheckDeathTest,Basics)150 TEST(CheckDeathTest, Basics) {
151 EXPECT_CHECK("Check failed: false. ", CHECK(false));
152
153 EXPECT_CHECK("Check failed: false. foo", CHECK(false) << "foo");
154
155 double a = 2, b = 1;
156 EXPECT_CHECK("Check failed: a < b (2.000000 vs. 1.000000)", CHECK_LT(a, b));
157
158 EXPECT_CHECK("Check failed: a < b (2.000000 vs. 1.000000)custom message",
159 CHECK_LT(a, b) << "custom message");
160 }
161
TEST(CheckDeathTest,PCheck)162 TEST(CheckDeathTest, PCheck) {
163 const char file[] = "/nonexistentfile123";
164 std::ignore = fopen(file, "r");
165 std::string err =
166 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
167
168 EXPECT_CHECK(
169 "Check failed: fopen(file, \"r\") != nullptr."
170 " : " +
171 err,
172 PCHECK(fopen(file, "r") != nullptr));
173
174 EXPECT_CHECK(
175 "Check failed: fopen(file, \"r\") != nullptr."
176 " foo: " +
177 err,
178 PCHECK(fopen(file, "r") != nullptr) << "foo");
179
180 EXPECT_DCHECK(
181 "Check failed: fopen(file, \"r\") != nullptr."
182 " : " +
183 err,
184 DPCHECK(fopen(file, "r") != nullptr));
185
186 EXPECT_DCHECK(
187 "Check failed: fopen(file, \"r\") != nullptr."
188 " foo: " +
189 err,
190 DPCHECK(fopen(file, "r") != nullptr) << "foo");
191 }
192
TEST(CheckDeathTest,CheckOp)193 TEST(CheckDeathTest, CheckOp) {
194 int a = 1, b = 2;
195 // clang-format off
196 EXPECT_CHECK("Check failed: a == b (1 vs. 2)", CHECK_EQ(a, b));
197 EXPECT_CHECK("Check failed: a != a (1 vs. 1)", CHECK_NE(a, a));
198 EXPECT_CHECK("Check failed: b <= a (2 vs. 1)", CHECK_LE(b, a));
199 EXPECT_CHECK("Check failed: b < a (2 vs. 1)", CHECK_LT(b, a));
200 EXPECT_CHECK("Check failed: a >= b (1 vs. 2)", CHECK_GE(a, b));
201 EXPECT_CHECK("Check failed: a > b (1 vs. 2)", CHECK_GT(a, b));
202
203 EXPECT_DCHECK("Check failed: a == b (1 vs. 2)", DCHECK_EQ(a, b));
204 EXPECT_DCHECK("Check failed: a != a (1 vs. 1)", DCHECK_NE(a, a));
205 EXPECT_DCHECK("Check failed: b <= a (2 vs. 1)", DCHECK_LE(b, a));
206 EXPECT_DCHECK("Check failed: b < a (2 vs. 1)", DCHECK_LT(b, a));
207 EXPECT_DCHECK("Check failed: a >= b (1 vs. 2)", DCHECK_GE(a, b));
208 EXPECT_DCHECK("Check failed: a > b (1 vs. 2)", DCHECK_GT(a, b));
209 // clang-format on
210
211 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a == b (1 vs. 2)",
212 DUMP_WILL_BE_CHECK_EQ(a, b));
213 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a != a (1 vs. 1)",
214 DUMP_WILL_BE_CHECK_NE(a, a));
215 EXPECT_DUMP_WILL_BE_CHECK("Check failed: b <= a (2 vs. 1)",
216 DUMP_WILL_BE_CHECK_LE(b, a));
217 EXPECT_DUMP_WILL_BE_CHECK("Check failed: b < a (2 vs. 1)",
218 DUMP_WILL_BE_CHECK_LT(b, a));
219 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a >= b (1 vs. 2)",
220 DUMP_WILL_BE_CHECK_GE(a, b));
221 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a > b (1 vs. 2)",
222 DUMP_WILL_BE_CHECK_GT(a, b));
223 }
224
TEST(CheckTest,CheckStreamsAreLazy)225 TEST(CheckTest, CheckStreamsAreLazy) {
226 int called_count = 0;
227 int not_called_count = 0;
228
229 auto Called = [&]() {
230 ++called_count;
231 // This returns a non-constant because returning 42 here directly triggers a
232 // dead-code warning when streaming to *CHECK(Called()) << NotCalled();
233 return called_count >= 0;
234 };
235 auto NotCalled = [&]() {
236 ++not_called_count;
237 return 42;
238 };
239
240 CHECK(Called()) << NotCalled();
241 CHECK_EQ(Called(), Called()) << NotCalled();
242 PCHECK(Called()) << NotCalled();
243
244 DCHECK(Called()) << NotCalled();
245 DCHECK_EQ(Called(), Called()) << NotCalled();
246 DPCHECK(Called()) << NotCalled();
247
248 EXPECT_EQ(not_called_count, 0);
249 #if DCHECK_IS_ON()
250 EXPECT_EQ(called_count, 8);
251 #else
252 EXPECT_EQ(called_count, 4);
253 #endif
254 }
255
DcheckEmptyFunction1()256 void DcheckEmptyFunction1() {
257 // Provide a body so that Release builds do not cause the compiler to
258 // optimize DcheckEmptyFunction1 and DcheckEmptyFunction2 as a single
259 // function, which breaks the Dcheck tests below.
260 LOG(INFO) << "DcheckEmptyFunction1";
261 }
DcheckEmptyFunction2()262 void DcheckEmptyFunction2() {}
263
264 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
265 class ScopedDcheckSeverity {
266 public:
ScopedDcheckSeverity(logging::LogSeverity new_severity)267 explicit ScopedDcheckSeverity(logging::LogSeverity new_severity)
268 : old_severity_(logging::LOGGING_DCHECK) {
269 logging::LOGGING_DCHECK = new_severity;
270 }
271
~ScopedDcheckSeverity()272 ~ScopedDcheckSeverity() { logging::LOGGING_DCHECK = old_severity_; }
273
274 private:
275 logging::LogSeverity old_severity_;
276 };
277 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
278
279 // https://crbug.com/709067 tracks test flakiness on iOS.
280 #if BUILDFLAG(IS_IOS)
281 #define MAYBE_Dcheck DISABLED_Dcheck
282 #else
283 #define MAYBE_Dcheck Dcheck
284 #endif
TEST(CheckDeathTest,MAYBE_Dcheck)285 TEST(CheckDeathTest, MAYBE_Dcheck) {
286 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
287 // DCHECKs are enabled, and LOGGING_DCHECK is mutable, but defaults to
288 // non-fatal. Set it to LOGGING_FATAL to get the expected behavior from the
289 // rest of this test.
290 ScopedDcheckSeverity dcheck_severity(logging::LOGGING_FATAL);
291 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
292
293 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
294 // Release build.
295 EXPECT_FALSE(DCHECK_IS_ON());
296 EXPECT_FALSE(DLOG_IS_ON(DCHECK));
297 #elif defined(NDEBUG) && defined(DCHECK_ALWAYS_ON)
298 // Release build with real DCHECKS.
299 EXPECT_TRUE(DCHECK_IS_ON());
300 EXPECT_TRUE(DLOG_IS_ON(DCHECK));
301 #else
302 // Debug build.
303 EXPECT_TRUE(DCHECK_IS_ON());
304 EXPECT_TRUE(DLOG_IS_ON(DCHECK));
305 #endif
306
307 EXPECT_DCHECK("Check failed: false. ", DCHECK(false));
308
309 // Produce a consistent error code so that both the main instance of this test
310 // and the EXPECT_DEATH invocation below get the same error codes for DPCHECK.
311 const char file[] = "/nonexistentfile123";
312 std::ignore = fopen(file, "r");
313 std::string err =
314 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
315 EXPECT_DCHECK("Check failed: false. : " + err, DPCHECK(false));
316 EXPECT_DCHECK("Check failed: 0 == 1 (0 vs. 1)", DCHECK_EQ(0, 1));
317
318 // Test DCHECK on std::nullptr_t
319 const void* p_null = nullptr;
320 const void* p_not_null = &p_null;
321 DCHECK_EQ(p_null, nullptr);
322 DCHECK_EQ(nullptr, p_null);
323 DCHECK_NE(p_not_null, nullptr);
324 DCHECK_NE(nullptr, p_not_null);
325
326 // Test DCHECK on a scoped enum.
327 enum class Animal { DOG, CAT };
328 DCHECK_EQ(Animal::DOG, Animal::DOG);
329 EXPECT_DCHECK("Check failed: Animal::DOG == Animal::CAT (0 vs. 1)",
330 DCHECK_EQ(Animal::DOG, Animal::CAT));
331
332 // Test DCHECK on functions and function pointers.
333 struct MemberFunctions {
334 void MemberFunction1() {
335 // See the comment in DcheckEmptyFunction1().
336 LOG(INFO) << "Do not merge with MemberFunction2.";
337 }
338 void MemberFunction2() {}
339 };
340 void (MemberFunctions::*mp1)() = &MemberFunctions::MemberFunction1;
341 void (MemberFunctions::*mp2)() = &MemberFunctions::MemberFunction2;
342 void (*fp1)() = DcheckEmptyFunction1;
343 void (*fp2)() = DcheckEmptyFunction2;
344 void (*fp3)() = DcheckEmptyFunction1;
345 DCHECK_EQ(fp1, fp3);
346 DCHECK_EQ(mp1, &MemberFunctions::MemberFunction1);
347 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction2);
348 EXPECT_DCHECK("=~Check failed: fp1 == fp2 \\(\\w+ vs. \\w+\\)",
349 DCHECK_EQ(fp1, fp2));
350 EXPECT_DCHECK(
351 "Check failed: mp2 == &MemberFunctions::MemberFunction1 (1 vs. 1)",
352 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction1));
353 }
354
TEST(CheckTest,DcheckReleaseBehavior)355 TEST(CheckTest, DcheckReleaseBehavior) {
356 int var1 = 1;
357 int var2 = 2;
358 int var3 = 3;
359 int var4 = 4;
360
361 // No warnings about unused variables even though no check fires and DCHECK
362 // may or may not be enabled.
363 DCHECK(var1) << var2;
364 DPCHECK(var1) << var3;
365 DCHECK_EQ(var1, 1) << var4;
366 }
367
TEST(CheckTest,DCheckEqStatements)368 TEST(CheckTest, DCheckEqStatements) {
369 bool reached = false;
370 if (false)
371 DCHECK_EQ(false, true); // Unreached.
372 else
373 DCHECK_EQ(true, reached = true); // Reached, passed.
374 ASSERT_EQ(DCHECK_IS_ON() ? true : false, reached);
375
376 if (false)
377 DCHECK_EQ(false, true); // Unreached.
378 }
379
TEST(CheckTest,CheckEqStatements)380 TEST(CheckTest, CheckEqStatements) {
381 bool reached = false;
382 if (false)
383 CHECK_EQ(false, true); // Unreached.
384 else
385 CHECK_EQ(true, reached = true); // Reached, passed.
386 ASSERT_TRUE(reached);
387
388 if (false)
389 CHECK_EQ(false, true); // Unreached.
390 }
391
392 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
TEST(CheckDeathTest,ConfigurableDCheck)393 TEST(CheckDeathTest, ConfigurableDCheck) {
394 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
395 "gtest_internal_run_death_test")) {
396 // This specific test relies on LOGGING_DCHECK not starting out as FATAL,
397 // even when run part of death tests (should die only after LOGGING_DCHECK
398 // gets reconfigured to FATAL below).
399 logging::LOGGING_DCHECK = logging::LOGGING_ERROR;
400 } else {
401 // Verify that DCHECKs default to non-fatal in configurable-DCHECK builds.
402 // Note that we require only that DCHECK is non-fatal by default, rather
403 // than requiring that it be exactly INFO, ERROR, etc level.
404 EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
405 }
406 DCHECK(false);
407
408 // Verify that DCHECK* aren't hard-wired to crash on failure.
409 logging::LOGGING_DCHECK = logging::LOG_INFO;
410 DCHECK(false);
411 DCHECK_EQ(1, 2);
412
413 // Verify that DCHECK does crash if LOGGING_DCHECK is set to LOGGING_FATAL.
414 logging::LOGGING_DCHECK = logging::LOGGING_FATAL;
415 EXPECT_CHECK("Check failed: false. ", DCHECK(false));
416 EXPECT_CHECK("Check failed: 1 == 2 (1 vs. 2)", DCHECK_EQ(1, 2));
417 }
418
TEST(CheckTest,ConfigurableDCheckFeature)419 TEST(CheckTest, ConfigurableDCheckFeature) {
420 // Initialize FeatureList with and without DcheckIsFatal, and verify the
421 // value of LOGGING_DCHECK. Note that we don't require that DCHECK take a
422 // specific value when the feature is off, only that it is non-fatal.
423
424 {
425 base::test::ScopedFeatureList feature_list;
426 feature_list.InitFromCommandLine("DcheckIsFatal", "");
427 EXPECT_EQ(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
428 }
429
430 {
431 base::test::ScopedFeatureList feature_list;
432 feature_list.InitFromCommandLine("", "DcheckIsFatal");
433 EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
434 }
435
436 // The default case is last, so we leave LOGGING_DCHECK in the default state.
437 {
438 base::test::ScopedFeatureList feature_list;
439 feature_list.InitFromCommandLine("", "");
440 EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
441 }
442 }
443 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
444
445 struct StructWithOstream {
operator ==__anoncccd141a0111::StructWithOstream446 bool operator==(const StructWithOstream& o) const { return &o == this; }
447 };
448 #if CHECK_WILL_STREAM()
operator <<(std::ostream & out,const StructWithOstream &)449 std::ostream& operator<<(std::ostream& out, const StructWithOstream&) {
450 return out << "ostream";
451 }
452 #endif // CHECK_WILL_STREAM()
453
454 struct StructWithToString {
operator ==__anoncccd141a0111::StructWithToString455 bool operator==(const StructWithToString& o) const { return &o == this; }
ToString__anoncccd141a0111::StructWithToString456 std::string ToString() const { return "ToString"; }
457 };
458
459 struct StructWithToStringAndOstream {
operator ==__anoncccd141a0111::StructWithToStringAndOstream460 bool operator==(const StructWithToStringAndOstream& o) const {
461 return &o == this;
462 }
ToString__anoncccd141a0111::StructWithToStringAndOstream463 std::string ToString() const { return "ToString"; }
464 };
465 #if CHECK_WILL_STREAM()
operator <<(std::ostream & out,const StructWithToStringAndOstream &)466 std::ostream& operator<<(std::ostream& out,
467 const StructWithToStringAndOstream&) {
468 return out << "ostream";
469 }
470 #endif // CHECK_WILL_STREAM()
471
472 struct StructWithToStringNotStdString {
473 struct PseudoString {};
474
operator ==__anoncccd141a0111::StructWithToStringNotStdString475 bool operator==(const StructWithToStringNotStdString& o) const {
476 return &o == this;
477 }
ToString__anoncccd141a0111::StructWithToStringNotStdString478 PseudoString ToString() const { return PseudoString(); }
479 };
480 #if CHECK_WILL_STREAM()
operator <<(std::ostream & out,const StructWithToStringNotStdString::PseudoString &)481 std::ostream& operator<<(std::ostream& out,
482 const StructWithToStringNotStdString::PseudoString&) {
483 return out << "ToString+ostream";
484 }
485 #endif // CHECK_WILL_STREAM()
486
TEST(CheckDeathTest,OstreamVsToString)487 TEST(CheckDeathTest, OstreamVsToString) {
488 StructWithOstream a, b;
489 EXPECT_CHECK("Check failed: a == b (ostream vs. ostream)", CHECK_EQ(a, b));
490
491 StructWithToString c, d;
492 EXPECT_CHECK("Check failed: c == d (ToString vs. ToString)", CHECK_EQ(c, d));
493
494 StructWithToStringAndOstream e, f;
495 EXPECT_CHECK("Check failed: e == f (ostream vs. ostream)", CHECK_EQ(e, f));
496
497 StructWithToStringNotStdString g, h;
498 EXPECT_CHECK("Check failed: g == h (ToString+ostream vs. ToString+ostream)",
499 CHECK_EQ(g, h));
500 }
501
502 // This non-void function is here to make sure that NOTREACHED_NORETURN() is
503 // properly annotated as [[noreturn]] and does not require a return statement.
NotReachedNoreturnInFunction()504 int NotReachedNoreturnInFunction() {
505 NOTREACHED_NORETURN();
506 // No return statement here.
507 }
508
TEST(CheckDeathTest,NotReached)509 TEST(CheckDeathTest, NotReached) {
510 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
511 // This specific death test relies on LOGGING_DCHECK not being FATAL, even
512 // when run as part of a death test.
513 ScopedDcheckSeverity dcheck_severity(logging::LOGGING_ERROR);
514 #endif
515
516 #if DCHECK_IS_ON()
517 // Expect a DCHECK with streamed params intact.
518 EXPECT_DCHECK("Check failed: false. foo", NOTREACHED() << "foo");
519 #elif CHECK_WILL_STREAM() || BUILDFLAG(ENABLE_LOG_ERROR_NOT_REACHED)
520 // This block makes sure that base::Location::Current() returns non-dummy
521 // values for file_name() and line_number(). This is necessary to avoid a
522 // false negative inside EXPECT_LOG_ERROR_WITH_FILENAME() where we exhonorate
523 // the NOTREACHED() macro below even though it didn't provide the expected
524 // filename and line numbers.
525 // See EXPECT_LOG_ERROR_WITH_FILENAME() for the exclusion of "" and -1.
526 ASSERT_NE(base::Location::Current().file_name(), nullptr);
527 EXPECT_STRNE(base::Location::Current().file_name(), "");
528 EXPECT_NE(base::Location::Current().line_number(), -1);
529 // Expect LOG(ERROR) that looks like CHECK(false) with streamed params intact.
530 // Note that this implementation uses base::Location::Current() which doesn't
531 // match __FILE__ (strips ../../ prefix) and __LINE__ (uses __builtin_LINE()).
532 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
533 base::Location::Current().line_number(),
534 NOTREACHED() << "foo",
535 "Check failed: false. foo\n");
536 #else
537 // Expect LOG(ERROR) that looks like CHECK(false) without file or line intact.
538 // We use `""` and `-1` to not expect a specific filename or line number.
539 // The actual location comes from
540 // logging::NotReachedError::TriggerNotReached() but we have no good way of
541 // asserting what that filename or line number is from here.
542 EXPECT_LOG_ERROR_WITH_FILENAME("", -1, NOTREACHED() << "foo",
543 "Check failed: false. NOTREACHED log messages "
544 "are omitted in official builds. Sorry!\n");
545 #endif
546 EXPECT_DEATH_IF_SUPPORTED(NotReachedNoreturnInFunction(),
547 CHECK_WILL_STREAM() ? "NOTREACHED hit. " : "");
548 }
549
TEST(CheckDeathTest,NotReachedFatalExperiment)550 TEST(CheckDeathTest, NotReachedFatalExperiment) {
551 base::test::ScopedFeatureList feature_list(
552 base::features::kNotReachedIsFatal);
553 EXPECT_CHECK_DEATH(NOTREACHED());
554 }
555
TEST(CheckDeathTest,DumpWillBeCheck)556 TEST(CheckDeathTest, DumpWillBeCheck) {
557 DUMP_WILL_BE_CHECK(true);
558
559 EXPECT_DUMP_WILL_BE_CHECK("Check failed: false. foo",
560 DUMP_WILL_BE_CHECK(false) << "foo");
561 }
562
TEST(CheckDeathTest,DumpWillBeNotReachedNoreturn)563 TEST(CheckDeathTest, DumpWillBeNotReachedNoreturn) {
564 EXPECT_DUMP_WILL_BE_CHECK("NOTREACHED hit. foo",
565 DUMP_WILL_BE_NOTREACHED_NORETURN() << "foo");
566 }
567
568 static const std::string kNotImplementedMessage = "Not implemented reached in ";
569
TEST(CheckTest,NotImplemented)570 TEST(CheckTest, NotImplemented) {
571 static const std::string expected_msg =
572 kNotImplementedMessage + __PRETTY_FUNCTION__;
573
574 #if DCHECK_IS_ON()
575 // Expect LOG(ERROR) with streamed params intact.
576 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
577 base::Location::Current().line_number(),
578 NOTIMPLEMENTED() << "foo",
579 expected_msg + "foo\n");
580 #else
581 // Expect nothing.
582 EXPECT_NO_LOG(NOTIMPLEMENTED() << "foo");
583 #endif
584 }
585
NiLogOnce()586 void NiLogOnce() {
587 NOTIMPLEMENTED_LOG_ONCE();
588 }
589
TEST(CheckTest,NotImplementedLogOnce)590 TEST(CheckTest, NotImplementedLogOnce) {
591 static const std::string expected_msg =
592 kNotImplementedMessage + "void (anonymous namespace)::NiLogOnce()\n";
593
594 #if DCHECK_IS_ON()
595 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
596 base::Location::Current().line_number() - 10,
597 NiLogOnce(), expected_msg);
598 EXPECT_NO_LOG(NiLogOnce());
599 #else
600 EXPECT_NO_LOG(NiLogOnce());
601 EXPECT_NO_LOG(NiLogOnce());
602 #endif
603 }
604
NiLogTenTimesWithStream()605 void NiLogTenTimesWithStream() {
606 for (int i = 0; i < 10; ++i) {
607 NOTIMPLEMENTED_LOG_ONCE() << " iteration: " << i;
608 }
609 }
610
TEST(CheckTest,NotImplementedLogOnceWithStreamedParams)611 TEST(CheckTest, NotImplementedLogOnceWithStreamedParams) {
612 static const std::string expected_msg1 =
613 kNotImplementedMessage +
614 "void (anonymous namespace)::NiLogTenTimesWithStream() iteration: 0\n";
615
616 #if DCHECK_IS_ON()
617 // Expect LOG(ERROR) with streamed params intact, exactly once.
618 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
619 base::Location::Current().line_number() - 13,
620 NiLogTenTimesWithStream(), expected_msg1);
621 // A different NOTIMPLEMENTED_LOG_ONCE() call is still logged.
622 static const std::string expected_msg2 =
623 kNotImplementedMessage + __PRETTY_FUNCTION__ + "tree fish\n";
624 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
625 base::Location::Current().line_number(),
626 NOTIMPLEMENTED_LOG_ONCE() << "tree fish",
627 expected_msg2);
628
629 #else
630 // Expect nothing.
631 EXPECT_NO_LOG(NiLogTenTimesWithStream());
632 EXPECT_NO_LOG(NOTIMPLEMENTED_LOG_ONCE() << "tree fish");
633 #endif
634 }
635
636 // Test CHECK_DEREF of `T*`
TEST(CheckTest,CheckDerefOfPointer)637 TEST(CheckTest, CheckDerefOfPointer) {
638 std::string pointee = "not-null";
639 std::string* value_pointer = &pointee;
640
641 auto& deref_result = CHECK_DEREF(value_pointer);
642 static_assert(std::is_lvalue_reference_v<decltype(deref_result)>);
643 // Compare the pointers to ensure they are the same object (and not a copy)
644 EXPECT_EQ(&deref_result, &pointee);
645 static_assert(std::is_same_v<decltype(deref_result), std::string&>);
646 }
647
TEST(CheckDeathTest,CheckDerefOfNullPointer)648 TEST(CheckDeathTest, CheckDerefOfNullPointer) {
649 std::string* null_pointer = nullptr;
650 EXPECT_CHECK("Check failed: null_pointer != nullptr. ",
651 CHECK_DEREF(null_pointer));
652 }
653
654 // Test CHECK_DEREF of `const T*`
TEST(CheckTest,CheckDerefOfConstPointer)655 TEST(CheckTest, CheckDerefOfConstPointer) {
656 std::string pointee = "not-null";
657 const std::string* const_value_pointer = &pointee;
658
659 auto& deref_result = CHECK_DEREF(const_value_pointer);
660 static_assert(std::is_lvalue_reference_v<decltype(deref_result)>);
661 // Compare the pointers to ensure they are the same object (and not a copy)
662 EXPECT_EQ(&deref_result, &pointee);
663 static_assert(std::is_same_v<decltype(deref_result), const std::string&>);
664 }
665
TEST(CheckDeathTest,CheckDerefOfConstNullPointer)666 TEST(CheckDeathTest, CheckDerefOfConstNullPointer) {
667 std::string* const_null_pointer = nullptr;
668 EXPECT_CHECK("Check failed: const_null_pointer != nullptr. ",
669 CHECK_DEREF(const_null_pointer));
670 }
671
672 } // namespace
673