1 // Copyright (c) 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.
5 #include "chrome/browser/profile_resetter/profile_resetter.h"
7 #include "base/json/json_string_value_serializer.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "base/test/scoped_path_override.h"
11 #include "chrome/browser/extensions/extension_service.h"
12 #include "chrome/browser/extensions/extension_service_test_base.h"
13 #include "chrome/browser/extensions/tab_helper.h"
14 #include "chrome/browser/prefs/session_startup_pref.h"
15 #include "chrome/browser/profile_resetter/brandcode_config_fetcher.h"
16 #include "chrome/browser/profile_resetter/profile_resetter_test_base.h"
17 #include "chrome/browser/profile_resetter/resettable_settings_snapshot.h"
18 #include "chrome/browser/search_engines/template_url_service_factory.h"
19 #include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
20 #include "chrome/browser/themes/theme_service.h"
21 #include "chrome/browser/themes/theme_service_factory.h"
22 #include "chrome/browser/ui/tabs/tab_strip_model.h"
23 #include "chrome/browser/webdata/web_data_service_factory.h"
24 #include "chrome/common/pref_names.h"
25 #include "chrome/test/base/browser_with_test_window_test.h"
26 #include "components/content_settings/core/browser/host_content_settings_map.h"
27 #include "components/search_engines/template_url_service.h"
28 #include "components/search_engines/template_url_service_client.h"
29 #include "content/public/browser/web_contents.h"
30 #include "content/public/test/test_browser_thread.h"
31 #include "extensions/browser/extension_registry.h"
32 #include "extensions/common/extension.h"
33 #include "extensions/common/manifest_constants.h"
34 #include "net/http/http_response_headers.h"
35 #include "net/http/http_status_code.h"
36 #include "net/url_request/test_url_fetcher_factory.h"
37 #include "net/url_request/url_request_status.h"
41 #include "base/files/file_util.h"
42 #include "base/path_service.h"
43 #include "base/process/process_handle.h"
44 #include "base/rand_util.h"
45 #include "base/strings/string_number_conversions.h"
46 #include "base/win/scoped_com_initializer.h"
47 #include "base/win/shortcut.h"
53 const char kDistributionConfig
[] = "{"
54 " \"homepage\" : \"http://www.foo.com\","
55 " \"homepage_is_newtabpage\" : false,"
57 " \"show_home_button\" : true"
60 " \"restore_on_startup\" : 4,"
61 " \"startup_urls\" : [\"http://goo.gl\", \"http://foo.de\"]"
63 " \"search_provider_overrides\" : ["
65 " \"name\" : \"first\","
66 " \"keyword\" : \"firstkey\","
67 " \"search_url\" : \"http://www.foo.com/s?q={searchTerms}\","
68 " \"favicon_url\" : \"http://www.foo.com/favicon.ico\","
69 " \"suggest_url\" : \"http://www.foo.com/s?q={searchTerms}\","
70 " \"encoding\" : \"UTF-8\","
76 " \"placeholder_for_id\": {"
82 const char kXmlConfig
[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
83 "<response protocol=\"3.0\" server=\"prod\">"
84 "<app appid=\"{8A69D345-D564-463C-AFF1-A69D9E530F96}\" status=\"ok\">"
85 "<data index=\"skipfirstrunui-importsearch-defaultbrowser\" "
86 "name=\"install\" status=\"ok\">"
87 "placeholder_for_data"
92 using extensions::Extension
;
93 using extensions::Manifest
;
96 // ProfileResetterTest --------------------------------------------------------
98 // ProfileResetterTest sets up the extension, WebData and TemplateURL services.
99 class ProfileResetterTest
: public extensions::ExtensionServiceTestBase
,
100 public ProfileResetterTestBase
{
102 ProfileResetterTest();
103 ~ProfileResetterTest() override
;
106 void SetUp() override
;
108 TestingProfile
* profile() { return profile_
.get(); }
110 static KeyedService
* CreateTemplateURLService(
111 content::BrowserContext
* context
);
115 base::ScopedPathOverride user_desktop_override_
;
116 base::ScopedPathOverride app_dir_override_
;
117 base::ScopedPathOverride start_menu_override_
;
118 base::ScopedPathOverride taskbar_pins_override_
;
119 base::win::ScopedCOMInitializer com_init_
;
123 ProfileResetterTest::ProfileResetterTest()
125 : user_desktop_override_(base::DIR_USER_DESKTOP
),
126 app_dir_override_(base::DIR_APP_DATA
),
127 start_menu_override_(base::DIR_START_MENU
),
128 taskbar_pins_override_(base::DIR_TASKBAR_PINS
)
132 ProfileResetterTest::~ProfileResetterTest() {
135 void ProfileResetterTest::SetUp() {
136 extensions::ExtensionServiceTestBase::SetUp();
137 InitializeEmptyExtensionService();
139 profile()->CreateWebDataService();
140 TemplateURLServiceFactory::GetInstance()->SetTestingFactory(
142 &ProfileResetterTest::CreateTemplateURLService
);
143 resetter_
.reset(new ProfileResetter(profile()));
147 KeyedService
* ProfileResetterTest::CreateTemplateURLService(
148 content::BrowserContext
* context
) {
149 Profile
* profile
= static_cast<Profile
*>(context
);
150 return new TemplateURLService(
152 scoped_ptr
<SearchTermsData
>(new UIThreadSearchTermsData(profile
)),
153 WebDataServiceFactory::GetKeywordWebDataForProfile(
154 profile
, ServiceAccessType::EXPLICIT_ACCESS
),
155 scoped_ptr
<TemplateURLServiceClient
>(), NULL
, NULL
, base::Closure());
159 // PinnedTabsResetTest --------------------------------------------------------
161 class PinnedTabsResetTest
: public BrowserWithTestWindowTest
,
162 public ProfileResetterTestBase
{
164 void SetUp() override
;
166 content::WebContents
* CreateWebContents();
169 void PinnedTabsResetTest::SetUp() {
170 BrowserWithTestWindowTest::SetUp();
171 resetter_
.reset(new ProfileResetter(profile()));
174 content::WebContents
* PinnedTabsResetTest::CreateWebContents() {
175 return content::WebContents::Create(
176 content::WebContents::CreateParams(profile()));
180 // ConfigParserTest -----------------------------------------------------------
182 // URLFetcher delegate that simply records the upload data.
183 struct URLFetcherRequestListener
: net::URLFetcherDelegate
{
184 URLFetcherRequestListener();
185 ~URLFetcherRequestListener() override
;
187 void OnURLFetchComplete(const net::URLFetcher
* source
) override
;
189 std::string upload_data
;
190 net::URLFetcherDelegate
* real_delegate
;
193 URLFetcherRequestListener::URLFetcherRequestListener()
194 : real_delegate(NULL
) {
197 URLFetcherRequestListener::~URLFetcherRequestListener() {
200 void URLFetcherRequestListener::OnURLFetchComplete(
201 const net::URLFetcher
* source
) {
202 const net::TestURLFetcher
* test_fetcher
=
203 static_cast<const net::TestURLFetcher
*>(source
);
204 upload_data
= test_fetcher
->upload_data();
205 DCHECK(real_delegate
);
206 real_delegate
->OnURLFetchComplete(source
);
209 class ConfigParserTest
: public testing::Test
{
212 virtual ~ConfigParserTest();
214 scoped_ptr
<BrandcodeConfigFetcher
> WaitForRequest(const GURL
& url
);
216 net::FakeURLFetcherFactory
& factory() { return factory_
; }
219 scoped_ptr
<net::FakeURLFetcher
> CreateFakeURLFetcher(
221 net::URLFetcherDelegate
* fetcher_delegate
,
222 const std::string
& response_data
,
223 net::HttpStatusCode response_code
,
224 net::URLRequestStatus::Status status
);
226 MOCK_METHOD0(Callback
, void(void));
228 base::MessageLoopForIO loop_
;
229 content::TestBrowserThread ui_thread_
;
230 content::TestBrowserThread io_thread_
;
231 URLFetcherRequestListener request_listener_
;
232 net::FakeURLFetcherFactory factory_
;
235 ConfigParserTest::ConfigParserTest()
236 : ui_thread_(content::BrowserThread::UI
, &loop_
),
237 io_thread_(content::BrowserThread::IO
, &loop_
),
238 factory_(NULL
, base::Bind(&ConfigParserTest::CreateFakeURLFetcher
,
239 base::Unretained(this))) {
242 ConfigParserTest::~ConfigParserTest() {}
244 scoped_ptr
<BrandcodeConfigFetcher
> ConfigParserTest::WaitForRequest(
246 EXPECT_CALL(*this, Callback());
247 scoped_ptr
<BrandcodeConfigFetcher
> fetcher(
248 new BrandcodeConfigFetcher(base::Bind(&ConfigParserTest::Callback
,
249 base::Unretained(this)),
252 base::MessageLoop::current()->RunUntilIdle();
253 EXPECT_FALSE(fetcher
->IsActive());
254 // Look for the brand code in the request.
255 EXPECT_NE(std::string::npos
, request_listener_
.upload_data
.find("ABCD"));
256 return fetcher
.Pass();
259 scoped_ptr
<net::FakeURLFetcher
> ConfigParserTest::CreateFakeURLFetcher(
261 net::URLFetcherDelegate
* fetcher_delegate
,
262 const std::string
& response_data
,
263 net::HttpStatusCode response_code
,
264 net::URLRequestStatus::Status status
) {
265 request_listener_
.real_delegate
= fetcher_delegate
;
266 scoped_ptr
<net::FakeURLFetcher
> fetcher(
267 new net::FakeURLFetcher(
268 url
, &request_listener_
, response_data
, response_code
, status
));
269 scoped_refptr
<net::HttpResponseHeaders
> download_headers
=
270 new net::HttpResponseHeaders("");
271 download_headers
->AddHeader("Content-Type: text/xml");
272 fetcher
->set_response_headers(download_headers
);
273 return fetcher
.Pass();
276 // A helper class to create/delete/check a Chrome desktop shortcut on Windows.
277 class ShortcutHandler
{
282 static bool IsSupported();
283 ShortcutCommand
CreateWithArguments(const base::string16
& name
,
284 const base::string16
& args
);
285 void CheckShortcutHasArguments(const base::string16
& desired_args
) const;
290 base::FilePath shortcut_path_
;
292 DISALLOW_COPY_AND_ASSIGN(ShortcutHandler
);
296 ShortcutHandler::ShortcutHandler() {
299 ShortcutHandler::~ShortcutHandler() {
300 if (!shortcut_path_
.empty())
305 bool ShortcutHandler::IsSupported() {
309 ShortcutCommand
ShortcutHandler::CreateWithArguments(
310 const base::string16
& name
,
311 const base::string16
& args
) {
312 EXPECT_TRUE(shortcut_path_
.empty());
313 base::FilePath path_to_create
;
314 EXPECT_TRUE(PathService::Get(base::DIR_USER_DESKTOP
, &path_to_create
));
315 path_to_create
= path_to_create
.Append(name
);
316 EXPECT_FALSE(base::PathExists(path_to_create
)) << path_to_create
.value();
318 base::FilePath path_exe
;
319 EXPECT_TRUE(PathService::Get(base::FILE_EXE
, &path_exe
));
320 base::win::ShortcutProperties shortcut_properties
;
321 shortcut_properties
.set_target(path_exe
);
322 shortcut_properties
.set_arguments(args
);
323 EXPECT_TRUE(base::win::CreateOrUpdateShortcutLink(
324 path_to_create
, shortcut_properties
,
325 base::win::SHORTCUT_CREATE_ALWAYS
)) << path_to_create
.value();
326 shortcut_path_
= path_to_create
;
327 return ShortcutCommand(shortcut_path_
, args
);
330 void ShortcutHandler::CheckShortcutHasArguments(
331 const base::string16
& desired_args
) const {
332 EXPECT_FALSE(shortcut_path_
.empty());
334 EXPECT_TRUE(base::win::ResolveShortcut(shortcut_path_
, NULL
, &args
));
335 EXPECT_EQ(desired_args
, args
);
338 void ShortcutHandler::Delete() {
339 EXPECT_FALSE(shortcut_path_
.empty());
340 EXPECT_TRUE(base::DeleteFile(shortcut_path_
, false));
341 shortcut_path_
.clear();
344 ShortcutHandler::ShortcutHandler() {}
346 ShortcutHandler::~ShortcutHandler() {}
349 bool ShortcutHandler::IsSupported() {
353 ShortcutCommand
ShortcutHandler::CreateWithArguments(
354 const base::string16
& name
,
355 const base::string16
& args
) {
356 return ShortcutCommand();
359 void ShortcutHandler::CheckShortcutHasArguments(
360 const base::string16
& desired_args
) const {
363 void ShortcutHandler::Delete() {
365 #endif // defined(OS_WIN)
368 // helper functions -----------------------------------------------------------
370 scoped_refptr
<Extension
> CreateExtension(const base::string16
& name
,
371 const base::FilePath
& path
,
372 Manifest::Location location
,
373 extensions::Manifest::Type type
,
374 bool installed_by_default
) {
375 base::DictionaryValue manifest
;
376 manifest
.SetString(extensions::manifest_keys::kVersion
, "1.0.0.0");
377 manifest
.SetString(extensions::manifest_keys::kName
, name
);
379 case extensions::Manifest::TYPE_THEME
:
380 manifest
.Set(extensions::manifest_keys::kTheme
,
381 new base::DictionaryValue
);
383 case extensions::Manifest::TYPE_HOSTED_APP
:
384 manifest
.SetString(extensions::manifest_keys::kLaunchWebURL
,
385 "http://www.google.com");
386 manifest
.SetString(extensions::manifest_keys::kUpdateURL
,
387 "http://clients2.google.com/service/update2/crx");
389 case extensions::Manifest::TYPE_EXTENSION
:
395 manifest
.SetString(extensions::manifest_keys::kOmniboxKeyword
, name
);
397 scoped_refptr
<Extension
> extension
= Extension::Create(
401 installed_by_default
? Extension::WAS_INSTALLED_BY_DEFAULT
402 : Extension::NO_FLAGS
,
404 EXPECT_TRUE(extension
.get() != NULL
) << error
;
408 void ReplaceString(std::string
* str
,
409 const std::string
& placeholder
,
410 const std::string
& substitution
) {
411 ASSERT_NE(static_cast<std::string
*>(NULL
), str
);
412 size_t placeholder_pos
= str
->find(placeholder
);
413 ASSERT_NE(std::string::npos
, placeholder_pos
);
414 str
->replace(placeholder_pos
, placeholder
.size(), substitution
);
418 /********************* Tests *********************/
420 TEST_F(ProfileResetterTest
, ResetNothing
) {
421 // The callback should be called even if there is nothing to reset.
425 TEST_F(ProfileResetterTest
, ResetDefaultSearchEngineNonOrganic
) {
426 ResetAndWait(ProfileResetter::DEFAULT_SEARCH_ENGINE
, kDistributionConfig
);
428 TemplateURLService
* model
=
429 TemplateURLServiceFactory::GetForProfile(profile());
430 TemplateURL
* default_engine
= model
->GetDefaultSearchProvider();
431 ASSERT_NE(static_cast<TemplateURL
*>(NULL
), default_engine
);
432 EXPECT_EQ(base::ASCIIToUTF16("first"), default_engine
->short_name());
433 EXPECT_EQ(base::ASCIIToUTF16("firstkey"), default_engine
->keyword());
434 EXPECT_EQ("http://www.foo.com/s?q={searchTerms}", default_engine
->url());
437 TEST_F(ProfileResetterTest
, ResetDefaultSearchEnginePartially
) {
438 // Search engine's logic is tested by
439 // TemplateURLServiceTest.RepairPrepopulatedSearchEngines.
440 // Make sure TemplateURLService has loaded.
441 ResetAndWait(ProfileResetter::DEFAULT_SEARCH_ENGINE
);
443 TemplateURLService
* model
=
444 TemplateURLServiceFactory::GetForProfile(profile());
445 TemplateURLService::TemplateURLVector urls
= model
->GetTemplateURLs();
447 // The second call should produce no effect.
448 ResetAndWait(ProfileResetter::DEFAULT_SEARCH_ENGINE
);
450 EXPECT_EQ(urls
, model
->GetTemplateURLs());
453 TEST_F(ProfileResetterTest
, ResetHomepageNonOrganic
) {
454 PrefService
* prefs
= profile()->GetPrefs();
456 prefs
->SetBoolean(prefs::kHomePageIsNewTabPage
, true);
457 prefs
->SetString(prefs::kHomePage
, "http://google.com");
458 prefs
->SetBoolean(prefs::kShowHomeButton
, false);
460 ResetAndWait(ProfileResetter::HOMEPAGE
, kDistributionConfig
);
462 EXPECT_FALSE(prefs
->GetBoolean(prefs::kHomePageIsNewTabPage
));
463 EXPECT_EQ("http://www.foo.com", prefs
->GetString(prefs::kHomePage
));
464 EXPECT_TRUE(prefs
->GetBoolean(prefs::kShowHomeButton
));
467 TEST_F(ProfileResetterTest
, ResetHomepagePartially
) {
468 PrefService
* prefs
= profile()->GetPrefs();
470 prefs
->SetBoolean(prefs::kHomePageIsNewTabPage
, false);
471 prefs
->SetString(prefs::kHomePage
, "http://www.foo.com");
472 prefs
->SetBoolean(prefs::kShowHomeButton
, true);
474 ResetAndWait(ProfileResetter::HOMEPAGE
);
476 EXPECT_TRUE(prefs
->GetBoolean(prefs::kHomePageIsNewTabPage
));
477 EXPECT_EQ("http://www.foo.com", prefs
->GetString(prefs::kHomePage
));
478 EXPECT_FALSE(prefs
->GetBoolean(prefs::kShowHomeButton
));
481 TEST_F(ProfileResetterTest
, ResetContentSettings
) {
482 HostContentSettingsMap
* host_content_settings_map
=
483 profile()->GetHostContentSettingsMap();
484 ContentSettingsPattern pattern
=
485 ContentSettingsPattern::FromString("[*.]example.org");
486 std::map
<ContentSettingsType
, ContentSetting
> default_settings
;
488 for (int type
= 0; type
< CONTENT_SETTINGS_NUM_TYPES
; ++type
) {
489 ContentSettingsType content_type
= static_cast<ContentSettingsType
>(type
);
490 if (content_type
== CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE
||
491 content_type
== CONTENT_SETTINGS_TYPE_MIXEDSCRIPT
||
492 content_type
== CONTENT_SETTINGS_TYPE_PROTOCOL_HANDLERS
) {
493 // These types are excluded because one can't call
494 // GetDefaultContentSetting() for them.
497 if (content_type
== CONTENT_SETTINGS_TYPE_MEDIASTREAM
) {
498 // This has been deprecated so we can neither set nor get it's value.
501 ContentSetting default_setting
=
502 host_content_settings_map
->GetDefaultContentSetting(content_type
, NULL
);
503 default_settings
[content_type
] = default_setting
;
504 ContentSetting wildcard_setting
= default_setting
== CONTENT_SETTING_BLOCK
505 ? CONTENT_SETTING_ALLOW
506 : CONTENT_SETTING_BLOCK
;
507 ContentSetting site_setting
= default_setting
== CONTENT_SETTING_ALLOW
508 ? CONTENT_SETTING_ALLOW
509 : CONTENT_SETTING_BLOCK
;
510 if (HostContentSettingsMap::IsSettingAllowedForType(
511 profile()->GetPrefs(), wildcard_setting
, content_type
)) {
512 host_content_settings_map
->SetDefaultContentSetting(content_type
,
515 if (!HostContentSettingsMap::ContentTypeHasCompoundValue(content_type
) &&
516 HostContentSettingsMap::IsSettingAllowedForType(
517 profile()->GetPrefs(), site_setting
, content_type
)) {
518 host_content_settings_map
->SetContentSetting(
519 pattern
, ContentSettingsPattern::Wildcard(), content_type
,
520 std::string(), site_setting
);
521 ContentSettingsForOneType host_settings
;
522 host_content_settings_map
->GetSettingsForOneType(
523 content_type
, std::string(), &host_settings
);
524 EXPECT_EQ(2U, host_settings
.size());
528 ResetAndWait(ProfileResetter::CONTENT_SETTINGS
);
530 for (int type
= 0; type
< CONTENT_SETTINGS_NUM_TYPES
; ++type
) {
531 ContentSettingsType content_type
= static_cast<ContentSettingsType
>(type
);
532 if (HostContentSettingsMap::ContentTypeHasCompoundValue(content_type
) ||
533 content_type
== CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE
||
534 content_type
== CONTENT_SETTINGS_TYPE_MIXEDSCRIPT
||
535 content_type
== CONTENT_SETTINGS_TYPE_MEDIASTREAM
||
536 content_type
== CONTENT_SETTINGS_TYPE_PROTOCOL_HANDLERS
)
538 ContentSetting default_setting
=
539 host_content_settings_map
->GetDefaultContentSetting(content_type
,
541 EXPECT_TRUE(default_settings
.count(content_type
));
542 EXPECT_EQ(default_settings
[content_type
], default_setting
);
543 if (!HostContentSettingsMap::ContentTypeHasCompoundValue(content_type
)) {
544 ContentSetting site_setting
=
545 host_content_settings_map
->GetContentSetting(
550 EXPECT_EQ(default_setting
, site_setting
);
553 ContentSettingsForOneType host_settings
;
554 host_content_settings_map
->GetSettingsForOneType(
555 content_type
, std::string(), &host_settings
);
556 EXPECT_EQ(1U, host_settings
.size());
560 TEST_F(ProfileResetterTest
, ResetExtensionsByDisabling
) {
563 base::ScopedTempDir temp_dir
;
564 ASSERT_TRUE(temp_dir
.CreateUniqueTempDir());
566 scoped_refptr
<Extension
> theme
=
567 CreateExtension(base::ASCIIToUTF16("example1"),
569 Manifest::INVALID_LOCATION
,
570 extensions::Manifest::TYPE_THEME
,
572 service_
->FinishInstallationForTest(theme
.get());
573 // Let ThemeService finish creating the theme pack.
574 base::MessageLoop::current()->RunUntilIdle();
576 ThemeService
* theme_service
=
577 ThemeServiceFactory::GetForProfile(profile());
578 EXPECT_FALSE(theme_service
->UsingDefaultTheme());
580 scoped_refptr
<Extension
> ext2
= CreateExtension(
581 base::ASCIIToUTF16("example2"),
582 base::FilePath(FILE_PATH_LITERAL("//nonexistent")),
583 Manifest::INVALID_LOCATION
,
584 extensions::Manifest::TYPE_EXTENSION
,
586 service_
->AddExtension(ext2
.get());
587 // Component extensions and policy-managed extensions shouldn't be disabled.
588 scoped_refptr
<Extension
> ext3
= CreateExtension(
589 base::ASCIIToUTF16("example3"),
590 base::FilePath(FILE_PATH_LITERAL("//nonexistent2")),
592 extensions::Manifest::TYPE_EXTENSION
,
594 service_
->AddExtension(ext3
.get());
595 scoped_refptr
<Extension
> ext4
=
596 CreateExtension(base::ASCIIToUTF16("example4"),
597 base::FilePath(FILE_PATH_LITERAL("//nonexistent3")),
598 Manifest::EXTERNAL_POLICY_DOWNLOAD
,
599 extensions::Manifest::TYPE_EXTENSION
,
601 service_
->AddExtension(ext4
.get());
602 scoped_refptr
<Extension
> ext5
= CreateExtension(
603 base::ASCIIToUTF16("example5"),
604 base::FilePath(FILE_PATH_LITERAL("//nonexistent4")),
605 Manifest::EXTERNAL_COMPONENT
,
606 extensions::Manifest::TYPE_EXTENSION
,
608 service_
->AddExtension(ext5
.get());
609 scoped_refptr
<Extension
> ext6
= CreateExtension(
610 base::ASCIIToUTF16("example6"),
611 base::FilePath(FILE_PATH_LITERAL("//nonexistent5")),
612 Manifest::EXTERNAL_POLICY
,
613 extensions::Manifest::TYPE_EXTENSION
,
615 service_
->AddExtension(ext6
.get());
616 EXPECT_EQ(6u, registry()->enabled_extensions().size());
618 ResetAndWait(ProfileResetter::EXTENSIONS
);
619 EXPECT_EQ(4u, registry()->enabled_extensions().size());
620 EXPECT_FALSE(registry()->enabled_extensions().Contains(theme
->id()));
621 EXPECT_FALSE(registry()->enabled_extensions().Contains(ext2
->id()));
622 EXPECT_TRUE(registry()->enabled_extensions().Contains(ext3
->id()));
623 EXPECT_TRUE(registry()->enabled_extensions().Contains(ext4
->id()));
624 EXPECT_TRUE(registry()->enabled_extensions().Contains(ext5
->id()));
625 EXPECT_TRUE(registry()->enabled_extensions().Contains(ext6
->id()));
626 EXPECT_TRUE(theme_service
->UsingDefaultTheme());
629 TEST_F(ProfileResetterTest
, ResetExtensionsByDisablingNonOrganic
) {
630 scoped_refptr
<Extension
> ext2
= CreateExtension(
631 base::ASCIIToUTF16("example2"),
632 base::FilePath(FILE_PATH_LITERAL("//nonexistent")),
633 Manifest::INVALID_LOCATION
,
634 extensions::Manifest::TYPE_EXTENSION
,
636 service_
->AddExtension(ext2
.get());
637 // Components and external policy extensions shouldn't be deleted.
638 scoped_refptr
<Extension
> ext3
= CreateExtension(
639 base::ASCIIToUTF16("example3"),
640 base::FilePath(FILE_PATH_LITERAL("//nonexistent2")),
641 Manifest::INVALID_LOCATION
,
642 extensions::Manifest::TYPE_EXTENSION
,
644 service_
->AddExtension(ext3
.get());
645 EXPECT_EQ(2u, registry()->enabled_extensions().size());
647 std::string
master_prefs(kDistributionConfig
);
648 ReplaceString(&master_prefs
, "placeholder_for_id", ext3
->id());
650 ResetAndWait(ProfileResetter::EXTENSIONS
, master_prefs
);
652 EXPECT_EQ(1u, registry()->enabled_extensions().size());
653 EXPECT_TRUE(registry()->enabled_extensions().Contains(ext3
->id()));
656 TEST_F(ProfileResetterTest
, ResetExtensionsAndDefaultApps
) {
659 base::ScopedTempDir temp_dir
;
660 ASSERT_TRUE(temp_dir
.CreateUniqueTempDir());
662 scoped_refptr
<Extension
> ext1
=
663 CreateExtension(base::ASCIIToUTF16("example1"),
665 Manifest::INVALID_LOCATION
,
666 extensions::Manifest::TYPE_THEME
,
668 service_
->FinishInstallationForTest(ext1
.get());
669 // Let ThemeService finish creating the theme pack.
670 base::MessageLoop::current()->RunUntilIdle();
672 ThemeService
* theme_service
=
673 ThemeServiceFactory::GetForProfile(profile());
674 EXPECT_FALSE(theme_service
->UsingDefaultTheme());
676 scoped_refptr
<Extension
> ext2
=
677 CreateExtension(base::ASCIIToUTF16("example2"),
678 base::FilePath(FILE_PATH_LITERAL("//nonexistent2")),
679 Manifest::INVALID_LOCATION
,
680 extensions::Manifest::TYPE_EXTENSION
,
682 service_
->AddExtension(ext2
.get());
684 scoped_refptr
<Extension
> ext3
=
685 CreateExtension(base::ASCIIToUTF16("example2"),
686 base::FilePath(FILE_PATH_LITERAL("//nonexistent3")),
687 Manifest::INVALID_LOCATION
,
688 extensions::Manifest::TYPE_HOSTED_APP
,
690 service_
->AddExtension(ext3
.get());
691 EXPECT_EQ(3u, registry()->enabled_extensions().size());
693 ResetAndWait(ProfileResetter::EXTENSIONS
);
695 EXPECT_EQ(1u, registry()->enabled_extensions().size());
696 EXPECT_FALSE(registry()->enabled_extensions().Contains(ext1
->id()));
697 EXPECT_FALSE(registry()->enabled_extensions().Contains(ext2
->id()));
698 EXPECT_TRUE(registry()->enabled_extensions().Contains(ext3
->id()));
699 EXPECT_TRUE(theme_service
->UsingDefaultTheme());
702 TEST_F(ProfileResetterTest
, ResetStartPageNonOrganic
) {
703 PrefService
* prefs
= profile()->GetPrefs();
706 SessionStartupPref
startup_pref(SessionStartupPref::LAST
);
707 SessionStartupPref::SetStartupPref(prefs
, startup_pref
);
709 ResetAndWait(ProfileResetter::STARTUP_PAGES
, kDistributionConfig
);
711 startup_pref
= SessionStartupPref::GetStartupPref(prefs
);
712 EXPECT_EQ(SessionStartupPref::URLS
, startup_pref
.type
);
713 const GURL urls
[] = {GURL("http://goo.gl"), GURL("http://foo.de")};
714 EXPECT_EQ(std::vector
<GURL
>(urls
, urls
+ arraysize(urls
)), startup_pref
.urls
);
718 TEST_F(ProfileResetterTest
, ResetStartPagePartially
) {
719 PrefService
* prefs
= profile()->GetPrefs();
722 const GURL urls
[] = {GURL("http://foo"), GURL("http://bar")};
723 SessionStartupPref
startup_pref(SessionStartupPref::URLS
);
724 startup_pref
.urls
.assign(urls
, urls
+ arraysize(urls
));
725 SessionStartupPref::SetStartupPref(prefs
, startup_pref
);
727 ResetAndWait(ProfileResetter::STARTUP_PAGES
, std::string());
729 startup_pref
= SessionStartupPref::GetStartupPref(prefs
);
730 EXPECT_EQ(SessionStartupPref::GetDefaultStartupType(), startup_pref
.type
);
731 EXPECT_EQ(std::vector
<GURL
>(urls
, urls
+ arraysize(urls
)), startup_pref
.urls
);
734 TEST_F(PinnedTabsResetTest
, ResetPinnedTabs
) {
735 scoped_refptr
<Extension
> extension_app
= CreateExtension(
736 base::ASCIIToUTF16("hello!"),
737 base::FilePath(FILE_PATH_LITERAL("//nonexistent")),
738 Manifest::INVALID_LOCATION
,
739 extensions::Manifest::TYPE_HOSTED_APP
,
741 scoped_ptr
<content::WebContents
> contents1(CreateWebContents());
742 extensions::TabHelper::CreateForWebContents(contents1
.get());
743 extensions::TabHelper::FromWebContents(contents1
.get())->
744 SetExtensionApp(extension_app
.get());
745 scoped_ptr
<content::WebContents
> contents2(CreateWebContents());
746 scoped_ptr
<content::WebContents
> contents3(CreateWebContents());
747 scoped_ptr
<content::WebContents
> contents4(CreateWebContents());
748 TabStripModel
* tab_strip_model
= browser()->tab_strip_model();
750 tab_strip_model
->AppendWebContents(contents4
.get(), true);
751 tab_strip_model
->AppendWebContents(contents3
.get(), true);
752 tab_strip_model
->AppendWebContents(contents2
.get(), true);
753 tab_strip_model
->SetTabPinned(2, true);
754 tab_strip_model
->AppendWebContents(contents1
.get(), true);
755 tab_strip_model
->SetTabPinned(3, true);
757 EXPECT_EQ(contents2
, tab_strip_model
->GetWebContentsAt(0));
758 EXPECT_EQ(contents1
, tab_strip_model
->GetWebContentsAt(1));
759 EXPECT_EQ(contents3
, tab_strip_model
->GetWebContentsAt(2));
760 EXPECT_EQ(contents4
, tab_strip_model
->GetWebContentsAt(3));
761 EXPECT_EQ(3, tab_strip_model
->IndexOfFirstNonMiniTab());
763 ResetAndWait(ProfileResetter::PINNED_TABS
);
765 EXPECT_EQ(contents1
, tab_strip_model
->GetWebContentsAt(0));
766 EXPECT_EQ(contents2
, tab_strip_model
->GetWebContentsAt(1));
767 EXPECT_EQ(contents3
, tab_strip_model
->GetWebContentsAt(2));
768 EXPECT_EQ(contents4
, tab_strip_model
->GetWebContentsAt(3));
769 EXPECT_EQ(1, tab_strip_model
->IndexOfFirstNonMiniTab());
772 TEST_F(ProfileResetterTest
, ResetShortcuts
) {
773 ShortcutHandler shortcut
;
774 ShortcutCommand command_line
= shortcut
.CreateWithArguments(
775 base::ASCIIToUTF16("chrome.lnk"),
776 base::ASCIIToUTF16("--profile-directory=Default foo.com"));
777 shortcut
.CheckShortcutHasArguments(base::ASCIIToUTF16(
778 "--profile-directory=Default foo.com"));
780 ResetAndWait(ProfileResetter::SHORTCUTS
);
782 shortcut
.CheckShortcutHasArguments(base::ASCIIToUTF16(
783 "--profile-directory=Default"));
786 TEST_F(ProfileResetterTest
, ResetFewFlags
) {
787 // mock_object_ is a StrictMock, so we verify that it is called only once.
788 ResetAndWait(ProfileResetter::DEFAULT_SEARCH_ENGINE
|
789 ProfileResetter::HOMEPAGE
|
790 ProfileResetter::CONTENT_SETTINGS
);
793 // Tries to load unavailable config file.
794 TEST_F(ConfigParserTest
, NoConnectivity
) {
795 const GURL
url("http://test");
796 factory().SetFakeResponse(url
, "", net::HTTP_INTERNAL_SERVER_ERROR
,
797 net::URLRequestStatus::FAILED
);
799 scoped_ptr
<BrandcodeConfigFetcher
> fetcher
= WaitForRequest(GURL(url
));
800 EXPECT_FALSE(fetcher
->GetSettings());
803 // Tries to load available config file.
804 TEST_F(ConfigParserTest
, ParseConfig
) {
805 const GURL
url("http://test");
806 std::string
xml_config(kXmlConfig
);
807 ReplaceString(&xml_config
, "placeholder_for_data", kDistributionConfig
);
808 ReplaceString(&xml_config
,
809 "placeholder_for_id",
810 "abbaabbaabbaabbaabbaabbaabbaabba");
811 factory().SetFakeResponse(url
, xml_config
, net::HTTP_OK
,
812 net::URLRequestStatus::SUCCESS
);
814 scoped_ptr
<BrandcodeConfigFetcher
> fetcher
= WaitForRequest(GURL(url
));
815 scoped_ptr
<BrandcodedDefaultSettings
> settings
= fetcher
->GetSettings();
816 ASSERT_TRUE(settings
);
818 std::vector
<std::string
> extension_ids
;
819 EXPECT_TRUE(settings
->GetExtensions(&extension_ids
));
820 EXPECT_EQ(1u, extension_ids
.size());
821 EXPECT_EQ("abbaabbaabbaabbaabbaabbaabbaabba", extension_ids
[0]);
823 std::string homepage
;
824 EXPECT_TRUE(settings
->GetHomepage(&homepage
));
825 EXPECT_EQ("http://www.foo.com", homepage
);
827 scoped_ptr
<base::ListValue
> startup_list(
828 settings
->GetUrlsToRestoreOnStartup());
829 EXPECT_TRUE(startup_list
);
830 std::vector
<std::string
> startup_pages
;
831 for (base::ListValue::iterator i
= startup_list
->begin();
832 i
!= startup_list
->end(); ++i
) {
834 EXPECT_TRUE((*i
)->GetAsString(&url
));
835 startup_pages
.push_back(url
);
837 ASSERT_EQ(2u, startup_pages
.size());
838 EXPECT_EQ("http://goo.gl", startup_pages
[0]);
839 EXPECT_EQ("http://foo.de", startup_pages
[1]);
842 TEST_F(ProfileResetterTest
, CheckSnapshots
) {
843 ResettableSettingsSnapshot
empty_snap(profile());
844 EXPECT_EQ(0, empty_snap
.FindDifferentFields(empty_snap
));
846 scoped_refptr
<Extension
> ext
= CreateExtension(
847 base::ASCIIToUTF16("example"),
848 base::FilePath(FILE_PATH_LITERAL("//nonexistent")),
849 Manifest::INVALID_LOCATION
,
850 extensions::Manifest::TYPE_EXTENSION
,
852 ASSERT_TRUE(ext
.get());
853 service_
->AddExtension(ext
.get());
855 std::string
master_prefs(kDistributionConfig
);
856 std::string ext_id
= ext
->id();
857 ReplaceString(&master_prefs
, "placeholder_for_id", ext_id
);
859 // Reset to non organic defaults.
860 ResetAndWait(ProfileResetter::DEFAULT_SEARCH_ENGINE
|
861 ProfileResetter::HOMEPAGE
|
862 ProfileResetter::STARTUP_PAGES
,
864 ShortcutHandler shortcut_hijacked
;
865 ShortcutCommand command_line
= shortcut_hijacked
.CreateWithArguments(
866 base::ASCIIToUTF16("chrome1.lnk"),
867 base::ASCIIToUTF16("--profile-directory=Default foo.com"));
868 shortcut_hijacked
.CheckShortcutHasArguments(
869 base::ASCIIToUTF16("--profile-directory=Default foo.com"));
870 ShortcutHandler shortcut_ok
;
871 shortcut_ok
.CreateWithArguments(
872 base::ASCIIToUTF16("chrome2.lnk"),
873 base::ASCIIToUTF16("--profile-directory=Default1"));
875 ResettableSettingsSnapshot
nonorganic_snap(profile());
876 nonorganic_snap
.RequestShortcuts(base::Closure());
877 // Let it enumerate shortcuts on the FILE thread.
878 base::MessageLoop::current()->RunUntilIdle();
879 int diff_fields
= ResettableSettingsSnapshot::ALL_FIELDS
;
880 if (!ShortcutHandler::IsSupported())
881 diff_fields
&= ~ResettableSettingsSnapshot::SHORTCUTS
;
882 EXPECT_EQ(diff_fields
,
883 empty_snap
.FindDifferentFields(nonorganic_snap
));
884 empty_snap
.Subtract(nonorganic_snap
);
885 EXPECT_TRUE(empty_snap
.startup_urls().empty());
886 EXPECT_EQ(SessionStartupPref::GetDefaultStartupType(),
887 empty_snap
.startup_type());
888 EXPECT_TRUE(empty_snap
.homepage().empty());
889 EXPECT_TRUE(empty_snap
.homepage_is_ntp());
890 EXPECT_FALSE(empty_snap
.show_home_button());
891 EXPECT_NE(std::string::npos
, empty_snap
.dse_url().find("{google:baseURL}"));
892 EXPECT_EQ(ResettableSettingsSnapshot::ExtensionList(),
893 empty_snap
.enabled_extensions());
894 EXPECT_EQ(std::vector
<ShortcutCommand
>(), empty_snap
.shortcuts());
896 // Reset to organic defaults.
897 ResetAndWait(ProfileResetter::DEFAULT_SEARCH_ENGINE
|
898 ProfileResetter::HOMEPAGE
|
899 ProfileResetter::STARTUP_PAGES
|
900 ProfileResetter::EXTENSIONS
|
901 ProfileResetter::SHORTCUTS
);
903 ResettableSettingsSnapshot
organic_snap(profile());
904 organic_snap
.RequestShortcuts(base::Closure());
905 // Let it enumerate shortcuts on the FILE thread.
906 base::MessageLoop::current()->RunUntilIdle();
907 EXPECT_EQ(diff_fields
, nonorganic_snap
.FindDifferentFields(organic_snap
));
908 nonorganic_snap
.Subtract(organic_snap
);
909 const GURL urls
[] = {GURL("http://foo.de"), GURL("http://goo.gl")};
910 EXPECT_EQ(std::vector
<GURL
>(urls
, urls
+ arraysize(urls
)),
911 nonorganic_snap
.startup_urls());
912 EXPECT_EQ(SessionStartupPref::URLS
, nonorganic_snap
.startup_type());
913 EXPECT_EQ("http://www.foo.com", nonorganic_snap
.homepage());
914 EXPECT_FALSE(nonorganic_snap
.homepage_is_ntp());
915 EXPECT_TRUE(nonorganic_snap
.show_home_button());
916 EXPECT_EQ("http://www.foo.com/s?q={searchTerms}", nonorganic_snap
.dse_url());
917 EXPECT_EQ(ResettableSettingsSnapshot::ExtensionList(
918 1, std::make_pair(ext_id
, "example")),
919 nonorganic_snap
.enabled_extensions());
920 if (ShortcutHandler::IsSupported()) {
921 std::vector
<ShortcutCommand
> shortcuts
= nonorganic_snap
.shortcuts();
922 ASSERT_EQ(1u, shortcuts
.size());
923 EXPECT_EQ(command_line
.first
.value(), shortcuts
[0].first
.value());
924 EXPECT_EQ(command_line
.second
, shortcuts
[0].second
);
928 TEST_F(ProfileResetterTest
, FeedbackSerializationTest
) {
929 // Reset to non organic defaults.
930 ResetAndWait(ProfileResetter::DEFAULT_SEARCH_ENGINE
|
931 ProfileResetter::HOMEPAGE
|
932 ProfileResetter::STARTUP_PAGES
,
933 kDistributionConfig
);
935 scoped_refptr
<Extension
> ext
= CreateExtension(
936 base::ASCIIToUTF16("example"),
937 base::FilePath(FILE_PATH_LITERAL("//nonexistent")),
938 Manifest::INVALID_LOCATION
,
939 extensions::Manifest::TYPE_EXTENSION
,
941 ASSERT_TRUE(ext
.get());
942 service_
->AddExtension(ext
.get());
944 ShortcutHandler shortcut
;
945 ShortcutCommand command_line
= shortcut
.CreateWithArguments(
946 base::ASCIIToUTF16("chrome.lnk"),
947 base::ASCIIToUTF16("--profile-directory=Default foo.com"));
949 ResettableSettingsSnapshot
nonorganic_snap(profile());
950 nonorganic_snap
.RequestShortcuts(base::Closure());
951 // Let it enumerate shortcuts on the FILE thread.
952 base::MessageLoop::current()->RunUntilIdle();
954 static_assert(ResettableSettingsSnapshot::ALL_FIELDS
== 31,
955 "this test needs to be expanded");
956 for (int field_mask
= 0; field_mask
<= ResettableSettingsSnapshot::ALL_FIELDS
;
958 std::string report
= SerializeSettingsReport(nonorganic_snap
, field_mask
);
959 JSONStringValueDeserializer
json(report
);
961 scoped_ptr
<base::Value
> root(json
.Deserialize(NULL
, &error
));
962 ASSERT_TRUE(root
) << error
;
963 ASSERT_TRUE(root
->IsType(base::Value::TYPE_DICTIONARY
)) << error
;
965 base::DictionaryValue
* dict
=
966 static_cast<base::DictionaryValue
*>(root
.get());
968 base::ListValue
* startup_urls
= NULL
;
969 int startup_type
= 0;
970 std::string homepage
;
971 bool homepage_is_ntp
= true;
972 bool show_home_button
= true;
973 std::string default_search_engine
;
974 base::ListValue
* extensions
= NULL
;
975 base::ListValue
* shortcuts
= NULL
;
977 EXPECT_EQ(!!(field_mask
& ResettableSettingsSnapshot::STARTUP_MODE
),
978 dict
->GetList("startup_urls", &startup_urls
));
979 EXPECT_EQ(!!(field_mask
& ResettableSettingsSnapshot::STARTUP_MODE
),
980 dict
->GetInteger("startup_type", &startup_type
));
981 EXPECT_EQ(!!(field_mask
& ResettableSettingsSnapshot::HOMEPAGE
),
982 dict
->GetString("homepage", &homepage
));
983 EXPECT_EQ(!!(field_mask
& ResettableSettingsSnapshot::HOMEPAGE
),
984 dict
->GetBoolean("homepage_is_ntp", &homepage_is_ntp
));
985 EXPECT_EQ(!!(field_mask
& ResettableSettingsSnapshot::HOMEPAGE
),
986 dict
->GetBoolean("show_home_button", &show_home_button
));
987 EXPECT_EQ(!!(field_mask
& ResettableSettingsSnapshot::DSE_URL
),
988 dict
->GetString("default_search_engine", &default_search_engine
));
989 EXPECT_EQ(!!(field_mask
& ResettableSettingsSnapshot::EXTENSIONS
),
990 dict
->GetList("enabled_extensions", &extensions
));
991 EXPECT_EQ(!!(field_mask
& ResettableSettingsSnapshot::SHORTCUTS
),
992 dict
->GetList("shortcuts", &shortcuts
));
996 struct FeedbackCapture
{
997 void SetFeedback(Profile
* profile
,
998 const ResettableSettingsSnapshot
& snapshot
) {
999 list_
= GetReadableFeedbackForSnapshot(profile
, snapshot
).Pass();
1004 ADD_FAILURE() << "This method shouldn't be called.";
1007 MOCK_METHOD0(OnUpdatedList
, void(void));
1009 scoped_ptr
<base::ListValue
> list_
;
1012 // Make sure GetReadableFeedback handles non-ascii letters.
1013 TEST_F(ProfileResetterTest
, GetReadableFeedback
) {
1014 scoped_refptr
<Extension
> ext
= CreateExtension(
1015 base::WideToUTF16(L
"Tiësto"),
1016 base::FilePath(FILE_PATH_LITERAL("//nonexistent")),
1017 Manifest::INVALID_LOCATION
,
1018 extensions::Manifest::TYPE_EXTENSION
,
1020 ASSERT_TRUE(ext
.get());
1021 service_
->AddExtension(ext
.get());
1023 PrefService
* prefs
= profile()->GetPrefs();
1025 // The URL is "http://россия.рф".
1026 std::wstring
url(L
"http://"
1027 L
"\u0440\u043e\u0441\u0441\u0438\u044f.\u0440\u0444");
1028 prefs
->SetBoolean(prefs::kHomePageIsNewTabPage
, false);
1029 prefs
->SetString(prefs::kHomePage
, base::WideToUTF8(url
));
1031 SessionStartupPref
startup_pref(SessionStartupPref::URLS
);
1032 startup_pref
.urls
.push_back(GURL(base::WideToUTF8(url
)));
1033 SessionStartupPref::SetStartupPref(prefs
, startup_pref
);
1035 ShortcutHandler shortcut
;
1036 ShortcutCommand command_line
= shortcut
.CreateWithArguments(
1037 base::ASCIIToUTF16("chrome.lnk"),
1038 base::ASCIIToUTF16("--profile-directory=Default foo.com"));
1040 FeedbackCapture capture
;
1041 EXPECT_CALL(capture
, OnUpdatedList());
1042 ResettableSettingsSnapshot
snapshot(profile());
1043 snapshot
.RequestShortcuts(base::Bind(&FeedbackCapture::SetFeedback
,
1044 base::Unretained(&capture
),
1046 base::ConstRef(snapshot
)));
1047 // Let it enumerate shortcuts on the FILE thread.
1048 base::MessageLoop::current()->RunUntilIdle();
1049 ::testing::Mock::VerifyAndClearExpectations(&capture
);
1050 // The homepage and the startup page are in punycode. They are unreadable.
1051 // Trying to find the extension name.
1052 scoped_ptr
<base::ListValue
> list
= capture
.list_
.Pass();
1054 bool checked_extensions
= false;
1055 bool checked_shortcuts
= false;
1056 for (size_t i
= 0; i
< list
->GetSize(); ++i
) {
1057 base::DictionaryValue
* dict
= NULL
;
1058 ASSERT_TRUE(list
->GetDictionary(i
, &dict
));
1060 ASSERT_TRUE(dict
->GetString("key", &value
));
1061 if (value
== "Extensions") {
1062 base::string16 extensions
;
1063 EXPECT_TRUE(dict
->GetString("value", &extensions
));
1064 EXPECT_EQ(base::WideToUTF16(L
"Tiësto"), extensions
);
1065 checked_extensions
= true;
1066 } else if (value
== "Shortcut targets") {
1067 base::string16 targets
;
1068 EXPECT_TRUE(dict
->GetString("value", &targets
));
1069 EXPECT_NE(base::string16::npos
,
1070 targets
.find(base::ASCIIToUTF16("foo.com"))) << targets
;
1071 checked_shortcuts
= true;
1074 EXPECT_TRUE(checked_extensions
);
1075 EXPECT_EQ(ShortcutHandler::IsSupported(), checked_shortcuts
);
1078 TEST_F(ProfileResetterTest
, DestroySnapshotFast
) {
1079 FeedbackCapture capture
;
1080 scoped_ptr
<ResettableSettingsSnapshot
> deleted_snapshot(
1081 new ResettableSettingsSnapshot(profile()));
1082 deleted_snapshot
->RequestShortcuts(base::Bind(&FeedbackCapture::Fail
,
1083 base::Unretained(&capture
)));
1084 deleted_snapshot
.reset();
1085 // Running remaining tasks shouldn't trigger the callback to be called as
1086 // |deleted_snapshot| was deleted before it could run.
1087 base::MessageLoop::current()->RunUntilIdle();