- add sources.
[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/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"
31
32 #if defined(OS_WIN)
33 #include "chrome/browser/enumerate_modules_model_win.h"
34 #endif
35
36 namespace {
37
38 // Test fixtures -------------------------------------------------------------
39
40 class AutomaticProfileResetterDelegateTest : public testing::Test {
41  protected:
42   AutomaticProfileResetterDelegateTest() {}
43   virtual ~AutomaticProfileResetterDelegateTest() {}
44
45   virtual void SetUp() OVERRIDE {
46     resetter_delegate_.reset(new AutomaticProfileResetterDelegateImpl(NULL));
47   }
48
49   virtual void TearDown() OVERRIDE { resetter_delegate_.reset(); }
50
51   AutomaticProfileResetterDelegate* resetter_delegate() {
52     return resetter_delegate_.get();
53   }
54
55  private:
56   content::TestBrowserThreadBundle thread_bundle_;
57   scoped_ptr<AutomaticProfileResetterDelegate> resetter_delegate_;
58
59   DISALLOW_COPY_AND_ASSIGN(AutomaticProfileResetterDelegateTest);
60 };
61
62 class AutomaticProfileResetterDelegateTestTemplateURLs : public testing::Test {
63  protected:
64   AutomaticProfileResetterDelegateTestTemplateURLs() {}
65   virtual ~AutomaticProfileResetterDelegateTestTemplateURLs() {}
66
67   virtual void SetUp() OVERRIDE {
68     test_util_.SetUp();
69     resetter_delegate_.reset(
70         new AutomaticProfileResetterDelegateImpl(test_util_.model()));
71   }
72
73   virtual void TearDown() OVERRIDE {
74     resetter_delegate_.reset();
75     test_util_.TearDown();
76   }
77
78   TestingProfile* profile() { return test_util_.profile(); }
79
80   AutomaticProfileResetterDelegate* resetter_delegate() {
81     return resetter_delegate_.get();
82   }
83
84   scoped_ptr<TemplateURL> CreateTestTemplateURL() {
85     TemplateURLData data;
86
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";
95
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}");
99
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;
106
107     return scoped_ptr<TemplateURL>(new TemplateURL(profile(), data));
108   }
109
110   TemplateURLServiceTestUtil test_util_;
111
112  private:
113   scoped_ptr<AutomaticProfileResetterDelegate> resetter_delegate_;
114
115   DISALLOW_COPY_AND_ASSIGN(AutomaticProfileResetterDelegateTestTemplateURLs);
116 };
117
118 // Helper classes and functions ----------------------------------------------
119
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);
132 }
133
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();
139        it.Advance()) {
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()));
144       continue;
145     }
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);
164       }
165       EXPECT_EQ(expected_encodings, JoinString(actual_encodings_vector, ';'));
166     } else {
167       // Everything else is the same format.
168       EXPECT_TRUE(actual_value->Equals(expected_value));
169     }
170   }
171 }
172
173 class MockCallbackTarget {
174  public:
175   MockCallbackTarget() {}
176   ~MockCallbackTarget() {}
177
178   MOCK_CONST_METHOD0(Run, void(void));
179
180   base::Closure CreateClosure() {
181     return base::Closure(
182         base::Bind(&MockCallbackTarget::Run, base::Unretained(this)));
183   }
184
185  private:
186   DISALLOW_COPY_AND_ASSIGN(MockCallbackTarget);
187 };
188
189 // Tests ---------------------------------------------------------------------
190
191 TEST_F(AutomaticProfileResetterDelegateTest,
192        TriggerAndWaitOnModuleEnumeration) {
193   testing::StrictMock<MockCallbackTarget> mock_target;
194
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();
204
205   testing::Mock::VerifyAndClearExpectations(&mock_target);
206
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();
213
214 #if defined(OS_WIN)
215   testing::Mock::VerifyAndClearExpectations(&mock_target);
216
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));
221
222   EXPECT_CALL(mock_target, Run());
223   late_resetter_delegate->RequestCallbackWhenLoadedModulesAreEnumerated(
224       mock_target.CreateClosure());
225   base::RunLoop().RunUntilIdle();
226 #endif
227 }
228
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());
234
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;
242
243     ASSERT_TRUE((*it)->GetAsString(&digest_hex));
244     ASSERT_TRUE(base::HexStringToBytes(digest_hex, &digest_raw));
245     EXPECT_EQ(16u, digest_raw.size());
246   }
247 #if defined(OS_WIN)
248   EXPECT_LE(1u, module_name_digests->GetSize());
249 #endif
250 }
251
252 TEST_F(AutomaticProfileResetterDelegateTestTemplateURLs,
253        LoadAndWaitOnTemplateURLService) {
254   testing::StrictMock<MockCallbackTarget> mock_target;
255
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();
261
262   EXPECT_CALL(mock_target, Run());
263   resetter_delegate()->LoadTemplateURLServiceIfNeeded();
264   base::RunLoop().RunUntilIdle();
265
266   testing::Mock::VerifyAndClearExpectations(&mock_target);
267
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();
274
275   testing::Mock::VerifyAndClearExpectations(&mock_target);
276
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()));
281
282   EXPECT_CALL(mock_target, Run());
283   late_resetter_delegate->RequestCallbackWhenTemplateURLServiceIsLoaded(
284       mock_target.CreateClosure());
285   base::RunLoop().RunUntilIdle();
286 }
287
288 TEST_F(AutomaticProfileResetterDelegateTestTemplateURLs,
289        DefaultSearchProviderDataWhenNotManaged) {
290   TemplateURLService* template_url_service = test_util_.model();
291   test_util_.VerifyLoad();
292
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);
300
301   PrefService* prefs = profile()->GetPrefs();
302   ASSERT_TRUE(prefs);
303   scoped_ptr<base::DictionaryValue> dsp_details(
304       resetter_delegate()->GetDefaultSearchProviderDetails());
305   scoped_ptr<base::DictionaryValue> expected_dsp_details(
306       GetDefaultSearchProviderDetailsFromPrefs(prefs));
307
308   ExpectDetailsMatch(*expected_dsp_details, *dsp_details);
309   EXPECT_FALSE(resetter_delegate()->IsDefaultSearchProviderManaged());
310 }
311
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";
317
318   test_util_.VerifyLoad();
319
320   EXPECT_FALSE(resetter_delegate()->IsDefaultSearchProviderManaged());
321
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());
326
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");
333
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());
340
341   dsp_details = resetter_delegate()->GetDefaultSearchProviderDetails();
342   EXPECT_TRUE(resetter_delegate()->IsDefaultSearchProviderManaged());
343   EXPECT_TRUE(dsp_details->empty());
344 }
345
346 TEST_F(AutomaticProfileResetterDelegateTestTemplateURLs,
347        GetPrepopulatedSearchProvidersDetails) {
348   TemplateURLService* template_url_service = test_util_.model();
349   test_util_.VerifyLoad();
350
351   scoped_ptr<base::ListValue> search_engines_details(
352       resetter_delegate()->GetPrepopulatedSearchProvidersDetails());
353
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();
360
361   ASSERT_EQ(prepopulated_engines.size(), search_engines_details->GetSize());
362
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));
366
367     std::string keyword;
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]);
373
374     PrefService* prefs = profile()->GetPrefs();
375     ASSERT_TRUE(prefs);
376     scoped_ptr<base::DictionaryValue> expected_dsp_details(
377         GetDefaultSearchProviderDetailsFromPrefs(prefs));
378     ExpectDetailsMatch(*expected_dsp_details, *details);
379   }
380 }
381
382 }  // namespace