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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
|
// Copyright 2023 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/ash/scalable_iph/scalable_iph_browser_test_base.h"
#include <memory>
#include "ash/constants/ash_features.h"
#include "base/containers/fixed_flat_set.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/ash/scalable_iph/customizable_test_env_browser_test_base.h"
#include "chrome/browser/ash/scalable_iph/mock_scalable_iph_delegate.h"
#include "chrome/browser/ash/scalable_iph/scalable_iph_delegate_impl.h"
#include "chrome/browser/ash/scalable_iph/scalable_iph_factory_impl.h"
#include "chrome/browser/feature_engagement/tracker_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chromeos/ash/components/browser_context_helper/browser_context_helper.h"
#include "chromeos/ash/components/scalable_iph/scalable_iph.h"
#include "chromeos/ash/components/scalable_iph/scalable_iph_constants.h"
#include "chromeos/ash/components/scalable_iph/scalable_iph_delegate.h"
#include "chromeos/ash/components/scalable_iph/scalable_iph_factory.h"
#include "chromeos/ash/services/network_config/in_process_instance.h"
#include "chromeos/ash/services/network_config/public/cpp/cros_network_config_test_helper.h"
#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h"
#include "components/feature_engagement/test/mock_tracker.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/signin/public/identity_manager/account_capabilities_test_mutator.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/signin/public/identity_manager/test_identity_manager_observer.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/browser_context.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace ash {
namespace {
using ::chromeos::network_config::mojom::ConnectionStateType;
using ::chromeos::network_config::mojom::NetworkType;
using Observer = ::scalable_iph::ScalableIphDelegate::Observer;
std::set<std::string> mock_delegate_created_;
constexpr char kTestWiFiId[] = "test-wifi-id";
constexpr auto kEligileUserSessionTypesForMantaService = base::MakeFixedFlatSet<
CustomizableTestEnvBrowserTestBase::UserSessionType>(
{CustomizableTestEnvBrowserTestBase::UserSessionType::kRegular,
CustomizableTestEnvBrowserTestBase::UserSessionType::kRegularNonOwner,
CustomizableTestEnvBrowserTestBase::UserSessionType::kManaged,
CustomizableTestEnvBrowserTestBase::UserSessionType::kRegularWithOobe});
BASE_FEATURE(kScalableIphTest,
"ScalableIphTest",
base::FEATURE_DISABLED_BY_DEFAULT);
// One off helper that waits for refresh token loading with nestable tasks
// allowed so that it could be used under nested `RunLoops`.
void EnsureRefreshTokensLoaded(signin::IdentityManager* identity_manager) {
base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
signin::TestIdentityManagerObserver load_credentials_observer(
identity_manager);
load_credentials_observer.SetOnRefreshTokensLoadedCallback(
run_loop.QuitClosure());
if (identity_manager->AreRefreshTokensLoaded()) {
return;
}
run_loop.Run();
ASSERT_TRUE(identity_manager->AreRefreshTokensLoaded());
}
} // namespace
ScalableIphBrowserTestBase::ScalableIphBrowserTestBase() {
scalable_iph::ScalableIph::ForceEnableIphFeatureForTesting();
}
ScalableIphBrowserTestBase::~ScalableIphBrowserTestBase() = default;
void ScalableIphBrowserTestBase::SetUp() {
InitializeScopedFeatureList();
network_config::OverrideInProcessInstanceForTesting(
&fake_cros_network_config_);
// Keyed service is a service which is tied to an object. For our use cases,
// the object is `BrowserContext` (e.g. `Profile`). See
// //components/keyed_service/README.md for details on keyed service.
//
// We set a testing factory to inject a mock. A testing factory must be set
// early enough as a service is not created before that, e.g. a `Tracker` must
// not be created before we set `CreateMockTracker`. If a keyed service is
// created before we set our testing factory, `SetTestingFactory` will
// destruct already created keyed services at a time we set our testing
// factory. It destructs a keyed service at an unusual timing. It can trigger
// a dangling pointer issue, etc.
//
// `SetUpOnMainThread` below is too late to set a testing factory. Note that
// `InProcessBrowserTest::SetUp` is called at the very early stage, e.g.
// before command lines are set, etc.
mock_tracker_factory_method_ = GetMockTrackerFactoryMethod();
CustomizableTestEnvBrowserTestBase::SetUp();
}
void ScalableIphBrowserTestBase::SetUpInProcessBrowserTestFixture() {
CustomizableTestEnvBrowserTestBase::SetUpInProcessBrowserTestFixture();
if (enable_multi_user_) {
// Add a secondary user.
LoginManagerMixin* login_manager_mixin = GetLoginManagerMixin();
CHECK(login_manager_mixin);
login_manager_mixin->AppendRegularUsers(1);
CHECK_EQ(login_manager_mixin->users().size(), 2ul);
}
}
void ScalableIphBrowserTestBase::SetUpBrowserContextKeyedServices(
content::BrowserContext* context) {
CustomizableTestEnvBrowserTestBase::SetUpBrowserContextKeyedServices(context);
if (mock_tracker_factory_method_) {
feature_engagement::TrackerFactory::GetInstance()->SetTestingFactory(
context, mock_tracker_factory_method_);
}
// The static cast is necessary to access the delegate functions declared in
// the `ScalableIphFactoryImpl` class.
ScalableIphFactoryImpl* scalable_iph_factory =
static_cast<ScalableIphFactoryImpl*>(ScalableIphFactory::GetInstance());
CHECK(scalable_iph_factory);
// This method can be called more than once for a single browser context.
if (scalable_iph_factory->has_delegate_factory_for_testing()) {
return;
}
// This is NOT a testing factory of a keyed service factory .But the delegate
// factory is called from the factory of `ScalableIphFactory`. Set this at the
// same time.
scalable_iph_factory->SetDelegateFactoryForTesting(
base::BindRepeating(&ScalableIphBrowserTestBase::CreateMockDelegate));
}
// `SetUpOnMainThread` is called just before a test body. Do the mock set up in
// this function as `browser()` is not available in `SetUp` above.
void ScalableIphBrowserTestBase::SetUpOnMainThread() {
if (kEligileUserSessionTypesForMantaService.contains(
test_environment().user_session_type()) &&
!force_disable_manta_service_) {
ScalableIphFactory::GetInstance()
->SetOnBuildingServiceInstanceForTestingCallback(base::BindRepeating(
&ScalableIphBrowserTestBase::SetCanUseMantaService));
}
// `CustomizableTestEnvBrowserTestBase::SetUpOnMainThread` must be called
// before our `SetUpOnMainThread` as login happens in the method, i.e. profile
// is not available before it.
CustomizableTestEnvBrowserTestBase::SetUpOnMainThread();
// If user session type is `kRegularWithOobe`, Chrome enters post login OOBE
// screens after a login. It means that there won't be `ScalableIph` as
// `ScalableIph` starts after post login OOBE screens. We have to wait the
// initialization of `ScalableIph` before setting up mocks.
if (test_environment().user_session_type() ==
CustomizableTestEnvBrowserTestBase::UserSessionType::kRegularWithOobe) {
return;
}
if (enable_multi_user_) {
// By default, `MultiUserWindowManager` is created with multi profile off.
// Re-create for multi profile tests. This has to be done after
// `SetUpOnMainThread` of a base class as the original multi-profile-off
// `MultiUserWindowManager` is created there.
MultiUserWindowManagerHelper::CreateInstanceForTest(
GetPrimaryUserContext().GetAccountId());
}
// If we don't intend to enforce ScalableIph setup (i.e. the user profile
// doesn't qualify for ScalableIph), do not set up mocks as ScalableIph
// should not be available for the profile.
if (!setup_scalable_iph_) {
return;
}
CHECK(enable_scalable_iph_)
<< "ScalableIph feature flag must be intended to be enabled to set up "
"fakes and mocks of ScalableIph";
SetUpMocks();
}
void ScalableIphBrowserTestBase::TearDownOnMainThread() {
// We are going to release references to mock objects below. Verify the
// expectations in advance to have a predictable behavior.
testing::Mock::VerifyAndClearExpectations(mock_tracker_);
mock_tracker_ = nullptr;
testing::Mock::VerifyAndClearExpectations(mock_delegate_);
mock_delegate_ = nullptr;
InProcessBrowserTest::TearDownOnMainThread();
}
void ScalableIphBrowserTestBase::SetUpMocks() {
CHECK(!mock_delegate_) << "Mocks have already been set up.";
// Do not access profile via `browser()` as a browser might not be created if
// session type is WithOobe.
Profile* profile = ProfileManager::GetActiveUserProfile();
CHECK(profile);
CHECK(IsMockDelegateCreatedFor(profile))
<< "ScalableIph service has a timer inside. The service must be created "
"at a login time. We check the behavior by confirming creation of a "
"delegate.";
if (mock_tracker_factory_method_) {
mock_tracker_ = static_cast<feature_engagement::test::MockTracker*>(
feature_engagement::TrackerFactory::GetForBrowserContext(profile));
CHECK(mock_tracker_)
<< "mock_tracker_ must be non-nullptr. GetForBrowserContext should "
"create one via CreateMockTracker if it does not exist.";
}
// The static cast is necessary to access the delegate functions declared in
// the `ScalableIphFactoryImpl` class.
ScalableIphFactoryImpl* scalable_iph_factory =
static_cast<ScalableIphFactoryImpl*>(ScalableIphFactory::GetInstance());
CHECK(scalable_iph_factory);
CHECK(scalable_iph_factory->has_delegate_factory_for_testing())
<< "This test uses MockScalableIphDelegate. A factory for testing must "
"be set.";
scalable_iph::ScalableIph* scalable_iph =
ScalableIphFactory::GetForBrowserContext(profile);
CHECK(scalable_iph);
// `ScalableIph` for the profile is initialzied in
// `CustomizableTestEnvBrowserTestBase::SetUpOnMainThread` above. We cannot
// simply use `TestMockTimeTaskRunner::ScopedContext` as `RunLoop` is used
// there and it's not supported by `ScopedContext`. We override a task runner
// after a timer has created and started.
task_runner_ = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
scalable_iph->OverrideTaskRunnerForTesting(task_runner());
mock_delegate_ = static_cast<test::MockScalableIphDelegate*>(
scalable_iph->delegate_for_testing());
CHECK(mock_delegate_);
}
void ScalableIphBrowserTestBase::InitializeScopedFeatureList() {
base::FieldTrialParams params;
AppendVersionNumber(params);
AppendUiParams(params);
base::test::FeatureRefAndParams test_config(kScalableIphTest, params);
std::vector<base::test::FeatureRefAndParams> enabled_features({test_config});
std::vector<base::test::FeatureRef> disabled_features;
AppendTestSpecificFeatures(enabled_features, disabled_features);
if (enable_scalable_iph_) {
enabled_features.push_back(
base::test::FeatureRefAndParams(ash::features::kScalableIph, {}));
} else {
disabled_features.push_back(
base::test::FeatureRef(ash::features::kScalableIph));
}
if (enable_scalable_iph_debug_) {
enabled_features.push_back(
base::test::FeatureRefAndParams(ash::features::kScalableIphDebug, {}));
} else {
disabled_features.push_back(
base::test::FeatureRef(ash::features::kScalableIphDebug));
}
scoped_feature_list_.InitWithFeaturesAndParameters(enabled_features,
disabled_features);
}
void ScalableIphBrowserTestBase::AppendUiParams(
base::FieldTrialParams& params) {
AppendFakeUiParamsNotification(params, /*has_body_text=*/true,
kScalableIphTest);
}
void ScalableIphBrowserTestBase::AppendVersionNumber(
base::FieldTrialParams& params,
const base::Feature& feature,
const std::string& version_number) {
params[FullyQualified(feature,
scalable_iph::kCustomParamsVersionNumberParamName)] =
version_number;
}
void ScalableIphBrowserTestBase::AppendVersionNumber(
base::FieldTrialParams& params,
const base::Feature& feature) {
AppendVersionNumber(
params, feature,
base::NumberToString(scalable_iph::kCurrentVersionNumber));
}
void ScalableIphBrowserTestBase::AppendVersionNumber(
base::FieldTrialParams& params) {
AppendVersionNumber(params, kScalableIphTest);
}
void ScalableIphBrowserTestBase::AppendFakeUiParamsNotification(
base::FieldTrialParams& params,
bool has_body_text,
const base::Feature& feature) {
params[FullyQualified(feature, scalable_iph::kCustomUiTypeParamName)] =
scalable_iph::kCustomUiTypeValueNotification;
params[FullyQualified(feature,
scalable_iph::kCustomNotificationIdParamName)] =
kTestNotificationId;
params[FullyQualified(feature,
scalable_iph::kCustomNotificationTitleParamName)] =
kTestNotificationTitle;
if (has_body_text) {
params[FullyQualified(feature,
scalable_iph::kCustomNotificationBodyTextParamName)] =
kTestNotificationBodyText;
}
params[FullyQualified(feature,
scalable_iph::kCustomNotificationButtonTextParamName)] =
kTestNotificationButtonText;
params[FullyQualified(feature,
scalable_iph::kCustomButtonActionTypeParamName)] =
kTestButtonActionTypeOpenChrome;
params[FullyQualified(feature,
scalable_iph::kCustomButtonActionEventParamName)] =
kTestActionEventName;
}
void ScalableIphBrowserTestBase::AppendFakeUiParamsBubble(
base::FieldTrialParams& params) {
params[FullyQualified(kScalableIphTest,
scalable_iph::kCustomUiTypeParamName)] =
scalable_iph::kCustomUiTypeValueBubble;
params[FullyQualified(kScalableIphTest,
scalable_iph::kCustomBubbleIdParamName)] =
kTestBubbleId;
params[FullyQualified(kScalableIphTest,
scalable_iph::kCustomBubbleTitleParamName)] =
kTestBubbleTitle;
params[FullyQualified(kScalableIphTest,
scalable_iph::kCustomBubbleTextParamName)] =
kTestBubbleText;
params[FullyQualified(kScalableIphTest,
scalable_iph::kCustomBubbleButtonTextParamName)] =
kTestBubbleButtonText;
params[FullyQualified(kScalableIphTest,
scalable_iph::kCustomButtonActionTypeParamName)] =
kTestButtonActionTypeOpenGoogleDocs;
params[FullyQualified(kScalableIphTest,
scalable_iph::kCustomButtonActionEventParamName)] =
kTestActionEventName;
params[FullyQualified(kScalableIphTest,
scalable_iph::kCustomBubbleIconParamName)] =
kTestBubbleIconString;
}
// static
std::string ScalableIphBrowserTestBase::FullyQualified(
const base::Feature& feature,
const std::string& param_name) {
return base::StrCat({feature.name, "_", param_name});
}
bool ScalableIphBrowserTestBase::IsMockDelegateCreatedFor(Profile* profile) {
return mock_delegate_created_.contains(profile->GetProfileUserName());
}
void ScalableIphBrowserTestBase::EnableTestIphFeatures(
const std::vector<raw_ptr<const base::Feature, VectorExperimental>>
test_iph_features) {
CHECK(mock_delegate_)
<< "To enable a test iph feature, mocks have to be set up.";
const base::flat_set<const base::Feature*> test_iph_features_set(
test_iph_features.begin(), test_iph_features.end());
ON_CALL(*mock_tracker(), ShouldTriggerHelpUI)
.WillByDefault([test_iph_features_set](const base::Feature& feature) {
return test_iph_features_set.contains(&feature);
});
// Do not access profile via `browser()` as this method can be called before a
// browser is created.
Profile* profile = ProfileManager::GetActiveUserProfile();
CHECK(profile);
// `OverrideFeatureListForTesting` prohibits calling it twice and it has a
// check. We don't need to do another check for `EnableTestIphFeature` being
// called twice.
scalable_iph::ScalableIph* scalable_iph =
ScalableIphFactory::GetForBrowserContext(profile);
scalable_iph->OverrideFeatureListForTesting(test_iph_features);
}
void ScalableIphBrowserTestBase::EnableTestIphFeature() {
EnableTestIphFeatures({&kScalableIphTest});
}
const base::Feature& ScalableIphBrowserTestBase::TestIphFeature() const {
return kScalableIphTest;
}
void ScalableIphBrowserTestBase::TriggerConditionsCheckWithAFakeEvent(
scalable_iph::ScalableIph::Event event) {
// Do not access profile via `browser()` as this method can be called before a
// browser is created.
Profile* profile = ProfileManager::GetActiveUserProfile();
CHECK(profile);
scalable_iph::ScalableIph* scalable_iph =
ScalableIphFactory::GetForBrowserContext(profile);
scalable_iph->RecordEvent(event);
}
ash::UserContext ScalableIphBrowserTestBase::GetPrimaryUserContext() {
return ash::LoginManagerMixin::CreateDefaultUserContext(
GetLoginManagerMixin()->users()[0]);
}
ash::UserContext ScalableIphBrowserTestBase::GetSecondaryUserContext() {
CHECK(enable_multi_user_);
return ash::LoginManagerMixin::CreateDefaultUserContext(
GetLoginManagerMixin()->users()[1]);
}
void ScalableIphBrowserTestBase::ShutdownScalableIph() {
scalable_iph::ScalableIph* scalable_iph =
ScalableIphFactory::GetForBrowserContext(browser()->profile());
CHECK(scalable_iph) << "ScalableIph does not exist for a current profile";
// `ScalableIph::Shutdown` destructs a delegate. Release the pointer to the
// mock delegate to avoid having a dangling pointer. We can retain a pointer
// to the mock tracker as a tracker is not destructed by the
// `ScalableIph::Shutdown`.
mock_delegate_ = nullptr;
scalable_iph->Shutdown();
}
void ScalableIphBrowserTestBase::AddOnlineNetwork() {
fake_cros_network_config_.AddNetworkAndDevice(
network_config::CrosNetworkConfigTestHelper::
CreateStandaloneNetworkProperties(kTestWiFiId, NetworkType::kWiFi,
ConnectionStateType::kOnline,
/*signal_strength=*/0));
}
ScalableIphBrowserTestBase::MockTrackerFactoryMethod
ScalableIphBrowserTestBase::GetMockTrackerFactoryMethod() {
return base::BindRepeating(&ScalableIphBrowserTestBase::CreateMockTracker);
}
// static
std::unique_ptr<feature_engagement::test::MockTracker>
ScalableIphBrowserTestBase::SetUpFakeInitializationCalls(
std::unique_ptr<feature_engagement::test::MockTracker> mock_tracker) {
ON_CALL(*mock_tracker, AddOnInitializedCallback)
.WillByDefault(
[](feature_engagement::Tracker::OnInitializedCallback callback) {
std::move(callback).Run(true);
});
ON_CALL(*mock_tracker, IsInitialized).WillByDefault(testing::Return(true));
return mock_tracker;
}
// static
std::unique_ptr<KeyedService> ScalableIphBrowserTestBase::CreateMockTracker(
content::BrowserContext* browser_context) {
return SetUpFakeInitializationCalls(
std::make_unique<feature_engagement::test::MockTracker>());
}
// static
std::unique_ptr<scalable_iph::ScalableIphDelegate>
ScalableIphBrowserTestBase::CreateMockDelegate(Profile* profile,
scalable_iph::Logger* logger) {
std::pair<std::set<std::string>::iterator, bool> result =
mock_delegate_created_.insert(profile->GetProfileUserName());
CHECK(result.second) << "Delegate is created twice for a profile";
std::unique_ptr<test::MockScalableIphDelegate> delegate =
std::make_unique<test::MockScalableIphDelegate>();
delegate->SetDelegate(
std::make_unique<ScalableIphDelegateImpl>(profile, logger));
// Fake behaviors of observers must be set at an early stage as those methods
// are called from constructors, i.e. Set up phases of test fixtures.
delegate->FakeObservers();
return delegate;
}
// static
void ScalableIphBrowserTestBase::SetCanUseMantaService(
content::BrowserContext* browser_context) {
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(
Profile::FromBrowserContext(browser_context));
CHECK(identity_manager);
EnsureRefreshTokensLoaded(identity_manager);
const user_manager::User* user =
ash::BrowserContextHelper::Get()->GetUserByBrowserContext(
browser_context);
CHECK(user);
AccountInfo account_info = identity_manager->FindExtendedAccountInfoByGaiaId(
user->GetAccountId().GetGaiaId());
AccountCapabilitiesTestMutator test_mutator(&account_info.capabilities);
test_mutator.set_can_use_manta_service(true);
signin::UpdateAccountInfoForAccount(identity_manager, account_info);
}
} // namespace ash
|