blob: 8f7095f8dba1f445ad2d58a91174bbd72e382e76 [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 Wennborg03c26aeb42020-04-07 10:33:1210#include "build/build_config.h"
11#include "testing/gmock/include/gmock/gmock.h"
12#include "testing/gtest/include/gtest/gtest.h"
13
14namespace {
15
16// Helper class which expects a check to fire with a certain location and
17// message before the end of the current scope.
18class ScopedCheckExpectation {
19 public:
20 ScopedCheckExpectation(const char* file, int line, std::string msg)
21 : file_(file),
22 line_(line),
23 msg_(msg),
24 assert_handler_(base::BindRepeating(&ScopedCheckExpectation::Check,
25 base::Unretained(this))),
26 fired_(false) {}
27 ~ScopedCheckExpectation() {
28 EXPECT_TRUE(fired_) << "CHECK at " << file_ << ":" << line_
29 << " never fired!";
30 }
31
32 private:
33 void Check(const char* file,
34 int line,
35 const base::StringPiece msg,
36 const base::StringPiece stack) {
37 fired_ = true;
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)));
42 } else {
43 EXPECT_EQ(std::string(msg), msg_);
44 }
45 }
46
47 std::string file_;
48 int line_;
49 std::string msg_;
50 logging::ScopedLogAssertHandler assert_handler_;
51 bool fired_;
52};
53
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) \
59 do { \
Hans Wennborg3b72df82020-04-07 20:47:4160 EXPECT_CHECK_DEATH(check_expr); \
Hans Wennborg03c26aeb42020-04-07 10:33:1261 } while (0)
62#else
63#define EXPECT_CHECK(msg, check_expr) \
64 do { \
65 ScopedCheckExpectation check_exp(__FILE__, __LINE__, msg); \
66 check_expr; \
67 } while (0)
68#endif
69
70// Macro which expects a DCHECK to fire if DCHECKs are enabled.
71#define EXPECT_DCHECK(msg, check_expr) \
72 do { \
73 if (DCHECK_IS_ON() && logging::LOG_DCHECK == logging::LOG_FATAL) { \
74 ScopedCheckExpectation check_exp(__FILE__, __LINE__, msg); \
75 check_expr; \
76 } else { \
77 check_expr; \
78 } \
79 } while (0)
80
81class CheckTest : public testing::Test {};
82
83TEST_F(CheckTest, Basics) {
84 EXPECT_CHECK("Check failed: false. ", CHECK(false));
85
86 EXPECT_CHECK("Check failed: false. foo", CHECK(false) << "foo");
87
88 double a = 2, b = 1;
89 EXPECT_CHECK("Check failed: a < b (2 vs. 1)", CHECK_LT(a, b));
90
91 EXPECT_CHECK("Check failed: a < b (2 vs. 1)foo", CHECK_LT(a, b) << "foo");
92}
93
94TEST_F(CheckTest, PCheck) {
95 const char file[] = "/nonexistentfile123";
96 ignore_result(fopen(file, "r"));
97 std::string err =
98 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
99
100 EXPECT_CHECK(
101 "Check failed: fopen(file, \"r\") != nullptr."
102 " : " +
103 err,
104 PCHECK(fopen(file, "r") != nullptr));
105
106 EXPECT_CHECK(
107 "Check failed: fopen(file, \"r\") != nullptr."
108 " foo: " +
109 err,
110 PCHECK(fopen(file, "r") != nullptr) << "foo");
111
112 EXPECT_DCHECK(
113 "Check failed: fopen(file, \"r\") != nullptr."
114 " : " +
115 err,
116 DPCHECK(fopen(file, "r") != nullptr));
117
118 EXPECT_DCHECK(
119 "Check failed: fopen(file, \"r\") != nullptr."
120 " foo: " +
121 err,
122 DPCHECK(fopen(file, "r") != nullptr) << "foo");
123}
124
125TEST_F(CheckTest, CheckOp) {
126 int a = 1, b = 2;
127 // clang-format off
128 EXPECT_CHECK("Check failed: a == b (1 vs. 2)", CHECK_EQ(a, b));
129 EXPECT_CHECK("Check failed: a != a (1 vs. 1)", CHECK_NE(a, a));
130 EXPECT_CHECK("Check failed: b <= a (2 vs. 1)", CHECK_LE(b, a));
131 EXPECT_CHECK("Check failed: b < a (2 vs. 1)", CHECK_LT(b, a));
132 EXPECT_CHECK("Check failed: a >= b (1 vs. 2)", CHECK_GE(a, b));
133 EXPECT_CHECK("Check failed: a > b (1 vs. 2)", CHECK_GT(a, b));
134
135 EXPECT_DCHECK("Check failed: a == b (1 vs. 2)", DCHECK_EQ(a, b));
136 EXPECT_DCHECK("Check failed: a != a (1 vs. 1)", DCHECK_NE(a, a));
137 EXPECT_DCHECK("Check failed: b <= a (2 vs. 1)", DCHECK_LE(b, a));
138 EXPECT_DCHECK("Check failed: b < a (2 vs. 1)", DCHECK_LT(b, a));
139 EXPECT_DCHECK("Check failed: a >= b (1 vs. 2)", DCHECK_GE(a, b));
140 EXPECT_DCHECK("Check failed: a > b (1 vs. 2)", DCHECK_GT(a, b));
141 // clang-format on
142}
143
144TEST_F(CheckTest, CheckStreamsAreLazy) {
145 int called_count = 0;
146 int not_called_count = 0;
147
148 auto Called = [&]() {
149 ++called_count;
150 return 42;
151 };
152 auto NotCalled = [&]() {
153 ++not_called_count;
154 return 42;
155 };
156
157 CHECK(Called()) << NotCalled();
158 CHECK_EQ(Called(), Called()) << NotCalled();
159 PCHECK(Called()) << NotCalled();
160
161 DCHECK(Called()) << NotCalled();
162 DCHECK_EQ(Called(), Called()) << NotCalled();
163 DPCHECK(Called()) << NotCalled();
164
165 EXPECT_EQ(not_called_count, 0);
166#if DCHECK_IS_ON()
167 EXPECT_EQ(called_count, 8);
168#else
169 EXPECT_EQ(called_count, 4);
170#endif
171}
172
173void DcheckEmptyFunction1() {
174 // Provide a body so that Release builds do not cause the compiler to
175 // optimize DcheckEmptyFunction1 and DcheckEmptyFunction2 as a single
176 // function, which breaks the Dcheck tests below.
177 LOG(INFO) << "DcheckEmptyFunction1";
178}
179void DcheckEmptyFunction2() {}
180
181#if defined(DCHECK_IS_CONFIGURABLE)
182class ScopedDcheckSeverity {
183 public:
184 ScopedDcheckSeverity(LogSeverity new_severity) : old_severity_(LOG_DCHECK) {
185 LOG_DCHECK = new_severity;
186 }
187
188 ~ScopedDcheckSeverity() { LOG_DCHECK = old_severity_; }
189
190 private:
191 LogSeverity old_severity_;
192};
193#endif // defined(DCHECK_IS_CONFIGURABLE)
194
195// https://crbug.com/709067 tracks test flakiness on iOS.
196#if defined(OS_IOS)
197#define MAYBE_Dcheck DISABLED_Dcheck
198#else
199#define MAYBE_Dcheck Dcheck
200#endif
201TEST_F(CheckTest, MAYBE_Dcheck) {
202#if defined(DCHECK_IS_CONFIGURABLE)
203 // DCHECKs are enabled, and LOG_DCHECK is mutable, but defaults to non-fatal.
204 // Set it to LOG_FATAL to get the expected behavior from the rest of this
205 // test.
206 ScopedDcheckSeverity dcheck_severity(LOG_FATAL);
207#endif // defined(DCHECK_IS_CONFIGURABLE)
208
209#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
210 // Release build.
211 EXPECT_FALSE(DCHECK_IS_ON());
212 EXPECT_FALSE(DLOG_IS_ON(DCHECK));
213#elif defined(NDEBUG) && defined(DCHECK_ALWAYS_ON)
214 // Release build with real DCHECKS.
215 EXPECT_TRUE(DCHECK_IS_ON());
216 EXPECT_TRUE(DLOG_IS_ON(DCHECK));
217#else
218 // Debug build.
219 EXPECT_TRUE(DCHECK_IS_ON());
220 EXPECT_TRUE(DLOG_IS_ON(DCHECK));
221#endif
222
223 EXPECT_DCHECK("Check failed: false. ", DCHECK(false));
224 std::string err =
225 logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
226 EXPECT_DCHECK("Check failed: false. : " + err, DPCHECK(false));
227 EXPECT_DCHECK("Check failed: 0 == 1 (0 vs. 1)", DCHECK_EQ(0, 1));
228
229 // Test DCHECK on std::nullptr_t
230 const void* p_null = nullptr;
231 const void* p_not_null = &p_null;
232 DCHECK_EQ(p_null, nullptr);
233 DCHECK_EQ(nullptr, p_null);
234 DCHECK_NE(p_not_null, nullptr);
235 DCHECK_NE(nullptr, p_not_null);
236
237 // Test DCHECK on a scoped enum.
238 enum class Animal { DOG, CAT };
239 DCHECK_EQ(Animal::DOG, Animal::DOG);
240 EXPECT_DCHECK("Check failed: Animal::DOG == Animal::CAT (0 vs. 1)",
241 DCHECK_EQ(Animal::DOG, Animal::CAT));
242
243 // Test DCHECK on functions and function pointers.
244 struct MemberFunctions {
245 void MemberFunction1() {
246 // See the comment in DcheckEmptyFunction1().
247 LOG(INFO) << "Do not merge with MemberFunction2.";
248 }
249 void MemberFunction2() {}
250 };
251 void (MemberFunctions::*mp1)() = &MemberFunctions::MemberFunction1;
252 void (MemberFunctions::*mp2)() = &MemberFunctions::MemberFunction2;
253 void (*fp1)() = DcheckEmptyFunction1;
254 void (*fp2)() = DcheckEmptyFunction2;
255 void (*fp3)() = DcheckEmptyFunction1;
256 DCHECK_EQ(fp1, fp3);
257 DCHECK_EQ(mp1, &MemberFunctions::MemberFunction1);
258 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction2);
259 EXPECT_DCHECK("=~Check failed: fp1 == fp2 \\(\\w+ vs. \\w+\\)",
260 DCHECK_EQ(fp1, fp2));
261 EXPECT_DCHECK(
262 "Check failed: mp2 == &MemberFunctions::MemberFunction1 (1 vs. 1)",
263 DCHECK_EQ(mp2, &MemberFunctions::MemberFunction1));
264}
265
266TEST_F(CheckTest, DcheckReleaseBehavior) {
267 int var1 = 1;
268 int var2 = 2;
269 int var3 = 3;
270 int var4 = 4;
271
272 // No warnings about unused variables even though no check fires and DCHECK
273 // may or may not be enabled.
274 DCHECK(var1) << var2;
275 DPCHECK(var1) << var3;
276 DCHECK_EQ(var1, 1) << var4;
277}
278
279TEST_F(CheckTest, DCheckEqStatements) {
280 bool reached = false;
281 if (false)
282 DCHECK_EQ(false, true); // Unreached.
283 else
284 DCHECK_EQ(true, reached = true); // Reached, passed.
285 ASSERT_EQ(DCHECK_IS_ON() ? true : false, reached);
286
287 if (false)
288 DCHECK_EQ(false, true); // Unreached.
289}
290
291TEST_F(CheckTest, CheckEqStatements) {
292 bool reached = false;
293 if (false)
294 CHECK_EQ(false, true); // Unreached.
295 else
296 CHECK_EQ(true, reached = true); // Reached, passed.
297 ASSERT_TRUE(reached);
298
299 if (false)
300 CHECK_EQ(false, true); // Unreached.
301}
302
303#if defined(DCHECK_IS_CONFIGURABLE)
304TEST_F(CheckTest, ConfigurableDCheck) {
305 // Verify that DCHECKs default to non-fatal in configurable-DCHECK builds.
306 // Note that we require only that DCHECK is non-fatal by default, rather
307 // than requiring that it be exactly INFO, ERROR, etc level.
308 EXPECT_LT(LOG_DCHECK, LOG_FATAL);
309 DCHECK(false);
310
311 // Verify that DCHECK* aren't hard-wired to crash on failure.
312 LOG_DCHECK = LOG_INFO;
313 DCHECK(false);
314 DCHECK_EQ(1, 2);
315
316 // Verify that DCHECK does crash if LOG_DCHECK is set to LOG_FATAL.
317 LOG_DCHECK = LOG_FATAL;
318 EXPECT_CHECK("Check failed: false. ", DCHECK(false));
319 EXPECT_CHECK("Check failed: 1 == 2 (1 vs. 2)", DCHECK_EQ(1, 2));
320}
321
322TEST_F(CheckTest, ConfigurableDCheckFeature) {
323 // Initialize FeatureList with and without DcheckIsFatal, and verify the
324 // value of LOG_DCHECK. Note that we don't require that DCHECK take a
325 // specific value when the feature is off, only that it is non-fatal.
326
327 {
328 base::test::ScopedFeatureList feature_list;
329 feature_list.InitFromCommandLine("DcheckIsFatal", "");
330 EXPECT_EQ(LOG_DCHECK, LOG_FATAL);
331 }
332
333 {
334 base::test::ScopedFeatureList feature_list;
335 feature_list.InitFromCommandLine("", "DcheckIsFatal");
336 EXPECT_LT(LOG_DCHECK, LOG_FATAL);
337 }
338
339 // The default case is last, so we leave LOG_DCHECK in the default state.
340 {
341 base::test::ScopedFeatureList feature_list;
342 feature_list.InitFromCommandLine("", "");
343 EXPECT_LT(LOG_DCHECK, LOG_FATAL);
344 }
345}
346#endif // defined(DCHECK_IS_CONFIGURABLE)
347
348struct StructWithOstream {
349 bool operator==(const StructWithOstream& o) const { return &o == this; }
350};
351#if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
352std::ostream& operator<<(std::ostream& out, const StructWithOstream&) {
353 return out << "ostream";
354}
355#endif
356
357struct StructWithToString {
358 bool operator==(const StructWithToString& o) const { return &o == this; }
359 std::string ToString() const { return "ToString"; }
360};
361
362struct StructWithToStringAndOstream {
363 bool operator==(const StructWithToStringAndOstream& o) const {
364 return &o == this;
365 }
366 std::string ToString() const { return "ToString"; }
367};
368#if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
369std::ostream& operator<<(std::ostream& out,
370 const StructWithToStringAndOstream&) {
371 return out << "ostream";
372}
373#endif
374
375TEST_F(CheckTest, OstreamVsToString) {
376 StructWithOstream a, b;
377 EXPECT_CHECK("Check failed: a == b (ostream vs. ostream)", CHECK_EQ(a, b));
378
379 StructWithToString c, d;
380 EXPECT_CHECK("Check failed: c == d (ToString vs. ToString)", CHECK_EQ(c, d));
381
382 StructWithToStringAndOstream e, f;
383 EXPECT_CHECK("Check failed: e == f (ostream vs. ostream)", CHECK_EQ(e, f));
384}
385
386} // namespace