Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / customization_document_unittest.cc
1 // Copyright (c) 2011 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/chromeos/customization_document.h"
6
7 #include "base/message_loop/message_loop.h"
8 #include "base/prefs/testing_pref_service.h"
9 #include "base/run_loop.h"
10 #include "base/strings/stringprintf.h"
11 #include "chrome/browser/chromeos/net/network_portal_detector_test_impl.h"
12 #include "chrome/browser/extensions/external_provider_impl.h"
13 #include "chrome/browser/prefs/browser_prefs.h"
14 #include "chrome/browser/prefs/pref_service_mock_factory.h"
15 #include "chrome/browser/prefs/pref_service_syncable.h"
16 #include "chrome/browser/ui/app_list/app_list_syncable_service.h"
17 #include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h"
18 #include "chrome/test/base/testing_browser_process.h"
19 #include "chrome/test/base/testing_profile.h"
20 #include "chromeos/dbus/dbus_thread_manager.h"
21 #include "chromeos/network/network_handler.h"
22 #include "chromeos/network/network_state.h"
23 #include "chromeos/network/network_state_handler.h"
24 #include "chromeos/system/fake_statistics_provider.h"
25 #include "components/pref_registry/pref_registry_syncable.h"
26 #include "content/public/test/test_browser_thread_bundle.h"
27 #include "extensions/common/extension.h"
28 #include "extensions/common/manifest.h"
29 #include "net/http/http_response_headers.h"
30 #include "net/http/http_status_code.h"
31 #include "net/url_request/test_url_fetcher_factory.h"
32 #include "net/url_request/url_request_status.h"
33 #include "testing/gmock/include/gmock/gmock.h"
34 #include "testing/gtest/include/gtest/gtest.h"
35
36 using ::testing::Exactly;
37 using ::testing::Invoke;
38 using ::testing::Mock;
39 using ::testing::_;
40
41 namespace {
42
43 const char kGoodStartupManifest[] =
44     "{"
45     "  \"version\": \"1.0\","
46     "  \"initial_locale\" : \"en-US\","
47     "  \"initial_timezone\" : \"US/Pacific\","
48     "  \"keyboard_layout\" : \"xkb:us::eng\","
49     "  \"setup_content\" : {"
50     "    \"en-US\" : {"
51     "      \"eula_page\" : \"file:///opt/oem/eula/en-US/eula.html\","
52     "    },"
53     "    \"ru-RU\" : {"
54     "      \"eula_page\" : \"file:///opt/oem/eula/ru-RU/eula.html\","
55     "    },"
56     "    \"default\" : {"
57     "      \"eula_page\" : \"file:///opt/oem/eula/en/eula.html\","
58     "    },"
59     "  },"
60     "  \"hwid_map\" : ["
61     "    {"
62     "      \"hwid_mask\": \"ZGA*34\","
63     "      \"initial_locale\" : \"ja\","
64     "      \"initial_timezone\" : \"Asia/Tokyo\","
65     "      \"keyboard_layout\" : \"mozc-jp\","
66     "    },"
67     "    {"
68     "      \"hwid_mask\": \"Mario 1?3*\","
69     "      \"initial_locale\" : \"ru-RU\","
70     "      \"initial_timezone\" : \"Europe/Moscow\","
71     "      \"keyboard_layout\" : \"xkb:ru::rus\","
72     "    },"
73     "  ],"
74     "}";
75
76 const char kBadManifest[] = "{\"version\": \"1\"}";
77
78 const char kGoodServicesManifest[] =
79     "{"
80     "  \"version\": \"1.0\","
81     "  \"default_apps\": [\n"
82     "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
83     "    \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
84     "  ],\n"
85     "  \"localized_content\": {\n"
86     "    \"en-US\": {\n"
87     "      \"default_apps_folder_name\": \"EN-US OEM Name\"\n"
88     "    },\n"
89     "    \"en\": {\n"
90     "      \"default_apps_folder_name\": \"EN OEM Name\"\n"
91     "    },\n"
92     "    \"default\": {\n"
93     "      \"default_apps_folder_name\": \"Default OEM Name\"\n"
94     "    }\n"
95     "  }\n"
96     "}";
97
98 const char kDummyCustomizationID[] = "test-dummy";
99
100 }  // anonymous namespace
101
102 namespace chromeos {
103
104 using ::testing::DoAll;
105 using ::testing::NotNull;
106 using ::testing::Return;
107 using ::testing::SetArgumentPointee;
108 using ::testing::_;
109
110 TEST(StartupCustomizationDocumentTest, Basic) {
111   system::ScopedFakeStatisticsProvider fake_statistics_provider;
112
113   // hardware_class selects the appropriate entry in hwid_map in the manifest.
114   fake_statistics_provider.SetMachineStatistic("hardware_class", "Mario 12345");
115   StartupCustomizationDocument customization(&fake_statistics_provider,
116                                              kGoodStartupManifest);
117   EXPECT_EQ("ru-RU", customization.initial_locale());
118   EXPECT_EQ("Europe/Moscow", customization.initial_timezone());
119   EXPECT_EQ("xkb:ru::rus", customization.keyboard_layout());
120
121   EXPECT_EQ("file:///opt/oem/eula/en-US/eula.html",
122             customization.GetEULAPage("en-US"));
123   EXPECT_EQ("file:///opt/oem/eula/ru-RU/eula.html",
124             customization.GetEULAPage("ru-RU"));
125   EXPECT_EQ("file:///opt/oem/eula/en/eula.html",
126             customization.GetEULAPage("ja"));
127 }
128
129 TEST(StartupCustomizationDocumentTest, VPD) {
130   system::ScopedFakeStatisticsProvider fake_statistics_provider;
131
132   // hardware_class selects the appropriate entry in hwid_map in the manifest.
133   fake_statistics_provider.SetMachineStatistic("hardware_class", "Mario 12345");
134   fake_statistics_provider.SetMachineStatistic("initial_locale", "ja");
135   fake_statistics_provider.SetMachineStatistic("initial_timezone",
136                                                "Asia/Tokyo");
137   fake_statistics_provider.SetMachineStatistic("keyboard_layout", "mozc-jp");
138   StartupCustomizationDocument customization(&fake_statistics_provider,
139                                              kGoodStartupManifest);
140   EXPECT_TRUE(customization.IsReady());
141   EXPECT_EQ("ja", customization.initial_locale());
142   EXPECT_EQ("Asia/Tokyo", customization.initial_timezone());
143   EXPECT_EQ("mozc-jp", customization.keyboard_layout());
144 }
145
146 TEST(StartupCustomizationDocumentTest, BadManifest) {
147   system::ScopedFakeStatisticsProvider fake_statistics_provider;
148   StartupCustomizationDocument customization(&fake_statistics_provider,
149                                              kBadManifest);
150   EXPECT_FALSE(customization.IsReady());
151 }
152
153 class TestURLFetcherCallback {
154  public:
155   scoped_ptr<net::FakeURLFetcher> CreateURLFetcher(
156       const GURL& url,
157       net::URLFetcherDelegate* d,
158       const std::string& response_data,
159       net::HttpStatusCode response_code,
160       net::URLRequestStatus::Status status) {
161     scoped_ptr<net::FakeURLFetcher> fetcher(
162         new net::FakeURLFetcher(url, d, response_data, response_code, status));
163     OnRequestCreate(url, fetcher.get());
164     return fetcher.Pass();
165   }
166   MOCK_METHOD2(OnRequestCreate,
167                void(const GURL&, net::FakeURLFetcher*));
168 };
169
170 void AddMimeHeader(const GURL& url, net::FakeURLFetcher* fetcher) {
171   scoped_refptr<net::HttpResponseHeaders> download_headers =
172       new net::HttpResponseHeaders("");
173   download_headers->AddHeader("Content-Type: application/json");
174   fetcher->set_response_headers(download_headers);
175 }
176
177 class MockExternalProviderVisitor
178     : public extensions::ExternalProviderInterface::VisitorInterface {
179  public:
180   MockExternalProviderVisitor() {}
181
182   MOCK_METHOD6(OnExternalExtensionFileFound,
183                bool(const std::string&,
184                     const base::Version*,
185                     const base::FilePath&,
186                     extensions::Manifest::Location,
187                     int,
188                     bool));
189   MOCK_METHOD6(OnExternalExtensionUpdateUrlFound,
190                bool(const std::string&,
191                     const std::string&,
192                     const GURL&,
193                     extensions::Manifest::Location,
194                     int,
195                     bool));
196   MOCK_METHOD1(OnExternalProviderReady,
197                void(const extensions::ExternalProviderInterface* provider));
198 };
199
200 class ServicesCustomizationDocumentTest : public testing::Test {
201  protected:
202   ServicesCustomizationDocumentTest()
203     : factory_(NULL,
204                base::Bind(&TestURLFetcherCallback::CreateURLFetcher,
205                base::Unretained(&url_callback_))) {
206   }
207
208   // testing::Test:
209   virtual void SetUp() override {
210     ServicesCustomizationDocument::InitializeForTesting();
211
212     DBusThreadManager::Initialize();
213     NetworkHandler::Initialize();
214     RunUntilIdle();
215     const NetworkState* default_network =
216         NetworkHandler::Get()->network_state_handler()->DefaultNetwork();
217     std::string default_network_path =
218         default_network ? default_network->path() : "";
219
220     NetworkPortalDetector::InitializeForTesting(&network_portal_detector_);
221     NetworkPortalDetector::CaptivePortalState online_state;
222     online_state.status = NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_ONLINE;
223     online_state.response_code = 204;
224     std::string guid =
225         default_network ? default_network->guid() : std::string();
226     network_portal_detector_.SetDefaultNetworkForTesting(guid);
227     if (!guid.empty()) {
228       network_portal_detector_.SetDetectionResultsForTesting(
229           guid, online_state);
230     }
231
232     TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_);
233     ServicesCustomizationDocument::RegisterPrefs(local_state_.registry());
234   }
235
236   virtual void TearDown() override {
237     TestingBrowserProcess::GetGlobal()->SetLocalState(NULL);
238     NetworkHandler::Shutdown();
239     DBusThreadManager::Shutdown();
240     NetworkPortalDetector::InitializeForTesting(NULL);
241
242     ServicesCustomizationDocument::ShutdownForTesting();
243   }
244
245   void RunUntilIdle() {
246     base::RunLoop().RunUntilIdle();
247   }
248
249   void AddCustomizationIdToVp(const std::string& id) {
250     fake_statistics_provider_.SetMachineStatistic(system::kCustomizationIdKey,
251                                                   id);
252   }
253
254   void AddExpectedManifest(const std::string& id,
255                            const std::string& manifest) {
256     GURL url(base::StringPrintf(ServicesCustomizationDocument::kManifestUrl,
257                                 id.c_str()));
258     factory_.SetFakeResponse(url,
259                              manifest,
260                              net::HTTP_OK,
261                              net::URLRequestStatus::SUCCESS);
262     EXPECT_CALL(url_callback_, OnRequestCreate(url, _))
263       .Times(Exactly(1))
264       .WillRepeatedly(Invoke(AddMimeHeader));
265   }
266
267   void AddManifestNotFound(const std::string& id) {
268     GURL url(base::StringPrintf(ServicesCustomizationDocument::kManifestUrl,
269                                 id.c_str()));
270     factory_.SetFakeResponse(url,
271                              std::string(),
272                              net::HTTP_NOT_FOUND,
273                              net::URLRequestStatus::SUCCESS);
274     EXPECT_CALL(url_callback_, OnRequestCreate(url, _))
275       .Times(Exactly(1))
276       .WillRepeatedly(Invoke(AddMimeHeader));
277   }
278
279   scoped_ptr<TestingProfile> CreateProfile() {
280     TestingProfile::Builder profile_builder;
281     PrefServiceMockFactory factory;
282     scoped_refptr<user_prefs::PrefRegistrySyncable> registry(
283         new user_prefs::PrefRegistrySyncable);
284     scoped_ptr<PrefServiceSyncable> prefs(
285         factory.CreateSyncable(registry.get()));
286     chrome::RegisterUserProfilePrefs(registry.get());
287     profile_builder.SetPrefService(prefs.Pass());
288     return profile_builder.Build();
289   }
290
291  private:
292   system::ScopedFakeStatisticsProvider fake_statistics_provider_;
293   content::TestBrowserThreadBundle thread_bundle_;
294   TestingPrefServiceSimple local_state_;
295   TestURLFetcherCallback url_callback_;
296   net::FakeURLFetcherFactory factory_;
297   NetworkPortalDetectorTestImpl network_portal_detector_;
298 };
299
300 TEST_F(ServicesCustomizationDocumentTest, Basic) {
301   AddCustomizationIdToVp(kDummyCustomizationID);
302   AddExpectedManifest(kDummyCustomizationID, kGoodServicesManifest);
303
304   ServicesCustomizationDocument* doc =
305       ServicesCustomizationDocument::GetInstance();
306   EXPECT_FALSE(doc->IsReady());
307
308   doc->StartFetching();
309   RunUntilIdle();
310   EXPECT_TRUE(doc->IsReady());
311
312   GURL wallpaper_url;
313   EXPECT_FALSE(doc->GetDefaultWallpaperUrl(&wallpaper_url));
314   EXPECT_EQ("", wallpaper_url.spec());
315
316   std::vector<std::string> default_apps;
317   EXPECT_TRUE(doc->GetDefaultApps(&default_apps));
318   ASSERT_EQ(default_apps.size(), 2u);
319
320   EXPECT_EQ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", default_apps[0]);
321   EXPECT_EQ("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", default_apps[1]);
322
323   EXPECT_EQ("EN-US OEM Name", doc->GetOemAppsFolderName("en-US"));
324   EXPECT_EQ("EN OEM Name", doc->GetOemAppsFolderName("en"));
325   EXPECT_EQ("Default OEM Name", doc->GetOemAppsFolderName("ru"));
326 }
327
328 TEST_F(ServicesCustomizationDocumentTest, NoCustomizationIdInVpd) {
329   ServicesCustomizationDocument* doc =
330       ServicesCustomizationDocument::GetInstance();
331   EXPECT_FALSE(doc->IsReady());
332
333   scoped_ptr<TestingProfile> profile = CreateProfile();
334   extensions::ExternalLoader* loader = doc->CreateExternalLoader(profile.get());
335   EXPECT_TRUE(loader);
336
337   MockExternalProviderVisitor visitor;
338   scoped_ptr<extensions::ExternalProviderImpl> provider(
339       new extensions::ExternalProviderImpl(
340           &visitor,
341           loader,
342           profile.get(),
343           extensions::Manifest::EXTERNAL_PREF,
344           extensions::Manifest::EXTERNAL_PREF_DOWNLOAD,
345           extensions::Extension::FROM_WEBSTORE |
346               extensions::Extension::WAS_INSTALLED_BY_DEFAULT));
347
348   EXPECT_CALL(visitor, OnExternalExtensionFileFound(_, _, _, _, _, _))
349       .Times(0);
350   EXPECT_CALL(visitor, OnExternalExtensionUpdateUrlFound(_, _, _, _, _, _))
351       .Times(0);
352   EXPECT_CALL(visitor, OnExternalProviderReady(_))
353       .Times(1);
354
355   // Manually request a load.
356   RunUntilIdle();
357   loader->StartLoading();
358   Mock::VerifyAndClearExpectations(&visitor);
359
360   RunUntilIdle();
361   // Empty customization is used when there is no customization ID in VPD.
362   EXPECT_TRUE(doc->IsReady());
363 }
364
365 TEST_F(ServicesCustomizationDocumentTest, DefaultApps) {
366   AddCustomizationIdToVp(kDummyCustomizationID);
367   AddExpectedManifest(kDummyCustomizationID, kGoodServicesManifest);
368
369   ServicesCustomizationDocument* doc =
370       ServicesCustomizationDocument::GetInstance();
371   EXPECT_FALSE(doc->IsReady());
372
373   scoped_ptr<TestingProfile> profile = CreateProfile();
374   extensions::ExternalLoader* loader = doc->CreateExternalLoader(profile.get());
375   EXPECT_TRUE(loader);
376
377   app_list::AppListSyncableServiceFactory::GetInstance()->
378       SetTestingFactoryAndUse(
379           profile.get(),
380           &app_list::AppListSyncableServiceFactory::BuildInstanceFor);
381
382   MockExternalProviderVisitor visitor;
383   scoped_ptr<extensions::ExternalProviderImpl> provider(
384       new extensions::ExternalProviderImpl(
385           &visitor,
386           loader,
387           profile.get(),
388           extensions::Manifest::EXTERNAL_PREF,
389           extensions::Manifest::EXTERNAL_PREF_DOWNLOAD,
390           extensions::Extension::FROM_WEBSTORE |
391               extensions::Extension::WAS_INSTALLED_BY_DEFAULT));
392
393   EXPECT_CALL(visitor, OnExternalExtensionFileFound(_, _, _, _, _, _))
394       .Times(0);
395   EXPECT_CALL(visitor, OnExternalExtensionUpdateUrlFound(_, _, _, _, _, _))
396       .Times(0);
397   EXPECT_CALL(visitor, OnExternalProviderReady(_))
398       .Times(1);
399
400   // Manually request a load.
401   loader->StartLoading();
402   Mock::VerifyAndClearExpectations(&visitor);
403
404   EXPECT_CALL(visitor, OnExternalExtensionFileFound(_, _, _, _, _, _))
405       .Times(0);
406   EXPECT_CALL(visitor, OnExternalExtensionUpdateUrlFound(_, _, _, _, _, _))
407       .Times(2);
408   EXPECT_CALL(visitor, OnExternalProviderReady(_))
409       .Times(1);
410
411   RunUntilIdle();
412   EXPECT_TRUE(doc->IsReady());
413
414   app_list::AppListSyncableService* service =
415       app_list::AppListSyncableServiceFactory::GetForProfile(profile.get());
416   ASSERT_TRUE(service);
417   EXPECT_EQ("EN OEM Name", service->GetOemFolderNameForTest());
418 }
419
420 TEST_F(ServicesCustomizationDocumentTest, CustomizationManifestNotFound) {
421   AddCustomizationIdToVp(kDummyCustomizationID);
422   AddManifestNotFound(kDummyCustomizationID);
423
424   ServicesCustomizationDocument* doc =
425       ServicesCustomizationDocument::GetInstance();
426   EXPECT_FALSE(doc->IsReady());
427
428   scoped_ptr<TestingProfile> profile = CreateProfile();
429   extensions::ExternalLoader* loader = doc->CreateExternalLoader(profile.get());
430   EXPECT_TRUE(loader);
431
432   MockExternalProviderVisitor visitor;
433   scoped_ptr<extensions::ExternalProviderImpl> provider(
434       new extensions::ExternalProviderImpl(
435           &visitor,
436           loader,
437           profile.get(),
438           extensions::Manifest::EXTERNAL_PREF,
439           extensions::Manifest::EXTERNAL_PREF_DOWNLOAD,
440           extensions::Extension::FROM_WEBSTORE |
441               extensions::Extension::WAS_INSTALLED_BY_DEFAULT));
442
443   EXPECT_CALL(visitor, OnExternalExtensionFileFound(_, _, _, _, _, _))
444       .Times(0);
445   EXPECT_CALL(visitor, OnExternalExtensionUpdateUrlFound(_, _, _, _, _, _))
446       .Times(0);
447   EXPECT_CALL(visitor, OnExternalProviderReady(_))
448       .Times(1);
449
450   // Manually request a load.
451   loader->StartLoading();
452   Mock::VerifyAndClearExpectations(&visitor);
453
454   EXPECT_CALL(visitor, OnExternalExtensionFileFound(_, _, _, _, _, _))
455       .Times(0);
456   EXPECT_CALL(visitor, OnExternalExtensionUpdateUrlFound(_, _, _, _, _, _))
457       .Times(0);
458   EXPECT_CALL(visitor, OnExternalProviderReady(_))
459       .Times(1);
460
461   RunUntilIdle();
462   EXPECT_TRUE(doc->IsReady());
463 }
464
465 }  // namespace chromeos