Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / profile_resetter / automatic_profile_resetter_unittest.cc
1 // Copyright 2013 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 "chrome/browser/profile_resetter/automatic_profile_resetter.h"
6
7 #include <string>
8
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/metrics/field_trial.h"
12 #include "base/prefs/pref_registry_simple.h"
13 #include "base/prefs/testing_pref_service.h"
14 #include "base/run_loop.h"
15 #include "base/test/test_simple_task_runner.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "base/values.h"
18 #include "chrome/browser/profile_resetter/automatic_profile_resetter_delegate.h"
19 #include "chrome/browser/profile_resetter/automatic_profile_resetter_factory.h"
20 #include "chrome/browser/profile_resetter/automatic_profile_resetter_mementos.h"
21 #include "chrome/browser/profile_resetter/jtl_foundation.h"
22 #include "chrome/browser/profile_resetter/jtl_instructions.h"
23 #include "chrome/test/base/scoped_testing_local_state.h"
24 #include "chrome/test/base/testing_browser_process.h"
25 #include "chrome/test/base/testing_pref_service_syncable.h"
26 #include "chrome/test/base/testing_profile.h"
27 #include "components/pref_registry/pref_registry_syncable.h"
28 #include "components/variations/variations_associated_data.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "content/public/test/test_browser_thread_bundle.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33
34 using testing::_;
35
36 namespace {
37
38 const char kAutomaticProfileResetStudyName[] = "AutomaticProfileReset";
39 const char kStudyDisabledGroupName[] = "Disabled";
40 const char kStudyDryRunGroupName[] = "DryRun";
41 const char kStudyEnabledGroupName[] = "Enabled";
42
43 const char kTestHashSeed[] = "testing-hash-seed";
44 const char kTestMementoValue[] = "01234567890123456789012345678901";
45 const char kTestInvalidMementoValue[] = "12345678901234567890123456789012";
46
47 const char kTestPreferencePath[] = "testing.preference";
48 const char kTestPreferenceValue[] = "testing-preference-value";
49
50 const char kSearchURLAttributeKey[] = "search_url";
51 const char kTestSearchURL[] = "http://example.com/search?q={searchTerms}";
52 const char kTestSearchURL2[] = "http://google.com/?q={searchTerms}";
53
54 const char kTestModuleDigest[] = "01234567890123456789012345678901";
55 const char kTestModuleDigest2[] = "12345678901234567890123456789012";
56
57 // Helpers ------------------------------------------------------------------
58
59 // A testing version of the AutomaticProfileResetter that differs from the real
60 // one only in that it has its statistics reporting mocked out for verification.
61 class AutomaticProfileResetterUnderTest : public AutomaticProfileResetter {
62  public:
63   explicit AutomaticProfileResetterUnderTest(Profile* profile)
64       : AutomaticProfileResetter(profile) {}
65   virtual ~AutomaticProfileResetterUnderTest() {}
66
67   MOCK_METHOD2(ReportStatistics, void(uint32, uint32));
68   MOCK_METHOD1(ReportPromptResult,
69       void(AutomaticProfileResetter::PromptResult));
70
71  private:
72   DISALLOW_COPY_AND_ASSIGN(AutomaticProfileResetterUnderTest);
73 };
74
75 class MockProfileResetterDelegate : public AutomaticProfileResetterDelegate {
76  public:
77   MockProfileResetterDelegate()
78       : emulated_is_default_search_provider_managed_(false) {}
79   virtual ~MockProfileResetterDelegate() {}
80
81   MOCK_METHOD0(EnumerateLoadedModulesIfNeeded, void());
82   MOCK_CONST_METHOD1(RequestCallbackWhenLoadedModulesAreEnumerated,
83                      void(const base::Closure&));
84
85   MOCK_METHOD0(LoadTemplateURLServiceIfNeeded, void());
86   MOCK_CONST_METHOD1(RequestCallbackWhenTemplateURLServiceIsLoaded,
87                      void(const base::Closure&));
88
89   MOCK_METHOD0(FetchBrandcodedDefaultSettingsIfNeeded, void());
90   MOCK_CONST_METHOD1(RequestCallbackWhenBrandcodedDefaultsAreFetched,
91                      void(const base::Closure&));
92
93   MOCK_CONST_METHOD0(OnGetLoadedModuleNameDigestsCalled, void());
94   MOCK_CONST_METHOD0(OnGetDefaultSearchProviderDetailsCalled, void());
95   MOCK_CONST_METHOD0(OnIsDefaultSearchProviderManagedCalled, void());
96   MOCK_CONST_METHOD0(OnGetPrepopulatedSearchProvidersDetailsCalled, void());
97
98   MOCK_METHOD0(TriggerPrompt, bool());
99   MOCK_METHOD2(TriggerProfileSettingsReset, void(bool, const base::Closure&));
100   MOCK_METHOD0(DismissPrompt, void());
101
102   virtual scoped_ptr<base::ListValue>
103       GetLoadedModuleNameDigests() const OVERRIDE {
104     OnGetLoadedModuleNameDigestsCalled();
105     return scoped_ptr<base::ListValue>(
106         emulated_loaded_module_digests_.DeepCopy());
107   }
108
109   virtual scoped_ptr<base::DictionaryValue>
110       GetDefaultSearchProviderDetails() const OVERRIDE {
111     OnGetDefaultSearchProviderDetailsCalled();
112     return scoped_ptr<base::DictionaryValue>(
113         emulated_default_search_provider_details_.DeepCopy());
114   }
115
116   virtual bool IsDefaultSearchProviderManaged() const OVERRIDE {
117     OnIsDefaultSearchProviderManagedCalled();
118     return emulated_is_default_search_provider_managed_;
119   }
120
121   virtual scoped_ptr<base::ListValue>
122       GetPrepopulatedSearchProvidersDetails() const OVERRIDE {
123     OnGetPrepopulatedSearchProvidersDetailsCalled();
124     return scoped_ptr<base::ListValue>(
125         emulated_search_providers_details_.DeepCopy());
126   }
127
128   static void ClosureInvoker(const base::Closure& closure) { closure.Run(); }
129
130   void ExpectCallsToDependenciesSetUpMethods() {
131     EXPECT_CALL(*this, EnumerateLoadedModulesIfNeeded());
132     EXPECT_CALL(*this, LoadTemplateURLServiceIfNeeded());
133     EXPECT_CALL(*this, RequestCallbackWhenLoadedModulesAreEnumerated(_))
134         .WillOnce(testing::Invoke(ClosureInvoker));
135     EXPECT_CALL(*this, RequestCallbackWhenTemplateURLServiceIsLoaded(_))
136         .WillOnce(testing::Invoke(ClosureInvoker));
137   }
138
139   void ExpectCallsToGetterMethods() {
140     EXPECT_CALL(*this, OnGetLoadedModuleNameDigestsCalled());
141     EXPECT_CALL(*this, OnGetDefaultSearchProviderDetailsCalled());
142     EXPECT_CALL(*this, OnIsDefaultSearchProviderManagedCalled());
143     EXPECT_CALL(*this, OnGetPrepopulatedSearchProvidersDetailsCalled());
144   }
145
146   void ExpectCallToShowPrompt() {
147     EXPECT_CALL(*this, TriggerPrompt()).WillOnce(testing::Return(true));
148     EXPECT_CALL(*this, FetchBrandcodedDefaultSettingsIfNeeded());
149   }
150
151   void ExpectCallToTriggerReset(bool send_feedback) {
152     EXPECT_CALL(*this, TriggerProfileSettingsReset(send_feedback, _))
153         .WillOnce(testing::SaveArg<1>(&reset_completion_));
154   }
155
156   base::DictionaryValue& emulated_default_search_provider_details() {
157     return emulated_default_search_provider_details_;
158   }
159
160   base::ListValue& emulated_search_providers_details() {
161     return emulated_search_providers_details_;
162   }
163
164   base::ListValue& emulated_loaded_module_digests() {
165     return emulated_loaded_module_digests_;
166   }
167
168   void set_emulated_is_default_search_provider_managed(bool value) {
169     emulated_is_default_search_provider_managed_ = value;
170   }
171
172   void EmulateProfileResetCompleted() {
173     reset_completion_.Run();
174   }
175
176  private:
177   base::DictionaryValue emulated_default_search_provider_details_;
178   base::ListValue emulated_search_providers_details_;
179   base::ListValue emulated_loaded_module_digests_;
180   bool emulated_is_default_search_provider_managed_;
181   base::Closure reset_completion_;
182
183   DISALLOW_COPY_AND_ASSIGN(MockProfileResetterDelegate);
184 };
185
186 class FileHostedPromptMementoSynchronous : protected FileHostedPromptMemento {
187  public:
188   explicit FileHostedPromptMementoSynchronous(Profile* profile)
189       : FileHostedPromptMemento(profile) {}
190
191   std::string ReadValue() const {
192     std::string result;
193     FileHostedPromptMemento::ReadValue(base::Bind(&AssignArgumentTo, &result));
194     base::RunLoop().RunUntilIdle();
195     return result;
196   }
197
198   void StoreValue(const std::string& value) {
199     FileHostedPromptMemento::StoreValue(value);
200     base::RunLoop().RunUntilIdle();
201   }
202
203  private:
204   static void AssignArgumentTo(std::string* target, const std::string& value) {
205     *target = value;
206   }
207
208   DISALLOW_COPY_AND_ASSIGN(FileHostedPromptMementoSynchronous);
209 };
210
211 std::string GetHash(const std::string& input) {
212   return jtl_foundation::Hasher(kTestHashSeed).GetHash(input);
213 }
214
215 // Encodes a Boolean argument value into JTL bytecode.
216 std::string EncodeBool(bool value) { return value ? VALUE_TRUE : VALUE_FALSE; }
217
218 // Constructs a simple evaluation program to test that basic input/output works
219 // well. It will emulate a scenario in which the reset criteria are satisfied as
220 // prescribed by |emulate_satisfied_criterion_{1|2}|, and the reset is triggered
221 // when either of them is true. The bits in the combined status mask will be set
222 // according to whether or not the memento values received in the input were as
223 // expected.
224 //
225 // More specifically, the output of the program will be as follows:
226 // {
227 //   "satisfied_criteria_mask_bit1": emulate_satisfied_criterion_1,
228 //   "satisfied_criteria_mask_bit2": emulate_satisfied_criterion_2,
229 //   "combined_status_mask_bit1":
230 //      (emulate_satisfied_criterion_1 || emulate_satisfied_criterion_2),
231 //   "combined_status_mask_bit2":
232 //      (input["memento_value_in_prefs"] == kTestMementoValue),
233 //   "combined_status_mask_bit3":
234 //      (input["memento_value_in_local_state"] == kTestMementoValue),
235 //   "combined_status_mask_bit4":
236 //      (input["memento_value_in_file"] == kTestMementoValue),
237 //   "should_prompt":
238 //      (emulate_satisfied_criterion_1 || emulate_satisfied_criterion_2),
239 //   "had_prompted_already": <OR-combination of above three>,
240 //   "memento_value_in_prefs": kTestMementoValue,
241 //   "memento_value_in_local_state": kTestMementoValue,
242 //   "memento_value_in_file": kTestMementoValue
243 // }
244 std::string ConstructProgram(bool emulate_satisfied_criterion_1,
245                              bool emulate_satisfied_criterion_2) {
246   std::string bytecode;
247   bytecode += OP_STORE_BOOL(GetHash("satisfied_criteria_mask_bit1"),
248                             EncodeBool(emulate_satisfied_criterion_1));
249   bytecode += OP_END_OF_SENTENCE;
250   bytecode += OP_STORE_BOOL(GetHash("satisfied_criteria_mask_bit2"),
251                             EncodeBool(emulate_satisfied_criterion_2));
252   bytecode += OP_END_OF_SENTENCE;
253   bytecode += OP_STORE_BOOL(GetHash("should_prompt"),
254                             EncodeBool(emulate_satisfied_criterion_1 ||
255                                        emulate_satisfied_criterion_2));
256   bytecode += OP_END_OF_SENTENCE;
257   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit1"),
258                             EncodeBool(emulate_satisfied_criterion_1 ||
259                                        emulate_satisfied_criterion_2));
260   bytecode += OP_END_OF_SENTENCE;
261   bytecode += OP_NAVIGATE(GetHash("memento_value_in_prefs"));
262   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestMementoValue));
263   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit2"), VALUE_TRUE);
264   bytecode += OP_STORE_BOOL(GetHash("had_prompted_already"), VALUE_TRUE);
265   bytecode += OP_END_OF_SENTENCE;
266   bytecode += OP_NAVIGATE(GetHash("memento_value_in_local_state"));
267   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestMementoValue));
268   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit3"), VALUE_TRUE);
269   bytecode += OP_STORE_BOOL(GetHash("had_prompted_already"), VALUE_TRUE);
270   bytecode += OP_END_OF_SENTENCE;
271   bytecode += OP_NAVIGATE(GetHash("memento_value_in_file"));
272   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestMementoValue));
273   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit4"), VALUE_TRUE);
274   bytecode += OP_STORE_BOOL(GetHash("had_prompted_already"), VALUE_TRUE);
275   bytecode += OP_END_OF_SENTENCE;
276   bytecode += OP_STORE_HASH(GetHash("memento_value_in_prefs"),
277                             kTestMementoValue);
278   bytecode += OP_END_OF_SENTENCE;
279   bytecode += OP_STORE_HASH(GetHash("memento_value_in_local_state"),
280                             kTestMementoValue);
281   bytecode += OP_END_OF_SENTENCE;
282   bytecode += OP_STORE_HASH(GetHash("memento_value_in_file"),
283                             kTestMementoValue);
284   bytecode += OP_END_OF_SENTENCE;
285   return bytecode;
286 }
287
288 // Constructs another evaluation program to specifically test that bits of the
289 // "satisfied_criteria_mask" are correctly assigned, and so is "should_prompt";
290 // and that reset is triggered iff the latter is true, regardless of the bits
291 // in the mask (so as to allow for a non-disjunctive compound criterion).
292 //
293 // More specifically, the output of the program will be as follows:
294 // {
295 //   "satisfied_criteria_mask_bitN": emulate_satisfied_odd_criteria,
296 //   "satisfied_criteria_mask_bitM": emulate_satisfied_even_criteria,
297 //   "combined_status_mask_bit1": emulate_should_prompt,
298 //   "should_prompt": emulate_should_prompt,
299 //   "memento_value_in_prefs": kTestMementoValue,
300 //   "memento_value_in_local_state": kTestMementoValue,
301 //   "memento_value_in_file": kTestMementoValue
302 // }
303 // ... such that N is {1,3,5} and M is {2,4}.
304 std::string ConstructProgramToExerciseCriteria(
305     bool emulate_should_prompt,
306     bool emulate_satisfied_odd_criteria,
307     bool emulate_satisfied_even_criteria) {
308   std::string bytecode;
309   bytecode += OP_STORE_BOOL(GetHash("satisfied_criteria_mask_bit1"),
310                             EncodeBool(emulate_satisfied_odd_criteria));
311   bytecode += OP_END_OF_SENTENCE;
312   bytecode += OP_STORE_BOOL(GetHash("satisfied_criteria_mask_bit3"),
313                             EncodeBool(emulate_satisfied_odd_criteria));
314   bytecode += OP_END_OF_SENTENCE;
315   bytecode += OP_STORE_BOOL(GetHash("satisfied_criteria_mask_bit5"),
316                             EncodeBool(emulate_satisfied_odd_criteria));
317   bytecode += OP_END_OF_SENTENCE;
318   bytecode += OP_STORE_BOOL(GetHash("satisfied_criteria_mask_bit2"),
319                             EncodeBool(emulate_satisfied_even_criteria));
320   bytecode += OP_END_OF_SENTENCE;
321   bytecode += OP_STORE_BOOL(GetHash("satisfied_criteria_mask_bit4"),
322                             EncodeBool(emulate_satisfied_even_criteria));
323   bytecode += OP_END_OF_SENTENCE;
324   bytecode += OP_STORE_BOOL(GetHash("should_prompt"),
325                             EncodeBool(emulate_should_prompt));
326   bytecode += OP_END_OF_SENTENCE;
327   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit1"),
328                             EncodeBool(emulate_should_prompt));
329   bytecode += OP_END_OF_SENTENCE;
330   bytecode += OP_STORE_HASH(GetHash("memento_value_in_prefs"),
331                             kTestMementoValue);
332   bytecode += OP_END_OF_SENTENCE;
333   bytecode += OP_STORE_HASH(GetHash("memento_value_in_local_state"),
334                             kTestMementoValue);
335   bytecode += OP_END_OF_SENTENCE;
336   bytecode += OP_STORE_HASH(GetHash("memento_value_in_file"),
337                             kTestMementoValue);
338   bytecode += OP_END_OF_SENTENCE;
339   return bytecode;
340 }
341
342 // Constructs another evaluation program to specifically test that local state
343 // and user preference values are included in the input as expected. We will
344 // re-purpose the output bitmasks to channel out information about the outcome
345 // of the checks.
346 //
347 // More specifically, the output of the program will be as follows:
348 // {
349 //   "combined_status_mask_bit1":
350 //       (input["preferences.testing.preference"] == kTestPreferenceValue)
351 //   "combined_status_mask_bit2":
352 //       (input["local_state.testing.preference"] == kTestPreferenceValue)
353 //   "combined_status_mask_bit3": input["preferences_iuc.testing.preference"]
354 //   "combined_status_mask_bit4": input["local_state_iuc.testing.preference"]
355 // }
356 std::string ConstructProgramToCheckPreferences() {
357   std::string bytecode;
358   bytecode += OP_NAVIGATE(GetHash("preferences"));
359   bytecode += OP_NAVIGATE(GetHash("testing"));
360   bytecode += OP_NAVIGATE(GetHash("preference"));
361   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestPreferenceValue));
362   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit1"),
363                             EncodeBool(true));
364   bytecode += OP_END_OF_SENTENCE;
365   bytecode += OP_NAVIGATE(GetHash("local_state"));
366   bytecode += OP_NAVIGATE(GetHash("testing"));
367   bytecode += OP_NAVIGATE(GetHash("preference"));
368   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestPreferenceValue));
369   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit2"),
370                             EncodeBool(true));
371   bytecode += OP_END_OF_SENTENCE;
372   bytecode += OP_NAVIGATE(GetHash("preferences_iuc"));
373   bytecode += OP_NAVIGATE(GetHash("testing"));
374   bytecode += OP_NAVIGATE(GetHash("preference"));
375   bytecode += OP_COMPARE_NODE_BOOL(EncodeBool(true));
376   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit3"),
377                             EncodeBool(true));
378   bytecode += OP_END_OF_SENTENCE;
379   bytecode += OP_NAVIGATE(GetHash("local_state_iuc"));
380   bytecode += OP_NAVIGATE(GetHash("testing"));
381   bytecode += OP_NAVIGATE(GetHash("preference"));
382   bytecode += OP_COMPARE_NODE_BOOL(EncodeBool(true));
383   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit4"),
384                             EncodeBool(true));
385   bytecode += OP_END_OF_SENTENCE;
386   return bytecode;
387 }
388
389 // Legend for the bitmask returned by the above program.
390 enum CombinedStatusMaskLegendForCheckingPreferences {
391   HAS_EXPECTED_USER_PREFERENCE = 1 << 0,
392   HAS_EXPECTED_LOCAL_STATE_PREFERENCE = 1 << 1,
393   USER_PREFERENCE_IS_USER_CONTROLLED = 1 << 2,
394   LOCAL_STATE_IS_USER_CONTROLLED = 1 << 3,
395 };
396
397 // Constructs yet another evaluation program to specifically test that default
398 // and pre-populated search engines are included in the input as expected. We
399 // will re-purpose the output bitmasks to channel out information about the
400 // outcome of the checks.
401 //
402 // More specifically, the output of the program will be as follows:
403 // {
404 //   "combined_status_mask_bit1":
405 //       (input["default_search_provider.search_url"] == kTestSearchURL)
406 //   "combined_status_mask_bit2": input["default_search_provider_iuc"]
407 //   "combined_status_mask_bit3":
408 //       (input["search_providers.*.search_url"] == kTestSearchURL)
409 //   "combined_status_mask_bit4":
410 //       (input["search_providers.*.search_url"] == kTestSearchURL2)
411 // }
412 std::string ConstructProgramToCheckSearchEngines() {
413   std::string bytecode;
414   bytecode += OP_NAVIGATE(GetHash("default_search_provider"));
415   bytecode += OP_NAVIGATE(GetHash("search_url"));
416   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestSearchURL));
417   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit1"),
418                             EncodeBool(true));
419   bytecode += OP_END_OF_SENTENCE;
420   bytecode += OP_NAVIGATE(GetHash("default_search_provider_iuc"));
421   bytecode += OP_COMPARE_NODE_BOOL(EncodeBool(true));
422   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit2"),
423                             EncodeBool(true));
424   bytecode += OP_END_OF_SENTENCE;
425   bytecode += OP_NAVIGATE(GetHash("search_providers"));
426   bytecode += OP_NAVIGATE_ANY;
427   bytecode += OP_NAVIGATE(GetHash("search_url"));
428   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestSearchURL));
429   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit3"),
430                             EncodeBool(true));
431   bytecode += OP_END_OF_SENTENCE;
432   bytecode += OP_NAVIGATE(GetHash("search_providers"));
433   bytecode += OP_NAVIGATE_ANY;
434   bytecode += OP_NAVIGATE(GetHash("search_url"));
435   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestSearchURL2));
436   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit4"),
437                             EncodeBool(true));
438   bytecode += OP_END_OF_SENTENCE;
439   return bytecode;
440 }
441
442 // Legend for the bitmask returned by the above program.
443 enum CombinedStatusMaskLegendForCheckingSearchEngines {
444   HAS_EXPECTED_DEFAULT_SEARCH_PROVIDER = 1 << 0,
445   DEFAULT_SEARCH_PROVIDER_IS_USER_CONTROLLED = 1 << 1,
446   HAS_EXPECTED_PREPOPULATED_SEARCH_PROVIDER_1 = 1 << 2,
447   HAS_EXPECTED_PREPOPULATED_SEARCH_PROVIDER_2 = 1 << 3,
448 };
449
450 // Constructs yet another evaluation program to specifically test that loaded
451 // module digests are included in the input as expected. We will re-purpose the
452 // output bitmasks to channel out information about the outcome of the checks.
453 //
454 // More specifically, the output of the program will be as follows:
455 // {
456 //   "combined_status_mask_bit1":
457 //       (input["loaded_modules.*"] == kTestModuleDigest)
458 //   "combined_status_mask_bit2":
459 //       (input["loaded_modules.*"] == kTestModuleDigest2)
460 // }
461 std::string ConstructProgramToCheckLoadedModuleDigests() {
462   std::string bytecode;
463   bytecode += OP_NAVIGATE(GetHash("loaded_modules"));
464   bytecode += OP_NAVIGATE_ANY;
465   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestModuleDigest));
466   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit1"),
467                             EncodeBool(true));
468   bytecode += OP_END_OF_SENTENCE;
469   bytecode += OP_NAVIGATE(GetHash("loaded_modules"));
470   bytecode += OP_NAVIGATE_ANY;
471   bytecode += OP_COMPARE_NODE_HASH(GetHash(kTestModuleDigest2));
472   bytecode += OP_STORE_BOOL(GetHash("combined_status_mask_bit2"),
473                             EncodeBool(true));
474   bytecode += OP_END_OF_SENTENCE;
475   return bytecode;
476 }
477
478 // Legend for the bitmask returned by the above program.
479 enum CombinedStatusMaskLegendForCheckingLoadedModules {
480   HAS_EXPECTED_MODULE_DIGEST_1 = 1 << 0,
481   HAS_EXPECTED_MODULE_DIGEST_2 = 1 << 1,
482 };
483
484 // Test fixtures -------------------------------------------------------------
485
486 class AutomaticProfileResetterTestBase : public testing::Test {
487  protected:
488   explicit AutomaticProfileResetterTestBase(
489       const std::string& experiment_group_name)
490       : waiting_task_runner_(new base::TestSimpleTaskRunner),
491         local_state_(TestingBrowserProcess::GetGlobal()),
492         profile_(new TestingProfile()),
493         field_trials_(new base::FieldTrialList(NULL)),
494         memento_in_prefs_(new PreferenceHostedPromptMemento(profile())),
495         memento_in_local_state_(new LocalStateHostedPromptMemento(profile())),
496         memento_in_file_(new FileHostedPromptMementoSynchronous(profile())),
497         experiment_group_name_(experiment_group_name),
498         inject_data_through_variation_params_(false),
499         mock_delegate_(NULL) {
500     // Make sure the factory is not optimized away, so whatever preferences it
501     // wants to register will actually get registered.
502     AutomaticProfileResetterFactory::GetInstance();
503
504     // Register some additional local state preferences for testing purposes.
505     PrefRegistrySimple* local_state_registry = local_state_.Get()->registry();
506     DCHECK(local_state_registry);
507     local_state_registry->RegisterStringPref(kTestPreferencePath, "");
508
509     // Register some additional user preferences for testing purposes.
510     user_prefs::PrefRegistrySyncable* user_prefs_registry =
511         profile_->GetTestingPrefService()->registry();
512     DCHECK(user_prefs_registry);
513     user_prefs_registry->RegisterStringPref(
514         kTestPreferencePath, std::string(),
515         user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
516   }
517
518   virtual void SetUp() OVERRIDE {
519     variations::testing::ClearAllVariationParams();
520     base::FieldTrialList::CreateFieldTrial(kAutomaticProfileResetStudyName,
521                                            experiment_group_name_);
522     resetter_.reset(
523         new testing::StrictMock<AutomaticProfileResetterUnderTest>(profile()));
524     mock_delegate_owned_.reset(
525         new testing::StrictMock<MockProfileResetterDelegate>());
526     mock_delegate_ = mock_delegate_owned_.get();
527
528     ExpectAllMementoValuesEqualTo(std::string());
529   }
530
531   void SetTestingHashSeed(const std::string& hash_seed) {
532     testing_hash_seed_ = hash_seed;
533   }
534
535   void SetTestingProgram(const std::string& source_code) {
536     testing_program_ = source_code;
537   }
538
539   void AllowInjectingTestDataThroughVariationParams(bool value) {
540     inject_data_through_variation_params_ = value;
541   }
542
543   void ExpectAllMementoValuesEqualTo(const std::string& value) {
544     EXPECT_EQ(value, memento_in_prefs_->ReadValue());
545     EXPECT_EQ(value, memento_in_local_state_->ReadValue());
546     EXPECT_EQ(value, memento_in_file_->ReadValue());
547   }
548
549   void UnleashResetterAndWait() {
550     if (inject_data_through_variation_params_) {
551       std::map<std::string, std::string> variation_params;
552       variation_params["program"] = testing_program_;
553       variation_params["hash_seed"] = testing_hash_seed_;
554       ASSERT_TRUE(variations::AssociateVariationParams(
555           kAutomaticProfileResetStudyName,
556           experiment_group_name_,
557           variation_params));
558     }
559     resetter_->Initialize();
560     resetter_->SetDelegateForTesting(
561         mock_delegate_owned_.PassAs<AutomaticProfileResetterDelegate>());
562     resetter_->SetTaskRunnerForWaitingForTesting(waiting_task_runner_);
563     if (!inject_data_through_variation_params_) {
564       resetter_->SetProgramForTesting(testing_program_);
565       resetter_->SetHashSeedForTesting(testing_hash_seed_);
566     }
567     resetter_->Activate();
568
569     if (waiting_task_runner_->HasPendingTask()) {
570       ASSERT_EQ(base::TimeDelta::FromSeconds(55),
571                 waiting_task_runner_->NextPendingTaskDelay());
572       waiting_task_runner_->RunPendingTasks();
573     }
574     base::RunLoop().RunUntilIdle();
575     content::BrowserThread::GetBlockingPool()->FlushForTesting();
576     base::RunLoop().RunUntilIdle();
577   }
578
579   // Goes through an evaluation flow such that the reset criteria are satisfied.
580   // Used to reduce boilerplate for tests that need to verify behavior during
581   // the reset prompt flow.
582   void OrchestrateThroughEvaluationFlow() {
583     SetTestingProgram(ConstructProgram(true, true));
584     SetTestingHashSeed(kTestHashSeed);
585
586     mock_delegate().ExpectCallsToDependenciesSetUpMethods();
587     mock_delegate().ExpectCallsToGetterMethods();
588     mock_delegate().ExpectCallToShowPrompt();
589     EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x01u));
590
591     UnleashResetterAndWait();
592
593     EXPECT_TRUE(resetter().ShouldShowResetBanner());
594     testing::Mock::VerifyAndClearExpectations(&resetter());
595     testing::Mock::VerifyAndClearExpectations(&mock_delegate());
596   }
597
598   // Explicitly shut down the service to double-check that nothing explodes, but
599   // first, verify expectations to make sure the service makes no more calls to
600   // any mocked functions during or after shutdown.
601   void VerifyExpectationsThenShutdownResetter() {
602     testing::Mock::VerifyAndClearExpectations(&resetter());
603     testing::Mock::VerifyAndClearExpectations(&mock_delegate());
604
605     resetter_->Shutdown();
606     resetter_.reset();
607   }
608
609   TestingProfile* profile() { return profile_.get(); }
610   TestingPrefServiceSimple* local_state() { return local_state_.Get(); }
611
612   PreferenceHostedPromptMemento& memento_in_prefs() {
613     return *memento_in_prefs_;
614   }
615
616   LocalStateHostedPromptMemento& memento_in_local_state() {
617     return *memento_in_local_state_;
618   }
619
620   FileHostedPromptMementoSynchronous& memento_in_file() {
621     return *memento_in_file_;
622   }
623
624   MockProfileResetterDelegate& mock_delegate() { return *mock_delegate_; }
625   AutomaticProfileResetterUnderTest& resetter() { return *resetter_; }
626
627  private:
628   content::TestBrowserThreadBundle thread_bundle_;
629   scoped_refptr<base::TestSimpleTaskRunner> waiting_task_runner_;
630   ScopedTestingLocalState local_state_;
631   scoped_ptr<TestingProfile> profile_;
632   scoped_ptr<base::FieldTrialList> field_trials_;
633   scoped_ptr<PreferenceHostedPromptMemento> memento_in_prefs_;
634   scoped_ptr<LocalStateHostedPromptMemento> memento_in_local_state_;
635   scoped_ptr<FileHostedPromptMementoSynchronous> memento_in_file_;
636
637   std::string experiment_group_name_;
638   std::string testing_program_;
639   std::string testing_hash_seed_;
640   bool inject_data_through_variation_params_;
641
642   scoped_ptr<AutomaticProfileResetterUnderTest> resetter_;
643   scoped_ptr<MockProfileResetterDelegate> mock_delegate_owned_;
644   MockProfileResetterDelegate* mock_delegate_;
645
646   DISALLOW_COPY_AND_ASSIGN(AutomaticProfileResetterTestBase);
647 };
648
649 class AutomaticProfileResetterTest : public AutomaticProfileResetterTestBase {
650  protected:
651   AutomaticProfileResetterTest()
652       : AutomaticProfileResetterTestBase(kStudyEnabledGroupName) {}
653 };
654
655 class AutomaticProfileResetterTestDryRun
656     : public AutomaticProfileResetterTestBase {
657  protected:
658   AutomaticProfileResetterTestDryRun()
659       : AutomaticProfileResetterTestBase(kStudyDryRunGroupName) {}
660 };
661
662 class AutomaticProfileResetterTestDisabled
663     : public AutomaticProfileResetterTestBase {
664  protected:
665   AutomaticProfileResetterTestDisabled()
666       : AutomaticProfileResetterTestBase(kStudyDisabledGroupName) {}
667 };
668
669 // Tests ---------------------------------------------------------------------
670
671 TEST_F(AutomaticProfileResetterTestDisabled, NothingIsDoneWhenDisabled) {
672   SetTestingProgram(ConstructProgram(true, true));
673   SetTestingHashSeed(kTestHashSeed);
674
675   // No calls are expected to the delegate.
676
677   UnleashResetterAndWait();
678
679   EXPECT_FALSE(resetter().ShouldShowResetBanner());
680   VerifyExpectationsThenShutdownResetter();
681
682   ExpectAllMementoValuesEqualTo(std::string());
683 }
684
685 TEST_F(AutomaticProfileResetterTestDryRun, CriteriaNotSatisfied) {
686   SetTestingProgram(ConstructProgramToExerciseCriteria(false, true, true));
687   SetTestingHashSeed(kTestHashSeed);
688
689   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
690   mock_delegate().ExpectCallsToGetterMethods();
691   EXPECT_CALL(resetter(), ReportStatistics(0x1fu, 0x00u));
692
693   UnleashResetterAndWait();
694
695   EXPECT_FALSE(resetter().ShouldShowResetBanner());
696   VerifyExpectationsThenShutdownResetter();
697
698   ExpectAllMementoValuesEqualTo(std::string());
699 }
700
701 TEST_F(AutomaticProfileResetterTestDryRun, OddCriteriaSatisfied) {
702   SetTestingProgram(ConstructProgramToExerciseCriteria(true, true, false));
703   SetTestingHashSeed(kTestHashSeed);
704
705   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
706   mock_delegate().ExpectCallsToGetterMethods();
707   EXPECT_CALL(resetter(), ReportStatistics(0x15u, 0x01u));
708   EXPECT_CALL(resetter(), ReportPromptResult(
709       AutomaticProfileResetter::PROMPT_NOT_TRIGGERED));
710
711   UnleashResetterAndWait();
712
713   ExpectAllMementoValuesEqualTo(kTestMementoValue);
714   EXPECT_FALSE(resetter().ShouldShowResetBanner());
715   VerifyExpectationsThenShutdownResetter();
716 }
717
718 TEST_F(AutomaticProfileResetterTestDryRun, EvenCriteriaSatisfied) {
719   SetTestingProgram(ConstructProgramToExerciseCriteria(true, false, true));
720   SetTestingHashSeed(kTestHashSeed);
721
722   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
723   mock_delegate().ExpectCallsToGetterMethods();
724   EXPECT_CALL(resetter(), ReportStatistics(0x0au, 0x01u));
725   EXPECT_CALL(resetter(), ReportPromptResult(
726       AutomaticProfileResetter::PROMPT_NOT_TRIGGERED));
727
728   UnleashResetterAndWait();
729
730   ExpectAllMementoValuesEqualTo(kTestMementoValue);
731   EXPECT_FALSE(resetter().ShouldShowResetBanner());
732   VerifyExpectationsThenShutdownResetter();
733 }
734
735 #if defined(GOOGLE_CHROME_BUILD)
736 TEST_F(AutomaticProfileResetterTestDryRun, ProgramSetThroughVariationParams) {
737   SetTestingProgram(ConstructProgram(true, true));
738   SetTestingHashSeed(kTestHashSeed);
739   AllowInjectingTestDataThroughVariationParams(true);
740
741   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
742   mock_delegate().ExpectCallsToGetterMethods();
743   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x01u));
744   EXPECT_CALL(resetter(), ReportPromptResult(
745       AutomaticProfileResetter::PROMPT_NOT_TRIGGERED));
746
747   UnleashResetterAndWait();
748
749   ExpectAllMementoValuesEqualTo(kTestMementoValue);
750   EXPECT_FALSE(resetter().ShouldShowResetBanner());
751   VerifyExpectationsThenShutdownResetter();
752 }
753 #endif
754
755 TEST_F(AutomaticProfileResetterTestDryRun,
756        ConditionsSatisfiedAndInvalidMementos) {
757   memento_in_prefs().StoreValue(kTestInvalidMementoValue);
758   memento_in_local_state().StoreValue(kTestInvalidMementoValue);
759   memento_in_file().StoreValue(kTestInvalidMementoValue);
760
761   SetTestingProgram(ConstructProgram(true, true));
762   SetTestingHashSeed(kTestHashSeed);
763
764   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
765   mock_delegate().ExpectCallsToGetterMethods();
766   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x01u));
767   EXPECT_CALL(resetter(), ReportPromptResult(
768       AutomaticProfileResetter::PROMPT_NOT_TRIGGERED));
769
770   UnleashResetterAndWait();
771
772   ExpectAllMementoValuesEqualTo(kTestMementoValue);
773   EXPECT_FALSE(resetter().ShouldShowResetBanner());
774   VerifyExpectationsThenShutdownResetter();
775 }
776
777 TEST_F(AutomaticProfileResetterTestDryRun, AlreadyHadPrefHostedMemento) {
778   memento_in_prefs().StoreValue(kTestMementoValue);
779
780   SetTestingProgram(ConstructProgram(true, true));
781   SetTestingHashSeed(kTestHashSeed);
782
783   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
784   mock_delegate().ExpectCallsToGetterMethods();
785   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x03u));
786
787   UnleashResetterAndWait();
788
789   EXPECT_FALSE(resetter().ShouldShowResetBanner());
790   VerifyExpectationsThenShutdownResetter();
791
792   EXPECT_EQ(kTestMementoValue, memento_in_prefs().ReadValue());
793   EXPECT_EQ(std::string(), memento_in_local_state().ReadValue());
794   EXPECT_EQ(std::string(), memento_in_file().ReadValue());
795 }
796
797 TEST_F(AutomaticProfileResetterTestDryRun, AlreadyHadLocalStateHostedMemento) {
798   memento_in_local_state().StoreValue(kTestMementoValue);
799
800   SetTestingProgram(ConstructProgram(true, true));
801   SetTestingHashSeed(kTestHashSeed);
802
803   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
804   mock_delegate().ExpectCallsToGetterMethods();
805   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x05u));
806
807   UnleashResetterAndWait();
808
809   EXPECT_FALSE(resetter().ShouldShowResetBanner());
810   VerifyExpectationsThenShutdownResetter();
811
812   EXPECT_EQ(std::string(), memento_in_prefs().ReadValue());
813   EXPECT_EQ(kTestMementoValue, memento_in_local_state().ReadValue());
814   EXPECT_EQ(std::string(), memento_in_file().ReadValue());
815 }
816
817 TEST_F(AutomaticProfileResetterTestDryRun, AlreadyHadFileHostedMemento) {
818   memento_in_file().StoreValue(kTestMementoValue);
819
820   SetTestingProgram(ConstructProgram(true, true));
821   SetTestingHashSeed(kTestHashSeed);
822
823   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
824   mock_delegate().ExpectCallsToGetterMethods();
825   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x09u));
826
827   UnleashResetterAndWait();
828
829   EXPECT_FALSE(resetter().ShouldShowResetBanner());
830   VerifyExpectationsThenShutdownResetter();
831
832   EXPECT_EQ(std::string(), memento_in_prefs().ReadValue());
833   EXPECT_EQ(std::string(), memento_in_local_state().ReadValue());
834   EXPECT_EQ(kTestMementoValue, memento_in_file().ReadValue());
835 }
836
837 TEST_F(AutomaticProfileResetterTestDryRun, DoNothingWhenResourcesAreMissing) {
838   SetTestingProgram(std::string());
839   SetTestingHashSeed(std::string());
840
841   // No calls are expected to the delegate.
842
843   UnleashResetterAndWait();
844
845   EXPECT_FALSE(resetter().ShouldShowResetBanner());
846   VerifyExpectationsThenShutdownResetter();
847
848   ExpectAllMementoValuesEqualTo(std::string());
849 }
850
851 TEST_F(AutomaticProfileResetterTest, CriteriaNotSatisfied) {
852   SetTestingProgram(ConstructProgramToExerciseCriteria(false, true, true));
853   SetTestingHashSeed(kTestHashSeed);
854
855   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
856   mock_delegate().ExpectCallsToGetterMethods();
857   EXPECT_CALL(resetter(), ReportStatistics(0x1fu, 0x00u));
858
859   UnleashResetterAndWait();
860
861   EXPECT_FALSE(resetter().ShouldShowResetBanner());
862   VerifyExpectationsThenShutdownResetter();
863
864   ExpectAllMementoValuesEqualTo(std::string());
865 }
866
867 TEST_F(AutomaticProfileResetterTest, OddCriteriaSatisfied) {
868   SetTestingProgram(ConstructProgramToExerciseCriteria(true, true, false));
869   SetTestingHashSeed(kTestHashSeed);
870
871   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
872   mock_delegate().ExpectCallsToGetterMethods();
873   mock_delegate().ExpectCallToShowPrompt();
874   EXPECT_CALL(resetter(), ReportStatistics(0x15u, 0x01u));
875
876   UnleashResetterAndWait();
877
878   EXPECT_TRUE(resetter().ShouldShowResetBanner());
879   VerifyExpectationsThenShutdownResetter();
880 }
881
882 TEST_F(AutomaticProfileResetterTest, EvenCriteriaSatisfied) {
883   SetTestingProgram(ConstructProgramToExerciseCriteria(true, false, true));
884   SetTestingHashSeed(kTestHashSeed);
885
886   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
887   mock_delegate().ExpectCallsToGetterMethods();
888   mock_delegate().ExpectCallToShowPrompt();
889   EXPECT_CALL(resetter(), ReportStatistics(0x0au, 0x01u));
890
891   UnleashResetterAndWait();
892
893   EXPECT_TRUE(resetter().ShouldShowResetBanner());
894   VerifyExpectationsThenShutdownResetter();
895 }
896
897 #if defined(GOOGLE_CHROME_BUILD)
898 TEST_F(AutomaticProfileResetterTest, ProgramSetThroughVariationParams) {
899   SetTestingProgram(ConstructProgram(true, true));
900   SetTestingHashSeed(kTestHashSeed);
901   AllowInjectingTestDataThroughVariationParams(true);
902
903   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
904   mock_delegate().ExpectCallsToGetterMethods();
905   mock_delegate().ExpectCallToShowPrompt();
906   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x01u));
907   EXPECT_CALL(resetter(), ReportPromptResult(
908       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
909
910   UnleashResetterAndWait();
911   resetter().NotifyDidShowResetBubble();
912
913   ExpectAllMementoValuesEqualTo(kTestMementoValue);
914   EXPECT_TRUE(resetter().ShouldShowResetBanner());
915   VerifyExpectationsThenShutdownResetter();
916 }
917 #endif
918
919 TEST_F(AutomaticProfileResetterTest, ConditionsSatisfiedAndInvalidMementos) {
920   memento_in_prefs().StoreValue(kTestInvalidMementoValue);
921   memento_in_local_state().StoreValue(kTestInvalidMementoValue);
922   memento_in_file().StoreValue(kTestInvalidMementoValue);
923
924   SetTestingProgram(ConstructProgram(true, true));
925   SetTestingHashSeed(kTestHashSeed);
926
927   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
928   mock_delegate().ExpectCallsToGetterMethods();
929   mock_delegate().ExpectCallToShowPrompt();
930   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x01u));
931   EXPECT_CALL(resetter(), ReportPromptResult(
932       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
933
934   UnleashResetterAndWait();
935   resetter().NotifyDidShowResetBubble();
936
937   ExpectAllMementoValuesEqualTo(kTestMementoValue);
938   EXPECT_TRUE(resetter().ShouldShowResetBanner());
939   VerifyExpectationsThenShutdownResetter();
940 }
941
942 TEST_F(AutomaticProfileResetterTest, PrefHostedMementoPreventsPrompt) {
943   memento_in_prefs().StoreValue(kTestMementoValue);
944
945   SetTestingProgram(ConstructProgram(true, true));
946   SetTestingHashSeed(kTestHashSeed);
947
948   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
949   mock_delegate().ExpectCallsToGetterMethods();
950   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x03u));
951
952   UnleashResetterAndWait();
953
954   EXPECT_TRUE(resetter().ShouldShowResetBanner());
955   VerifyExpectationsThenShutdownResetter();
956
957   EXPECT_EQ(kTestMementoValue, memento_in_prefs().ReadValue());
958   EXPECT_EQ(std::string(), memento_in_local_state().ReadValue());
959   EXPECT_EQ(std::string(), memento_in_file().ReadValue());
960 }
961
962 TEST_F(AutomaticProfileResetterTest, LocalStateHostedMementoPreventsPrompt) {
963   memento_in_local_state().StoreValue(kTestMementoValue);
964
965   SetTestingProgram(ConstructProgram(true, true));
966   SetTestingHashSeed(kTestHashSeed);
967
968   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
969   mock_delegate().ExpectCallsToGetterMethods();
970   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x05u));
971
972   UnleashResetterAndWait();
973
974   EXPECT_TRUE(resetter().ShouldShowResetBanner());
975   VerifyExpectationsThenShutdownResetter();
976
977   EXPECT_EQ(std::string(), memento_in_prefs().ReadValue());
978   EXPECT_EQ(kTestMementoValue, memento_in_local_state().ReadValue());
979   EXPECT_EQ(std::string(), memento_in_file().ReadValue());
980 }
981
982 TEST_F(AutomaticProfileResetterTest, FileHostedMementoPreventsPrompt) {
983   memento_in_file().StoreValue(kTestMementoValue);
984
985   SetTestingProgram(ConstructProgram(true, true));
986   SetTestingHashSeed(kTestHashSeed);
987
988   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
989   mock_delegate().ExpectCallsToGetterMethods();
990   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x09u));
991
992   UnleashResetterAndWait();
993
994   EXPECT_TRUE(resetter().ShouldShowResetBanner());
995   VerifyExpectationsThenShutdownResetter();
996
997   EXPECT_EQ(std::string(), memento_in_prefs().ReadValue());
998   EXPECT_EQ(std::string(), memento_in_local_state().ReadValue());
999   EXPECT_EQ(kTestMementoValue, memento_in_file().ReadValue());
1000 }
1001
1002 TEST_F(AutomaticProfileResetterTest, DoNothingWhenResourcesAreMissing) {
1003   SetTestingProgram(std::string());
1004   SetTestingHashSeed(std::string());
1005
1006   // No calls are expected to the delegate.
1007
1008   UnleashResetterAndWait();
1009
1010   EXPECT_FALSE(resetter().ShouldShowResetBanner());
1011   VerifyExpectationsThenShutdownResetter();
1012
1013   ExpectAllMementoValuesEqualTo(std::string());
1014 }
1015
1016 TEST_F(AutomaticProfileResetterTest, PromptSuppressed) {
1017   OrchestrateThroughEvaluationFlow();
1018
1019   VerifyExpectationsThenShutdownResetter();
1020
1021   ExpectAllMementoValuesEqualTo(std::string());
1022 }
1023
1024 TEST_F(AutomaticProfileResetterTest, PromptNotSupported) {
1025   SetTestingProgram(ConstructProgram(true, true));
1026   SetTestingHashSeed(kTestHashSeed);
1027
1028   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1029   mock_delegate().ExpectCallsToGetterMethods();
1030   EXPECT_CALL(mock_delegate(), TriggerPrompt())
1031       .WillOnce(testing::Return(false));
1032   EXPECT_CALL(resetter(), ReportStatistics(0x03u, 0x01u));
1033   EXPECT_CALL(resetter(), ReportPromptResult(
1034       AutomaticProfileResetter::PROMPT_NOT_TRIGGERED));
1035
1036   UnleashResetterAndWait();
1037
1038   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1039   EXPECT_TRUE(resetter().ShouldShowResetBanner());
1040   VerifyExpectationsThenShutdownResetter();
1041 }
1042
1043 TEST_F(AutomaticProfileResetterTest, PromptIgnored) {
1044   OrchestrateThroughEvaluationFlow();
1045
1046   EXPECT_CALL(resetter(), ReportPromptResult(
1047       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
1048   resetter().NotifyDidShowResetBubble();
1049   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1050   VerifyExpectationsThenShutdownResetter();
1051 }
1052
1053 TEST_F(AutomaticProfileResetterTest, PromptActionReset) {
1054   OrchestrateThroughEvaluationFlow();
1055
1056   EXPECT_CALL(resetter(), ReportPromptResult(
1057       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
1058   resetter().NotifyDidShowResetBubble();
1059   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1060   testing::Mock::VerifyAndClearExpectations(&resetter());
1061
1062   mock_delegate().ExpectCallToTriggerReset(false);
1063   EXPECT_CALL(resetter(), ReportPromptResult(
1064       AutomaticProfileResetter::PROMPT_ACTION_RESET));
1065   resetter().TriggerProfileReset(false /*send_feedback*/);
1066   testing::Mock::VerifyAndClearExpectations(&resetter());
1067   testing::Mock::VerifyAndClearExpectations(&mock_delegate());
1068
1069   EXPECT_CALL(mock_delegate(), DismissPrompt());
1070   mock_delegate().EmulateProfileResetCompleted();
1071   EXPECT_FALSE(resetter().ShouldShowResetBanner());
1072   VerifyExpectationsThenShutdownResetter();
1073 }
1074
1075 TEST_F(AutomaticProfileResetterTest, PromptActionResetWithFeedback) {
1076   OrchestrateThroughEvaluationFlow();
1077
1078   EXPECT_CALL(resetter(), ReportPromptResult(
1079       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
1080   resetter().NotifyDidShowResetBubble();
1081   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1082   testing::Mock::VerifyAndClearExpectations(&resetter());
1083
1084   mock_delegate().ExpectCallToTriggerReset(true);
1085   EXPECT_CALL(resetter(), ReportPromptResult(
1086       AutomaticProfileResetter::PROMPT_ACTION_RESET));
1087   resetter().TriggerProfileReset(true /*send_feedback*/);
1088   testing::Mock::VerifyAndClearExpectations(&resetter());
1089   testing::Mock::VerifyAndClearExpectations(&mock_delegate());
1090
1091   EXPECT_CALL(mock_delegate(), DismissPrompt());
1092   mock_delegate().EmulateProfileResetCompleted();
1093   EXPECT_FALSE(resetter().ShouldShowResetBanner());
1094   VerifyExpectationsThenShutdownResetter();
1095 }
1096
1097 TEST_F(AutomaticProfileResetterTest, PromptActionNoReset) {
1098   OrchestrateThroughEvaluationFlow();
1099
1100   EXPECT_CALL(resetter(), ReportPromptResult(
1101       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
1102   resetter().NotifyDidShowResetBubble();
1103   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1104   testing::Mock::VerifyAndClearExpectations(&resetter());
1105
1106   EXPECT_CALL(mock_delegate(), DismissPrompt());
1107   EXPECT_CALL(resetter(), ReportPromptResult(
1108       AutomaticProfileResetter::PROMPT_ACTION_NO_RESET));
1109   resetter().SkipProfileReset();
1110   EXPECT_FALSE(resetter().ShouldShowResetBanner());
1111   VerifyExpectationsThenShutdownResetter();
1112 }
1113
1114 TEST_F(AutomaticProfileResetterTest, PromptFollowedByWebUIReset) {
1115   OrchestrateThroughEvaluationFlow();
1116
1117   EXPECT_CALL(resetter(), ReportPromptResult(
1118       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
1119   resetter().NotifyDidShowResetBubble();
1120   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1121   testing::Mock::VerifyAndClearExpectations(&resetter());
1122
1123   EXPECT_CALL(mock_delegate(), DismissPrompt());
1124   resetter().NotifyDidOpenWebUIResetDialog();
1125   testing::Mock::VerifyAndClearExpectations(&mock_delegate());
1126
1127   EXPECT_CALL(resetter(), ReportPromptResult(
1128       AutomaticProfileResetter::PROMPT_FOLLOWED_BY_WEBUI_RESET));
1129   resetter().NotifyDidCloseWebUIResetDialog(true);
1130   EXPECT_TRUE(resetter().ShouldShowResetBanner());
1131   VerifyExpectationsThenShutdownResetter();
1132 }
1133
1134 TEST_F(AutomaticProfileResetterTest, PromptFollowedByWebUINoReset) {
1135   OrchestrateThroughEvaluationFlow();
1136
1137   EXPECT_CALL(resetter(), ReportPromptResult(
1138       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
1139   resetter().NotifyDidShowResetBubble();
1140   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1141   testing::Mock::VerifyAndClearExpectations(&resetter());
1142
1143   EXPECT_CALL(mock_delegate(), DismissPrompt());
1144   resetter().NotifyDidOpenWebUIResetDialog();
1145   testing::Mock::VerifyAndClearExpectations(&mock_delegate());
1146
1147   EXPECT_CALL(resetter(), ReportPromptResult(
1148       AutomaticProfileResetter::PROMPT_FOLLOWED_BY_WEBUI_NO_RESET));
1149   resetter().NotifyDidCloseWebUIResetDialog(false);
1150   EXPECT_TRUE(resetter().ShouldShowResetBanner());
1151   VerifyExpectationsThenShutdownResetter();
1152 }
1153
1154 TEST_F(AutomaticProfileResetterTest, PromptFollowedByIncidentalWebUIReset) {
1155   OrchestrateThroughEvaluationFlow();
1156
1157   EXPECT_CALL(resetter(), ReportPromptResult(
1158       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
1159   resetter().NotifyDidShowResetBubble();
1160   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1161   testing::Mock::VerifyAndClearExpectations(&resetter());
1162
1163   // Missing NotifyDidOpenWebUIResetDialog().
1164   // This can arise if a settings page was already opened at the time the prompt
1165   // was triggered, and this already opened dialog was used to initiate a reset
1166   // after having dismissed the prompt.
1167
1168   EXPECT_CALL(mock_delegate(), DismissPrompt());
1169   EXPECT_CALL(resetter(), ReportPromptResult(
1170       AutomaticProfileResetter::PROMPT_FOLLOWED_BY_WEBUI_RESET));
1171   resetter().NotifyDidCloseWebUIResetDialog(true);
1172   EXPECT_TRUE(resetter().ShouldShowResetBanner());
1173   VerifyExpectationsThenShutdownResetter();
1174 }
1175
1176 TEST_F(AutomaticProfileResetterTest, PromptSuppressedButHadWebUIReset) {
1177   OrchestrateThroughEvaluationFlow();
1178
1179   EXPECT_CALL(mock_delegate(), DismissPrompt());
1180   resetter().NotifyDidOpenWebUIResetDialog();
1181   testing::Mock::VerifyAndClearExpectations(&mock_delegate());
1182
1183   EXPECT_CALL(resetter(), ReportPromptResult(
1184       AutomaticProfileResetter::PROMPT_NOT_SHOWN_BUBBLE_BUT_HAD_WEBUI_RESET));
1185   resetter().NotifyDidCloseWebUIResetDialog(true);
1186   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1187   EXPECT_TRUE(resetter().ShouldShowResetBanner());
1188   VerifyExpectationsThenShutdownResetter();
1189 }
1190
1191 TEST_F(AutomaticProfileResetterTest, PromptSuppressedButHadWebUINoReset) {
1192   OrchestrateThroughEvaluationFlow();
1193
1194   EXPECT_CALL(mock_delegate(), DismissPrompt());
1195   resetter().NotifyDidOpenWebUIResetDialog();
1196   testing::Mock::VerifyAndClearExpectations(&mock_delegate());
1197
1198   EXPECT_CALL(resetter(), ReportPromptResult(AutomaticProfileResetter::
1199       PROMPT_NOT_SHOWN_BUBBLE_BUT_HAD_WEBUI_NO_RESET));
1200   resetter().NotifyDidCloseWebUIResetDialog(false);
1201   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1202   EXPECT_TRUE(resetter().ShouldShowResetBanner());
1203   VerifyExpectationsThenShutdownResetter();
1204 }
1205
1206 TEST_F(AutomaticProfileResetterTest, BannerDismissed) {
1207   OrchestrateThroughEvaluationFlow();
1208
1209   EXPECT_CALL(resetter(), ReportPromptResult(
1210       AutomaticProfileResetter::PROMPT_SHOWN_BUBBLE));
1211   resetter().NotifyDidShowResetBubble();
1212   ExpectAllMementoValuesEqualTo(kTestMementoValue);
1213   testing::Mock::VerifyAndClearExpectations(&resetter());
1214
1215   resetter().NotifyDidCloseWebUIResetBanner();
1216
1217   EXPECT_TRUE(resetter().IsResetPromptFlowActive());
1218   EXPECT_FALSE(resetter().ShouldShowResetBanner());
1219
1220   // Note: we use strict mocks, so this also checks the bubble is not closed.
1221   VerifyExpectationsThenShutdownResetter();
1222 }
1223
1224 TEST_F(AutomaticProfileResetterTest, BannerDismissedWhilePromptSuppressed) {
1225   OrchestrateThroughEvaluationFlow();
1226
1227   resetter().NotifyDidCloseWebUIResetBanner();
1228
1229   EXPECT_TRUE(resetter().IsResetPromptFlowActive());
1230   EXPECT_FALSE(resetter().ShouldShowResetBanner());
1231   VerifyExpectationsThenShutdownResetter();
1232
1233   ExpectAllMementoValuesEqualTo(std::string());
1234 }
1235
1236 // Please see comments above ConstructProgramToCheckPreferences() to understand
1237 // how the following tests work.
1238
1239 TEST_F(AutomaticProfileResetterTest, InputUserPreferencesCorrect) {
1240   SetTestingProgram(ConstructProgramToCheckPreferences());
1241   SetTestingHashSeed(kTestHashSeed);
1242
1243   PrefService* prefs = profile()->GetPrefs();
1244   prefs->SetString(kTestPreferencePath, kTestPreferenceValue);
1245
1246   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1247   mock_delegate().ExpectCallsToGetterMethods();
1248   uint32 expected_mask = HAS_EXPECTED_USER_PREFERENCE |
1249                          USER_PREFERENCE_IS_USER_CONTROLLED;
1250   EXPECT_CALL(resetter(), ReportStatistics(0x00u, expected_mask));
1251
1252   UnleashResetterAndWait();
1253 }
1254
1255 TEST_F(AutomaticProfileResetterTest, InputLocalStateCorrect) {
1256   SetTestingProgram(ConstructProgramToCheckPreferences());
1257   SetTestingHashSeed(kTestHashSeed);
1258
1259   PrefService* prefs = local_state();
1260   prefs->SetString(kTestPreferencePath, kTestPreferenceValue);
1261
1262   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1263   mock_delegate().ExpectCallsToGetterMethods();
1264   uint32 expected_mask = HAS_EXPECTED_LOCAL_STATE_PREFERENCE |
1265                          LOCAL_STATE_IS_USER_CONTROLLED;
1266   EXPECT_CALL(resetter(), ReportStatistics(0x00u, expected_mask));
1267
1268   UnleashResetterAndWait();
1269 }
1270
1271 TEST_F(AutomaticProfileResetterTest, InputManagedUserPreferencesCorrect) {
1272   SetTestingProgram(ConstructProgramToCheckPreferences());
1273   SetTestingHashSeed(kTestHashSeed);
1274
1275   TestingPrefServiceSyncable* prefs = profile()->GetTestingPrefService();
1276   prefs->SetManagedPref(kTestPreferencePath,
1277                         new base::StringValue(kTestPreferenceValue));
1278
1279   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1280   mock_delegate().ExpectCallsToGetterMethods();
1281   uint32 expected_mask = HAS_EXPECTED_USER_PREFERENCE;
1282   EXPECT_CALL(resetter(), ReportStatistics(0x00u, expected_mask));
1283
1284   UnleashResetterAndWait();
1285 }
1286
1287 TEST_F(AutomaticProfileResetterTest, InputManagedLocalStateCorrect) {
1288   SetTestingProgram(ConstructProgramToCheckPreferences());
1289   SetTestingHashSeed(kTestHashSeed);
1290
1291   TestingPrefServiceSimple* prefs = local_state();
1292   prefs->SetManagedPref(kTestPreferencePath,
1293                         new base::StringValue(kTestPreferenceValue));
1294
1295   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1296   mock_delegate().ExpectCallsToGetterMethods();
1297   uint32 expected_mask = HAS_EXPECTED_LOCAL_STATE_PREFERENCE;
1298   EXPECT_CALL(resetter(), ReportStatistics(0x00u, expected_mask));
1299
1300   UnleashResetterAndWait();
1301 }
1302
1303 // Please see comments above ConstructProgramToCheckSearchEngines() to
1304 // understand how the following tests work.
1305
1306 TEST_F(AutomaticProfileResetterTest, InputDefaultSearchProviderCorrect) {
1307   SetTestingProgram(ConstructProgramToCheckSearchEngines());
1308   SetTestingHashSeed(kTestHashSeed);
1309
1310   mock_delegate().emulated_default_search_provider_details().SetString(
1311       kSearchURLAttributeKey, kTestSearchURL);
1312
1313   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1314   mock_delegate().ExpectCallsToGetterMethods();
1315   uint32 expected_mask = HAS_EXPECTED_DEFAULT_SEARCH_PROVIDER |
1316                          DEFAULT_SEARCH_PROVIDER_IS_USER_CONTROLLED;
1317   EXPECT_CALL(resetter(), ReportStatistics(0x00u, expected_mask));
1318
1319   UnleashResetterAndWait();
1320 }
1321
1322 TEST_F(AutomaticProfileResetterTest, InputSearchProviderManagedCorrect) {
1323   SetTestingProgram(ConstructProgramToCheckSearchEngines());
1324   SetTestingHashSeed(kTestHashSeed);
1325
1326   mock_delegate().emulated_default_search_provider_details().SetString(
1327       kSearchURLAttributeKey, kTestSearchURL);
1328   mock_delegate().set_emulated_is_default_search_provider_managed(true);
1329
1330   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1331   mock_delegate().ExpectCallsToGetterMethods();
1332   uint32 expected_mask = HAS_EXPECTED_DEFAULT_SEARCH_PROVIDER;
1333   EXPECT_CALL(resetter(), ReportStatistics(0x00u, expected_mask));
1334
1335   UnleashResetterAndWait();
1336 }
1337
1338 TEST_F(AutomaticProfileResetterTest, InputSearchProvidersCorrect) {
1339   SetTestingProgram(ConstructProgramToCheckSearchEngines());
1340   SetTestingHashSeed(kTestHashSeed);
1341
1342   base::DictionaryValue* search_provider_1 = new base::DictionaryValue;
1343   base::DictionaryValue* search_provider_2 = new base::DictionaryValue;
1344   search_provider_1->SetString(kSearchURLAttributeKey, kTestSearchURL);
1345   search_provider_2->SetString(kSearchURLAttributeKey, kTestSearchURL2);
1346   mock_delegate().emulated_search_providers_details().Append(search_provider_1);
1347   mock_delegate().emulated_search_providers_details().Append(search_provider_2);
1348
1349   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1350   mock_delegate().ExpectCallsToGetterMethods();
1351   uint32 expected_mask = DEFAULT_SEARCH_PROVIDER_IS_USER_CONTROLLED |
1352                          HAS_EXPECTED_PREPOPULATED_SEARCH_PROVIDER_1 |
1353                          HAS_EXPECTED_PREPOPULATED_SEARCH_PROVIDER_2;
1354   EXPECT_CALL(resetter(), ReportStatistics(0x00u, expected_mask));
1355
1356   UnleashResetterAndWait();
1357 }
1358
1359 // Please see comments above ConstructProgramToCheckLoadedModuleDigests() to
1360 // understand how the following tests work.
1361
1362 TEST_F(AutomaticProfileResetterTest, InputModuleDigestsCorrect) {
1363   SetTestingProgram(ConstructProgramToCheckLoadedModuleDigests());
1364   SetTestingHashSeed(kTestHashSeed);
1365
1366   mock_delegate().emulated_loaded_module_digests().AppendString(
1367       kTestModuleDigest);
1368   mock_delegate().emulated_loaded_module_digests().AppendString(
1369       kTestModuleDigest2);
1370
1371   mock_delegate().ExpectCallsToDependenciesSetUpMethods();
1372   mock_delegate().ExpectCallsToGetterMethods();
1373   uint32 expected_mask =
1374       HAS_EXPECTED_MODULE_DIGEST_1 | HAS_EXPECTED_MODULE_DIGEST_2;
1375   EXPECT_CALL(resetter(), ReportStatistics(0x00u, expected_mask));
1376
1377   UnleashResetterAndWait();
1378 }
1379
1380 }  // namespace