Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / profile_resetter / automatic_profile_resetter_delegate_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_delegate.h"
6
7 #include <algorithm>
8
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/prefs/pref_service.h"
14 #include "base/run_loop.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_split.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/test/values_test_util.h"
20 #include "base/values.h"
21 #include "chrome/app/chrome_command_ids.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/extensions/extension_service_unittest.h"
24 #include "chrome/browser/google/google_util.h"
25 #include "chrome/browser/profile_resetter/brandcoded_default_settings.h"
26 #include "chrome/browser/profile_resetter/profile_reset_global_error.h"
27 #include "chrome/browser/search_engines/default_search_manager.h"
28 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
29 #include "chrome/browser/search_engines/template_url_service.h"
30 #include "chrome/browser/search_engines/template_url_service_factory.h"
31 #include "chrome/browser/search_engines/template_url_service_test_util.h"
32 #include "chrome/browser/ui/global_error/global_error.h"
33 #include "chrome/browser/ui/global_error/global_error_service.h"
34 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
35 #include "chrome/common/pref_names.h"
36 #include "chrome/test/base/testing_pref_service_syncable.h"
37 #include "chrome/test/base/testing_profile.h"
38 #include "content/public/browser/notification_service.h"
39 #include "net/http/http_response_headers.h"
40 #include "net/url_request/test_url_fetcher_factory.h"
41 #include "testing/gmock/include/gmock/gmock.h"
42 #include "testing/gtest/include/gtest/gtest.h"
43
44 #if defined(OS_WIN)
45 #include "chrome/browser/enumerate_modules_model_win.h"
46 #endif
47
48 namespace {
49
50 const char kTestBrandcode[] = "FOOBAR";
51
52 const char kTestHomepage[] = "http://google.com";
53 const char kTestBrandedHomepage[] = "http://example.com";
54
55 const ProfileResetter::ResettableFlags kResettableAspectsForTest =
56     ProfileResetter::ALL & ~ProfileResetter::COOKIES_AND_SITE_DATA;
57
58 // Helpers -------------------------------------------------------------------
59
60 // A testing version of the AutomaticProfileResetterDelegate that differs from
61 // the real one only in that it has its feedback reporting mocked out, and it
62 // will not reset COOKIES_AND_SITE_DATA, due to difficulties to set up some
63 // required URLRequestContexts in unit tests.
64 class AutomaticProfileResetterDelegateUnderTest
65     : public AutomaticProfileResetterDelegateImpl {
66  public:
67   explicit AutomaticProfileResetterDelegateUnderTest(Profile* profile)
68       : AutomaticProfileResetterDelegateImpl(
69             profile, kResettableAspectsForTest) {}
70   virtual ~AutomaticProfileResetterDelegateUnderTest() {}
71
72   MOCK_CONST_METHOD1(SendFeedback, void(const std::string&));
73
74  private:
75   DISALLOW_COPY_AND_ASSIGN(AutomaticProfileResetterDelegateUnderTest);
76 };
77
78 class MockCallbackTarget {
79  public:
80   MockCallbackTarget() {}
81   ~MockCallbackTarget() {}
82
83   MOCK_CONST_METHOD0(Run, void(void));
84
85   base::Closure CreateClosure() {
86     return base::Bind(&MockCallbackTarget::Run, base::Unretained(this));
87   }
88
89  private:
90   DISALLOW_COPY_AND_ASSIGN(MockCallbackTarget);
91 };
92
93 // Returns the details of the default search provider from |prefs| in a format
94 // suitable for usage as |expected_details| in ExpectDetailsMatch().
95 const base::DictionaryValue* GetDefaultSearchProviderDetailsFromPrefs(
96     const PrefService* prefs) {
97   return prefs->GetDictionary(
98       DefaultSearchManager::kDefaultSearchProviderDataPrefName);
99 }
100
101 // Verifies that the |details| of a search engine as provided by the delegate
102 // are correct in comparison to the |expected_details| coming from the Prefs.
103 void ExpectDetailsMatch(const base::DictionaryValue& expected_details,
104                         const base::DictionaryValue& details) {
105   for (base::DictionaryValue::Iterator it(expected_details); !it.IsAtEnd();
106        it.Advance()) {
107     SCOPED_TRACE(testing::Message("Key: ") << it.key());
108     if (it.key() == "enabled" || it.key() == "synced_guid") {
109       // These attributes should not be present.
110       EXPECT_FALSE(details.HasKey(it.key()));
111       continue;
112     }
113     const base::Value* expected_value = &it.value();
114     const base::Value* actual_value = NULL;
115     ASSERT_TRUE(details.Get(it.key(), &actual_value));
116
117     // Ignore ID as it is dynamically assigned by the TemplateURLService.
118     // last_modified may get updated during a run, so ignore value differences.
119     if (it.key() != "id" && it.key() != "last_modified") {
120       // Everything else is the same format.
121       EXPECT_TRUE(actual_value->Equals(expected_value))
122           << "Expected: " << *expected_value << ". Actual: " << *actual_value;
123     }
124   }
125 }
126
127 // If |simulate_failure| is false, then replies to the pending request on
128 // |fetcher| with a brandcoded config that only specifies a home page URL.
129 // If |simulate_failure| is true, replies with 404.
130 void ServicePendingBrancodedConfigFetch(net::TestURLFetcher* fetcher,
131                                         bool simulate_failure) {
132   const char kBrandcodedXmlSettings[] =
133       "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
134       "<response protocol=\"3.0\" server=\"prod\">"
135         "<app appid=\"{8A69D345-D564-463C-AFF1-A69D9E530F96}\" status=\"ok\">"
136           "<data index=\"skipfirstrunui-importsearch-defaultbrowser\" "
137           "name=\"install\" status=\"ok\">"
138             "{\"homepage\" : \"$1\"}"
139           "</data>"
140         "</app>"
141       "</response>";
142
143   fetcher->set_response_code(simulate_failure ? 404 : 200);
144   scoped_refptr<net::HttpResponseHeaders> response_headers(
145       new net::HttpResponseHeaders(""));
146   response_headers->AddHeader("Content-Type: text/xml");
147   fetcher->set_response_headers(response_headers);
148   if (!simulate_failure) {
149     std::string response(kBrandcodedXmlSettings);
150     size_t placeholder_index = response.find("$1");
151     ASSERT_NE(std::string::npos, placeholder_index);
152     response.replace(placeholder_index, 2, kTestBrandedHomepage);
153     fetcher->SetResponseString(response);
154   }
155   fetcher->delegate()->OnURLFetchComplete(fetcher);
156 }
157
158
159 // Test fixture --------------------------------------------------------------
160
161 // ExtensionServiceTestBase sets up a TestingProfile with the ExtensionService,
162 // we then add the TemplateURLService, so the ProfileResetter can be exercised.
163 class AutomaticProfileResetterDelegateTest
164     : public ExtensionServiceTestBase,
165       public TemplateURLServiceTestUtilBase {
166  protected:
167   AutomaticProfileResetterDelegateTest() {}
168   virtual ~AutomaticProfileResetterDelegateTest() {}
169
170   virtual void SetUp() OVERRIDE {
171     ExtensionServiceTestBase::SetUp();
172     ExtensionServiceInitParams params = CreateDefaultInitParams();
173     params.pref_file.clear();  // Prescribes a TestingPrefService to be created.
174     InitializeExtensionService(params);
175     TemplateURLServiceTestUtilBase::CreateTemplateUrlService();
176     resetter_delegate_.reset(
177         new AutomaticProfileResetterDelegateUnderTest(profile()));
178   }
179
180   virtual void TearDown() OVERRIDE {
181     resetter_delegate_.reset();
182     ExtensionServiceTestBase::TearDown();
183   }
184
185   scoped_ptr<TemplateURL> CreateTestTemplateURL() {
186     TemplateURLData data;
187
188     data.SetURL("http://example.com/search?q={searchTerms}");
189     data.suggestions_url = "http://example.com/suggest?q={searchTerms}";
190     data.instant_url = "http://example.com/instant?q={searchTerms}";
191     data.image_url = "http://example.com/image?q={searchTerms}";
192     data.search_url_post_params = "search-post-params";
193     data.suggestions_url_post_params = "suggest-post-params";
194     data.instant_url_post_params = "instant-post-params";
195     data.image_url_post_params = "image-post-params";
196
197     data.favicon_url = GURL("http://example.com/favicon.ico");
198     data.new_tab_url = "http://example.com/newtab.html";
199     data.alternate_urls.push_back("http://example.com/s?q={searchTerms}");
200
201     data.short_name = base::ASCIIToUTF16("name");
202     data.SetKeyword(base::ASCIIToUTF16("keyword"));
203     data.search_terms_replacement_key = "search-terms-replacment-key";
204     data.prepopulate_id = 42;
205     data.input_encodings.push_back("UTF-8");
206     data.safe_for_autoreplace = true;
207
208     return scoped_ptr<TemplateURL>(new TemplateURL(profile(), data));
209   }
210
211   void ExpectNoPendingBrandcodedConfigFetch() {
212     EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0));
213   }
214
215   void ExpectAndServicePendingBrandcodedConfigFetch(bool simulate_failure) {
216     net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID(0);
217     ASSERT_TRUE(fetcher);
218     EXPECT_THAT(fetcher->upload_data(),
219                 testing::HasSubstr(kTestBrandcode));
220     ServicePendingBrancodedConfigFetch(fetcher, simulate_failure);
221   }
222
223   void ExpectResetPromptState(bool active) {
224     GlobalErrorService* global_error_service =
225         GlobalErrorServiceFactory::GetForProfile(profile());
226     GlobalError* global_error = global_error_service->
227         GetGlobalErrorByMenuItemCommandID(IDC_SHOW_SETTINGS_RESET_BUBBLE);
228     EXPECT_EQ(active, !!global_error);
229   }
230
231   AutomaticProfileResetterDelegateUnderTest* resetter_delegate() {
232     return resetter_delegate_.get();
233   }
234
235   // TemplateURLServiceTestUtilBase:
236   virtual TestingProfile* profile() const OVERRIDE { return profile_.get(); }
237
238  private:
239   net::TestURLFetcherFactory test_url_fetcher_factory_;
240   scoped_ptr<AutomaticProfileResetterDelegateUnderTest> resetter_delegate_;
241
242   DISALLOW_COPY_AND_ASSIGN(AutomaticProfileResetterDelegateTest);
243 };
244
245
246 // Tests ---------------------------------------------------------------------
247
248 TEST_F(AutomaticProfileResetterDelegateTest,
249        TriggerAndWaitOnModuleEnumeration) {
250   // Expect ready_callback to be called just after the modules have been
251   // enumerated. Fail if it is not called. Note: as the EnumerateModulesModel is
252   // a global singleton, the callback might be invoked immediately if another
253   // test-case (e.g. the one below) has already performed module enumeration.
254   testing::StrictMock<MockCallbackTarget> mock_target;
255   EXPECT_CALL(mock_target, Run());
256   resetter_delegate()->RequestCallbackWhenLoadedModulesAreEnumerated(
257       mock_target.CreateClosure());
258   resetter_delegate()->EnumerateLoadedModulesIfNeeded();
259   base::RunLoop().RunUntilIdle();
260
261   testing::Mock::VerifyAndClearExpectations(&mock_target);
262
263   // Expect ready_callback to be posted immediately when the modules have
264   // already been enumerated.
265   EXPECT_CALL(mock_target, Run());
266   resetter_delegate()->RequestCallbackWhenLoadedModulesAreEnumerated(
267       mock_target.CreateClosure());
268   base::RunLoop().RunUntilIdle();
269
270 #if defined(OS_WIN)
271   testing::Mock::VerifyAndClearExpectations(&mock_target);
272
273   // Expect ready_callback to be posted immediately even when the modules had
274   // already been enumerated when the delegate was constructed.
275   scoped_ptr<AutomaticProfileResetterDelegate> late_resetter_delegate(
276       new AutomaticProfileResetterDelegateImpl(profile(),
277                                                ProfileResetter::ALL));
278
279   EXPECT_CALL(mock_target, Run());
280   late_resetter_delegate->RequestCallbackWhenLoadedModulesAreEnumerated(
281       mock_target.CreateClosure());
282   base::RunLoop().RunUntilIdle();
283 #endif
284 }
285
286 TEST_F(AutomaticProfileResetterDelegateTest, GetLoadedModuleNameDigests) {
287   resetter_delegate()->EnumerateLoadedModulesIfNeeded();
288   base::RunLoop().RunUntilIdle();
289   scoped_ptr<base::ListValue> module_name_digests(
290       resetter_delegate()->GetLoadedModuleNameDigests());
291
292   // Just verify that each element looks like an MD5 hash in hexadecimal, and
293   // also that we have at least one element on Win.
294   ASSERT_TRUE(module_name_digests);
295   for (base::ListValue::const_iterator it = module_name_digests->begin();
296        it != module_name_digests->end(); ++it) {
297     std::string digest_hex;
298     std::vector<uint8> digest_raw;
299
300     ASSERT_TRUE((*it)->GetAsString(&digest_hex));
301     ASSERT_TRUE(base::HexStringToBytes(digest_hex, &digest_raw));
302     EXPECT_EQ(16u, digest_raw.size());
303   }
304 #if defined(OS_WIN)
305   EXPECT_LE(1u, module_name_digests->GetSize());
306 #endif
307 }
308
309 TEST_F(AutomaticProfileResetterDelegateTest, LoadAndWaitOnTemplateURLService) {
310   // Expect ready_callback to be called just after the template URL service gets
311   // initialized. Fail if it is not called, or called too early.
312   testing::StrictMock<MockCallbackTarget> mock_target;
313   resetter_delegate()->RequestCallbackWhenTemplateURLServiceIsLoaded(
314       mock_target.CreateClosure());
315   base::RunLoop().RunUntilIdle();
316
317   EXPECT_CALL(mock_target, Run());
318   resetter_delegate()->LoadTemplateURLServiceIfNeeded();
319   base::RunLoop().RunUntilIdle();
320
321   testing::Mock::VerifyAndClearExpectations(&mock_target);
322
323   // Expect ready_callback to be posted immediately when the template URL
324   // service is already initialized.
325   EXPECT_CALL(mock_target, Run());
326   resetter_delegate()->RequestCallbackWhenTemplateURLServiceIsLoaded(
327       mock_target.CreateClosure());
328   base::RunLoop().RunUntilIdle();
329
330   testing::Mock::VerifyAndClearExpectations(&mock_target);
331
332   // Expect ready_callback to be posted immediately even when the template URL
333   // service had already been initialized when the delegate was constructed.
334   scoped_ptr<AutomaticProfileResetterDelegate> late_resetter_delegate(
335       new AutomaticProfileResetterDelegateImpl(profile(),
336                                                ProfileResetter::ALL));
337
338   EXPECT_CALL(mock_target, Run());
339   late_resetter_delegate->RequestCallbackWhenTemplateURLServiceIsLoaded(
340       mock_target.CreateClosure());
341   base::RunLoop().RunUntilIdle();
342 }
343
344 TEST_F(AutomaticProfileResetterDelegateTest,
345        DefaultSearchProviderDataWhenNotManaged) {
346   TemplateURLService* template_url_service =
347       TemplateURLServiceFactory::GetForProfile(profile());
348   TemplateURLServiceTestUtilBase::VerifyLoad();
349
350   // Check that the "managed state" and the details returned by the delegate are
351   // correct. We verify the details against the data stored by
352   // TemplateURLService into Prefs.
353   scoped_ptr<TemplateURL> owned_custom_dsp(CreateTestTemplateURL());
354   TemplateURL* custom_dsp = owned_custom_dsp.get();
355   template_url_service->Add(owned_custom_dsp.release());
356   template_url_service->SetUserSelectedDefaultSearchProvider(custom_dsp);
357
358   PrefService* prefs = profile()->GetPrefs();
359   ASSERT_TRUE(prefs);
360   scoped_ptr<base::DictionaryValue> dsp_details(
361       resetter_delegate()->GetDefaultSearchProviderDetails());
362   const base::DictionaryValue* expected_dsp_details =
363       GetDefaultSearchProviderDetailsFromPrefs(prefs);
364
365   ExpectDetailsMatch(*expected_dsp_details, *dsp_details);
366   EXPECT_FALSE(resetter_delegate()->IsDefaultSearchProviderManaged());
367 }
368
369 TEST_F(AutomaticProfileResetterDelegateTest,
370        DefaultSearchProviderDataWhenManaged) {
371   const char kTestSearchURL[] = "http://example.com/search?q={searchTerms}";
372   const char kTestName[] = "name";
373   const char kTestKeyword[] = "keyword";
374
375   TemplateURLServiceTestUtilBase::VerifyLoad();
376
377   EXPECT_FALSE(resetter_delegate()->IsDefaultSearchProviderManaged());
378
379   // Set managed preferences to emulate a default search provider set by policy.
380   SetManagedDefaultSearchPreferences(
381       true, kTestName, kTestKeyword, kTestSearchURL, std::string(),
382       std::string(), std::string(), std::string(), std::string());
383
384   EXPECT_TRUE(resetter_delegate()->IsDefaultSearchProviderManaged());
385   scoped_ptr<base::DictionaryValue> dsp_details(
386       resetter_delegate()->GetDefaultSearchProviderDetails());
387   // Checking that all details are correct is already done by the above test.
388   // Just make sure details are reported about the correct engine.
389   base::ExpectDictStringValue(kTestSearchURL, *dsp_details, "search_url");
390
391   // Set managed preferences to emulate that having a default search provider is
392   // disabled by policy.
393   RemoveManagedDefaultSearchPreferences();
394   SetManagedDefaultSearchPreferences(
395       false, std::string(), std::string(), std::string(), std::string(),
396       std::string(), std::string(), std::string(), std::string());
397
398   dsp_details = resetter_delegate()->GetDefaultSearchProviderDetails();
399   EXPECT_TRUE(resetter_delegate()->IsDefaultSearchProviderManaged());
400   EXPECT_TRUE(dsp_details->empty());
401 }
402
403 TEST_F(AutomaticProfileResetterDelegateTest,
404        GetPrepopulatedSearchProvidersDetails) {
405   TemplateURLService* template_url_service =
406       TemplateURLServiceFactory::GetForProfile(profile());
407   TemplateURLServiceTestUtilBase::VerifyLoad();
408
409   scoped_ptr<base::ListValue> search_engines_details(
410       resetter_delegate()->GetPrepopulatedSearchProvidersDetails());
411
412   // Do the same kind of verification as for GetDefaultSearchEngineDetails:
413   // subsequently set each pre-populated engine as the default, so we can verify
414   // that the details returned by the delegate about one particular engine are
415   // correct in comparison to what has been stored to the Prefs.
416   std::vector<TemplateURL*> prepopulated_engines =
417       template_url_service->GetTemplateURLs();
418
419   ASSERT_EQ(prepopulated_engines.size(), search_engines_details->GetSize());
420
421   for (size_t i = 0; i < search_engines_details->GetSize(); ++i) {
422     const base::DictionaryValue* details = NULL;
423     ASSERT_TRUE(search_engines_details->GetDictionary(i, &details));
424
425     std::string keyword;
426     ASSERT_TRUE(details->GetString("keyword", &keyword));
427     TemplateURL* search_engine =
428         template_url_service->GetTemplateURLForKeyword(
429             base::ASCIIToUTF16(keyword));
430     ASSERT_TRUE(search_engine);
431     template_url_service->SetUserSelectedDefaultSearchProvider(
432         prepopulated_engines[i]);
433
434     PrefService* prefs = profile()->GetPrefs();
435     ASSERT_TRUE(prefs);
436     const base::DictionaryValue* expected_dsp_details =
437         GetDefaultSearchProviderDetailsFromPrefs(prefs);
438     ExpectDetailsMatch(*expected_dsp_details, *details);
439   }
440 }
441
442 TEST_F(AutomaticProfileResetterDelegateTest,
443        FetchAndWaitOnDefaultSettingsVanilla) {
444   google_util::BrandForTesting scoped_brand_for_testing((std::string()));
445
446   // Expect ready_callback to be called just after empty brandcoded settings
447   // are loaded, given this is a vanilla build. Fail if it is not called, or
448   // called too early.
449   testing::StrictMock<MockCallbackTarget> mock_target;
450   resetter_delegate()->RequestCallbackWhenBrandcodedDefaultsAreFetched(
451       mock_target.CreateClosure());
452   base::RunLoop().RunUntilIdle();
453   EXPECT_FALSE(resetter_delegate()->brandcoded_defaults());
454
455   EXPECT_CALL(mock_target, Run());
456   resetter_delegate()->FetchBrandcodedDefaultSettingsIfNeeded();
457   base::RunLoop().RunUntilIdle();
458   ExpectNoPendingBrandcodedConfigFetch();
459
460   testing::Mock::VerifyAndClearExpectations(&mock_target);
461   EXPECT_TRUE(resetter_delegate()->brandcoded_defaults());
462
463   // Expect ready_callback to be posted immediately when the brandcoded settings
464   // have already been loaded.
465   EXPECT_CALL(mock_target, Run());
466   resetter_delegate()->RequestCallbackWhenBrandcodedDefaultsAreFetched(
467       mock_target.CreateClosure());
468   base::RunLoop().RunUntilIdle();
469
470   // No test for a new instance of AutomaticProfileResetterDelegate. That will
471   // need to fetch the brandcoded settings again.
472 }
473
474 TEST_F(AutomaticProfileResetterDelegateTest,
475        FetchAndWaitOnDefaultSettingsBranded) {
476   google_util::BrandForTesting scoped_brand_for_testing(kTestBrandcode);
477
478   // Expect ready_callback to be called just after the brandcoded settings are
479   // downloaded. Fail if it is not called, or called too early.
480   testing::StrictMock<MockCallbackTarget> mock_target;
481   resetter_delegate()->RequestCallbackWhenBrandcodedDefaultsAreFetched(
482       mock_target.CreateClosure());
483   base::RunLoop().RunUntilIdle();
484   EXPECT_FALSE(resetter_delegate()->brandcoded_defaults());
485
486   EXPECT_CALL(mock_target, Run());
487   resetter_delegate()->FetchBrandcodedDefaultSettingsIfNeeded();
488   ExpectAndServicePendingBrandcodedConfigFetch(false /*simulate_failure*/);
489   base::RunLoop().RunUntilIdle();
490
491   testing::Mock::VerifyAndClearExpectations(&mock_target);
492   const BrandcodedDefaultSettings* brandcoded_defaults =
493       resetter_delegate()->brandcoded_defaults();
494   ASSERT_TRUE(brandcoded_defaults);
495   std::string homepage_url;
496   EXPECT_TRUE(brandcoded_defaults->GetHomepage(&homepage_url));
497   EXPECT_EQ(kTestBrandedHomepage, homepage_url);
498
499   // Expect ready_callback to be posted immediately when the brandcoded settings
500   // have already been downloaded.
501   EXPECT_CALL(mock_target, Run());
502   resetter_delegate()->RequestCallbackWhenBrandcodedDefaultsAreFetched(
503       mock_target.CreateClosure());
504   base::RunLoop().RunUntilIdle();
505 }
506
507 TEST_F(AutomaticProfileResetterDelegateTest,
508        FetchAndWaitOnDefaultSettingsBrandedFailure) {
509   google_util::BrandForTesting scoped_brand_for_testing(kTestBrandcode);
510
511   // Expect ready_callback to be called just after the brandcoded settings have
512   // failed to download. Fail if it is not called, or called too early.
513   testing::StrictMock<MockCallbackTarget> mock_target;
514   resetter_delegate()->RequestCallbackWhenBrandcodedDefaultsAreFetched(
515       mock_target.CreateClosure());
516   base::RunLoop().RunUntilIdle();
517
518   EXPECT_CALL(mock_target, Run());
519   resetter_delegate()->FetchBrandcodedDefaultSettingsIfNeeded();
520   ExpectAndServicePendingBrandcodedConfigFetch(true /*simulate_failure*/);
521   base::RunLoop().RunUntilIdle();
522
523   testing::Mock::VerifyAndClearExpectations(&mock_target);
524   EXPECT_TRUE(resetter_delegate()->brandcoded_defaults());
525
526   // Expect ready_callback to be posted immediately when the brandcoded settings
527   // have already been attempted to be downloaded, but failed.
528   EXPECT_CALL(mock_target, Run());
529   resetter_delegate()->RequestCallbackWhenBrandcodedDefaultsAreFetched(
530       mock_target.CreateClosure());
531   base::RunLoop().RunUntilIdle();
532 }
533
534 TEST_F(AutomaticProfileResetterDelegateTest, TriggerReset) {
535   google_util::BrandForTesting scoped_brand_for_testing(kTestBrandcode);
536
537   PrefService* prefs = profile()->GetPrefs();
538   DCHECK(prefs);
539   prefs->SetString(prefs::kHomePage, kTestHomepage);
540
541   testing::StrictMock<MockCallbackTarget> mock_target;
542   EXPECT_CALL(mock_target, Run());
543   EXPECT_CALL(*resetter_delegate(), SendFeedback(testing::_)).Times(0);
544   resetter_delegate()->TriggerProfileSettingsReset(
545       false /*send_feedback*/, mock_target.CreateClosure());
546   ExpectAndServicePendingBrandcodedConfigFetch(false /*simulate_failure*/);
547   base::RunLoop().RunUntilIdle();
548
549   EXPECT_EQ(kTestBrandedHomepage, prefs->GetString(prefs::kHomePage));
550 }
551
552 TEST_F(AutomaticProfileResetterDelegateTest,
553        TriggerResetWithDefaultSettingsAlreadyLoaded) {
554   google_util::BrandForTesting scoped_brand_for_testing(kTestBrandcode);
555
556   PrefService* prefs = profile()->GetPrefs();
557   DCHECK(prefs);
558   prefs->SetString(prefs::kHomePage, kTestHomepage);
559
560   resetter_delegate()->FetchBrandcodedDefaultSettingsIfNeeded();
561   ExpectAndServicePendingBrandcodedConfigFetch(false /*simulate_failure*/);
562   base::RunLoop().RunUntilIdle();
563
564   testing::StrictMock<MockCallbackTarget> mock_target;
565   EXPECT_CALL(mock_target, Run());
566   EXPECT_CALL(*resetter_delegate(), SendFeedback(testing::_)).Times(0);
567   resetter_delegate()->TriggerProfileSettingsReset(
568       false /*send_feedback*/, mock_target.CreateClosure());
569   base::RunLoop().RunUntilIdle();
570
571   EXPECT_EQ(kTestBrandedHomepage, prefs->GetString(prefs::kHomePage));
572 }
573
574 TEST_F(AutomaticProfileResetterDelegateTest,
575        TriggerResetAndSendFeedback) {
576   google_util::BrandForTesting scoped_brand_for_testing(kTestBrandcode);
577
578   PrefService* prefs = profile()->GetPrefs();
579   DCHECK(prefs);
580   prefs->SetString(prefs::kHomePage, kTestHomepage);
581
582   testing::StrictMock<MockCallbackTarget> mock_target;
583   EXPECT_CALL(mock_target, Run());
584   EXPECT_CALL(*resetter_delegate(),
585               SendFeedback(testing::HasSubstr(kTestHomepage)));
586
587   resetter_delegate()->TriggerProfileSettingsReset(
588       true /*send_feedback*/, mock_target.CreateClosure());
589   ExpectAndServicePendingBrandcodedConfigFetch(false /*simulate_failure*/);
590   base::RunLoop().RunUntilIdle();
591 }
592
593 TEST_F(AutomaticProfileResetterDelegateTest, ShowAndDismissPrompt) {
594   resetter_delegate()->TriggerPrompt();
595   if (ProfileResetGlobalError::IsSupportedOnPlatform())
596     ExpectResetPromptState(true /*active*/);
597   else
598     ExpectResetPromptState(false /*active*/);
599   resetter_delegate()->DismissPrompt();
600   ExpectResetPromptState(false /*active*/);
601   resetter_delegate()->DismissPrompt();
602 }
603
604 }  // namespace