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 <string>
6 #include <string_view>
7 #include <tuple>
8
9 #include "base/check_deref.h"
10 #include "base/check_version_internal.h"
11 #include "base/dcheck_is_on.h"
12 #include "base/debug/dump_without_crashing.h"
13 #include "base/functional/bind.h"
14 #include "base/functional/callback.h"
15 #include "base/logging.h"
16 #include "base/macros/concat.h"
17 #include "base/notimplemented.h"
18 #include "base/notreached.h"
19 #include "base/strings/cstring_view.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/test/gtest_util.h"
23 #include "base/test/scoped_feature_list.h"
24 #include "build/build_config.h"
25 #include "testing/gmock/include/gmock/gmock.h"
26 #include "testing/gtest/include/gtest/gtest.h"
27
28 #if BUILDFLAG(IS_POSIX)
29 #include <errno.h>
30 #endif
31
32 #if BUILDFLAG(IS_WIN)
33 #include <windows.h>
34 #endif
35
36 namespace {
37
38 int g_dump_without_crashing_count = 0;
39
40 constexpr base::NotFatalUntil kNextMilestone =
41 BASE_CONCAT(base::NotFatalUntil::M, BASE_CHECK_NEXT_VERSION_INTERNAL);
42 constexpr base::NotFatalUntil kCurrentMilestone =
43 BASE_CONCAT(base::NotFatalUntil::M, BASE_CHECK_VERSION_INTERNAL);
44
45 class ScopedExpectDumpWithoutCrashing {
46 public:
ScopedExpectDumpWithoutCrashing()47 ScopedExpectDumpWithoutCrashing() {
48 g_dump_without_crashing_count = 0;
49 base::debug::SetDumpWithoutCrashingFunction(&DumpWithoutCrashing);
50 }
51
~ScopedExpectDumpWithoutCrashing()52 ~ScopedExpectDumpWithoutCrashing() {
53 EXPECT_EQ(1, g_dump_without_crashing_count);
54 base::debug::SetDumpWithoutCrashingFunction(nullptr);
55 }
56
57 private:
DumpWithoutCrashing()58 static void DumpWithoutCrashing() { ++g_dump_without_crashing_count; }
59 };
60
61 MATCHER_P2(LogErrorMatches, line, expected_msg, "") {
62 EXPECT_THAT(arg, testing::HasSubstr(
63 base::StringPrintf("check_unittest.cc(%d)] ", line)));
64 if (std::string(expected_msg).find("=~") == 0) {
65 EXPECT_THAT(std::string(arg),
66 testing::ContainsRegex(std::string(expected_msg).substr(2)));
67 } else {
68 EXPECT_THAT(std::string(arg), testing::HasSubstr(expected_msg));
69 }
70 return true;
71 }
72
73 // TODO(pbos): Upstream support for ignoring matchers in gtest when death
74 // testing is not available.
75 // Without this we get a compile failure on iOS because
76 // GTEST_UNSUPPORTED_DEATH_TEST does not compile with a MATCHER as parameter.
77 #if GTEST_HAS_DEATH_TEST
78 #define CHECK_MATCHER(line, msg) LogErrorMatches(line, msg)
79 #else
80 #define CHECK_MATCHER(line, msg) msg
81 #endif
82
83 // Macro which expects a CHECK to fire with a certain message. If msg starts
84 // with "=~", it's interpreted as a regular expression.
85 // Example: EXPECT_CHECK("Check failed: false.", CHECK(false));
86 //
87 // Note: Please use the `CheckDeathTest` fixture when using this check.
88 #if !CHECK_WILL_STREAM()
89 #define EXPECT_CHECK(msg, check_expr) \
90 do { \
91 EXPECT_CHECK_DEATH(check_expr); \
92 } while (0)
93 #else
94 #define EXPECT_CHECK(msg, check_expr) \
95 BASE_EXPECT_DEATH(check_expr, CHECK_MATCHER(__LINE__, msg))
96 #endif // !CHECK_WILL_STREAM()
97
98 // Macro which expects a DCHECK to fire if DCHECKs are enabled.
99 //
100 // Note: Please use the `CheckDeathTest` fixture when using this check.
101 #define EXPECT_DCHECK(msg, check_expr) \
102 do { \
103 if (DCHECK_IS_ON() && logging::LOGGING_DCHECK == logging::LOGGING_FATAL) { \
104 BASE_EXPECT_DEATH(check_expr, CHECK_MATCHER(__LINE__, msg)); \
105 } else if (DCHECK_IS_ON()) { \
106 ScopedExpectDumpWithoutCrashing expect_dump; \
107 check_expr; \
108 } else { \
109 check_expr; \
110 } \
111 } while (0)
112
113 #define EXPECT_LOG_ERROR_WITH_FILENAME(expected_file, expected_line, expr, \
114 msg) \
115 do { \
116 static bool got_log_message = false; \
117 ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \
118 logging::SetLogMessageHandler([](int severity, const char* file, int line, \
119 size_t message_start, \
120 const std::string& str) { \
121 EXPECT_FALSE(got_log_message); \
122 got_log_message = true; \
123 EXPECT_EQ(severity, logging::LOGGING_ERROR); \
124 EXPECT_EQ(str.substr(message_start), (msg)); \
125 if (std::string_view(expected_file) != "") { \
126 EXPECT_STREQ(expected_file, file); \
127 } \
128 if (expected_line != -1) { \
129 EXPECT_EQ(expected_line, line); \
130 } \
131 return true; \
132 }); \
133 expr; \
134 EXPECT_TRUE(got_log_message); \
135 logging::SetLogMessageHandler(nullptr); \
136 } while (0)
137
138 #define EXPECT_LOG_ERROR(expected_line, expr, msg) \
139 EXPECT_LOG_ERROR_WITH_FILENAME(__FILE__, expected_line, expr, msg)
140
141 #define EXPECT_NO_LOG(expr) \
142 do { \
143 ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \
144 logging::SetLogMessageHandler([](int severity, const char* file, int line, \
145 size_t message_start, \
146 const std::string& str) { \
147 EXPECT_TRUE(false) << "Unexpected log: " << str; \
148 return true; \
149 }); \
150 expr; \
151 logging::SetLogMessageHandler(nullptr); \
152 } while (0)
153
154 #if defined(OFFICIAL_BUILD)
155 #if DCHECK_IS_ON()
156 #define EXPECT_DUMP_WILL_BE_CHECK EXPECT_DCHECK
157 #else
158 #define EXPECT_DUMP_WILL_BE_CHECK(expected_string, statement) \
159 do { \
160 ScopedExpectDumpWithoutCrashing expect_dump; \
161 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(), \
162 base::Location::Current().line_number(), \
163 statement, expected_string "\n"); \
164 } while (0)
165 #endif // DCHECK_IS_ON()
166 #else
167 #define EXPECT_DUMP_WILL_BE_CHECK EXPECT_CHECK
168 #endif // defined(OFFICIAL_BUILD)
169
TEST(CheckDeathTest,Basics)170 TEST(CheckDeathTest, Basics) {
171 EXPECT_CHECK("Check failed: false. ", CHECK(false));
172
173 EXPECT_CHECK("Check failed: false. foo", CHECK(false) << "foo");
174
175 double a = 2, b = 1;
176 EXPECT_CHECK("Check failed: a < b (2.000000 vs. 1.000000)", CHECK_LT(a, b));
177
178 EXPECT_CHECK("Check failed: a < b (2.000000 vs. 1.000000)custom message",
179 CHECK_LT(a, b) << "custom message");
180 }
181
TEST(CheckDeathTest,PCheck)182 TEST(CheckDeathTest, PCheck) {
183 const char file[] = "/nonexistentfile123";
184 std::ignore = fopen(file, "r");
185 std::string err =
186 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
187
188 EXPECT_CHECK(
189 "Check failed: fopen(file, \"r\") != nullptr."
190 " : " +
191 err,
192 PCHECK(fopen(file, "r") != nullptr));
193
194 EXPECT_CHECK(
195 "Check failed: fopen(file, \"r\") != nullptr."
196 " foo: " +
197 err,
198 PCHECK(fopen(file, "r") != nullptr) << "foo");
199
200 EXPECT_DCHECK(
201 "Check failed: fopen(file, \"r\") != nullptr."
202 " : " +
203 err,
204 DPCHECK(fopen(file, "r") != nullptr));
205
206 EXPECT_DCHECK(
207 "Check failed: fopen(file, \"r\") != nullptr."
208 " foo: " +
209 err,
210 DPCHECK(fopen(file, "r") != nullptr) << "foo");
211 }
212
TEST(CheckDeathTest,CheckOp)213 TEST(CheckDeathTest, CheckOp) {
214 const int a = 1, b = 2;
215 // clang-format off
216 EXPECT_CHECK("Check failed: a == b (1 vs. 2)", CHECK_EQ(a, b));
217 EXPECT_CHECK("Check failed: a != a (1 vs. 1)", CHECK_NE(a, a));
218 EXPECT_CHECK("Check failed: b <= a (2 vs. 1)", CHECK_LE(b, a));
219 EXPECT_CHECK("Check failed: b < a (2 vs. 1)", CHECK_LT(b, a));
220 EXPECT_CHECK("Check failed: a >= b (1 vs. 2)", CHECK_GE(a, b));
221 EXPECT_CHECK("Check failed: a > b (1 vs. 2)", CHECK_GT(a, b));
222
223 EXPECT_DCHECK("Check failed: a == b (1 vs. 2)", DCHECK_EQ(a, b));
224 EXPECT_DCHECK("Check failed: a != a (1 vs. 1)", DCHECK_NE(a, a));
225 EXPECT_DCHECK("Check failed: b <= a (2 vs. 1)", DCHECK_LE(b, a));
226 EXPECT_DCHECK("Check failed: b < a (2 vs. 1)", DCHECK_LT(b, a));
227 EXPECT_DCHECK("Check failed: a >= b (1 vs. 2)", DCHECK_GE(a, b));
228 EXPECT_DCHECK("Check failed: a > b (1 vs. 2)", DCHECK_GT(a, b));
229 // clang-format on
230
231 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a == b (1 vs. 2)",
232 DUMP_WILL_BE_CHECK_EQ(a, b));
233 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a != a (1 vs. 1)",
234 DUMP_WILL_BE_CHECK_NE(a, a));
235 EXPECT_DUMP_WILL_BE_CHECK("Check failed: b <= a (2 vs. 1)",
236 DUMP_WILL_BE_CHECK_LE(b, a));
237 EXPECT_DUMP_WILL_BE_CHECK("Check failed: b < a (2 vs. 1)",
238 DUMP_WILL_BE_CHECK_LT(b, a));
239 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a >= b (1 vs. 2)",
240 DUMP_WILL_BE_CHECK_GE(a, b));
241 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a > b (1 vs. 2)",
242 DUMP_WILL_BE_CHECK_GT(a, b));
243 }
244
TEST(CheckDeathTest,CheckOpStrings)245 TEST(CheckDeathTest, CheckOpStrings) {
246 std::string_view sv = "1";
247 base::cstring_view csv = "2";
248 std::string s = "3";
249
250 EXPECT_CHECK("Check failed: sv == csv (1 vs. 2)", CHECK_EQ(sv, csv));
251 EXPECT_CHECK("Check failed: csv == s (2 vs. 3)", CHECK_EQ(csv, s));
252 EXPECT_CHECK("Check failed: sv == s (1 vs. 3)", CHECK_EQ(sv, s));
253
254 EXPECT_DCHECK("Check failed: sv == csv (1 vs. 2)", DCHECK_EQ(sv, csv));
255 EXPECT_DCHECK("Check failed: csv == s (2 vs. 3)", DCHECK_EQ(csv, s));
256 EXPECT_DCHECK("Check failed: sv == s (1 vs. 3)", DCHECK_EQ(sv, s));
257 }
258
TEST(CheckDeathTest,CheckOpPointers)259 TEST(CheckDeathTest, CheckOpPointers) {
260 uint8_t arr[] = {3, 2, 1, 0};
261 uint8_t* arr_start = &arr[0];
262 // Print pointers and not the binary data in `arr`.
263 #if BUILDFLAG(IS_WIN)
264 EXPECT_CHECK(
265 "=~Check failed: arr_start != arr_start \\([0-9A-F]+ vs. "
266 "[0-9A-F]+\\)",
267 CHECK_NE(arr_start, arr_start));
268 #else
269 EXPECT_CHECK(
270 "=~Check failed: arr_start != arr_start \\(0x[0-9a-f]+ vs. "
271 "0x[0-9a-f]+\\)",
272 CHECK_NE(arr_start, arr_start));
273 #endif
274 }
275
TEST(CheckTest,CheckStreamsAreLazy)276 TEST(CheckTest, CheckStreamsAreLazy) {
277 int called_count = 0;
278 int not_called_count = 0;
279
280 auto Called = [&] {
281 ++called_count;
282 // This returns a non-constant because returning 42 here directly triggers a
283 // dead-code warning when streaming to *CHECK(Called()) << NotCalled();
284 return called_count >= 0;
285 };
286 auto NotCalled = [&] {
287 ++not_called_count;
288 return 42;
289 };
290
291 CHECK(Called()) << NotCalled();
292 CHECK_EQ(Called(), Called()) << NotCalled();
293 PCHECK(Called()) << NotCalled();
294
295 DCHECK(Called()) << NotCalled();
296 DCHECK_EQ(Called(), Called()) << NotCalled();
297 DPCHECK(Called()) << NotCalled();
298
299 EXPECT_EQ(not_called_count, 0);
300 #if DCHECK_IS_ON()
301 EXPECT_EQ(called_count, 8);
302 #else
303 EXPECT_EQ(called_count, 4);
304 #endif
305 }
306
DcheckEmptyFunction1()307 void DcheckEmptyFunction1() {
308 // Provide a body so that Release builds do not cause the compiler to
309 // optimize DcheckEmptyFunction1 and DcheckEmptyFunction2 as a single
310 // function, which breaks the Dcheck tests below.
311 LOG(INFO) << "DcheckEmptyFunction1";
312 }
DcheckEmptyFunction2()313 void DcheckEmptyFunction2() {}
314
315 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
316 class ScopedDcheckSeverity {
317 public:
ScopedDcheckSeverity(logging::LogSeverity new_severity)318 explicit ScopedDcheckSeverity(logging::LogSeverity new_severity)
319 : old_severity_(logging::LOGGING_DCHECK) {
320 logging::LOGGING_DCHECK = new_severity;
321 }
322
~ScopedDcheckSeverity()323 ~ScopedDcheckSeverity() { logging::LOGGING_DCHECK = old_severity_; }
324
325 private:
326 logging::LogSeverity old_severity_;
327 };
328 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
329
TEST(CheckDeathTest,Dcheck)330 TEST(CheckDeathTest, Dcheck) {
331 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
332 // DCHECKs are enabled, and LOGGING_DCHECK is mutable, but defaults to
333 // non-fatal. Set it to LOGGING_FATAL to get the expected behavior from the
334 // rest of this test.
335 ScopedDcheckSeverity dcheck_severity(logging::LOGGING_FATAL);
336 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
337
338 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
339 // Release build.
340 EXPECT_FALSE(DCHECK_IS_ON());
341 #elif defined(NDEBUG) && defined(DCHECK_ALWAYS_ON)
342 // Release build with real DCHECKS.
343 EXPECT_TRUE(DCHECK_IS_ON());
344 #else
345 // Debug build.
346 EXPECT_TRUE(DCHECK_IS_ON());
347 #endif
348
349 EXPECT_DCHECK("Check failed: false. ", DCHECK(false));
350
351 // Produce a consistent error code so that both the main instance of this test
352 // and the EXPECT_DEATH invocation below get the same error codes for DPCHECK.
353 const char file[] = "/nonexistentfile123";
354 std::ignore = fopen(file, "r");
355 std::string err =
356 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
357 EXPECT_DCHECK("Check failed: false. : " + err, DPCHECK(false));
358 EXPECT_DCHECK("Check failed: 0 == 1 (0 vs. 1)", DCHECK_EQ(0, 1));
359
360 // Test DCHECK on std::nullptr_t
361 const void* p_null = nullptr;
362 const void* p_not_null = &p_null;
363 DCHECK_EQ(p_null, nullptr);
364 DCHECK_EQ(nullptr, p_null);
365 DCHECK_NE(p_not_null, nullptr);
366 DCHECK_NE(nullptr, p_not_null);
367
368 // Test DCHECK on a scoped enum.
369 enum class Animal { DOG, CAT };
370 DCHECK_EQ(Animal::DOG, Animal::DOG);
371 EXPECT_DCHECK("Check failed: Animal::DOG == Animal::CAT (0 vs. 1)",
372 DCHECK_EQ(Animal::DOG, Animal::CAT));
373
374 // Test DCHECK on functions and function pointers.
375 struct MemberFunctions {
376 void MemberFunction1() {
377 // See the comment in DcheckEmptyFunction1().
378 LOG(INFO) << "Do not merge with MemberFunction2.";
379 }
380 void MemberFunction2() {}
381 };
382 void (MemberFunctions::*mp1)() = &MemberFunctions::MemberFunction1;
383 void (MemberFunctions::*mp2)() = &MemberFunctions::MemberFunction2;
384 void (*fp1)() = DcheckEmptyFunction1;
385 void (*fp2)() = DcheckEmptyFunction2;
386 void (*fp3)() = DcheckEmptyFunction1;
387 DCHECK_EQ(fp1, fp3);
388 DCHECK_EQ(mp1, &MemberFunctions::MemberFunction1);
389 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction2);
390 EXPECT_DCHECK("=~Check failed: fp1 == fp2 \\(\\w+ vs. \\w+\\)",
391 DCHECK_EQ(fp1, fp2));
392 EXPECT_DCHECK(
393 "Check failed: mp2 == &MemberFunctions::MemberFunction1 (1 vs. 1)",
394 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction1));
395 }
396
TEST(CheckTest,DcheckReleaseBehavior)397 TEST(CheckTest, DcheckReleaseBehavior) {
398 int var1 = 1;
399 int var2 = 2;
400 int var3 = 3;
401 int var4 = 4;
402
403 // No warnings about unused variables even though no check fires and DCHECK
404 // may or may not be enabled.
405 DCHECK(var1) << var2;
406 DPCHECK(var1) << var3;
407 DCHECK_EQ(var1, 1) << var4;
408 }
409
TEST(CheckTest,DCheckEqStatements)410 TEST(CheckTest, DCheckEqStatements) {
411 bool reached = false;
412 if (false)
413 DCHECK_EQ(false, true); // Unreached.
414 else
415 DCHECK_EQ(true, reached = true); // Reached, passed.
416 ASSERT_EQ(DCHECK_IS_ON() ? true : false, reached);
417
418 if (false)
419 DCHECK_EQ(false, true); // Unreached.
420 }
421
TEST(CheckTest,CheckEqStatements)422 TEST(CheckTest, CheckEqStatements) {
423 bool reached = false;
424 if (false)
425 CHECK_EQ(false, true); // Unreached.
426 else
427 CHECK_EQ(true, reached = true); // Reached, passed.
428 ASSERT_TRUE(reached);
429
430 if (false)
431 CHECK_EQ(false, true); // Unreached.
432 }
433
434 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
TEST(CheckDeathTest,ConfigurableDCheck)435 TEST(CheckDeathTest, ConfigurableDCheck) {
436 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
437 "gtest_internal_run_death_test")) {
438 // This specific test relies on LOGGING_DCHECK not starting out as FATAL,
439 // even when run part of death tests (should die only after LOGGING_DCHECK
440 // gets reconfigured to FATAL below).
441 logging::LOGGING_DCHECK = logging::LOGGING_ERROR;
442 } else {
443 // Verify that DCHECKs default to non-fatal in configurable-DCHECK builds.
444 // Note that we require only that DCHECK is non-fatal by default, rather
445 // than requiring that it be exactly INFO, ERROR, etc level.
446 EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
447 }
448 DCHECK(false);
449
450 // Verify that DCHECK* aren't hard-wired to crash on failure.
451 logging::LOGGING_DCHECK = logging::LOGGING_ERROR;
452 DCHECK(false);
453 DCHECK_EQ(1, 2);
454
455 // Verify that DCHECK does crash if LOGGING_DCHECK is set to LOGGING_FATAL.
456 logging::LOGGING_DCHECK = logging::LOGGING_FATAL;
457 EXPECT_CHECK("Check failed: false. ", DCHECK(false));
458 EXPECT_CHECK("Check failed: 1 == 2 (1 vs. 2)", DCHECK_EQ(1, 2));
459 }
460
TEST(CheckTest,ConfigurableDCheckFeature)461 TEST(CheckTest, ConfigurableDCheckFeature) {
462 // Initialize FeatureList with and without DcheckIsFatal, and verify the
463 // value of LOGGING_DCHECK. Note that we don't require that DCHECK take a
464 // specific value when the feature is off, only that it is non-fatal.
465
466 {
467 base::test::ScopedFeatureList feature_list;
468 feature_list.InitFromCommandLine("DcheckIsFatal", "");
469 EXPECT_EQ(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
470 }
471
472 {
473 base::test::ScopedFeatureList feature_list;
474 feature_list.InitFromCommandLine("", "DcheckIsFatal");
475 EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
476 }
477
478 // The default case is last, so we leave LOGGING_DCHECK in the default state.
479 {
480 base::test::ScopedFeatureList feature_list;
481 feature_list.InitFromCommandLine("", "");
482 EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
483 }
484 }
485 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
486
487 struct StructWithOstream {
operator ==__anonda2f13020111::StructWithOstream488 bool operator==(const StructWithOstream& o) const { return &o == this; }
489 };
490 #if CHECK_WILL_STREAM()
operator <<(std::ostream & out,const StructWithOstream &)491 std::ostream& operator<<(std::ostream& out, const StructWithOstream&) {
492 return out << "ostream";
493 }
494 #endif // CHECK_WILL_STREAM()
495
496 struct StructWithToString {
operator ==__anonda2f13020111::StructWithToString497 bool operator==(const StructWithToString& o) const { return &o == this; }
ToString__anonda2f13020111::StructWithToString498 std::string ToString() const { return "ToString"; }
499 };
500
501 struct StructWithToStringAndOstream {
operator ==__anonda2f13020111::StructWithToStringAndOstream502 bool operator==(const StructWithToStringAndOstream& o) const {
503 return &o == this;
504 }
ToString__anonda2f13020111::StructWithToStringAndOstream505 std::string ToString() const { return "ToString"; }
506 };
507 #if CHECK_WILL_STREAM()
operator <<(std::ostream & out,const StructWithToStringAndOstream &)508 std::ostream& operator<<(std::ostream& out,
509 const StructWithToStringAndOstream&) {
510 return out << "ostream";
511 }
512 #endif // CHECK_WILL_STREAM()
513
514 struct StructWithToStringNotStdString {
515 struct PseudoString {};
516
operator ==__anonda2f13020111::StructWithToStringNotStdString517 bool operator==(const StructWithToStringNotStdString& o) const {
518 return &o == this;
519 }
ToString__anonda2f13020111::StructWithToStringNotStdString520 PseudoString ToString() const { return PseudoString(); }
521 };
522 #if CHECK_WILL_STREAM()
operator <<(std::ostream & out,const StructWithToStringNotStdString::PseudoString &)523 std::ostream& operator<<(std::ostream& out,
524 const StructWithToStringNotStdString::PseudoString&) {
525 return out << "ToString+ostream";
526 }
527 #endif // CHECK_WILL_STREAM()
528
TEST(CheckDeathTest,OstreamVsToString)529 TEST(CheckDeathTest, OstreamVsToString) {
530 StructWithOstream a, b;
531 EXPECT_CHECK("Check failed: a == b (ostream vs. ostream)", CHECK_EQ(a, b));
532
533 StructWithToString c, d;
534 EXPECT_CHECK("Check failed: c == d (ToString vs. ToString)", CHECK_EQ(c, d));
535
536 StructWithToStringAndOstream e, f;
537 EXPECT_CHECK("Check failed: e == f (ostream vs. ostream)", CHECK_EQ(e, f));
538
539 StructWithToStringNotStdString g, h;
540 EXPECT_CHECK("Check failed: g == h (ToString+ostream vs. ToString+ostream)",
541 CHECK_EQ(g, h));
542 }
543
TEST(CheckDeathTest,NotReached)544 TEST(CheckDeathTest, NotReached) {
545 // Expect to be CHECK fatal but with a different error message.
546 EXPECT_CHECK("NOTREACHED hit. foo", NOTREACHED() << "foo");
547 }
548
549 // These non-void functions are here to make sure that CHECK failures and
550 // NOTREACHED() are properly annotated as [[noreturn]] by not requiring a return
551 // statement.
NotReachedInFunction()552 int NotReachedInFunction() {
553 NOTREACHED();
554 // No return statement here.
555 }
556
CheckFailureInFunction()557 int CheckFailureInFunction() {
558 constexpr int kFalse = false;
559 CHECK(kFalse);
560
561 // No return statement here.
562 }
563
PCheckFailureInFunction()564 int PCheckFailureInFunction() {
565 constexpr int kFalse = false;
566 PCHECK(kFalse);
567
568 // No return statement here.
569 }
570
TEST(CheckDeathTest,CheckFailuresAreNoreturn)571 TEST(CheckDeathTest, CheckFailuresAreNoreturn) {
572 // This call can't use EXPECT_CHECK as the NOTREACHED happens on a different
573 // line.
574 EXPECT_DEATH_IF_SUPPORTED(NotReachedInFunction(),
575 CHECK_WILL_STREAM() ? "NOTREACHED hit. " : "");
576
577 // This call can't use EXPECT_CHECK as the CHECK failure happens on a
578 // different line.
579 EXPECT_DEATH_IF_SUPPORTED(CheckFailureInFunction(),
580 CHECK_WILL_STREAM() ? "Check failed: " : "");
581
582 // This call can't use EXPECT_CHECK as the PCHECK failure happens on a
583 // different line.
584 EXPECT_DEATH_IF_SUPPORTED(PCheckFailureInFunction(),
585 CHECK_WILL_STREAM() ? "Check failed: " : "");
586
587 // TODO(crbug.com/40122554): Make sure CHECK_LT(1, 1) is [[noreturn]]. That
588 // doesn't work in the current developer build.
589 }
590
TEST(CheckDeathTest,DumpWillBeCheck)591 TEST(CheckDeathTest, DumpWillBeCheck) {
592 DUMP_WILL_BE_CHECK(true);
593
594 EXPECT_DUMP_WILL_BE_CHECK("Check failed: false. foo",
595 DUMP_WILL_BE_CHECK(false) << "foo");
596 }
597
TEST(CheckDeathTest,DumpWillBeNotReachedNoreturn)598 TEST(CheckDeathTest, DumpWillBeNotReachedNoreturn) {
599 EXPECT_DUMP_WILL_BE_CHECK("NOTREACHED hit. foo", DUMP_WILL_BE_NOTREACHED()
600 << "foo");
601 }
602
603 static const std::string kNotImplementedMessage = "Not implemented reached in ";
604
TEST(CheckTest,NotImplemented)605 TEST(CheckTest, NotImplemented) {
606 static const std::string expected_msg =
607 kNotImplementedMessage + __PRETTY_FUNCTION__;
608
609 #if DCHECK_IS_ON()
610 // Expect LOG(ERROR) with streamed params intact.
611 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
612 base::Location::Current().line_number(),
613 NOTIMPLEMENTED() << "foo",
614 expected_msg + "foo\n");
615 #else
616 // Expect nothing.
617 EXPECT_NO_LOG(NOTIMPLEMENTED() << "foo");
618 #endif
619 }
620
NiLogOnce()621 void NiLogOnce() {
622 NOTIMPLEMENTED_LOG_ONCE();
623 }
624
TEST(CheckTest,NotImplementedLogOnce)625 TEST(CheckTest, NotImplementedLogOnce) {
626 static const std::string expected_msg =
627 kNotImplementedMessage + "void (anonymous namespace)::NiLogOnce()\n";
628
629 #if DCHECK_IS_ON()
630 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
631 base::Location::Current().line_number() - 10,
632 NiLogOnce(), expected_msg);
633 EXPECT_NO_LOG(NiLogOnce());
634 #else
635 EXPECT_NO_LOG(NiLogOnce());
636 EXPECT_NO_LOG(NiLogOnce());
637 #endif
638 }
639
NiLogTenTimesWithStream()640 void NiLogTenTimesWithStream() {
641 for (int i = 0; i < 10; ++i) {
642 NOTIMPLEMENTED_LOG_ONCE() << " iteration: " << i;
643 }
644 }
645
TEST(CheckTest,NotImplementedLogOnceWithStreamedParams)646 TEST(CheckTest, NotImplementedLogOnceWithStreamedParams) {
647 static const std::string expected_msg1 =
648 kNotImplementedMessage +
649 "void (anonymous namespace)::NiLogTenTimesWithStream() iteration: 0\n";
650
651 #if DCHECK_IS_ON()
652 // Expect LOG(ERROR) with streamed params intact, exactly once.
653 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
654 base::Location::Current().line_number() - 13,
655 NiLogTenTimesWithStream(), expected_msg1);
656 // A different NOTIMPLEMENTED_LOG_ONCE() call is still logged.
657 static const std::string expected_msg2 =
658 kNotImplementedMessage + __PRETTY_FUNCTION__ + "tree fish\n";
659 EXPECT_LOG_ERROR_WITH_FILENAME(base::Location::Current().file_name(),
660 base::Location::Current().line_number(),
661 NOTIMPLEMENTED_LOG_ONCE() << "tree fish",
662 expected_msg2);
663
664 #else
665 // Expect nothing.
666 EXPECT_NO_LOG(NiLogTenTimesWithStream());
667 EXPECT_NO_LOG(NOTIMPLEMENTED_LOG_ONCE() << "tree fish");
668 #endif
669 }
670
671 // Test CHECK_DEREF of `T*`
TEST(CheckTest,CheckDerefOfPointer)672 TEST(CheckTest, CheckDerefOfPointer) {
673 std::string pointee = "not-null";
674 std::string* value_pointer = &pointee;
675
676 auto& deref_result = CHECK_DEREF(value_pointer);
677 static_assert(std::is_lvalue_reference_v<decltype(deref_result)>);
678 // Compare the pointers to ensure they are the same object (and not a copy)
679 EXPECT_EQ(&deref_result, &pointee);
680 static_assert(std::is_same_v<decltype(deref_result), std::string&>);
681 }
682
TEST(CheckDeathTest,CheckDerefOfNullPointer)683 TEST(CheckDeathTest, CheckDerefOfNullPointer) {
684 std::string* null_pointer = nullptr;
685 EXPECT_CHECK("Check failed: null_pointer != nullptr. ",
686 std::ignore = CHECK_DEREF(null_pointer));
687 }
688
689 // Test CHECK_DEREF of `const T*`
TEST(CheckTest,CheckDerefOfConstPointer)690 TEST(CheckTest, CheckDerefOfConstPointer) {
691 std::string pointee = "not-null";
692 const std::string* const_value_pointer = &pointee;
693
694 auto& deref_result = CHECK_DEREF(const_value_pointer);
695 static_assert(std::is_lvalue_reference_v<decltype(deref_result)>);
696 // Compare the pointers to ensure they are the same object (and not a copy)
697 EXPECT_EQ(&deref_result, &pointee);
698 static_assert(std::is_same_v<decltype(deref_result), const std::string&>);
699 }
700
TEST(CheckDeathTest,CheckDerefOfConstNullPointer)701 TEST(CheckDeathTest, CheckDerefOfConstNullPointer) {
702 std::string* const_null_pointer = nullptr;
703 EXPECT_CHECK("Check failed: const_null_pointer != nullptr. ",
704 std::ignore = CHECK_DEREF(const_null_pointer));
705 }
706
TEST(CheckDeathTest,CheckNotFatalUntil)707 TEST(CheckDeathTest, CheckNotFatalUntil) {
708 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
709 // This specific death test relies on LOGGING_DCHECK not being FATAL, even
710 // when run as part of a death test, as CHECK with a milestone acts like a
711 // DCHECK.
712 ScopedDcheckSeverity dcheck_severity(logging::LOGGING_ERROR);
713 #endif
714
715 // Next milestone not yet fatal.
716 EXPECT_DUMP_WILL_BE_CHECK("Check failed: false. foo",
717 CHECK(false, kNextMilestone) << "foo");
718
719 // Fatal in current major version.
720 EXPECT_CHECK("Check failed: false. foo", CHECK(false, kCurrentMilestone)
721 << "foo");
722 }
723
TEST(CheckDeathTest,CheckOpNotFatalUntil)724 TEST(CheckDeathTest, CheckOpNotFatalUntil) {
725 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
726 // This specific death test relies on LOGGING_DCHECK not being FATAL, even
727 // when run as part of a death test, as CHECK with a milestone acts like a
728 // DCHECK.
729 ScopedDcheckSeverity dcheck_severity(logging::LOGGING_ERROR);
730 #endif
731 const int a = 1, b = 2;
732
733 // Next milestone not yet fatal.
734 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a == b (1 vs. 2)",
735 CHECK_EQ(a, b, kNextMilestone));
736 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a != a (1 vs. 1)",
737 CHECK_NE(a, a, kNextMilestone));
738 EXPECT_DUMP_WILL_BE_CHECK("Check failed: b <= a (2 vs. 1)",
739 CHECK_LE(b, a, kNextMilestone));
740 EXPECT_DUMP_WILL_BE_CHECK("Check failed: b < a (2 vs. 1)",
741 CHECK_LT(b, a, kNextMilestone));
742 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a >= b (1 vs. 2)",
743 CHECK_GE(a, b, kNextMilestone));
744 EXPECT_DUMP_WILL_BE_CHECK("Check failed: a > b (1 vs. 2)",
745 CHECK_GT(a, b, kNextMilestone));
746
747 // Fatal in current major version.
748 EXPECT_CHECK("Check failed: a == b (1 vs. 2)",
749 CHECK_EQ(a, b, kCurrentMilestone));
750 EXPECT_CHECK("Check failed: a != a (1 vs. 1)",
751 CHECK_NE(a, a, kCurrentMilestone));
752 EXPECT_CHECK("Check failed: b <= a (2 vs. 1)",
753 CHECK_LE(b, a, kCurrentMilestone));
754 EXPECT_CHECK("Check failed: b < a (2 vs. 1)",
755 CHECK_LT(b, a, kCurrentMilestone));
756 EXPECT_CHECK("Check failed: a >= b (1 vs. 2)",
757 CHECK_GE(a, b, kCurrentMilestone));
758 EXPECT_CHECK("Check failed: a > b (1 vs. 2)",
759 CHECK_GT(a, b, kCurrentMilestone));
760 }
761
TEST(CheckDeathTest,NotReachedNotFatalUntil)762 TEST(CheckDeathTest, NotReachedNotFatalUntil) {
763 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
764 // This specific death test relies on LOGGING_DCHECK not being FATAL, even
765 // when run as part of a death test, as CHECK with a milestone acts like a
766 // DCHECK.
767 ScopedDcheckSeverity dcheck_severity(logging::LOGGING_ERROR);
768 #endif
769
770 // Next milestone not yet fatal.
771 EXPECT_DUMP_WILL_BE_CHECK("Check failed: false. foo",
772 NOTREACHED(kNextMilestone) << "foo");
773
774 // Fatal in current major version.
775 EXPECT_CHECK("Check failed: false. foo", NOTREACHED(kCurrentMilestone)
776 << "foo");
777 }
778
TEST(CheckDeathTest,CorrectSystemErrorUsed)779 TEST(CheckDeathTest, CorrectSystemErrorUsed) {
780 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
781 // DCHECKs are enabled, and LOGGING_DCHECK is mutable, but defaults to
782 // non-fatal. Set it to LOGGING_FATAL to get the expected behavior from the
783 // rest of this test.
784 ScopedDcheckSeverity dcheck_severity(logging::LOGGING_FATAL);
785 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
786 const logging::SystemErrorCode kTestError = 28;
787 const std::string kExpectedCheckMessageRegex = base::StrCat(
788 {" Check failed: false. ", base::NumberToString(kTestError)});
789 const std::string kExpectedPCheckMessageRegex =
790 base::StrCat({" Check failed: false. ", base::NumberToString(kTestError),
791 ": ", logging::SystemErrorCodeToString(kTestError)});
792 const std::string kExpectedNotreachedMessageRegex =
793 base::StrCat({" NOTREACHED hit. ", base::NumberToString(kTestError)});
794
795 auto set_last_error = [](logging::SystemErrorCode error) {
796 #if BUILDFLAG(IS_WIN)
797 ::SetLastError(error);
798 #else
799 errno = error;
800 #endif
801 };
802
803 // Test that the last system error code was used as expected.
804 set_last_error(kTestError);
805 EXPECT_CHECK(kExpectedCheckMessageRegex,
806 CHECK(false) << logging::GetLastSystemErrorCode());
807
808 set_last_error(kTestError);
809 EXPECT_DCHECK(kExpectedCheckMessageRegex,
810 DCHECK(false) << logging::GetLastSystemErrorCode());
811
812 set_last_error(kTestError);
813 EXPECT_CHECK(kExpectedPCheckMessageRegex,
814 PCHECK(false) << logging::GetLastSystemErrorCode());
815
816 set_last_error(kTestError);
817 EXPECT_DCHECK(kExpectedPCheckMessageRegex,
818 DPCHECK(false) << logging::GetLastSystemErrorCode());
819
820 set_last_error(kTestError);
821 EXPECT_CHECK(kExpectedNotreachedMessageRegex,
822 NOTREACHED() << logging::GetLastSystemErrorCode());
823 }
824
825 } // namespace
826