1 // Copyright 2014 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.
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/macros.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/histogram_base.h"
14 #include "base/metrics/histogram_samples.h"
15 #include "base/metrics/statistics_recorder.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/strings/string16.h"
18 #include "base/threading/sequenced_worker_pool.h"
19 #include "base/values.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
22 #include "chrome/browser/prefs/pref_hash_store.h"
23 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/profiles/profile_info_cache.h"
25 #include "chrome/browser/profiles/profile_manager.h"
26 #include "chrome/browser/profiles/profiles_state.h"
27 #include "chrome/common/pref_names.h"
28 #include "chrome/test/base/in_process_browser_test.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "content/public/common/content_switches.h"
31 #include "content/public/test/test_utils.h"
32 #include "testing/gtest/include/gtest/gtest.h"
36 // An observer that returns back to test code after a new profile is
38 void OnUnblockOnProfileCreation(const base::Closure& callback,
40 Profile::CreateStatus status) {
42 case Profile::CREATE_STATUS_CREATED:
43 // Wait for CREATE_STATUS_INITIALIZED.
45 case Profile::CREATE_STATUS_INITIALIZED:
49 ADD_FAILURE() << "Unexpected Profile::CreateStatus: " << status;
55 // Finds a profile path corresponding to a profile that has not been loaded yet.
56 base::FilePath GetUnloadedProfilePath() {
57 ProfileManager* profile_manager = g_browser_process->profile_manager();
58 const ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
59 const std::vector<Profile*> loaded_profiles =
60 profile_manager->GetLoadedProfiles();
61 std::set<base::FilePath> profile_paths;
62 for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i)
63 profile_paths.insert(cache.GetPathOfProfileAtIndex(i));
64 for (size_t i = 0; i < loaded_profiles.size(); ++i)
65 EXPECT_EQ(1U, profile_paths.erase(loaded_profiles[i]->GetPath()));
66 if (profile_paths.size())
67 return *profile_paths.begin();
68 return base::FilePath();
71 // Returns the number of times |histogram_name| was reported so far; adding the
72 // results of the first 100 buckets (there are only ~14 reporting IDs as of this
73 // writting; varies depending on the platform). If |expect_zero| is true, this
74 // method will explicitly report IDs that are non-zero for ease of diagnosis.
75 int GetTrackedPrefHistogramCount(const char* histogram_name, bool expect_zero) {
76 const base::HistogramBase* histogram =
77 base::StatisticsRecorder::FindHistogram(histogram_name);
81 scoped_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples());
83 for (int i = 0; i < 100; ++i) {
84 int count_for_id = samples->GetCount(i);
88 EXPECT_EQ(0, count_for_id) << "Faulty reporting_id: " << i;
95 class PrefHashBrowserTest : public InProcessBrowserTest,
96 public testing::WithParamInterface<std::string> {
99 : is_unloaded_profile_seeding_allowed_(
101 chrome_prefs::internals::kSettingsEnforcementGroupEnforceAlways) {}
103 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
104 InProcessBrowserTest::SetUpCommandLine(command_line);
105 command_line->AppendSwitchASCII(
106 switches::kForceFieldTrials,
107 std::string(chrome_prefs::internals::kSettingsEnforcementTrialName) +
108 "/" + GetParam() + "/");
111 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
112 // Force the delayed PrefHashStore update task to happen immediately.
113 chrome_prefs::EnableZeroDelayPrefHashStoreUpdateForTesting();
116 virtual void SetUpOnMainThread() OVERRIDE {
117 // content::RunAllPendingInMessageLoop() is already called before
118 // SetUpOnMainThread() in in_process_browser_test.cc which guarantees that
119 // UpdateAllPrefHashStoresIfRequired() has already been called.
121 // Now flush the blocking pool to force any pending JsonPrefStore async read
123 content::BrowserThread::GetBlockingPool()->FlushForTesting();
125 // And finally run tasks on this message loop again to process the OnRead()
126 // callbacks resulting from the file reads above.
127 content::RunAllPendingInMessageLoop();
131 const bool is_unloaded_profile_seeding_allowed_;
134 IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
135 PRE_PRE_InitializeUnloadedProfiles) {
136 if (!profiles::IsMultipleProfilesEnabled())
138 ProfileManager* profile_manager = g_browser_process->profile_manager();
140 // Create an additional profile.
141 const base::FilePath new_path =
142 profile_manager->GenerateNextProfileDirectoryPath();
143 const scoped_refptr<content::MessageLoopRunner> runner(
144 new content::MessageLoopRunner);
145 profile_manager->CreateProfileAsync(
147 base::Bind(&OnUnblockOnProfileCreation, runner->QuitClosure()),
152 // Spin to allow profile creation to take place, loop is terminated
153 // by OnUnblockOnProfileCreation when the profile is created.
156 // No profile should have gone through the unloaded profile initialization in
157 // this phase as both profiles should have been loaded normally.
159 0, GetTrackedPrefHistogramCount(
160 "Settings.TrackedPreferencesInitializedForUnloadedProfile",
164 IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
165 PRE_InitializeUnloadedProfiles) {
166 if (!profiles::IsMultipleProfilesEnabled())
169 // Creating the profile would have initialized its hash store. Also, we don't
170 // know whether the newly created or original profile will be launched (does
171 // creating a profile cause it to be the most recently used?).
173 // So we will find the profile that isn't loaded, reset its hash store, and
174 // then verify in the _next_ launch that it is, indeed, restored despite not
175 // having been loaded.
177 const base::DictionaryValue* hashes =
178 g_browser_process->local_state()->GetDictionary(
179 prefs::kProfilePreferenceHashes);
181 // 4 is for hash_of_hashes, versions_dict, default profile, and new profile.
182 EXPECT_EQ(4U, hashes->size());
184 // One of the two profiles should not have been loaded. Reset its hash store.
185 const base::FilePath unloaded_profile_path = GetUnloadedProfilePath();
186 chrome_prefs::ResetPrefHashStore(unloaded_profile_path);
188 // One of the profile hash collections should be gone.
189 EXPECT_EQ(3U, hashes->size());
191 // No profile should have gone through the unloaded profile initialization in
192 // this phase as both profiles were already initialized at the beginning of
193 // this phase (resetting the unloaded profile's PrefHashStore should only
194 // force initialization in the next phase's startup).
196 0, GetTrackedPrefHistogramCount(
197 "Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
201 IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
202 InitializeUnloadedProfiles) {
203 if (!profiles::IsMultipleProfilesEnabled())
206 const base::DictionaryValue* hashes =
207 g_browser_process->local_state()->GetDictionary(
208 prefs::kProfilePreferenceHashes);
210 // The deleted hash collection should be restored only if the current
211 // SettingsEnforcement group allows it.
212 if (is_unloaded_profile_seeding_allowed_) {
213 EXPECT_EQ(4U, hashes->size());
215 // Verify that the initialization truly did occur in this phase's startup;
216 // rather than in the previous phase's shutdown.
218 1, GetTrackedPrefHistogramCount(
219 "Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
222 EXPECT_EQ(3U, hashes->size());
225 0, GetTrackedPrefHistogramCount(
226 "Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
230 ProfileManager* profile_manager = g_browser_process->profile_manager();
232 // Verify that only one profile was loaded. We assume that the unloaded
233 // profile is the same one that wasn't loaded in the last launch (i.e., it's
234 // the one whose hash store we reset, and the fact that it is now restored is
235 // evidence that we restored the hashes of an unloaded profile.).
236 ASSERT_EQ(1U, profile_manager->GetLoadedProfiles().size());
238 // Loading the first profile should only have produced unchanged reports.
240 0, GetTrackedPrefHistogramCount(
241 "Settings.TrackedPreferenceChanged", true));
243 0, GetTrackedPrefHistogramCount(
244 "Settings.TrackedPreferenceCleared", true));
246 0, GetTrackedPrefHistogramCount(
247 "Settings.TrackedPreferenceInitialized", true));
249 0, GetTrackedPrefHistogramCount(
250 "Settings.TrackedPreferenceTrustedInitialized", true));
252 0, GetTrackedPrefHistogramCount(
253 "Settings.TrackedPreferenceMigrated", true));
254 int initial_unchanged_count =
255 GetTrackedPrefHistogramCount("Settings.TrackedPreferenceUnchanged",
257 EXPECT_GT(initial_unchanged_count, 0);
259 if (is_unloaded_profile_seeding_allowed_) {
260 // Explicitly load the unloaded profile.
261 profile_manager->GetProfile(GetUnloadedProfilePath());
262 ASSERT_EQ(2U, profile_manager->GetLoadedProfiles().size());
264 // Loading the unloaded profile should only generate unchanged pings; and
265 // should have produced as many of them as loading the first profile.
267 0, GetTrackedPrefHistogramCount(
268 "Settings.TrackedPreferenceChanged", true));
270 0, GetTrackedPrefHistogramCount(
271 "Settings.TrackedPreferenceCleared", true));
273 0, GetTrackedPrefHistogramCount(
274 "Settings.TrackedPreferenceInitialized", true));
276 0, GetTrackedPrefHistogramCount(
277 "Settings.TrackedPreferenceTrustedInitialized", true));
279 0, GetTrackedPrefHistogramCount(
280 "Settings.TrackedPreferenceMigrated", true));
282 initial_unchanged_count * 2,
283 GetTrackedPrefHistogramCount("Settings.TrackedPreferenceUnchanged",
288 // TODO(gab): Also test kSettingsEnforcementGroupEnforceAlways below; for some
289 // reason it doesn't pass on the try bots, yet I can't repro the failure
290 // locally, it's as if GROUP_NO_ENFORCEMENT is always picked on bots..?
291 INSTANTIATE_TEST_CASE_P(
292 PrefHashBrowserTestInstance,
295 chrome_prefs::internals::kSettingsEnforcementGroupNoEnforcement,
296 chrome_prefs::internals::kSettingsEnforcementGroupEnforceOnload));