Commit 9a39401c authored by Maksim Ivanov's avatar Maksim Ivanov Committed by Commit Bot

Add convenience Get method into base::PathService

Add a new CheckedGet() method that is equivalent to
base::PathService::Get(), but returns the result as a return value (and
CHECKs that the operation succeeded).

This is a pure convenience addition that allows to simplify the code
that anyway cannot correctly handle the path service being unavailable.
(In the existing codebase, there are already >100 callsites that do
CHECK(PathService::Get(...)), and also many callsites in tests that just
take the path returned by PathService::Get() without checking its return
value.)

Bug: none
Change-Id: I38535138ea08f0fd71e0eaf1979a1bdc99c504ab
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2279813Reviewed-by: default avatarMitsuru Oshima <oshima@chromium.org>
Reviewed-by: default avatarLei Zhang <thestig@chromium.org>
Commit-Queue: Maksim Ivanov <emaxx@chromium.org>
Cr-Commit-Position: refs/heads/master@{#786413}
parent 717da8fa
...@@ -228,6 +228,12 @@ bool PathService::Get(int key, FilePath* result) { ...@@ -228,6 +228,12 @@ bool PathService::Get(int key, FilePath* result) {
return true; return true;
} }
FilePath PathService::CheckedGet(int key) {
FilePath path;
CHECK(Get(key, &path));
return path;
}
// static // static
bool PathService::Override(int key, const FilePath& path) { bool PathService::Override(int key, const FilePath& path) {
// Just call the full function with true for the value of |create|, and // Just call the full function with true for the value of |create|, and
......
...@@ -27,6 +27,9 @@ class BASE_EXPORT PathService { ...@@ -27,6 +27,9 @@ class BASE_EXPORT PathService {
// |path| will not be changed. // |path| will not be changed.
static bool Get(int key, FilePath* path); static bool Get(int key, FilePath* path);
// Returns the corresponding path; CHECKs that the operation succeeds.
static FilePath CheckedGet(int key);
// Overrides the path to a special directory or file. This cannot be used to // Overrides the path to a special directory or file. This cannot be used to
// change the value of DIR_CURRENT, but that should be obvious. Also, if the // change the value of DIR_CURRENT, but that should be obvious. Also, if the
// path specifies a directory that does not exist, the directory will be // path specifies a directory that does not exist, the directory will be
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
#include "base/files/scoped_temp_dir.h" #include "base/files/scoped_temp_dir.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "base/test/gtest_util.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest-spi.h" #include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
...@@ -141,6 +142,26 @@ TEST_F(PathServiceTest, Get) { ...@@ -141,6 +142,26 @@ TEST_F(PathServiceTest, Get) {
#endif #endif
} }
// Tests that CheckedGet returns the same path as Get.
TEST_F(PathServiceTest, CheckedGet) {
constexpr int kKey = DIR_CURRENT;
FilePath path;
ASSERT_TRUE(PathService::Get(kKey, &path));
EXPECT_EQ(path, PathService::CheckedGet(kKey));
}
#if defined(GTEST_HAS_DEATH_TEST)
// Tests that CheckedGet CHECKs on failure.
TEST_F(PathServiceTest, CheckedGetFailure) {
constexpr int kBadKey = PATH_END;
FilePath path;
EXPECT_FALSE(PathService::Get(kBadKey, &path));
EXPECT_CHECK_DEATH(PathService::CheckedGet(kBadKey));
}
#endif // GTEST_HAS_DEATH_TEST
// Test that all versions of the Override function of PathService do what they // Test that all versions of the Override function of PathService do what they
// are supposed to do. // are supposed to do.
TEST_F(PathServiceTest, Override) { TEST_F(PathServiceTest, Override) {
......
...@@ -536,8 +536,7 @@ MULTIPROCESS_TEST_MAIN(CheckCwdProcess) { ...@@ -536,8 +536,7 @@ MULTIPROCESS_TEST_MAIN(CheckCwdProcess) {
event.Wait(); event.Wait();
// Get a new cwd for the process. // Get a new cwd for the process.
FilePath home_dir; const FilePath home_dir = PathService::CheckedGet(DIR_HOME);
CHECK(PathService::Get(DIR_HOME, &home_dir));
// Change the cwd on the secondary thread. IgnoreResult is used when setting // Change the cwd on the secondary thread. IgnoreResult is used when setting
// because it is checked immediately after. // because it is checked immediately after.
......
...@@ -27,13 +27,6 @@ namespace chromeos { ...@@ -27,13 +27,6 @@ namespace chromeos {
namespace { namespace {
base::FilePath GetExtensionsCachePath() {
base::FilePath extensions_cache_path;
CHECK(base::PathService::Get(DIR_SIGNIN_PROFILE_EXTENSIONS,
&extensions_cache_path));
return extensions_cache_path;
}
base::Value GetForceInstalledExtensionsFromPrefs(const PrefService* prefs) { base::Value GetForceInstalledExtensionsFromPrefs(const PrefService* prefs) {
const PrefService::Preference* const login_screen_extensions_pref = const PrefService::Preference* const login_screen_extensions_pref =
prefs->FindPreference(extensions::pref_names::kLoginScreenExtensions); prefs->FindPreference(extensions::pref_names::kLoginScreenExtensions);
...@@ -58,14 +51,15 @@ base::Value GetForceInstalledExtensionsFromPrefs(const PrefService* prefs) { ...@@ -58,14 +51,15 @@ base::Value GetForceInstalledExtensionsFromPrefs(const PrefService* prefs) {
SigninScreenExtensionsExternalLoader::SigninScreenExtensionsExternalLoader( SigninScreenExtensionsExternalLoader::SigninScreenExtensionsExternalLoader(
Profile* profile) Profile* profile)
: profile_(profile), : profile_(profile),
external_cache_(GetExtensionsCachePath(), external_cache_(
g_browser_process->shared_url_loader_factory(), base::PathService::CheckedGet(DIR_SIGNIN_PROFILE_EXTENSIONS),
base::ThreadPool::CreateSequencedTaskRunner( g_browser_process->shared_url_loader_factory(),
{base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::ThreadPool::CreateSequencedTaskRunner(
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}), {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
this, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}),
/*always_check_updates=*/true, this,
/*wait_for_cache_initialization=*/false) { /*always_check_updates=*/true,
/*wait_for_cache_initialization=*/false) {
DCHECK(ProfileHelper::IsSigninProfile(profile)); DCHECK(ProfileHelper::IsSigninProfile(profile));
} }
......
...@@ -434,11 +434,11 @@ void TimeoutCallback(const std::string& timeout_message) { ...@@ -434,11 +434,11 @@ void TimeoutCallback(const std::string& timeout_message) {
class DevToolsExtensionTest : public DevToolsSanityTest, class DevToolsExtensionTest : public DevToolsSanityTest,
public content::NotificationObserver { public content::NotificationObserver {
public: public:
DevToolsExtensionTest() : DevToolsSanityTest() { DevToolsExtensionTest()
base::PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); : test_extensions_dir_(
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); .AppendASCII("devtools")
} .AppendASCII("extensions")) {}
protected: protected:
// Load an extension from test\data\devtools\extensions\<extension_name> // Load an extension from test\data\devtools\extensions\<extension_name>
...@@ -606,7 +606,7 @@ class DevToolsExtensionTest : public DevToolsSanityTest, ...@@ -606,7 +606,7 @@ class DevToolsExtensionTest : public DevToolsSanityTest,
std::vector<std::unique_ptr<extensions::TestExtensionDir>> std::vector<std::unique_ptr<extensions::TestExtensionDir>>
test_extension_dirs_; test_extension_dirs_;
base::FilePath test_extensions_dir_; const base::FilePath test_extensions_dir_;
}; };
class DevToolsExperimentalExtensionTest : public DevToolsExtensionTest { class DevToolsExperimentalExtensionTest : public DevToolsExtensionTest {
...@@ -2344,13 +2344,11 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestOpenInNewTabFilter) { ...@@ -2344,13 +2344,11 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestOpenInNewTabFilter) {
} }
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, LoadNetworkResourceForFrontend) { IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, LoadNetworkResourceForFrontend) {
base::FilePath root_dir;
CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &root_dir));
std::string file_url = std::string file_url =
"file://" + "file://" + base::PathService::CheckedGet(base::DIR_SOURCE_ROOT)
root_dir.AppendASCII("content/test/data/devtools/navigation.html") .AppendASCII("content/test/data/devtools/navigation.html")
.NormalizePathSeparatorsTo('/') .NormalizePathSeparatorsTo('/')
.AsUTF8Unsafe(); .AsUTF8Unsafe();
embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(embedded_test_server()->Start());
......
...@@ -13,10 +13,9 @@ ...@@ -13,10 +13,9 @@
namespace extensions { namespace extensions {
ChromeOSExtensionCacheDelegate::ChromeOSExtensionCacheDelegate() { ChromeOSExtensionCacheDelegate::ChromeOSExtensionCacheDelegate()
CHECK(base::PathService::Get(chromeos::DIR_DEVICE_EXTENSION_LOCAL_CACHE, : cache_dir_(base::PathService::CheckedGet(
&cache_dir_)); chromeos::DIR_DEVICE_EXTENSION_LOCAL_CACHE)) {}
}
ChromeOSExtensionCacheDelegate::ChromeOSExtensionCacheDelegate( ChromeOSExtensionCacheDelegate::ChromeOSExtensionCacheDelegate(
const base::FilePath& cache_dir) const base::FilePath& cache_dir)
......
...@@ -26,7 +26,7 @@ class ChromeOSExtensionCacheDelegate { ...@@ -26,7 +26,7 @@ class ChromeOSExtensionCacheDelegate {
base::TimeDelta GetMaximumCacheAge() const; base::TimeDelta GetMaximumCacheAge() const;
private: private:
base::FilePath cache_dir_; const base::FilePath cache_dir_;
DISALLOW_COPY_AND_ASSIGN(ChromeOSExtensionCacheDelegate); DISALLOW_COPY_AND_ASSIGN(ChromeOSExtensionCacheDelegate);
}; };
......
...@@ -170,9 +170,8 @@ TEST_F(SharedSamplerTest, MultipleRefreshTypes) { ...@@ -170,9 +170,8 @@ TEST_F(SharedSamplerTest, MultipleRefreshTypes) {
static int ReturnZeroThreadProcessInformation(unsigned char* buffer, static int ReturnZeroThreadProcessInformation(unsigned char* buffer,
int buffer_size) { int buffer_size) {
// Calculate the number of bytes required for the structure, and ImageName. // Calculate the number of bytes required for the structure, and ImageName.
base::FilePath current_exe; base::string16 image_name =
CHECK(base::PathService::Get(base::FILE_EXE, &current_exe)); base::PathService::CheckedGet(base::FILE_EXE).BaseName().value();
base::string16 image_name = current_exe.BaseName().value();
const int kImageNameBytes = image_name.length() * sizeof(base::char16); const int kImageNameBytes = image_name.length() * sizeof(base::char16);
const int kRequiredBytes = sizeof(SYSTEM_PROCESS_INFORMATION) + const int kRequiredBytes = sizeof(SYSTEM_PROCESS_INFORMATION) +
......
...@@ -39,10 +39,9 @@ using extensions::TestManagementPolicyProvider; ...@@ -39,10 +39,9 @@ using extensions::TestManagementPolicyProvider;
ExtensionSettingsUIBrowserTest::ExtensionSettingsUIBrowserTest() ExtensionSettingsUIBrowserTest::ExtensionSettingsUIBrowserTest()
: policy_provider_(TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS | : policy_provider_(TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS |
TestManagementPolicyProvider::MUST_REMAIN_ENABLED | TestManagementPolicyProvider::MUST_REMAIN_ENABLED |
TestManagementPolicyProvider::MUST_REMAIN_INSTALLED) { TestManagementPolicyProvider::MUST_REMAIN_INSTALLED),
CHECK(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_)); test_data_dir_(base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
test_data_dir_ = test_data_dir_.AppendASCII("extensions"); .AppendASCII("extensions")) {}
}
ExtensionSettingsUIBrowserTest::~ExtensionSettingsUIBrowserTest() {} ExtensionSettingsUIBrowserTest::~ExtensionSettingsUIBrowserTest() {}
......
...@@ -63,7 +63,7 @@ class ExtensionSettingsUIBrowserTest : public WebUIBrowserTest { ...@@ -63,7 +63,7 @@ class ExtensionSettingsUIBrowserTest : public WebUIBrowserTest {
// Used to simulate managed extensions (by being registered as a provider). // Used to simulate managed extensions (by being registered as a provider).
extensions::TestManagementPolicyProvider policy_provider_; extensions::TestManagementPolicyProvider policy_provider_;
base::FilePath test_data_dir_; const base::FilePath test_data_dir_;
// Disable extension content verification. // Disable extension content verification.
extensions::ScopedIgnoreContentVerifierForTest ignore_content_verification_; extensions::ScopedIgnoreContentVerifierForTest ignore_content_verification_;
......
...@@ -10,10 +10,9 @@ ...@@ -10,10 +10,9 @@
#include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_paths.h"
ManagementA11yUIBrowserTest::ManagementA11yUIBrowserTest() { ManagementA11yUIBrowserTest::ManagementA11yUIBrowserTest()
CHECK(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_)); : test_data_dir_(base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
test_data_dir_ = test_data_dir_.AppendASCII("extensions"); .AppendASCII("extensions")) {}
}
ManagementA11yUIBrowserTest::~ManagementA11yUIBrowserTest() {} ManagementA11yUIBrowserTest::~ManagementA11yUIBrowserTest() {}
......
...@@ -17,7 +17,7 @@ class ManagementA11yUIBrowserTest : public WebUIBrowserTest { ...@@ -17,7 +17,7 @@ class ManagementA11yUIBrowserTest : public WebUIBrowserTest {
protected: protected:
void InstallPowerfulPolicyEnforcedExtension(); void InstallPowerfulPolicyEnforcedExtension();
base::FilePath test_data_dir_; const base::FilePath test_data_dir_;
}; };
#endif // CHROME_BROWSER_UI_WEBUI_MANAGEMENT_A11Y_BROWSERTEST_H_ #endif // CHROME_BROWSER_UI_WEBUI_MANAGEMENT_A11Y_BROWSERTEST_H_
...@@ -38,36 +38,34 @@ TEST(PreFetchedPathsTest, CheckExpectedPaths) { ...@@ -38,36 +38,34 @@ TEST(PreFetchedPathsTest, CheckExpectedPaths) {
PreFetchedPaths* pre_fetched_paths = PreFetchedPaths::GetInstance(); PreFetchedPaths* pre_fetched_paths = PreFetchedPaths::GetInstance();
// Note: pre_fetched_paths->Initialized() is already called in test_main.cc. // Note: pre_fetched_paths->Initialized() is already called in test_main.cc.
auto GetExpectedPath = [](int key) -> base::FilePath { EXPECT_EQ(base::PathService::CheckedGet(base::FILE_EXE),
base::FilePath expected_path;
CHECK(base::PathService::Get(key, &expected_path));
return expected_path;
};
EXPECT_EQ(GetExpectedPath(base::FILE_EXE),
pre_fetched_paths->GetExecutablePath()); pre_fetched_paths->GetExecutablePath());
EXPECT_EQ(GetExpectedPath(base::DIR_PROGRAM_FILES), EXPECT_EQ(base::PathService::CheckedGet(base::DIR_PROGRAM_FILES),
pre_fetched_paths->GetProgramFilesFolder()); pre_fetched_paths->GetProgramFilesFolder());
EXPECT_EQ(GetExpectedPath(base::DIR_WINDOWS), EXPECT_EQ(base::PathService::CheckedGet(base::DIR_WINDOWS),
pre_fetched_paths->GetWindowsFolder()); pre_fetched_paths->GetWindowsFolder());
EXPECT_EQ(GetExpectedPath(base::DIR_COMMON_APP_DATA), EXPECT_EQ(base::PathService::CheckedGet(base::DIR_COMMON_APP_DATA),
pre_fetched_paths->GetCommonAppDataFolder()); pre_fetched_paths->GetCommonAppDataFolder());
EXPECT_EQ(GetExpectedPath(base::DIR_LOCAL_APP_DATA), EXPECT_EQ(base::PathService::CheckedGet(base::DIR_LOCAL_APP_DATA),
pre_fetched_paths->GetLocalAppDataFolder()); pre_fetched_paths->GetLocalAppDataFolder());
EXPECT_EQ(GetExpectedPath(CsidlToPathServiceKey(CSIDL_PROGRAM_FILES)), EXPECT_EQ(
pre_fetched_paths->GetCsidlProgramFilesFolder()); base::PathService::CheckedGet(CsidlToPathServiceKey(CSIDL_PROGRAM_FILES)),
EXPECT_EQ(GetExpectedPath(CsidlToPathServiceKey(CSIDL_PROGRAM_FILESX86)), pre_fetched_paths->GetCsidlProgramFilesFolder());
EXPECT_EQ(base::PathService::CheckedGet(
CsidlToPathServiceKey(CSIDL_PROGRAM_FILESX86)),
pre_fetched_paths->GetCsidlProgramFilesX86Folder()); pre_fetched_paths->GetCsidlProgramFilesX86Folder());
EXPECT_EQ(GetExpectedPath(CsidlToPathServiceKey(CSIDL_WINDOWS)), EXPECT_EQ(base::PathService::CheckedGet(CsidlToPathServiceKey(CSIDL_WINDOWS)),
pre_fetched_paths->GetCsidlWindowsFolder()); pre_fetched_paths->GetCsidlWindowsFolder());
EXPECT_EQ(GetExpectedPath(CsidlToPathServiceKey(CSIDL_STARTUP)), EXPECT_EQ(base::PathService::CheckedGet(CsidlToPathServiceKey(CSIDL_STARTUP)),
pre_fetched_paths->GetCsidlStartupFolder()); pre_fetched_paths->GetCsidlStartupFolder());
EXPECT_EQ(GetExpectedPath(CsidlToPathServiceKey(CSIDL_SYSTEM)), EXPECT_EQ(base::PathService::CheckedGet(CsidlToPathServiceKey(CSIDL_SYSTEM)),
pre_fetched_paths->GetCsidlSystemFolder()); pre_fetched_paths->GetCsidlSystemFolder());
EXPECT_EQ(GetExpectedPath(CsidlToPathServiceKey(CSIDL_COMMON_APPDATA)), EXPECT_EQ(base::PathService::CheckedGet(
CsidlToPathServiceKey(CSIDL_COMMON_APPDATA)),
pre_fetched_paths->GetCsidlCommonAppDataFolder()); pre_fetched_paths->GetCsidlCommonAppDataFolder());
EXPECT_EQ(GetExpectedPath(CsidlToPathServiceKey(CSIDL_LOCAL_APPDATA)), EXPECT_EQ(
pre_fetched_paths->GetCsidlLocalAppDataFolder()); base::PathService::CheckedGet(CsidlToPathServiceKey(CSIDL_LOCAL_APPDATA)),
pre_fetched_paths->GetCsidlLocalAppDataFolder());
} }
} // namespace } // namespace
......
...@@ -252,12 +252,10 @@ void MediaRouterIntegrationBrowserTest::SetTestData( ...@@ -252,12 +252,10 @@ void MediaRouterIntegrationBrowserTest::SetTestData(
base::FilePath MediaRouterIntegrationBrowserTest::GetResourceFile( base::FilePath MediaRouterIntegrationBrowserTest::GetResourceFile(
base::FilePath::StringPieceType relative_path) const { base::FilePath::StringPieceType relative_path) const {
base::FilePath base_dir; const base::FilePath full_path =
// ASSERT_TRUE can only be used in void returning functions. base::PathService::CheckedGet(base::DIR_MODULE)
// Use CHECK instead in non-void returning functions. .Append(kResourcePath)
CHECK(base::PathService::Get(base::DIR_MODULE, &base_dir)); .Append(relative_path);
base::FilePath full_path =
base_dir.Append(kResourcePath).Append(relative_path);
{ {
// crbug.com/724573 // crbug.com/724573
base::ScopedAllowBlockingForTesting allow_blocking; base::ScopedAllowBlockingForTesting allow_blocking;
......
...@@ -31,10 +31,9 @@ class MediaRouterIntegrationOneUABrowserTest ...@@ -31,10 +31,9 @@ class MediaRouterIntegrationOneUABrowserTest
// Set up embedded test server to serve offscreen presentation with relative // Set up embedded test server to serve offscreen presentation with relative
// URL "presentation_receiver.html". // URL "presentation_receiver.html".
base::FilePath base_dir; base::FilePath resource_dir =
CHECK(base::PathService::Get(base::DIR_MODULE, &base_dir)); base::PathService::CheckedGet(base::DIR_MODULE)
base::FilePath resource_dir = base_dir.Append( .Append(FILE_PATH_LITERAL("media_router/browser_test_resources/"));
FILE_PATH_LITERAL("media_router/browser_test_resources/"));
embedded_test_server()->ServeFilesFromDirectory(resource_dir); embedded_test_server()->ServeFilesFromDirectory(resource_dir);
ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(embedded_test_server()->Start());
} }
......
...@@ -77,10 +77,8 @@ void InstallAttributes::Initialize() { ...@@ -77,10 +77,8 @@ void InstallAttributes::Initialize() {
DCHECK(!g_install_attributes); DCHECK(!g_install_attributes);
g_install_attributes = new InstallAttributes(CryptohomeClient::Get()); g_install_attributes = new InstallAttributes(CryptohomeClient::Get());
base::FilePath install_attrs_file; g_install_attributes->Init(
CHECK(base::PathService::Get(dbus_paths::FILE_INSTALL_ATTRIBUTES, base::PathService::CheckedGet(dbus_paths::FILE_INSTALL_ATTRIBUTES));
&install_attrs_file));
g_install_attributes->Init(install_attrs_file);
} }
// static // static
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment