1 // Copyright 2022 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 #ifndef BASE_CHECK_IS_TEST_H_ 6 #define BASE_CHECK_IS_TEST_H_ 7 8 #include "base/base_export.h" 9 #include "base/check.h" 10 #include "base/not_fatal_until.h" 11 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 // 37 // `CHECK_IS_TEST` is thread safe. 38 // 39 // An optional base::NotFatalUntil argument can be provided to make the 40 // instance non-fatal (dumps without crashing) before a provided milestone. 41 // See base/check.h for details. 42 43 namespace base::internal { 44 BASE_EXPORT bool get_is_test_impl(); 45 } // namespace base::internal 46 47 #define CHECK_IS_TEST(...) \ 48 CHECK(base::internal::get_is_test_impl() __VA_OPT__(, ) __VA_ARGS__) 49 50 // In special cases, code should not execute in a test. 51 #define CHECK_IS_NOT_TEST() CHECK(!base::internal::get_is_test_impl()) 52 53 #endif // BASE_CHECK_IS_TEST_H_ 54