blob: 9638b2f83de82e4baf967ea52dcedc41b7c930e1 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2022 The Chromium Authors
Roland Bockd662a2d2022-07-12 20:55:272// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_CHECK_IS_TEST_H_
6#define BASE_CHECK_IS_TEST_H_
7
8#include "base/base_export.h"
Daniel Murphy5fa7a3192024-04-17 23:08:439#include "base/check.h"
Ari Chivukulac0ee1d02024-03-26 20:12:2410#include "base/not_fatal_until.h"
Roland Bockd662a2d2022-07-12 20:55:2711
12// Code paths taken in tests are sometimes different from those taken in
13// production. This might be because the respective tests do not initialize some
14// objects that would be required for the "normal" code path.
15//
16// Ideally, such code constructs should be avoided, so that tests really test
17// the production code and not something different.
18//
19// However, there already are hundreds of test-only paths in production code
20// Cleaning up all these cases retroactively and completely avoiding such cases
21// in the future seems unrealistic.
22//
23// Thus, it is useful to prevent the test code-only paths to be taken in
24// production scenarios.
25//
26// `CHECK_IS_TEST` can be used to assert that a test-only path is actually taken
27// only in tests. For instance:
28//
29// // This only happens in unit tests:
30// if (!url_loader_factory)
31// {
32// // Assert that this code path is really only taken in tests.
33// CHECK_IS_TEST();
34// return;
35// }
36//
Reilly Grant442ef2e2025-04-22 23:50:0837// `CHECK_IS_TEST` should not be used within functions named `*ForTesting`,
38// `*ForTests`, etc. because there is a presubmit check which warns against
39// calling such functions in production code.
40//
Roland Bockd662a2d2022-07-12 20:55:2741// `CHECK_IS_TEST` is thread safe.
Ari Chivukulac0ee1d02024-03-26 20:12:2442//
43// An optional base::NotFatalUntil argument can be provided to make the
44// instance non-fatal (dumps without crashing) before a provided milestone.
45// See base/check.h for details.
Roland Bockd662a2d2022-07-12 20:55:2746
Roland Bockd662a2d2022-07-12 20:55:2747namespace base::internal {
Peter Boström39497a602024-11-19 22:20:2448BASE_EXPORT bool get_is_test_impl();
Roland Bockd662a2d2022-07-12 20:55:2749} // namespace base::internal
50
Peter Boström39497a602024-11-19 22:20:2451#define CHECK_IS_TEST(...) \
52 CHECK(base::internal::get_is_test_impl() __VA_OPT__(, ) __VA_ARGS__)
53
54// In special cases, code should not execute in a test.
Daniel Chengad9b7a12025-04-29 18:39:1955#define CHECK_IS_NOT_TEST(...) \
56 CHECK(!base::internal::get_is_test_impl(), __VA_ARGS__)
Daniel Murphy5fa7a3192024-04-17 23:08:4357
Roland Bockd662a2d2022-07-12 20:55:2758#endif // BASE_CHECK_IS_TEST_H_