1 // Copyright (c) 2020 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 #include "base/callback.h"
7 #include "base/logging.h"
8 #include "base/strings/string_piece.h"
9 #include "base/test/gtest_util.h"
10 #include "base/test/scoped_feature_list.h"
11 #include "testing/gmock/include/gmock/gmock.h"
12 #include "testing/gtest/include/gtest/gtest.h"
16 // Helper class which expects a check to fire with a certain location and
17 // message before the end of the current scope.
18 class ScopedCheckExpectation {
20 ScopedCheckExpectation(const char* file, int line, std::string msg)
24 assert_handler_(base::BindRepeating(&ScopedCheckExpectation::Check,
25 base::Unretained(this))),
27 ~ScopedCheckExpectation() {
28 EXPECT_TRUE(fired_) << "CHECK at " << file_ << ":" << line_
33 void Check(const char* file,
35 const base::StringPiece msg,
36 const base::StringPiece stack) {
38 EXPECT_EQ(file, file_);
39 EXPECT_EQ(line, line_);
40 if (msg_.find("=~") == 0) {
41 EXPECT_THAT(std::string(msg), testing::MatchesRegex(msg_.substr(2)));
43 EXPECT_EQ(std::string(msg), msg_);
50 logging::ScopedLogAssertHandler assert_handler_;
54 // Macro which expects a CHECK to fire with a certain message. If msg starts
55 // with "=~", it's interpreted as a regular expression.
56 // Example: EXPECT_CHECK("Check failed: false.", CHECK(false));
57 #if defined(OFFICIAL_BUILD) && defined(NDEBUG)
58 #define EXPECT_CHECK(msg, check_expr) \
60 EXPECT_CHECK_DEATH(check_expr); \
63 #define EXPECT_CHECK(msg, check_expr) \
65 ScopedCheckExpectation check_exp(__FILE__, __LINE__, msg); \
70 // Macro which expects a DCHECK to fire if DCHECKs are enabled.
71 #define EXPECT_DCHECK(msg, check_expr) \
73 if (DCHECK_IS_ON() && logging::LOG_DCHECK == logging::LOG_FATAL) { \
74 ScopedCheckExpectation check_exp(__FILE__, __LINE__, msg); \
81 class CheckTest : public testing::Test {};
83 TEST_F(CheckTest, Basics) {
84 EXPECT_CHECK("Check failed: false. ", CHECK(false));
86 EXPECT_CHECK("Check failed: false. foo", CHECK(false) << "foo");
89 EXPECT_CHECK("Check failed: a < b (2.000000 vs. 1.000000)", CHECK_LT(a, b));
91 EXPECT_CHECK("Check failed: a < b (2.000000 vs. 1.000000)foo",
92 CHECK_LT(a, b) << "foo");
95 TEST_F(CheckTest, PCheck) {
96 const char file[] = "/nonexistentfile123";
97 ignore_result(fopen(file, "r"));
99 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
102 "Check failed: fopen(file, \"r\") != nullptr."
105 PCHECK(fopen(file, "r") != nullptr));
108 "Check failed: fopen(file, \"r\") != nullptr."
111 PCHECK(fopen(file, "r") != nullptr) << "foo");
114 "Check failed: fopen(file, \"r\") != nullptr."
117 DPCHECK(fopen(file, "r") != nullptr));
120 "Check failed: fopen(file, \"r\") != nullptr."
123 DPCHECK(fopen(file, "r") != nullptr) << "foo");
126 TEST_F(CheckTest, CheckOp) {
129 EXPECT_CHECK("Check failed: a == b (1 vs. 2)", CHECK_EQ(a, b));
130 EXPECT_CHECK("Check failed: a != a (1 vs. 1)", CHECK_NE(a, a));
131 EXPECT_CHECK("Check failed: b <= a (2 vs. 1)", CHECK_LE(b, a));
132 EXPECT_CHECK("Check failed: b < a (2 vs. 1)", CHECK_LT(b, a));
133 EXPECT_CHECK("Check failed: a >= b (1 vs. 2)", CHECK_GE(a, b));
134 EXPECT_CHECK("Check failed: a > b (1 vs. 2)", CHECK_GT(a, b));
136 EXPECT_DCHECK("Check failed: a == b (1 vs. 2)", DCHECK_EQ(a, b));
137 EXPECT_DCHECK("Check failed: a != a (1 vs. 1)", DCHECK_NE(a, a));
138 EXPECT_DCHECK("Check failed: b <= a (2 vs. 1)", DCHECK_LE(b, a));
139 EXPECT_DCHECK("Check failed: b < a (2 vs. 1)", DCHECK_LT(b, a));
140 EXPECT_DCHECK("Check failed: a >= b (1 vs. 2)", DCHECK_GE(a, b));
141 EXPECT_DCHECK("Check failed: a > b (1 vs. 2)", DCHECK_GT(a, b));
145 TEST_F(CheckTest, CheckStreamsAreLazy) {
146 int called_count = 0;
147 int not_called_count = 0;
149 auto Called = [&]() {
153 auto NotCalled = [&]() {
158 CHECK(Called()) << NotCalled();
159 CHECK_EQ(Called(), Called()) << NotCalled();
160 PCHECK(Called()) << NotCalled();
162 DCHECK(Called()) << NotCalled();
163 DCHECK_EQ(Called(), Called()) << NotCalled();
164 DPCHECK(Called()) << NotCalled();
166 EXPECT_EQ(not_called_count, 0);
168 EXPECT_EQ(called_count, 8);
170 EXPECT_EQ(called_count, 4);
174 void DcheckEmptyFunction1() {
175 // Provide a body so that Release builds do not cause the compiler to
176 // optimize DcheckEmptyFunction1 and DcheckEmptyFunction2 as a single
177 // function, which breaks the Dcheck tests below.
178 LOG(INFO) << "DcheckEmptyFunction1";
180 void DcheckEmptyFunction2() {}
182 #if defined(DCHECK_IS_CONFIGURABLE)
183 class ScopedDcheckSeverity {
185 ScopedDcheckSeverity(logging::LogSeverity new_severity)
186 : old_severity_(logging::LOG_DCHECK) {
187 logging::LOG_DCHECK = new_severity;
190 ~ScopedDcheckSeverity() { logging::LOG_DCHECK = old_severity_; }
193 logging::LogSeverity old_severity_;
195 #endif // defined(DCHECK_IS_CONFIGURABLE)
197 // https://crbug.com/709067 tracks test flakiness on iOS.
199 #define MAYBE_Dcheck DISABLED_Dcheck
201 #define MAYBE_Dcheck Dcheck
203 TEST_F(CheckTest, MAYBE_Dcheck) {
204 #if defined(DCHECK_IS_CONFIGURABLE)
205 // DCHECKs are enabled, and LOG_DCHECK is mutable, but defaults to non-fatal.
206 // Set it to LOG_FATAL to get the expected behavior from the rest of this
208 ScopedDcheckSeverity dcheck_severity(logging::LOG_FATAL);
209 #endif // defined(DCHECK_IS_CONFIGURABLE)
211 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
213 EXPECT_FALSE(DCHECK_IS_ON());
214 EXPECT_FALSE(DLOG_IS_ON(DCHECK));
215 #elif defined(NDEBUG) && defined(DCHECK_ALWAYS_ON)
216 // Release build with real DCHECKS.
217 EXPECT_TRUE(DCHECK_IS_ON());
218 EXPECT_TRUE(DLOG_IS_ON(DCHECK));
221 EXPECT_TRUE(DCHECK_IS_ON());
222 EXPECT_TRUE(DLOG_IS_ON(DCHECK));
225 EXPECT_DCHECK("Check failed: false. ", DCHECK(false));
227 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
228 EXPECT_DCHECK("Check failed: false. : " + err, DPCHECK(false));
229 EXPECT_DCHECK("Check failed: 0 == 1 (0 vs. 1)", DCHECK_EQ(0, 1));
231 // Test DCHECK on std::nullptr_t
232 const void* p_null = nullptr;
233 const void* p_not_null = &p_null;
234 DCHECK_EQ(p_null, nullptr);
235 DCHECK_EQ(nullptr, p_null);
236 DCHECK_NE(p_not_null, nullptr);
237 DCHECK_NE(nullptr, p_not_null);
239 // Test DCHECK on a scoped enum.
240 enum class Animal { DOG, CAT };
241 DCHECK_EQ(Animal::DOG, Animal::DOG);
242 EXPECT_DCHECK("Check failed: Animal::DOG == Animal::CAT (0 vs. 1)",
243 DCHECK_EQ(Animal::DOG, Animal::CAT));
245 // Test DCHECK on functions and function pointers.
246 struct MemberFunctions {
247 void MemberFunction1() {
248 // See the comment in DcheckEmptyFunction1().
249 LOG(INFO) << "Do not merge with MemberFunction2.";
251 void MemberFunction2() {}
253 void (MemberFunctions::*mp1)() = &MemberFunctions::MemberFunction1;
254 void (MemberFunctions::*mp2)() = &MemberFunctions::MemberFunction2;
255 void (*fp1)() = DcheckEmptyFunction1;
256 void (*fp2)() = DcheckEmptyFunction2;
257 void (*fp3)() = DcheckEmptyFunction1;
259 DCHECK_EQ(mp1, &MemberFunctions::MemberFunction1);
260 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction2);
261 EXPECT_DCHECK("=~Check failed: fp1 == fp2 \\(\\w+ vs. \\w+\\)",
262 DCHECK_EQ(fp1, fp2));
264 "Check failed: mp2 == &MemberFunctions::MemberFunction1 (1 vs. 1)",
265 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction1));
268 TEST_F(CheckTest, DcheckReleaseBehavior) {
274 // No warnings about unused variables even though no check fires and DCHECK
275 // may or may not be enabled.
276 DCHECK(var1) << var2;
277 DPCHECK(var1) << var3;
278 DCHECK_EQ(var1, 1) << var4;
281 TEST_F(CheckTest, DCheckEqStatements) {
282 bool reached = false;
284 DCHECK_EQ(false, true); // Unreached.
286 DCHECK_EQ(true, reached = true); // Reached, passed.
287 ASSERT_EQ(DCHECK_IS_ON() ? true : false, reached);
290 DCHECK_EQ(false, true); // Unreached.
293 TEST_F(CheckTest, CheckEqStatements) {
294 bool reached = false;
296 CHECK_EQ(false, true); // Unreached.
298 CHECK_EQ(true, reached = true); // Reached, passed.
299 ASSERT_TRUE(reached);
302 CHECK_EQ(false, true); // Unreached.
305 #if defined(DCHECK_IS_CONFIGURABLE)
306 TEST_F(CheckTest, ConfigurableDCheck) {
307 // Verify that DCHECKs default to non-fatal in configurable-DCHECK builds.
308 // Note that we require only that DCHECK is non-fatal by default, rather
309 // than requiring that it be exactly INFO, ERROR, etc level.
310 EXPECT_LT(logging::LOG_DCHECK, logging::LOG_FATAL);
313 // Verify that DCHECK* aren't hard-wired to crash on failure.
314 logging::LOG_DCHECK = logging::LOG_INFO;
318 // Verify that DCHECK does crash if LOG_DCHECK is set to LOG_FATAL.
319 logging::LOG_DCHECK = logging::LOG_FATAL;
320 EXPECT_CHECK("Check failed: false. ", DCHECK(false));
321 EXPECT_CHECK("Check failed: 1 == 2 (1 vs. 2)", DCHECK_EQ(1, 2));
324 TEST_F(CheckTest, ConfigurableDCheckFeature) {
325 // Initialize FeatureList with and without DcheckIsFatal, and verify the
326 // value of LOG_DCHECK. Note that we don't require that DCHECK take a
327 // specific value when the feature is off, only that it is non-fatal.
330 base::test::ScopedFeatureList feature_list;
331 feature_list.InitFromCommandLine("DcheckIsFatal", "");
332 EXPECT_EQ(logging::LOG_DCHECK, logging::LOG_FATAL);
336 base::test::ScopedFeatureList feature_list;
337 feature_list.InitFromCommandLine("", "DcheckIsFatal");
338 EXPECT_LT(logging::LOG_DCHECK, logging::LOG_FATAL);
341 // The default case is last, so we leave LOG_DCHECK in the default state.
343 base::test::ScopedFeatureList feature_list;
344 feature_list.InitFromCommandLine("", "");
345 EXPECT_LT(logging::LOG_DCHECK, logging::LOG_FATAL);
348 #endif // defined(DCHECK_IS_CONFIGURABLE)
350 struct StructWithOstream {
351 bool operator==(const StructWithOstream& o) const { return &o == this; }
353 #if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
354 std::ostream& operator<<(std::ostream& out, const StructWithOstream&) {
355 return out << "ostream";
359 struct StructWithToString {
360 bool operator==(const StructWithToString& o) const { return &o == this; }
361 std::string ToString() const { return "ToString"; }
364 struct StructWithToStringAndOstream {
365 bool operator==(const StructWithToStringAndOstream& o) const {
368 std::string ToString() const { return "ToString"; }
370 #if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
371 std::ostream& operator<<(std::ostream& out,
372 const StructWithToStringAndOstream&) {
373 return out << "ostream";
377 struct StructWithToStringNotStdString {
378 struct PseudoString {};
380 bool operator==(const StructWithToStringNotStdString& o) const {
383 PseudoString ToString() const { return PseudoString(); }
385 #if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
386 std::ostream& operator<<(std::ostream& out,
387 const StructWithToStringNotStdString::PseudoString&) {
388 return out << "ToString+ostream";
392 TEST_F(CheckTest, OstreamVsToString) {
393 StructWithOstream a, b;
394 EXPECT_CHECK("Check failed: a == b (ostream vs. ostream)", CHECK_EQ(a, b));
396 StructWithToString c, d;
397 EXPECT_CHECK("Check failed: c == d (ToString vs. ToString)", CHECK_EQ(c, d));
399 StructWithToStringAndOstream e, f;
400 EXPECT_CHECK("Check failed: e == f (ostream vs. ostream)", CHECK_EQ(e, f));
402 StructWithToStringNotStdString g, h;
403 EXPECT_CHECK("Check failed: g == h (ToString+ostream vs. ToString+ostream)",
407 #define EXPECT_LOG_ERROR(msg, expr, expected_line) \
409 static bool got_log_message = false; \
410 ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \
411 logging::SetLogMessageHandler([](int severity, const char* file, int line, \
412 size_t message_start, \
413 const std::string& str) { \
414 EXPECT_FALSE(got_log_message); \
415 got_log_message = true; \
416 EXPECT_EQ(severity, logging::LOG_ERROR); \
417 EXPECT_EQ(str.substr(message_start), (msg)); \
418 EXPECT_STREQ(__FILE__, file); \
419 EXPECT_EQ(expected_line, line); \
423 EXPECT_TRUE(got_log_message); \
424 logging::SetLogMessageHandler(nullptr); \
427 #define EXPECT_NO_LOG(expr) \
429 ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \
430 logging::SetLogMessageHandler([](int severity, const char* file, int line, \
431 size_t message_start, \
432 const std::string& str) { \
433 EXPECT_TRUE(false) << "Unexpected log: " << str; \
437 logging::SetLogMessageHandler(nullptr); \
440 TEST_F(CheckTest, NotReached) {
441 #if BUILDFLAG(ENABLE_LOG_ERROR_NOT_REACHED)
442 // Expect LOG(ERROR) without the streamed params.
443 EXPECT_LOG_ERROR("NOTREACHED() hit.\n", NOTREACHED() << "foo", __LINE__);
445 // Expect a DCHECK with streamed params intact.
446 EXPECT_DCHECK("Check failed: false. foo", NOTREACHED() << "foo");
450 TEST_F(CheckTest, NotImplemented) {
451 static const std::string expected_msg =
452 std::string("Not implemented reached in ") + __PRETTY_FUNCTION__;
455 // Expect LOG(ERROR) with streamed params intact.
456 EXPECT_LOG_ERROR(expected_msg + "foo\n", NOTIMPLEMENTED() << "foo", __LINE__);
459 EXPECT_NO_LOG(NOTIMPLEMENTED() << "foo");
464 // Note: The stream param is not logged.
465 NOTIMPLEMENTED_LOG_ONCE() << "foo";
468 TEST_F(CheckTest, NotImplementedLogOnce) {
469 static const std::string expected_msg =
470 "Not implemented reached in void (anonymous namespace)::NiLogOnce()\n";
473 EXPECT_LOG_ERROR(expected_msg, NiLogOnce(), __LINE__ - 8);
474 EXPECT_NO_LOG(NiLogOnce());
476 EXPECT_NO_LOG(NiLogOnce());
477 EXPECT_NO_LOG(NiLogOnce());