blob: 6cdc372b290b58a640446891622ff5807e810409 [file] [log] [blame]
Hans Wennborg03c26aeb42020-04-07 10:33:121// 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.
4
5#include "base/bind.h"
6#include "base/callback.h"
7#include "base/logging.h"
8#include "base/strings/string_piece.h"
Hans Wennborg3b72df82020-04-07 20:47:419#include "base/test/gtest_util.h"
Hans Wennborg9bc226d2020-04-08 15:40:0710#include "base/test/scoped_feature_list.h"
Hans Wennborg03c26aeb42020-04-07 10:33:1211#include "build/build_config.h"
12#include "testing/gmock/include/gmock/gmock.h"
13#include "testing/gtest/include/gtest/gtest.h"
14
15namespace {
16
17// Helper class which expects a check to fire with a certain location and
18// message before the end of the current scope.
19class ScopedCheckExpectation {
20 public:
21 ScopedCheckExpectation(const char* file, int line, std::string msg)
22 : file_(file),
23 line_(line),
24 msg_(msg),
25 assert_handler_(base::BindRepeating(&ScopedCheckExpectation::Check,
26 base::Unretained(this))),
27 fired_(false) {}
28 ~ScopedCheckExpectation() {
29 EXPECT_TRUE(fired_) << "CHECK at " << file_ << ":" << line_
30 << " never fired!";
31 }
32
33 private:
34 void Check(const char* file,
35 int line,
36 const base::StringPiece msg,
37 const base::StringPiece stack) {
38 fired_ = true;
39 EXPECT_EQ(file, file_);
40 EXPECT_EQ(line, line_);
41 if (msg_.find("=~") == 0) {
42 EXPECT_THAT(std::string(msg), testing::MatchesRegex(msg_.substr(2)));
43 } else {
44 EXPECT_EQ(std::string(msg), msg_);
45 }
46 }
47
48 std::string file_;
49 int line_;
50 std::string msg_;
51 logging::ScopedLogAssertHandler assert_handler_;
52 bool fired_;
53};
54
55// Macro which expects a CHECK to fire with a certain message. If msg starts
56// with "=~", it's interpreted as a regular expression.
57// Example: EXPECT_CHECK("Check failed: false.", CHECK(false));
58#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
59#define EXPECT_CHECK(msg, check_expr) \
60 do { \
Hans Wennborg3b72df82020-04-07 20:47:4161 EXPECT_CHECK_DEATH(check_expr); \
Hans Wennborg03c26aeb42020-04-07 10:33:1262 } while (0)
63#else
64#define EXPECT_CHECK(msg, check_expr) \
65 do { \
66 ScopedCheckExpectation check_exp(__FILE__, __LINE__, msg); \
67 check_expr; \
68 } while (0)
69#endif
70
71// Macro which expects a DCHECK to fire if DCHECKs are enabled.
72#define EXPECT_DCHECK(msg, check_expr) \
73 do { \
74 if (DCHECK_IS_ON() && logging::LOG_DCHECK == logging::LOG_FATAL) { \
75 ScopedCheckExpectation check_exp(__FILE__, __LINE__, msg); \
76 check_expr; \
77 } else { \
78 check_expr; \
79 } \
80 } while (0)
81
82class CheckTest : public testing::Test {};
83
84TEST_F(CheckTest, Basics) {
85 EXPECT_CHECK("Check failed: false. ", CHECK(false));
86
87 EXPECT_CHECK("Check failed: false. foo", CHECK(false) << "foo");
88
89 double a = 2, b = 1;
90 EXPECT_CHECK("Check failed: a < b (2 vs. 1)", CHECK_LT(a, b));
91
92 EXPECT_CHECK("Check failed: a < b (2 vs. 1)foo", CHECK_LT(a, b) << "foo");
93}
94
95TEST_F(CheckTest, PCheck) {
96 const char file[] = "/nonexistentfile123";
97 ignore_result(fopen(file, "r"));
98 std::string err =
99 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
100
101 EXPECT_CHECK(
102 "Check failed: fopen(file, \"r\") != nullptr."
103 " : " +
104 err,
105 PCHECK(fopen(file, "r") != nullptr));
106
107 EXPECT_CHECK(
108 "Check failed: fopen(file, \"r\") != nullptr."
109 " foo: " +
110 err,
111 PCHECK(fopen(file, "r") != nullptr) << "foo");
112
113 EXPECT_DCHECK(
114 "Check failed: fopen(file, \"r\") != nullptr."
115 " : " +
116 err,
117 DPCHECK(fopen(file, "r") != nullptr));
118
119 EXPECT_DCHECK(
120 "Check failed: fopen(file, \"r\") != nullptr."
121 " foo: " +
122 err,
123 DPCHECK(fopen(file, "r") != nullptr) << "foo");
124}
125
126TEST_F(CheckTest, CheckOp) {
127 int a = 1, b = 2;
128 // clang-format off
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));
135
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));
142 // clang-format on
143}
144
145TEST_F(CheckTest, CheckStreamsAreLazy) {
146 int called_count = 0;
147 int not_called_count = 0;
148
149 auto Called = [&]() {
150 ++called_count;
151 return 42;
152 };
153 auto NotCalled = [&]() {
154 ++not_called_count;
155 return 42;
156 };
157
158 CHECK(Called()) << NotCalled();
159 CHECK_EQ(Called(), Called()) << NotCalled();
160 PCHECK(Called()) << NotCalled();
161
162 DCHECK(Called()) << NotCalled();
163 DCHECK_EQ(Called(), Called()) << NotCalled();
164 DPCHECK(Called()) << NotCalled();
165
166 EXPECT_EQ(not_called_count, 0);
167#if DCHECK_IS_ON()
168 EXPECT_EQ(called_count, 8);
169#else
170 EXPECT_EQ(called_count, 4);
171#endif
172}
173
174void 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";
179}
180void DcheckEmptyFunction2() {}
181
182#if defined(DCHECK_IS_CONFIGURABLE)
183class ScopedDcheckSeverity {
184 public:
Hans Wennborg9bc226d2020-04-08 15:40:07185 ScopedDcheckSeverity(logging::LogSeverity new_severity)
186 : old_severity_(logging::LOG_DCHECK) {
187 logging::LOG_DCHECK = new_severity;
Hans Wennborg03c26aeb42020-04-07 10:33:12188 }
189
Hans Wennborg9bc226d2020-04-08 15:40:07190 ~ScopedDcheckSeverity() { logging::LOG_DCHECK = old_severity_; }
Hans Wennborg03c26aeb42020-04-07 10:33:12191
192 private:
Hans Wennborg9bc226d2020-04-08 15:40:07193 logging::LogSeverity old_severity_;
Hans Wennborg03c26aeb42020-04-07 10:33:12194};
195#endif // defined(DCHECK_IS_CONFIGURABLE)
196
197// https://crbug.com/709067 tracks test flakiness on iOS.
198#if defined(OS_IOS)
199#define MAYBE_Dcheck DISABLED_Dcheck
200#else
201#define MAYBE_Dcheck Dcheck
202#endif
203TEST_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
207 // test.
Hans Wennborg9bc226d2020-04-08 15:40:07208 ScopedDcheckSeverity dcheck_severity(logging::LOG_FATAL);
Hans Wennborg03c26aeb42020-04-07 10:33:12209#endif // defined(DCHECK_IS_CONFIGURABLE)
210
211#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
212 // Release build.
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));
219#else
220 // Debug build.
221 EXPECT_TRUE(DCHECK_IS_ON());
222 EXPECT_TRUE(DLOG_IS_ON(DCHECK));
223#endif
224
225 EXPECT_DCHECK("Check failed: false. ", DCHECK(false));
226 std::string err =
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));
230
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);
238
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));
244
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.";
250 }
251 void MemberFunction2() {}
252 };
253 void (MemberFunctions::*mp1)() = &MemberFunctions::MemberFunction1;
254 void (MemberFunctions::*mp2)() = &MemberFunctions::MemberFunction2;
255 void (*fp1)() = DcheckEmptyFunction1;
256 void (*fp2)() = DcheckEmptyFunction2;
257 void (*fp3)() = DcheckEmptyFunction1;
258 DCHECK_EQ(fp1, fp3);
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));
263 EXPECT_DCHECK(
264 "Check failed: mp2 == &MemberFunctions::MemberFunction1 (1 vs. 1)",
265 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction1));
266}
267
268TEST_F(CheckTest, DcheckReleaseBehavior) {
269 int var1 = 1;
270 int var2 = 2;
271 int var3 = 3;
272 int var4 = 4;
273
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;
279}
280
281TEST_F(CheckTest, DCheckEqStatements) {
282 bool reached = false;
283 if (false)
284 DCHECK_EQ(false, true); // Unreached.
285 else
286 DCHECK_EQ(true, reached = true); // Reached, passed.
287 ASSERT_EQ(DCHECK_IS_ON() ? true : false, reached);
288
289 if (false)
290 DCHECK_EQ(false, true); // Unreached.
291}
292
293TEST_F(CheckTest, CheckEqStatements) {
294 bool reached = false;
295 if (false)
296 CHECK_EQ(false, true); // Unreached.
297 else
298 CHECK_EQ(true, reached = true); // Reached, passed.
299 ASSERT_TRUE(reached);
300
301 if (false)
302 CHECK_EQ(false, true); // Unreached.
303}
304
305#if defined(DCHECK_IS_CONFIGURABLE)
306TEST_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.
Hans Wennborg9bc226d2020-04-08 15:40:07310 EXPECT_LT(logging::LOG_DCHECK, logging::LOG_FATAL);
Hans Wennborg03c26aeb42020-04-07 10:33:12311 DCHECK(false);
312
313 // Verify that DCHECK* aren't hard-wired to crash on failure.
Hans Wennborg9bc226d2020-04-08 15:40:07314 logging::LOG_DCHECK = logging::LOG_INFO;
Hans Wennborg03c26aeb42020-04-07 10:33:12315 DCHECK(false);
316 DCHECK_EQ(1, 2);
317
318 // Verify that DCHECK does crash if LOG_DCHECK is set to LOG_FATAL.
Hans Wennborg9bc226d2020-04-08 15:40:07319 logging::LOG_DCHECK = logging::LOG_FATAL;
Hans Wennborg03c26aeb42020-04-07 10:33:12320 EXPECT_CHECK("Check failed: false. ", DCHECK(false));
321 EXPECT_CHECK("Check failed: 1 == 2 (1 vs. 2)", DCHECK_EQ(1, 2));
322}
323
324TEST_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.
328
329 {
330 base::test::ScopedFeatureList feature_list;
331 feature_list.InitFromCommandLine("DcheckIsFatal", "");
Hans Wennborg9bc226d2020-04-08 15:40:07332 EXPECT_EQ(logging::LOG_DCHECK, logging::LOG_FATAL);
Hans Wennborg03c26aeb42020-04-07 10:33:12333 }
334
335 {
336 base::test::ScopedFeatureList feature_list;
337 feature_list.InitFromCommandLine("", "DcheckIsFatal");
Hans Wennborg9bc226d2020-04-08 15:40:07338 EXPECT_LT(logging::LOG_DCHECK, logging::LOG_FATAL);
Hans Wennborg03c26aeb42020-04-07 10:33:12339 }
340
341 // The default case is last, so we leave LOG_DCHECK in the default state.
342 {
343 base::test::ScopedFeatureList feature_list;
344 feature_list.InitFromCommandLine("", "");
Hans Wennborg9bc226d2020-04-08 15:40:07345 EXPECT_LT(logging::LOG_DCHECK, logging::LOG_FATAL);
Hans Wennborg03c26aeb42020-04-07 10:33:12346 }
347}
348#endif // defined(DCHECK_IS_CONFIGURABLE)
349
350struct StructWithOstream {
351 bool operator==(const StructWithOstream& o) const { return &o == this; }
352};
353#if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
354std::ostream& operator<<(std::ostream& out, const StructWithOstream&) {
355 return out << "ostream";
356}
357#endif
358
359struct StructWithToString {
360 bool operator==(const StructWithToString& o) const { return &o == this; }
361 std::string ToString() const { return "ToString"; }
362};
363
364struct StructWithToStringAndOstream {
365 bool operator==(const StructWithToStringAndOstream& o) const {
366 return &o == this;
367 }
368 std::string ToString() const { return "ToString"; }
369};
370#if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
371std::ostream& operator<<(std::ostream& out,
372 const StructWithToStringAndOstream&) {
373 return out << "ostream";
374}
375#endif
376
377TEST_F(CheckTest, OstreamVsToString) {
378 StructWithOstream a, b;
379 EXPECT_CHECK("Check failed: a == b (ostream vs. ostream)", CHECK_EQ(a, b));
380
381 StructWithToString c, d;
382 EXPECT_CHECK("Check failed: c == d (ToString vs. ToString)", CHECK_EQ(c, d));
383
384 StructWithToStringAndOstream e, f;
385 EXPECT_CHECK("Check failed: e == f (ostream vs. ostream)", CHECK_EQ(e, f));
386}
387
388} // namespace