File: app_preload_service_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (299 lines) | stat: -rw-r--r-- 12,150 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/apps/app_preload_service/app_preload_service.h"

#include <algorithm>
#include <memory>

#include "base/functional/callback_forward.h"
#include "base/memory/scoped_refptr.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "chrome/browser/apps/app_preload_service/app_preload_almanac_endpoint.h"
#include "chrome/browser/apps/app_preload_service/app_preload_service_factory.h"
#include "chrome/browser/apps/app_preload_service/proto/app_preload.pb.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/ash/app_list/arc/arc_app_list_prefs.h"
#include "chrome/browser/ash/settings/scoped_testing_cros_settings.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/scoped_testing_local_state.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/ash/components/settings/cros_settings.h"
#include "chromeos/ash/components/system/fake_statistics_provider.h"
#include "components/prefs/pref_service.h"
#include "components/services/app_service/public/cpp/app_registry_cache.h"
#include "components/services/app_service/public/cpp/app_update.h"
#include "components/user_manager/fake_user_manager_delegate.h"
#include "components/user_manager/scoped_user_manager.h"
#include "components/user_manager/user_manager.h"
#include "components/user_manager/user_manager_impl.h"
#include "content/public/test/browser_task_environment.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

constexpr char kFirstLoginFlowStartedKey[] = "first_login_flow_started";
constexpr char kFirstLoginFlowCompletedKey[] = "first_login_flow_completed";

constexpr char kApsStateManager[] = "apps.app_preload_service.state_manager";

const base::Value::Dict& GetStateManager(Profile* profile) {
  return profile->GetPrefs()->GetDict(kApsStateManager);
}

}  // namespace

namespace apps {

class AppPreloadServiceTest : public testing::Test {
 protected:
  AppPreloadServiceTest()
      : startup_check_resetter_(
            AppPreloadService::DisablePreloadsOnStartupForTesting()) {
    scoped_feature_list_.InitWithFeatures(
        {features::kAppPreloadService, kAppPreloadServiceEnableShelfPin}, {});
    AppPreloadServiceFactory::SkipApiKeyCheckForTesting(true);
  }

  void SetUp() override {
    testing::Test::SetUp();

    user_manager::UserManager::Get()->SetIsCurrentUserNew(true);

    TestingProfile::Builder profile_builder;
    profile_builder.SetSharedURLLoaderFactory(
        url_loader_factory_.GetSafeWeakWrapper());
    profile_ = profile_builder.Build();

    web_app::test::AwaitStartWebAppProviderAndSubsystems(GetProfile());
  }

  void TearDown() override {
    AppPreloadServiceFactory::SkipApiKeyCheckForTesting(false);
  }

  Profile* GetProfile() { return profile_.get(); }

  network::TestURLLoaderFactory url_loader_factory_;

 private:
  // BrowserTaskEnvironment has to be the first member or test will break.
  content::BrowserTaskEnvironment task_environment_;
  base::test::ScopedFeatureList scoped_feature_list_;
  ScopedTestingLocalState testing_local_state_{
      TestingBrowserProcess::GetGlobal()};
  ash::ScopedTestingCrosSettings testing_cros_settings_;
  user_manager::ScopedUserManager scoped_user_manager_{
      std::make_unique<user_manager::UserManagerImpl>(
          std::make_unique<user_manager::FakeUserManagerDelegate>(),
          testing_local_state_.Get(),
          ash::CrosSettings::Get())};
  std::unique_ptr<TestingProfile> profile_;
  ash::system::ScopedFakeStatisticsProvider fake_statistics_provider_;
  base::AutoReset<bool> startup_check_resetter_;
};

TEST_F(AppPreloadServiceTest, ServiceAccessPerProfile) {
  // We expect the App Preload Service to be available in a normal profile.
  TestingProfile::Builder profile_builder;
  auto profile = profile_builder.Build();
  EXPECT_TRUE(AppPreloadServiceFactory::IsAvailable(profile.get()));
  auto* service = AppPreloadServiceFactory::GetForProfile(profile.get());
  EXPECT_NE(nullptr, service);

  // The service is unsupported in incognito.
  TestingProfile::Builder incognito_builder;
  auto* incognito_profile = incognito_builder.BuildIncognito(profile.get());
  EXPECT_FALSE(AppPreloadServiceFactory::IsAvailable(incognito_profile));
  EXPECT_EQ(nullptr,
            AppPreloadServiceFactory::GetForProfile(incognito_profile));

  // We expect the App Preload Service to not be available in either regular or
  // OTR guest profiles.
  TestingProfile::Builder guest_builder;
  guest_builder.SetGuestSession();
  auto guest_profile = guest_builder.Build();
  EXPECT_FALSE(AppPreloadServiceFactory::IsAvailable(guest_profile.get()));
  EXPECT_EQ(nullptr,
            AppPreloadServiceFactory::GetForProfile(guest_profile.get()));

  auto* guest_otr_profile =
      guest_profile->GetPrimaryOTRProfile(/*create_if_needed=*/true);
  EXPECT_FALSE(AppPreloadServiceFactory::IsAvailable(guest_otr_profile));
  EXPECT_EQ(nullptr,
            AppPreloadServiceFactory::GetForProfile(guest_otr_profile));

  // The service is unsupported for managed and supervised accounts.
  TestingProfile::Builder child_builder;
  child_builder.SetIsSupervisedProfile();
  std::unique_ptr<TestingProfile> child_profile = child_builder.Build();

  EXPECT_FALSE(AppPreloadServiceFactory::IsAvailable(child_profile.get()));
  EXPECT_EQ(nullptr,
            AppPreloadServiceFactory::GetForProfile(child_profile.get()));

  TestingProfile::Builder managed_builder;
  managed_builder.OverridePolicyConnectorIsManagedForTesting(true);
  std::unique_ptr<TestingProfile> managed_profile = managed_builder.Build();

  EXPECT_FALSE(AppPreloadServiceFactory::IsAvailable(managed_profile.get()));
  EXPECT_EQ(nullptr,
            AppPreloadServiceFactory::GetForProfile(managed_profile.get()));
}

TEST_F(AppPreloadServiceTest, FirstLoginStartedPrefSet) {
  auto* service = AppPreloadService::Get(GetProfile());
  // Start the login flow, but do not wait for it to finish.
  service->StartFirstLoginFlowForTesting(base::DoNothing());

  auto flow_started =
      GetStateManager(GetProfile()).FindBool(kFirstLoginFlowStartedKey);
  auto flow_completed =
      GetStateManager(GetProfile()).FindBool(kFirstLoginFlowCompletedKey);
  // Since we're creating a new profile with no saved state, we expect the state
  // to be "started", but not "completed".
  EXPECT_TRUE(flow_started.has_value() && flow_started.value());
  EXPECT_EQ(flow_completed, std::nullopt);
}

TEST_F(AppPreloadServiceTest, FirstLoginCompletedPrefSetAfterSuccess) {
  // An empty response indicates that the request completed successfully, but
  // there are no apps to install.
  proto::AppPreloadListResponse response;

  url_loader_factory_.AddResponse(
      app_preload_almanac_endpoint::GetServerUrl().spec(),
      response.SerializeAsString());

  base::test::TestFuture<bool> result;
  auto* service = AppPreloadService::Get(GetProfile());
  service->StartFirstLoginFlowForTesting(result.GetCallback());
  ASSERT_TRUE(result.Get());

  // We expect that the key has been set after the first login flow has been
  // completed.
  auto flow_completed =
      GetStateManager(GetProfile()).FindBool(kFirstLoginFlowCompletedKey);
  EXPECT_NE(flow_completed, std::nullopt);
  EXPECT_TRUE(flow_completed.value());
}

TEST_F(AppPreloadServiceTest, FirstLoginExistingUserNotStarted) {
  user_manager::UserManager::Get()->SetIsCurrentUserNew(false);
  TestingProfile existing_user_profile;

  auto* service = AppPreloadService::Get(&existing_user_profile);
  service->StartFirstLoginFlowForTesting(base::DoNothing());

  auto flow_started = GetStateManager(&existing_user_profile)
                          .FindBool(kFirstLoginFlowStartedKey);
  // Existing users should not start the first-login flow.
  EXPECT_FALSE(flow_started.has_value());
}

TEST_F(AppPreloadServiceTest, IgnoreAndroidAppInstall) {
  constexpr char kPackageName[] = "com.peanuttypes";
  constexpr char kActivityName[] = "com.peanuttypes.PeanutTypesActivity";

  proto::AppPreloadListResponse response;
  auto* app = response.add_apps_to_install();
  app->set_name("Peanut Types");
  app->set_install_reason(proto::AppPreloadListResponse::INSTALL_REASON_OEM);

  url_loader_factory_.AddResponse(
      app_preload_almanac_endpoint::GetServerUrl().spec(),
      response.SerializeAsString());

  base::test::TestFuture<bool> result;
  auto* service = AppPreloadService::Get(GetProfile());
  service->StartFirstLoginFlowForTesting(result.GetCallback());
  ASSERT_TRUE(result.Get());

  // It's hard to assert conclusively that nothing happens in this case, but for
  // now we just assert that the app wasn't added to App Service.
  auto app_id = ArcAppListPrefs::GetAppId(kPackageName, kActivityName);
  bool found = AppServiceProxyFactory::GetForProfile(GetProfile())
                   ->AppRegistryCache()
                   .ForOneApp(app_id, [](const AppUpdate&) {});
  ASSERT_FALSE(found);
}

TEST_F(AppPreloadServiceTest, FirstLoginStartedNotCompletedAfterServerError) {
  url_loader_factory_.AddResponse(
      app_preload_almanac_endpoint::GetServerUrl().spec(), /*content=*/"",
      net::HTTP_INTERNAL_SERVER_ERROR);

  base::test::TestFuture<bool> result;
  auto* service = AppPreloadService::Get(GetProfile());
  service->StartFirstLoginFlowForTesting(result.GetCallback());
  ASSERT_FALSE(result.Get());

  auto flow_started =
      GetStateManager(GetProfile()).FindBool(kFirstLoginFlowStartedKey);
  auto flow_completed =
      GetStateManager(GetProfile()).FindBool(kFirstLoginFlowCompletedKey);
  // Since there was an error fetching apps, the flow should be "started" but
  // not "completed".
  EXPECT_EQ(flow_started, true);
  EXPECT_EQ(flow_completed, std::nullopt);
}

TEST_F(AppPreloadServiceTest, GetPinApps) {
  PackageId app1 = *PackageId::FromString("web:https://example.com/app1");
  PackageId app2 = *PackageId::FromString("web:https://example.com/app2");
  PackageId app3 = *PackageId::FromString("web:https://example.com/app3");
  PackageId app4 = *PackageId::FromString("web:https://example.com/app4");

  proto::AppPreloadListResponse response;
  auto add_app = [&](const std::string& package_id) {
    auto* app = response.add_apps_to_install();
    app->set_package_id(package_id);
    app->set_install_reason(
        proto::AppPreloadListResponse::INSTALL_REASON_DEFAULT);
  };
  auto add_shelf_config = [&](const std::string& package_id, uint32_t order) {
    auto* config = response.add_shelf_config();
    config->add_package_id(package_id);
    config->set_order(order);
  };
  add_app(app4.ToString());
  add_app(app2.ToString());
  add_app(app1.ToString());
  add_shelf_config(app3.ToString(), 3);
  add_shelf_config(app2.ToString(), 2);
  add_shelf_config(app1.ToString(), 1);

  url_loader_factory_.AddResponse(
      app_preload_almanac_endpoint::GetServerUrl().spec(),
      response.SerializeAsString());

  auto* service = AppPreloadService::Get(GetProfile());
  service->StartFirstLoginFlowForTesting(base::DoNothing());

  base::test::TestFuture<const std::vector<PackageId>&,
                         const std::vector<PackageId>&>
      result;
  service->GetPinApps(result.GetCallback());

  // Pin apps should ignore app4 since it is not in pin ordering.
  std::vector<apps::PackageId> pin_apps = result.Get<0>();
  EXPECT_EQ(pin_apps.size(), 2u);
  EXPECT_EQ(pin_apps[0], app2);
  EXPECT_EQ(pin_apps[1], app1);

  // Pin order should be sorted.
  std::vector<apps::PackageId> pin_order = result.Get<1>();
  EXPECT_EQ(pin_order.size(), 3u);
  EXPECT_EQ(pin_order[0], app1);
  EXPECT_EQ(pin_order[1], app2);
  EXPECT_EQ(pin_order[2], app3);
}

}  // namespace apps