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.
5 #include "chrome/browser/profile_resetter/automatic_profile_resetter_delegate.h"
10 #include "base/bind_helpers.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/run_loop.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/test/values_test_util.h"
19 #include "base/values.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
22 #include "chrome/browser/search_engines/template_url_service.h"
23 #include "chrome/browser/search_engines/template_url_service_factory.h"
24 #include "chrome/browser/search_engines/template_url_service_test_util.h"
25 #include "chrome/common/pref_names.h"
26 #include "chrome/test/base/testing_pref_service_syncable.h"
27 #include "chrome/test/base/testing_profile.h"
28 #include "content/public/browser/notification_service.h"
29 #include "testing/gmock/include/gmock/gmock.h"
30 #include "testing/gtest/include/gtest/gtest.h"
33 #include "chrome/browser/enumerate_modules_model_win.h"
38 // Test fixtures -------------------------------------------------------------
40 class AutomaticProfileResetterDelegateTest : public testing::Test {
42 AutomaticProfileResetterDelegateTest() {}
43 virtual ~AutomaticProfileResetterDelegateTest() {}
45 virtual void SetUp() OVERRIDE {
46 resetter_delegate_.reset(new AutomaticProfileResetterDelegateImpl(NULL));
49 virtual void TearDown() OVERRIDE { resetter_delegate_.reset(); }
51 AutomaticProfileResetterDelegate* resetter_delegate() {
52 return resetter_delegate_.get();
56 content::TestBrowserThreadBundle thread_bundle_;
57 scoped_ptr<AutomaticProfileResetterDelegate> resetter_delegate_;
59 DISALLOW_COPY_AND_ASSIGN(AutomaticProfileResetterDelegateTest);
62 class AutomaticProfileResetterDelegateTestTemplateURLs : public testing::Test {
64 AutomaticProfileResetterDelegateTestTemplateURLs() {}
65 virtual ~AutomaticProfileResetterDelegateTestTemplateURLs() {}
67 virtual void SetUp() OVERRIDE {
69 resetter_delegate_.reset(
70 new AutomaticProfileResetterDelegateImpl(test_util_.model()));
73 virtual void TearDown() OVERRIDE {
74 resetter_delegate_.reset();
75 test_util_.TearDown();
78 TestingProfile* profile() { return test_util_.profile(); }
80 AutomaticProfileResetterDelegate* resetter_delegate() {
81 return resetter_delegate_.get();
84 scoped_ptr<TemplateURL> CreateTestTemplateURL() {
87 data.SetURL("http://example.com/search?q={searchTerms}");
88 data.suggestions_url = "http://example.com/suggest?q={searchTerms}";
89 data.instant_url = "http://example.com/instant?q={searchTerms}";
90 data.image_url = "http://example.com/image?q={searchTerms}";
91 data.search_url_post_params = "search-post-params";
92 data.suggestions_url_post_params = "suggest-post-params";
93 data.instant_url_post_params = "instant-post-params";
94 data.image_url_post_params = "image-post-params";
96 data.favicon_url = GURL("http://example.com/favicon.ico");
97 data.new_tab_url = "http://example.com/newtab.html";
98 data.alternate_urls.push_back("http://example.com/s?q={searchTerms}");
100 data.short_name = base::ASCIIToUTF16("name");
101 data.SetKeyword(base::ASCIIToUTF16("keyword"));
102 data.search_terms_replacement_key = "search-terms-replacment-key";
103 data.prepopulate_id = 42;
104 data.input_encodings.push_back("UTF-8");
105 data.safe_for_autoreplace = true;
107 return scoped_ptr<TemplateURL>(new TemplateURL(profile(), data));
110 TemplateURLServiceTestUtil test_util_;
113 scoped_ptr<AutomaticProfileResetterDelegate> resetter_delegate_;
115 DISALLOW_COPY_AND_ASSIGN(AutomaticProfileResetterDelegateTestTemplateURLs);
118 // Helper classes and functions ----------------------------------------------
120 // Returns the details of the default search provider from |prefs| in a format
121 // suitable for usage as |expected_details| in ExpectDetailsMatch().
122 scoped_ptr<base::DictionaryValue> GetDefaultSearchProviderDetailsFromPrefs(
123 const PrefService* prefs) {
124 const char kDefaultSearchProviderPrefix[] = "default_search_provider";
125 scoped_ptr<base::DictionaryValue> pref_values_with_path_expansion(
126 prefs->GetPreferenceValues());
127 const base::DictionaryValue* dsp_details = NULL;
128 EXPECT_TRUE(pref_values_with_path_expansion->GetDictionary(
129 kDefaultSearchProviderPrefix, &dsp_details));
130 return scoped_ptr<base::DictionaryValue>(
131 dsp_details ? dsp_details->DeepCopy() : new base::DictionaryValue);
134 // Verifies that the |details| of a search engine as provided by the delegate
135 // are correct in comparison to the |expected_details| coming from the Prefs.
136 void ExpectDetailsMatch(const base::DictionaryValue& expected_details,
137 const base::DictionaryValue& details) {
138 for (base::DictionaryValue::Iterator it(expected_details); !it.IsAtEnd();
140 SCOPED_TRACE(testing::Message("Key: ") << it.key());
141 if (it.key() == "enabled" || it.key() == "synced_guid") {
142 // These attributes should not be present.
143 EXPECT_FALSE(details.HasKey(it.key()));
146 const base::Value* expected_value = &it.value();
147 const base::Value* actual_value = NULL;
148 ASSERT_TRUE(details.Get(it.key(), &actual_value));
149 if (it.key() == "id") {
150 // Ignore ID as it is dynamically assigned by the TemplateURLService.
151 } else if (it.key() == "encodings") {
152 // Encoding list is stored in Prefs as a single string with tokens
153 // delimited by semicolons.
154 std::string expected_encodings;
155 ASSERT_TRUE(expected_value->GetAsString(&expected_encodings));
156 const base::ListValue* actual_encodings_list = NULL;
157 ASSERT_TRUE(actual_value->GetAsList(&actual_encodings_list));
158 std::vector<std::string> actual_encodings_vector;
159 for (base::ListValue::const_iterator it = actual_encodings_list->begin();
160 it != actual_encodings_list->end(); ++it) {
161 std::string encoding;
162 ASSERT_TRUE((*it)->GetAsString(&encoding));
163 actual_encodings_vector.push_back(encoding);
165 EXPECT_EQ(expected_encodings, JoinString(actual_encodings_vector, ';'));
167 // Everything else is the same format.
168 EXPECT_TRUE(actual_value->Equals(expected_value));
173 class MockCallbackTarget {
175 MockCallbackTarget() {}
176 ~MockCallbackTarget() {}
178 MOCK_CONST_METHOD0(Run, void(void));
180 base::Closure CreateClosure() {
181 return base::Closure(
182 base::Bind(&MockCallbackTarget::Run, base::Unretained(this)));
186 DISALLOW_COPY_AND_ASSIGN(MockCallbackTarget);
189 // Tests ---------------------------------------------------------------------
191 TEST_F(AutomaticProfileResetterDelegateTest,
192 TriggerAndWaitOnModuleEnumeration) {
193 testing::StrictMock<MockCallbackTarget> mock_target;
195 // Expect ready_callback to be called just after the modules have been
196 // enumerated. Fail if it is not called. Note: as the EnumerateModulesModel is
197 // a global singleton, the callback might be invoked immediately if another
198 // test-case (e.g. the one below) has already performed module enumeration.
199 EXPECT_CALL(mock_target, Run());
200 resetter_delegate()->RequestCallbackWhenLoadedModulesAreEnumerated(
201 mock_target.CreateClosure());
202 resetter_delegate()->EnumerateLoadedModulesIfNeeded();
203 base::RunLoop().RunUntilIdle();
205 testing::Mock::VerifyAndClearExpectations(&mock_target);
207 // Expect ready_callback to be posted immediately when the modules have
208 // already been enumerated.
209 EXPECT_CALL(mock_target, Run());
210 resetter_delegate()->RequestCallbackWhenLoadedModulesAreEnumerated(
211 mock_target.CreateClosure());
212 base::RunLoop().RunUntilIdle();
215 testing::Mock::VerifyAndClearExpectations(&mock_target);
217 // Expect ready_callback to be posted immediately even when the modules had
218 // already been enumerated when the delegate was constructed.
219 scoped_ptr<AutomaticProfileResetterDelegate> late_resetter_delegate(
220 new AutomaticProfileResetterDelegateImpl(NULL));
222 EXPECT_CALL(mock_target, Run());
223 late_resetter_delegate->RequestCallbackWhenLoadedModulesAreEnumerated(
224 mock_target.CreateClosure());
225 base::RunLoop().RunUntilIdle();
229 TEST_F(AutomaticProfileResetterDelegateTest, GetLoadedModuleNameDigests) {
230 resetter_delegate()->EnumerateLoadedModulesIfNeeded();
231 base::RunLoop().RunUntilIdle();
232 scoped_ptr<base::ListValue> module_name_digests(
233 resetter_delegate()->GetLoadedModuleNameDigests());
235 // Just verify that each element looks like an MD5 hash in hexadecimal, and
236 // also that we have at least one element on Win.
237 ASSERT_TRUE(module_name_digests);
238 for (base::ListValue::const_iterator it = module_name_digests->begin();
239 it != module_name_digests->end(); ++it) {
240 std::string digest_hex;
241 std::vector<uint8> digest_raw;
243 ASSERT_TRUE((*it)->GetAsString(&digest_hex));
244 ASSERT_TRUE(base::HexStringToBytes(digest_hex, &digest_raw));
245 EXPECT_EQ(16u, digest_raw.size());
248 EXPECT_LE(1u, module_name_digests->GetSize());
252 TEST_F(AutomaticProfileResetterDelegateTestTemplateURLs,
253 LoadAndWaitOnTemplateURLService) {
254 testing::StrictMock<MockCallbackTarget> mock_target;
256 // Expect ready_callback to be called just after the template URL service gets
257 // initialized. Fail if it is not called, or called too early.
258 resetter_delegate()->RequestCallbackWhenTemplateURLServiceIsLoaded(
259 mock_target.CreateClosure());
260 base::RunLoop().RunUntilIdle();
262 EXPECT_CALL(mock_target, Run());
263 resetter_delegate()->LoadTemplateURLServiceIfNeeded();
264 base::RunLoop().RunUntilIdle();
266 testing::Mock::VerifyAndClearExpectations(&mock_target);
268 // Expect ready_callback to be posted immediately when the template URL
269 // service is already initialized.
270 EXPECT_CALL(mock_target, Run());
271 resetter_delegate()->RequestCallbackWhenTemplateURLServiceIsLoaded(
272 mock_target.CreateClosure());
273 base::RunLoop().RunUntilIdle();
275 testing::Mock::VerifyAndClearExpectations(&mock_target);
277 // Expect ready_callback to be posted immediately even when the template URL
278 // service had already been initialized when the delegate was constructed.
279 scoped_ptr<AutomaticProfileResetterDelegate> late_resetter_delegate(
280 new AutomaticProfileResetterDelegateImpl(test_util_.model()));
282 EXPECT_CALL(mock_target, Run());
283 late_resetter_delegate->RequestCallbackWhenTemplateURLServiceIsLoaded(
284 mock_target.CreateClosure());
285 base::RunLoop().RunUntilIdle();
288 TEST_F(AutomaticProfileResetterDelegateTestTemplateURLs,
289 DefaultSearchProviderDataWhenNotManaged) {
290 TemplateURLService* template_url_service = test_util_.model();
291 test_util_.VerifyLoad();
293 // Check that the "managed state" and the details returned by the delegate are
294 // correct. We verify the details against the data stored by
295 // TemplateURLService into Prefs.
296 scoped_ptr<TemplateURL> owned_custom_dsp(CreateTestTemplateURL());
297 TemplateURL* custom_dsp = owned_custom_dsp.get();
298 template_url_service->Add(owned_custom_dsp.release());
299 template_url_service->SetDefaultSearchProvider(custom_dsp);
301 PrefService* prefs = profile()->GetPrefs();
303 scoped_ptr<base::DictionaryValue> dsp_details(
304 resetter_delegate()->GetDefaultSearchProviderDetails());
305 scoped_ptr<base::DictionaryValue> expected_dsp_details(
306 GetDefaultSearchProviderDetailsFromPrefs(prefs));
308 ExpectDetailsMatch(*expected_dsp_details, *dsp_details);
309 EXPECT_FALSE(resetter_delegate()->IsDefaultSearchProviderManaged());
312 TEST_F(AutomaticProfileResetterDelegateTestTemplateURLs,
313 DefaultSearchProviderDataWhenManaged) {
314 const char kTestSearchURL[] = "http://example.com/search?q={searchTerms}";
315 const char kTestName[] = "name";
316 const char kTestKeyword[] = "keyword";
318 test_util_.VerifyLoad();
320 EXPECT_FALSE(resetter_delegate()->IsDefaultSearchProviderManaged());
322 // Set managed preferences to emulate a default search provider set by policy.
323 test_util_.SetManagedDefaultSearchPreferences(
324 true, kTestName, kTestKeyword, kTestSearchURL, std::string(),
325 std::string(), std::string(), std::string(), std::string());
327 EXPECT_TRUE(resetter_delegate()->IsDefaultSearchProviderManaged());
328 scoped_ptr<base::DictionaryValue> dsp_details(
329 resetter_delegate()->GetDefaultSearchProviderDetails());
330 // Checking that all details are correct is already done by the above test.
331 // Just make sure details are reported about the correct engine.
332 base::ExpectDictStringValue(kTestSearchURL, *dsp_details, "search_url");
334 // Set managed preferences to emulate that having a default search provider is
335 // disabled by policy.
336 test_util_.RemoveManagedDefaultSearchPreferences();
337 test_util_.SetManagedDefaultSearchPreferences(
338 true, std::string(), std::string(), std::string(), std::string(),
339 std::string(), std::string(), std::string(), std::string());
341 dsp_details = resetter_delegate()->GetDefaultSearchProviderDetails();
342 EXPECT_TRUE(resetter_delegate()->IsDefaultSearchProviderManaged());
343 EXPECT_TRUE(dsp_details->empty());
346 TEST_F(AutomaticProfileResetterDelegateTestTemplateURLs,
347 GetPrepopulatedSearchProvidersDetails) {
348 TemplateURLService* template_url_service = test_util_.model();
349 test_util_.VerifyLoad();
351 scoped_ptr<base::ListValue> search_engines_details(
352 resetter_delegate()->GetPrepopulatedSearchProvidersDetails());
354 // Do the same kind of verification as for GetDefaultSearchEngineDetails:
355 // subsequently set each pre-populated engine as the default, so we can verify
356 // that the details returned by the delegate about one particular engine are
357 // correct in comparison to what has been stored to the Prefs.
358 std::vector<TemplateURL*> prepopulated_engines =
359 template_url_service->GetTemplateURLs();
361 ASSERT_EQ(prepopulated_engines.size(), search_engines_details->GetSize());
363 for (size_t i = 0; i < search_engines_details->GetSize(); ++i) {
364 const base::DictionaryValue* details = NULL;
365 ASSERT_TRUE(search_engines_details->GetDictionary(i, &details));
368 ASSERT_TRUE(details->GetString("keyword", &keyword));
369 TemplateURL* search_engine =
370 template_url_service->GetTemplateURLForKeyword(ASCIIToUTF16(keyword));
371 ASSERT_TRUE(search_engine);
372 template_url_service->SetDefaultSearchProvider(prepopulated_engines[i]);
374 PrefService* prefs = profile()->GetPrefs();
376 scoped_ptr<base::DictionaryValue> expected_dsp_details(
377 GetDefaultSearchProviderDetailsFromPrefs(prefs));
378 ExpectDetailsMatch(*expected_dsp_details, *details);